Agent 配套工具

mergekit|预训练语言模型权重合并工具包

mergekit

mergekit 是一个用于合并预训练语言模型权重的 Python 工具包,通过 YAML 配置在权重空间组合多个模型,无需额外训练。

获取与使用

需要部署

按官方资料自行安装或部署

使用难度待核验
国内可用性待核验

2026-11-09 更新 · 本站尚未实测

项目介绍

Agent 配套工具 · 2026-11-09 更新 · 本站尚未实测

mergekit 是 arcee-ai 维护的模型合并工具包,仓库描述为 “Tools for merging pretrained large language models.”。README 说明其采用 out-of-core 方式,可在资源受限环境中执行较复杂的合并,合并可完全在 CPU 上运行,或用低至 8 GB 显存加速。它面向的是预训练权重层面的组合,而非在线调用模型;用途侧重把多个已微调模型组合成一个多任务模型、在无训练数据情况下迁移能力、寻找行为折中方案等。

需要明确:mergekit 本身不是 Agent 框架、不是 MCP 服务、也不是可直接下载的工作流文件;它是一个本地运行的 Python 命令行工具包/库。

核心能力

点击能力名称查看输入、输出和原文依据。

  • README 列出的支持架构包括 Llama、Mistral、GPT-NeoX、StableLM 等,并称“and more”,具体覆盖范围待核验。
  • 多种合并方法:Linear、SLERP、NuSLERP、Multi-SLERP、Karcher Mean、Task Arithmetic、TIES、DARE、DELLA、Model Breadcrumbs、SCE、Model Stock、Nearswap、Arcee Fusion、Passthrough 等。
  • 张量惰性加载以降低内存占用;支持 GPU 或 CPU 执行。
  • 分层拼装(“Frankenmerging”)、Mixture of Experts 合并、LoRA 提取、进化式合并方法、多阶段合并(mergekit-multi)。
  • 支持对任意 PyTorch 模型(非必须是 Hugging Face Transformers)的 .pt / .safetensors 检查点合并(mergekit-pytorch),但该模式不支持层切片与分词器配置。
  • 分词器移植工具 mergekit-tokensurgeon,可用于为投机解码制作草稿模型等场景。
  • 提供内存内 Python API:merge_tensors 与 merge_state_dicts。

实际应用场景

适用场景

  • 把多个同一基础模型衍生的微调检查点合并,得到一个多能力模型。
  • 在没有原始训练数据时,尝试在模型间迁移或组合能力。
  • 对已有模型做 LoRA 低秩近似提取。
  • 将多个稠密模型合并为 MoE 结构,用于直接使用或后续训练。
  • 需要多步组合的复杂合并流程,用单个 YAML 定义多阶段任务。

以上为 README 描述的能力方向;实际效果、合并后质量与稳定性需自行实验评估,资料未给出基准数据。

安装与接入

README 给出的安装方式为从源码克隆后以可编辑模式安装:

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

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

若出现 setup.py / setup.cfg 相关的 editable 模式报错,README 建议将 pip 升级到 21.3 以上:python3 -m pip install --upgrade pip。

主要入口为 mergekit-yaml,接受 YAML 配置与输出路径,README 示例:

请参阅原仓库 README 的 YAML 配置与命令示例,并用 mergekit-yaml --help 查看参数。

更多参数以 mergekit-yaml --help 为准。另提供 mergekit-extract-lora、mergekit-pytorch 等脚本,示例配置见仓库 examples/ 目录。README 提到可用 huggingface_hub 上传合并结果,需先登录并具备写权限;上传属于可选步骤,是否使用取决于你的账号与权限。

仓库中还提到第三方托管平台 FrankensteinAI 提供基于 mergekit 的浏览器端体验,该平台的服务条款、费用与数据处理方式需向该平台核验,与 mergekit 仓库本身是不同主体。

使用条件与限制

是否需要部署
需自行准备运行环境,具体要求见正文
是否需要注册
账号和认证要求见正文;未明确说明的项目仍待核验
是否需要 API Key
待核验
费用与额度
费用边界见正文,项目许可不代表模型或托管服务免费
所需权限
待核验
许可证与服务条款
待核验

权限费用与限制

  • 本地运行需要自行准备 Python 环境、依赖与模型权重,硬件需求取决于模型规模;README 仅称可纯 CPU 运行或以低至 8 GB 显存加速,实际所需内存/显存待核验。
  • 合并过程本身不调用云端模型 API;README 未说明需要任何模型 API Key。
  • 从 Hugging Face 下载模型与上传结果涉及该平台的账号、令牌与使用条款,需自行核验。
  • 部分参数(如 --allow-crimes、--unsafe-truncate-embeddings)涉及可能破坏输出可用性的操作,README 对这些选项有风险说明,使用前应阅读原文。
  • 合并后模型是否可再分发,取决于各输入模型自身的许可证,README 未逐一说明。

