Overview
alloy is a Rust CLI for merging, diffing, and converting the weights of large language models. It supports 10 merge algorithms, including linear, SLERP, TIES, DARE, and DELLA, reads mergekit-compatible YAML configs, and writes standard safetensors files.
Merging models is arithmetic on arrays of floats, so it doesn’t need Python, PyTorch, or a GPU. alloy memory-maps the model files and uses fused SIMD kernels (AVX2 and NEON) that read BF16 values straight from disk and compute in F32 registers, with no intermediate allocations. On real 7B and 14B models, IO-bound methods such as linear and SLERP run 1.4 to 2.1 times faster than mergekit. Compute-heavy methods such as TIES and DARE are still slower, because PyTorch’s C tensor kernels are heavily optimized.
It compiles to a static binary of about 4 MB, runs on CPU-only hardware, and produces results that are bit-identical to mergekit’s for the same config.
Why Merge Models?
Training LLMs is expensive. Fine-tuning one for a specific task, such as code generation, medical QA, or creative writing, takes hundreds of GPU hours and a curated dataset. But if you want a model that’s good at two things, you’re stuck: retraining from scratch on a combined dataset is too expensive, and running both models at inference time doubles your cost.
Model merging avoids all of that. You take two fine-tuned models that share a common base and combine their weights into a single model. The result costs the same to run as one model, and it needs no extra training, no access to the original datasets, and no additional compute at serving time.
Why does this work at all? Fine-tuning moves weights in a structured way. The difference between a base model and its fine-tune, known as a task vector, captures what the model “learned” during training. Adding together task vectors from different fine-tunes composes their capabilities, so a code model combined with a chat model gives you a model that can do both, usually without much loss in either skill.
This isn’t a niche technique. Some of the most downloaded open models on HuggingFace, including NeuralBeagle, Goliath-120B, and dozens of community favorites, are merges rather than models trained from scratch.
Motivation
mergekit (Goddard et al., Arcee AI) is the standard tool for model merging, and the community has built great things with it. It is also slow, and the reason is structural: it treats merging as a PyTorch workload.
Consider what happens when you run a merge with mergekit. Python starts, imports dozens of modules, initializes the PyTorch runtime, builds a task DAG, and begins loading model shards through LazyTensorLoader. Every tensor access opens a file, seeks to an offset, reads the bytes, deserializes them into a PyTorch tensor, and allocates memory. A 7B model in FP16 holds about 14 GB of raw weights, yet mergekit’s peak memory can exceed 64 GB, because it keeps several tensors alive at once during the merge.
The math behind merging is relatively simple: weighted sums, some trigonometry, and element-wise operations on arrays of floats. None of it needs autograd, a CUDA runtime, or PyTorch’s tensor abstraction. What it needs is fast reads and fast arithmetic.
alloy is built around that observation. It is a Rust CLI that memory-maps safetensors files, processes one tensor at a time, and writes each result straight to disk. The whole program compiles to a static binary of about 4 MB with no runtime dependencies.
MERGEKIT
- Python and PyTorch runtime
- DAG-based task scheduler
- LazyTensorLoader opens and closes files repeatedly
- Multiple tensors in memory at once
- High peak memory from multiple tensors in flight
ALLOY
- Native Rust, no runtime
- Sequential streaming pipeline
- Zero-copy mmap with no deserialization
- One tensor in memory at a time
- Peak RAM proportional to the largest tensor
Both tools write standard safetensors output, so the files load in any HuggingFace tool or inference server.
Architecture
Everything in alloy follows from one constraint: process one tensor at a time. Tensors stream through the pipeline in sequence instead of being loaded into memory together.
TensorStore
When alloy opens a model, it memory-maps every shard file with mmap. The OS maps the file contents into the process’s virtual address space without reading anything into RAM. Tensor data stays on disk until it is touched, and the kernel pages it in and out automatically.
On open, we parse each shard’s JSON header, which lists tensor names and byte offsets, and build a HashMap index, so every later lookup is O(1). F32 tensors are read as slices that point directly into the mmap region, which makes those reads zero-copy. FP16 and BF16 tensors are converted to F32 on the fly. That conversion does allocate, but only for one tensor at a time.
pub fn tensor_bytes(&self, name: &str) -> &[u8] {
let loc = &self.index[name]; // O(1) HashMap lookup
let shard = &self.shards[loc.shard_idx]; // which file this tensor lives in
&shard.mmap[loc.abs_start..loc.abs_end] // zero-copy slice into mmap
}StreamingWriter
Writing safetensors is harder than reading them. The format puts a header with the byte offset of every tensor at the start of the file, so the exact sizes have to be known before a single byte is written. We handle this in two phases.
Phase 1 (planning): we walk every tensor name and shape in the merge config, compute the byte sizes, and assign each tensor to an output shard. This gives us a complete header and a shard assignment map. Only metadata is read in this phase, never tensor data.
Phase 2 (writing): for each tensor in order, we read it from the TensorStore, run the merge op, cast the result to the output dtype, and write it directly into the output file at its precomputed offset. Each tensor is dropped from memory as soon as it has been written.
Writes go to a .tmp file first and are renamed atomically on completion. If alloy crashes mid-write, you’re left with a .tmp file and the original output is untouched, so there are never partial or corrupted files.
// Phase 1: plan shard layout (metadata only)
let plan = planner.assign_shards(&tensor_names, &shapes, max_shard_size);
// Phase 2: stream tensors one at a time
for name in &plan.tensor_order {
let data = store.tensor_as_f32(name)?; // mmap read
let merged = merge_op.merge(&inputs)?; // compute
writer.write_tensor(name, &merged)?; // write + drop
}Numerical Stability
Weights are stored as FP16 or BF16, but all merge math happens in F32 after conversion. Operations that accumulate across many elements, such as the dot products behind cosine similarity and the norms used by SLERP, use F64 accumulators to prevent floating-point drift. This matters in practice: summing 10 million F32 values without an F64 accumulator can lose several digits of precision.
Parallelism comes from rayon’s par_chunks, with each thread processing 8,192 elements independently. The per-chunk results are then folded sequentially rather than reduced in parallel, so the output is deterministic regardless of thread count or scheduling. Running the same merge twice gives bit-identical results.
Algorithms
We implement 10 merge methods, and they are interchangeable because the pipeline doesn’t know or care which algorithm is running. It feeds tensors in and gets a merged result back.
Linear and Task Arithmetic
The simplest merge is a weighted average, . It works surprisingly well when models share the same base, because fine-tuning tends to push weights in similar directions.
Task arithmetic goes a step further and operates on task vectors instead of raw weights. A task vector is the difference between a fine-tuned model and its base, . You add a weighted sum of task vectors back onto the base, scaled by a factor :
controls how far the merged model strays from the base. A larger value gives stronger specialization, and a smaller one keeps the merge closer to the base model’s behavior.
SLERP
Linear interpolation (LERP) blends two weight vectors along a straight line through the interior of the space. The problem is that the interpolated vector ends up shorter than either input, and for weight tensors that loss of magnitude degrades model quality.
SLERP fixes this by interpolating along the surface of the hypersphere instead, preserving the norm the whole way. Geometrically, it follows the great-circle arc between two points on a sphere rather than cutting through the interior:
is the angle between and , computed as , and is the interpolation parameter. When the vectors are nearly parallel (), the formula becomes numerically unstable, so we fall back to LERP.
TIES
Merging more than two models gets complicated. Task vectors from different fine-tunes often conflict, with one model pushing a weight up and another pushing it down, and averaging those opposing signals cancels them out. TIES (Yadav et al., 2023) resolves this in three steps.
1. Trim: for each task vector, zero out the elements with the smallest magnitudes. This removes noise from insignificant weight changes. The trim fraction, set by density, is a hyperparameter that usually falls between 0.2 and 0.5.
2. Elect sign: at each weight position, take a weighted vote across all models to pick the “consensus” sign. If models A and C increased a weight and model B decreased it, and A and C together outweigh B, the consensus is positive.
3. Disjoint merge: at each position, keep only the contributions from models whose sign matches the consensus. Models that disagree are excluded entirely:
where is the elected sign at position . The merge keeps the direction of change that most models agree on, instead of diluting it with conflicting signals.
DARE
DARE (Yu et al., 2023) takes a very different approach, based on random dropout. Before merging, each element of each task vector is zeroed out at random with probability , where is the keep rate, usually between 0.1 and 0.5. The surviving elements are rescaled by to preserve the expected magnitude.
The reasoning is that fine-tuning changes are highly redundant. The learned behavior is spread across a very large number of weights, and most of them can be dropped without losing the capability. Picking a different random subset for each model reduces conflicting signals while keeping each model’s overall contribution intact.
DARE can be paired with linear merging (dare_linear) or with TIES sign election (dare_ties).
DELLA
DELLA (Bansal et al., 2024) builds on DARE with one change: the dropout probability depends on the magnitude of each weight change. Larger changes are more likely to be important, so they are dropped less often. The dropout probability for each element is:
is the base density, similar to DARE’s keep rate, is the task vector magnitude at position , and controls how strongly dropout favors large elements. At the dropout is uniform, which is plain DARE. As increases, small changes are dropped more often while large changes survive.
Model Comparison
alloy also has a diff command that compares two models tensor by tensor. It is useful for seeing how much a fine-tune changed its base, or for sanity-checking a merge. For each shared tensor, it computes four metrics in a single parallel pass:
Cosine similarity measures directional alignment between two weight vectors, where 1.0 is the same direction and 0.0 is orthogonal. L2 distance gives the total magnitude of change, max absolute difference isolates the single weight that moved the most, and mean absolute difference averages the change across every element.
Tensors that exist in only one model, or whose shapes don’t match, are reported separately. The comparison streams one tensor at a time, just like the merge pipeline.
Benchmarks
We benchmarked alloy against mergekit on real models, using an Azure Standard_E48s_v5 with 48 cores and 384 GB of RAM. Timings come from hyperfine, using three runs after a warmup.
| METHOD | ALLOY | MERGEKIT | PERFORMANCE |
|---|---|---|---|
| linear | 7.3 s | 15.4 s | 2.1x faster |
| slerp | 9.5 s | 12.9 s | 1.4x faster |
| ties | 23.3 s | 13.1 s | 1.8x slower |
| dare_ties | 38.0 s | 15.3 s | 2.5x slower |
| METHOD | ALLOY | MERGEKIT | PERFORMANCE |
|---|---|---|---|
| linear | 14.1 s | 25.8 s | 1.8x faster |
| slerp | 18.5 s | 22.1 s | 1.2x faster |
| ties | 44.9 s | 21.9 s | 2.0x slower |
| dare_ties | 75.7 s | 27.3 s | 2.8x slower |
alloy uses fused SIMD kernels (AVX2 on x86_64, NEON on aarch64) that read BF16 values directly from memory-mapped safetensors files and compute in F32 registers. This removes the intermediate F32 allocation that a naive pipeline needs when it converts BF16 to F32 and back again. For IO-bound methods such as linear and slerp, this makes alloy consistently faster than mergekit at all model scales. For compute-heavy methods such as ties and dare_ties, mergekit’s PyTorch C tensor kernels remain faster per element.
Memory Usage
We also measured peak memory (RSS) for linear and SLERP merges of the 1.24B synthetic models, on an Apple M2 Max with 34 GB of memory:
| METHOD | ALLOY | MERGEKIT | REDUCTION |
|---|---|---|---|
| linear | 3.9 GB | 6.5 GB | 40% less |
| slerp | 5.2 GB | 7.7 GB | 33% less |
Because alloy streams one tensor at a time through mmap, the OS can evict pages that are no longer in use. That keeps peak RSS well below mergekit’s, which holds several tensors in memory at once during its DAG-based execution.
Where alloy Wins (at This Scale)
At this scale, linear and SLERP are IO-bound, since the merge math is trivial next to reading data off disk. Our mmap reader avoids Python startup, PyTorch initialization, and mergekit’s repeated cycles of opening and closing files. For small models that overhead is a large share of the total runtime, so removing it gives a real speedup.
Limitations
Optimized for small and medium models
alloy’s speed advantage comes from removing Python and PyTorch startup and IO overhead. For models of around 1 to 2B parameters, that overhead is a large share of the total runtime. For larger models, compute dominates, and the advantage moves to PyTorch’s optimized C++ kernels.
Compute-heavy methods are slower at all scales
TIES and DARE involve per-element magnitude sorting, random mask generation, and conditional accumulation. PyTorch runs these through vectorized C++ kernels. Our inner loops are parallelized with rayon but don’t use explicit SIMD intrinsics.
mmap behavior varies by environment
Our streaming design keeps peak RSS low on memory-constrained machines. On servers with a lot of RAM, though, the kernel may keep mmap pages resident for longer than necessary after they have been read.
No GGUF support
Both alloy and mergekit operate on safetensors files. Neither can merge GGUF-quantized models directly, so models already quantized for llama.cpp or ollama have to be converted back first.
No evaluation loop
Neither tool tells you whether a merge actually improved the model. You merge first and then run evals by hand. Pipelines that merge, evaluate, and iterate automatically are still an open problem for both.
No GPU acceleration
All merging happens on the CPU. For IO-bound methods that is fine, but compute-heavy algorithms could benefit from offloading. Neither alloy nor mergekit uses the GPU for the merge itself.
Future Work
Hand-written SIMD kernels
This is the single biggest performance gap. PyTorch’s ATen library uses hand-tuned AVX2 and AVX-512 kernels for element-wise operations, while our inner loops rely on LLVM’s auto-vectorization. Writing explicit SIMD with
std::archfor the hot paths, which are weighted accumulation, magnitude partitioning, and masked conditional accumulation, is the most impactful thing we can do.Buffered IO for large models
Above a certain size threshold, switching from mmap to explicit
pread()with a reusable buffer would give more control over memory on high-RAM servers without hurting performance on small models.Scaling to larger models
With SIMD kernels and buffered IO, alloy should scale competitively to larger models. The streaming architecture is sound, and the remaining work is in low-level compute optimization.
GGUF format support
Local inference engines such as llama.cpp and ollama use GGUF rather than safetensors. Reading and writing GGUF would let us merge quantized models directly.
GPU acceleration
For compute-bound methods, offloading merge kernels to a GPU with wgpu or CUDA could pair our streaming IO with hardware-accelerated math.
References
mergekit by Charles Goddard, Shamane Siriwardhana, Malikeh Ehghaghi, Luke Meyers, Vladimir Karpukhin, Brian Benedict, Mark McQuade, Jacob Solawetz. mergekit: Tools for Merging Pretrained Language Models. 2024. The tool that started the model merging ecosystem.
Task Arithmetic by Gabriel Ilharco, Marco Tulio Ribeiro, Mitchell Wortsman, Suchin Gururangan, Ludwig Schmidt, Hannaneh Hajishirzi, Ali Farhadi. Editing Models with Task Arithmetic. ICLR 2023.
TIES by Prateek Yadav, Derek Tam, Leshem Choshen, Colin Raffel, Mohit Bansal. TIES-Merging: Resolving Interference When Merging Models. NeurIPS 2023.
DARE by Le Yu, Bowen Yu, Haiyang Yu, Fei Huang, Yongbin Li. Language Models are Super Mario: Absorbing Abilities from Homologous Models as a Free Lunch. ICML 2024.
DELLA by Pala Tej Deep, Nikhil Prakash, Atharva Parikh, Mohit Bansal. DELLA-Merging: Reducing Interference in Model Merging through Magnitude-Based Sampling. 2024.
SLERP for neural networks was first applied to model merging by the open-source community. The technique itself comes from Ken Shoemake’s 1985 SIGGRAPH paper on quaternion interpolation.
alloy is open source under the MIT license. GitHub