Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
M

mergekit

> AI 编程
Open source

Tools for merging pretrained large language models.

7.3K stars0 likes2 views
WebsiteGitHub

About

Tools for merging pretrained large language models.

mergekit

mergekit is a toolkit for merging pre-trained language models. mergekit uses an out-of-core approach to perform unreasonably elaborate merges in resource-constrained situations. Merges can be run entirely on CPU or accelerated with as little as 8 GB of VRAM. Many merging algorithms are supported, with more coming as they catch my attention.

Contents

  • Why Merge Models?
  • Features
  • Installation
  • Community & Support
    • Contributing
    • Community Tools
  • Usage
  • Merge Configuration
    • Parameter Specification
    • Tokenizer Configuration
    • Chat Template Configuration
    • Examples
  • Merge Methods
  • LoRA Extraction
  • Mixture of Experts Merging
  • Evolutionary Merge Methods
  • Multi-Stage Merging (mergekit-multi)
  • Raw PyTorch Model Merging (mergekit-pytorch)
  • Tokenizer Transplantation (mergekit-tokensurgeon)
  • Citation

Why Merge Models?

Model merging is a powerful technique that allows combining the strengths of different models without the computational overhead of ensembling or the need for additional training. By operating directly in the weight space of models, merging can:

  • Combine multiple specialized models into a single versatile model
  • Transfer capabilities between models without access to training data
  • Find optimal trade-offs between different model behaviors
  • Improve performance while maintaining inference costs
  • Create new capabilities through creative model combinations

Unlike traditional ensembling which requires running multiple models, merged models maintain the same inference cost as a single model while often achieving comparable or superior performance.

Features