国内使用情况

网友核验 用户经验分享

与站长实测独立,不代表官方认证或本站已实测。

我要核验
0 位参与者0 份有效分项记录

最近核验:暂无有效核验。参与人数按当前项目有效身份去重;不同核验项分别统计,不合并成用户总结果。仅统计审核通过且未过期的记录。

分项统计、有效期与样本量
核验项目有效人数成功 / 部分 / 失败 / 无法判断成功率最近核验 / 有效期
官方网站访问00 / 0 / 0 / 0样本不足暂无 / 7 天
GitHub 仓库访问00 / 0 / 0 / 0样本不足暂无 / 7 天
安装与运行00 / 0 / 0 / 0样本不足暂无 / 30 天
官方服务国内连接 / MCP 连接00 / 0 / 0 / 0样本不足暂无 / 30 天
国内网络情况00 / 0 / 0 / 0样本不足暂无 / 7 天
国内模型兼容性00 / 0 / 0 / 0样本不足暂无 / 30 天
自定义 API00 / 0 / 0 / 0样本不足暂无 / 30 天
海外服务依赖
00 / 0 / 0 / 0样本不足暂无 / 30 天
海外账号要求
00 / 0 / 0 / 0样本不足暂无 / 30 天
中文界面
00 / 0 / 0 / 0样本不足暂无 / 30 天
客户端兼容性00 / 0 / 0 / 0样本不足暂无 / 30 天
账号及费用信息
00 / 0 / 0 / 0样本不足暂无 / 30 天

成功率 = 成功 ÷(成功 + 部分成功 + 失败);无法判断不计入分母。至少 5 份可判断结果才显示成功率。账号、费用、海外依赖与语言等事实项,成功表示核查结论与资料吻合,具体观察另行统计;不表示免费或没有海外依赖。不同网络、客户端和版本的结果不能直接等同。

最近有效核验

暂无审核通过且未过期的网友核验。欢迎提交真实使用记录。

查看全部有效核验 →

国内实测状态:国内可用性待核验。协议兼容和官方资料说明不等于国内网络可用。

官方网站访问
尚未实测 待核验
GitHub 仓库访问
尚未实测 待核验
官方服务国内连接
尚未实测 待核验
国内网络情况
尚未实测 待核验
国内模型兼容性
尚未实测 待核验
自定义 API
尚未实测 待核验
海外服务依赖
尚未实测 待核验
海外账号要求
尚未实测 待核验
中文界面
尚未实测 待核验
国内最后核验时间
尚未实测

许可与国内使用

仓库包含 LICENSE 文件,内容为 GNU Lesser General Public License v3.0(LGPL-3.0),徽章亦标注 LGPL v3。该许可适用于仓库代码;第三方托管平台、Hugging Face 等外部服务,以及被合并的模型权重,各有独立条款,需分别核验。

README 未提供中国大陆网络环境下的可用性、镜像下载或兼容性说明,相关情况待核验。仓库未声明针对特定地区的服务部署安排。

项目资料与来源

官方网站 ↗

GitHub 仓库 ↗

官方文档 ↗

字段依据与待核验事项

access:来源确认 · git clone https://github.com/arcee-ai/mergekit.git

project_type:来源确认 · `mergekit` is a toolkit for merging pre-trained language models.

原始 README(折叠技术参考)
# mergekit

[![License: LGPL v3](https://img.shields.io/badge/License-LGPL_v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0)
[![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/arcee-ai/mergekit/pre-commit.yml?label=Tests)](https://github.com/arcee-ai/mergekit/actions/workflows/pre-commit.yml)
[![Arcee Discord](https://img.shields.io/badge/Arcee%20Discord-Arcee%20Discord?logo=discord&logoColor=white&color=5865F2)](https://discord.gg/arceeai)

`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?](#why-merge-models)
- [Features](#features)
- [Installation](#installation)
- [Community & Support](#community--support)
  - [Contributing](#contributing)
  - [Community Tools](#community-tools)
- [Usage](#usage)
- [Merge Configuration](#merge-configuration)
  - [Parameter Specification](#parameter-specification)
  - [Tokenizer Configuration](#tokenizer-configuration)
  - [Chat Template Configuration](#chat-template-configuration)
  - [Examples](#examples)
- [Merge Methods](#merge-methods)
- [LoRA Extraction](#lora-extraction)
- [Mixture of Experts Merging](#mixture-of-experts-merging)
- [Evolutionary Merge Methods](#evolutionary-merge-methods)
- [Multi-Stage Merging (`mergekit-multi`)](#multi-stage-merging-mergekit-multi)
- [Raw PyTorch Model Merging (`mergekit-pytorch`)](#raw-pytorch-model-merging-mergekit-pytorch)
- [Tokenizer Transplantation (`mergekit-tokensurgeon`)](#tokenizer-transplantation-mergekit-tokensurgeon)
- [Citation](#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](#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](https://github.com/Gryphe/BlockMerge_Gradient) script)
- Piecewise assembly of language models from layers ("Frankenmerging")
- [Mixture of Experts merging](#mixture-of-experts-merging)
- [LORA extraction](#lora-extraction)
- [Evolutionary merge methods](#evolutionary-merge-methods)
- [Multi-stage merging](#multi-stage-merging-mergekit-multi) for complex workflows.
- [Merging of raw PyTorch models (`mergekit-pytorch`)](#raw-pytorch-model-merging-mergekit-pytorch).

## Installation

```sh
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](https://github.com/arcee-ai/mergekit/issues)
- **Discussions**: [Arcee Discord](https://discord.gg/arceeai)

### Contributing

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

### Community Tools

- **[FrankensteinAI](https://frankenstein-ai.com/)**: 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:

```sh
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](docs/create_a_merge_method.md)
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](https://huggingface.co/docs/huggingface_hub/index) Python library.

```sh
# 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](https://huggingface.co/docs/huggingface_hub/guides/cli#huggingface-cli-upload) 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](#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
  tokens:
    # Use embedding from a specific model
    <|im_start|>:
      source: "path/to/chatml/model"

    # Force a specific embedding for all models
    <|special|>:
      source: "path/to/model"
      force: true

    # Map a token to another model's token embedding
    <|renamed_token|>:
      source:
        kind: "model_token"
        model: "path/to/model"
        token: "<|original_token|>"  # or use token_id: 1234

    # Use a zero embedding
    <|unused|>:
      source:
        kind: "zero"
```

##### Practical Example

Here's how you might preserve both Llama 3 Instruct and ChatML prompt formats when merging models:

```yaml
tokenizer:
  source: union
  tokens:
    # ChatML tokens
    <|im_start|>:
      source: "chatml_model"
    <|im_end|>:
      source: "chatml_model"

    # Llama 3 tokens - force original embeddings
    <|start_header_id|>:
      source: "llama3_model"
      force: true
    <|end_header_id|>:
      source: "llama3_model"
      force: true
    <|eot_id|>:
      source: "llama3_model"
      force: true
```

#### Legacy Configuration (tokenizer_source)

For backward compatibility, the `tokenizer_source` field is still supported:

```yaml
tokenizer_source: "union"  # or "base" or a model path
```

This provides basic tokenizer selection but lacks the fine-grained control of the modern `tokenizer` field.

#### Unsafe embedding truncation

`mergekit-yaml config.yml output/ --unsafe-truncate-embeddings` opts into
tokenizer-unaware truncation. It discards trailing slices along each parameter's
`vocabulary_axis` to match the smallest input; all other dimensions must match.
Token IDs are not checked; every retained ID must have the same meaning in every
input. Use tokenizer configuration to align tokens when this is not guaranteed.

- Disabled by default and independent of `--allow-crimes`.
- If `tokenizer` or `tokenizer_source` is configured, tokenizer alignment takes
  precedence and this option has no effect.
- Each truncation logs the tensor name and original and retained shapes.
- Configs and tokenizers are copied without adjusting vocabulary sizes or token
  IDs. They may disagree with the truncated weights, preventing the output from
  loading or generating correctly.

For direct Python callers,
`mergekit.merge_methods.preprocessing.truncate_vocabulary(group)` performs
the same preprocessing on a `TensorGroup` with `vocabulary_axis` set. It returns
borrowed views, preserving input IDs and base designation. Merge methods require
matching tensor shapes.

### Chat Template Configuration

The optional `chat_template` field allows overriding the chat template used for the merged model.

```yaml
chat_template: "auto"  # or a template name or Jinja2 template
```

Options include:

- `"auto"`: Automatically select the most common template among input models
- Built-in templates: `"alpaca"`, `"chatml"`, `"llama3"`, `"mistral"`, `"exaone"`
- A Jinja2 template string for custom formatting

### Examples

Several examples of merge configurations are available in [`examples/`](examples/).

## Merge Methods

`mergekit` offers many methods for merging models, each with its own strengths and weaknesses. Choosing the right method depends on your specific goals, the relationship between the models you're merging, and the desired characteristics of the final model.

For detailed explanations, parameter descriptions, and use cases for each method, please see our [**Merge Method Guide**](docs/merge_methods.md).

### Method Overview

| Method (`value`)                                                                                                      | Core Idea                                                            | # Models | Base Model | Key Strengths / Use Cases                                       |
|:----------------------------------------------------------------------------------------------------------------------|:--------------------------------------------------------------------|:--------:|:----:|:---------------------------------------------------------------|
| [**Linear** (`linear`)](docs/merge_methods.md#linear-linear)                                                          | Simple weighted average of model parameters.                         |    ≥2    |  -   | Averaging similar checkpoints, model soups.                     |
| [**SLERP** (`slerp`)](docs/merge_methods.md#slerp-slerp)                                                              | Spherical linear interpolation between two models.                   |     2    |  ✓   | Smoothly transitioning between two models.                      |
| [**NuSLERP** (`nuslerp`)](docs/merge_methods.md#nuslerp-nuslerp)                                                        | Enhanced SLERP with flexible weighting.                              |     2    |  *   | More intuitive SLERP; task vector SLERP.                        |
| [**Multi-SLERP** (`multislerp`)](docs/merge_methods.md#multi-slerp-multislerp)                                          | Barycentric SLERP for multiple models.                               |    ≥2    |  *   | Spherical interpolation for >2 models.                          |
| [**Karcher Mean** (`karcher`)](docs/merge_methods.md#karcher-mean-karcher)                                              | Riemannian barycenter of model parameters.                           |    ≥2    |  -   | Geometrically sound averaging on manifolds.                     |
| [**Task Arithmetic** (`task_arithmetic`)](docs/merge_methods.md#task-arithmetic-task_arithmetic)                      | Linearly combine "task vectors" (differences from a base).           |    ≥2    |  ✓   | Transferring/combining fine-tuned skills.                       |
| [**TIES** (`ties`)](docs/merge_methods.md#ties-merging-ties)                                                          | Task arithmetic + sparsification & sign consensus.                   |    ≥2    |  ✓   | Merging many models, reducing interference.                     |
| [**DARE** (`dare_linear`, `dare_ties`)](docs/merge_methods.md#dare-dare_linear-dare_ties)                               | Task arithmetic + random pruning & rescaling.                        |    ≥2    |  ✓   | Robust skill retention, similar to TIES.                        |
| [**DELLA** (`della`, `della_linear`)](docs/merge_methods.md#della-della-della_linear)                                   | Task arithmetic + adaptive magnitude-based pruning.                  |    ≥2    |  ✓   | Prioritizing important changes, reducing interference.          |
| [**Model Breadcrumbs** (`breadcrumbs`, `breadcrumbs_ties`)](docs/merge_methods.md#model-breadcrumbs-breadcrumbs_ties)   | Task arithmetic + outlier removal (small & large diffs).             |    ≥2    |  ✓   | Refining task vectors by removing extreme changes.              |
| [**SCE** (`sce`)](docs/merge_methods.md#sce-sce)                                                                      | Task arithmetic + adaptive matrix-level weighting based on variance. |    ≥2    |  ✓   | Dynamically weighting models based on parameter variance.       |
| [**Model Stock** (`model_stock`)](docs/merge_methods.md#model-stock-model_stock)                                        | Geometric weight calculation for linear interpolation.               |    ≥3    |  ✓   | Finding good linear interpolation weights for many checkpoints. |
| [**Nearswap** (`nearswap`)](docs/merge_methods.md#nearswap-nearswap)                                                    | Interpolate where parameters are similar.                            |     2    |  ✓   | Selective merging based on parameter similarity.                |
| [**Arcee Fusion** (`arcee_fusion`)](docs/merge_methods.md#arcee-fusion-arcee_fusion)                                    | Dynamic thresholding for fusing important changes.                   |     2    |  ✓   | Identifying and merging salient features.                       |
| [**Passthrough** (`passthrough`)](docs/merge_methods.md#passthrough-passthrough)                                        | Directly copies tensors from a single input model.                      |     1    |  -   | Frankenmerging, layer stacking, model surgery.                  |

**Key for `Base Model` Column:**

- ✓: **Required** - One of the input models *must* be designated as the `base_model`.
- *: **Optional** - One of the input models *can* be designated as the `base_model`.
- -: **Not Applicable** - `base_model` has no effect on this method.

## LoRA Extraction

Mergekit allows extracting PEFT-compatible low-rank approximations of finetuned models.

### Usage

```sh
mergekit-extract-lora --model finetuned_model_id_or_path --base-model base_model_id_or_path --out-path output_path [--no-lazy-unpickle] [--cuda] [--max-rank=desired_rank] [--sv-epsilon=tol]
```

## Mixture of Experts Merging

The `mergekit-moe` script supports merging multiple dense models into a mixture of experts, either for direct use or for further training. For more details see the [`mergekit-moe` documentation](docs/moe.md).

## Evolutionary Merge Methods

See [`docs/evolve.md`](docs/evolve.md) for details.

## Multi-Stage Merging (`mergekit-multi`)

`mergekit-multi` enables the execution of complex, multi-stage model merging workflows. You can define multiple merge configurations in a single YAML file, where later merges can use the outputs of earlier ones as inputs. This is useful for building up sophisticated models through a series of targeted merges.

See the [`mergekit-multi` documentation](docs/multimerge.md) for usage details and examples.

## Raw PyTorch Model Merging (`mergekit-pytorch`)

For merging arbitrary PyTorch models (not necessarily Hugging Face Transformers), `mergekit-pytorch` provides a way to apply mergekit's algorithms directly to `.pt` or `.safetensors` checkpoints. The configuration is similar to the YAML format used in `mergekit-yaml`, but does not support layer slicing or tokenizer configuration.

### Usage

```sh
mergekit-pytorch path/to/your/raw_config.yml ./output_pytorch_model_directory [options]
```

Use `mergekit-pytorch --help` for detailed options.

## Tokenizer Transplantation (`mergekit-tokensurgeon`)

`mergekit-tokensurgeon` is a specialized tool for transplanting tokenizers between models, allowing you to align the vocabulary of one model with another. This is particularly useful for cheaply producing draft models for speculative decoding or for cross-tokenizer knowledge distillation. See the [documentation](docs/tokensurgeon.md) for more details and how to use it.

Vocabulary-dependent biases and other auxiliary parameters are remapped by exact
token identity; entries for new tokens are initialized to zero. Embedding matrices
use the selected approximation method.

## Citation

If you find `mergekit` useful in your research, please consider citing the [paper](https://aclanthology.org/2024.emnlp-industry.36/):

```bibtex
@inproceedings{goddard-etal-2024-arcees,
    title = "Arcee{'}s {M}erge{K}it: A Toolkit for Merging Large Language Models",
    author = "Goddard, Charles  and
      Siriwardhana, Shamane  and
      Ehghaghi, Malikeh  and
      Meyers, Luke  and
      Karpukhin, Vladimir  and
      Benedict, Brian  and
      McQuade, Mark  and
      Solawetz, Jacob",
    editor = "Dernoncourt, Franck  and
      Preo{\c{t}}iuc-Pietro, Daniel  and
      Shimorina, Anastasia",
    booktitle = "Proceedings of the 2024 Conference on Empirical Methods in Natural Language Processing: Industry Track",
    month = nov,
    year = "2024",
    address = "Miami, Florida, US",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2024.emnlp-industry.36",
    doi = "10.18653/v1/2024.emnlp-industry.36",
    pages = "477--485",
    abstract = "The rapid growth of open-source language models provides the opportunity to merge model checkpoints, combining their parameters to improve performance and versatility. Advances in transfer learning have led to numerous task-specific models, which model merging can integrate into powerful multitask models without additional training. MergeKit is an open-source library designed to support this process with an efficient and extensible framework suitable for any hardware. It has facilitated the merging of thousands of models, contributing to some of the world{'}s most powerful open-source model checkpoints. The library is accessible at: https://github.com/arcee-ai/mergekit.",
}
```
历史前置条件说明(补充参考)

需要 Python 环境与 pip(README 提示 editable 安装需 pip > 21.3);需自行准备待合并的模型权重;GPU 可选,README 称可用低至 8 GB 显存加速;未说明需要任何模型 API Key;可选上传到 Hugging Face 需账号与写权限令牌;境外依赖(GitHub、Hugging Face)的可访问性与具体依赖版本待核验。

项目来源与清单版权许可

https://github.com/arcee-ai/mergekit

整理来源:https://github.com/slavakurilyak/awesome-ai-agents

清单版权与许可:

MIT License

Copyright (c) 2024 Slava Kurilyak

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.