Key features of mergekit include:

  • Supports Llama, Mistral, GPT-NeoX, StableLM, and more
  • Many merge methods
  • GPU or CPU execution
  • Lazy loading of tensors for low memory use
  • Interpolated gradients for parameter values (inspired by Gryphe's BlockMerge_Gradient script)
  • Piecewise assembly of language models from layers ("Frankenmerging")
  • Mixture of Experts merging
  • LORA extraction
  • Evolutionary merge methods
  • Multi-stage merging for complex workflows.
  • Merging of raw PyTorch models (mergekit-pytorch).

Installation

bash
git clone https://github.com/arcee-ai/mergekit.git
cd mergekit

pip install -e .  # install the package and make scripts available

If the above fails with the error of:

ERROR: File "setup.py" or "setup.cfg" not found. Directory cannot be installed in editable mode:
(A "pyproject.toml" file was found, but editable mode currently requires a setuptools-based build.)

You may need to upgrade pip to > 21.3 with the command python3 -m pip install --upgrade pip.

Community & Support

  • Issues: GitHub Issues
  • Discussions: Arcee Discord

Contributing

We welcome contributions to mergekit! If you have ideas for new merge methods, features, or other improvements, please check out our contributing guide for details on how to get started.

Community Tools

  • FrankensteinAI: For those who prefer a browser-based experience without local setup or hardware wrangling, the team at FrankensteinAI has built a hosted platform powered by mergekit. Also features a community gallery and leaderboard for sharing and comparing merged models.

Usage

The script mergekit-yaml is the main entry point for mergekit. It takes a YAML configuration file and an output path, like so:

bash
mergekit-yaml path/to/your/config.yml ./output-model-directory [--cuda] [--lazy-unpickle] [--allow-crimes] [... other options]

This will run the merge and write your merged model to ./output-model-directory.

For more information on the arguments accepted by mergekit-yaml run the command mergekit-yaml --help.

In-memory Python API

Use merge_tensors for one output tensor, or merge_state_dicts for modules and state dictionaries already in memory:

python
from mergekit.merge_methods import merge_state_dicts, merge_tensors

merged_tensor = merge_tensors(
    [tensor_a, tensor_b], "linear", parameters={"weight": [0.25, 0.75]}
)
merged_weights = merge_state_dicts(
    [model_a, model_b], "linear", parameters={"weight": [0.25, 0.75]}
)

Both accept a method name or a method object, plus dtype and out_dtype. For base-aware methods, use base_index with merge_tensors or base with merge_state_dicts. See Defining Merge Methods for custom methods and batching.

Uploading to Huggingface

When you have a merged model you're happy with, you may want to share it on the Hugging Face Hub. mergekit generates a README.md for your merge with some basic information for a model card. You can edit it to include more details about your merge, like giving it a good name or explaining what it's good at; rewrite it entirely; or use the generated README.md as-is. It is also possible to edit your README.md online once it has been uploaded to the Hub.

Once you're happy with your model card and merged model, you can upload it to the Hugging Face Hub using the huggingface_hub Python library.

bash
# log in to huggingface with an access token (must have write permission)
huggingface-cli login
# upload your model
huggingface-cli upload your_hf_username/my-cool-model ./output-model-directory .

The documentation for huggingface_hub goes into more detail about other options for uploading.

Merge Configuration

Merge configurations are YAML documents specifying the operations to perform in order to produce your merged model. Below are the primary elements of a configuration file:

  • merge_method: Specifies the method to use for merging models. See Merge Methods for a list.
  • slices: Defines slices of layers from different models to be used. This field is mutually exclusive with models.
  • models: Defines entire models to be used for merging. This field is mutually exclusive with slices.
  • base_model: Specifies the base model used in some merging methods.
  • parameters: Holds various parameters such as weights and densities, which can also be specified at different levels of the configuration.
  • dtype: Casts inputs to this dtype before merging, including downcasting when requested. If omitted, corresponding weights are promoted to a common dtype independently: matching bfloat16 weights stay bfloat16, while bfloat16 with float16 or float32 promotes to float32. Float64 inputs retain float64 precision.
  • out_dtype: Casts merged weights after computation; it does not change input precision. If omitted, the method's output dtype is retained.
  • tokenizer or tokenizer_source: Determines how to construct a tokenizer for the merged model.
  • chat_template: Specifies a chat template for the merged model.

Methods control their intermediate precision independently of PyTorch autocast. Linear and SLERP compute in float32 for float16, bfloat16, and float32 inputs, and float64 for float64 inputs, then cast back to the aligned input dtype. Normalized linear merges require weights with a nonzero sum in the working precision; a zero sum produces NaN or infinity through tensor division. Nearly cancelling weights can lose accuracy. Architecture-specific forced dtypes take precedence over dtype and out_dtype for those weights.

Parameter Specification

Parameters are flexible and can be set with varying precedence. They can be specified conditionally using tensor name filters, which allows finer control such as differentiating between attention heads and fully connected layers.

Parameters can be specified as:

  • Scalars: Numbers, booleans, or strings, according to the merge parameter's type.
  • Gradients: Lists of values. Numeric endpoints are validated and interpolated; booleans and strings select discrete steps. Scientific notation such as [1e-5, 1e-3] is supported for numeric parameters.

The parameters can be set at different levels, with decreasing precedence as follows:

  1. slices.*.sources.parameters - applying to a specific input slice
  2. slices.*.parameters - applying to a specific output slice
  3. models.*.parameters or input_model_parameters - applying to any tensors coming from specific input models
  4. parameters - catchall

Tokenizer Configuration

The tokenizer behavior can be configured in two ways: using the new tokenizer field (recommended) or the legacy tokenizer_source field (maintained for backward compatibility). These fields are mutually exclusive - you should use one or the other, not both.

Modern Configuration (tokenizer)

The tokenizer field provides fine-grained control over vocabulary and embeddings:

By default, inputs with different vocabulary sizes must be aligned using this configuration (or tokenizer_source) before merging. Use source: base to retain the base vocabulary, source: union to combine vocabularies, or a model path to select its vocabulary. All non-vocabulary dimensions must match regardless of tokenizer configuration. Alignment applies to every vocabulary-indexed parameter, including output biases. Architecture definitions identify these using vocabulary_axis: a nonnegative axis index (0 for conventional embedding matrices and output biases), or null for tensors not indexed by token IDs. Positional, token-type, and vision embeddings are not vocabulary-indexed.

yaml
tokenizer:
  source: "union"  # or "base" or a specific model path
  tokens:          # Optional: configure specific tokens
    <token_name>:
      source: ...  # Specify embedding source
      force: false # Optional: force this embedding for all models
  pad_to_multiple_of: null  # Optional: pad vocabulary size
Tokenizer Source

The source field determines the vocabulary of the output model:

  • union: Combine vocabularies from all input models (default)
  • base: Use vocabulary from the base model
  • "path/to/model": Use vocabulary from a specific model
Token Embedding Handling

When a tokenizer is configured, each input model's embedding matrix is adjusted to match the output vocabulary before being passed to the merge method. For tokens a model already has, its own embedding is used. For tokens a model is missing, a fallback embedding is assigned using these rules:

  • If the base model has the token, use the base model's embedding
  • If only one model has the token, use that model's embedding
  • Otherwise, use an average of all available embeddings

The merge method then combines these per-model embeddings (original and filled-in) to produce the final output. This means the final embedding for a token present in multiple models is determined by your merge method (SLERP, linear, TIES, etc.), not simply taken from one model.

You can override these defaults for specific tokens. Any tokens listed here that don't already exist in the output vocabulary will be added automatically, making this useful for introducing new special tokens.

yaml
tokenizer:
  source: union
  to

Issues· 272 open

View all issuesOpen on GitHub
  • #711

    Critical bug in arcee.ai: cache anomaly.

    Updated Sep 24, 2026
  • #708

    Cross-architecture merging: proposal — canonicalization as a preprocessing transform

    Updated Sep 21, 2026
  • #707

    Will your Huggingface mergekit-gui space ever work again?

    Updated Sep 13, 2026
  • #669

    Qwen3.5 27B

    Updated Jun 5, 2026
  • #681

    Pydantic error when merging models

    Updated May 26, 2026
  • #494

    how to merge gguf quntizated models?

    Updated May 19, 2026
  • #687

    Why I can't merge Deepseek R1 with Deepseek V3.1?

    Updated May 11, 2026
  • #680

    Feature Request: Support strict parameter filtering (exclude non-matched parameters from merging)

    Updated Apr 6, 2026
  • #676

    Merging multiple different architectures using MergeKit.

    Updated Mar 28, 2026
  • #675

    Documentation Enhancement Suggestion

    Updated Mar 26, 2026

> Tags

Pythonllamallmmodel-merging

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 2, 2026
CategoryAI 编程
PricingOpen source

> Related tools

G
GitHub Copilot
GitHub 官方 AI 编程助手,覆盖补全、Chat 与 Agent 模式。
C
Cursor
AI 原生代码编辑器,对话改代码、多文件 Agent 与规则体系是其核心。
S
skills
Skills for Real Engineers. Straight from my .agents directory.