> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/xun-lian/mergekit.md).

# Mergekit 模型合并

**Mergekit** 是用于合并预训练大语言模型的权威工具包。它在 GitHub 上拥有 5K+ 星标，实现了所有主要的模型合并算法——SLERP、TIES、DARE、DARE-TIES、MoE 合并等——让你无需任何训练数据或 GPU 训练时间即可创建强大的新模型。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

***

## 什么是 Mergekit？

模型合并是一种强大的技术，可将多个 LLM 的优势整合到单一模型中：

* **无需训练** ——合并在权重空间中进行，而非通过反向传播
* **组合能力** ——将编码模型与指令遵循模型融合
* **减少弱点** ——通过集成平均掉各个模型的失败情况
* **创建专家混合模型** ——将模型组合为稀疏 MoE 架构
* **领域适配** ——将基础模型与领域专用模型合并

Mergekit 实现了所有最先进的算法：

| 算法            | 描述             | 最适合           |
| ------------- | -------------- | ------------- |
| **SLERP**     | 两个模型之间的球面线性插值  | 平滑融合两个相似模型    |
| **TIES**      | 修剪冗余参数、选择符号并合并 | 以最小干扰组合多个模型   |
| **DARE**      | 随机丢弃并重缩放参数     | 减少大规模合并中的参数干扰 |
| **DARE-TIES** | DARE + TIES 结合 | 多模型合并的最佳全能方案  |
| **线性**        | 简单加权平均         | 快速基准合并        |
| **任务算术**      | 添加/减去任务向量      | 添加/移除特定能力     |
| **直通**        | 直接复制层          | MoE 构建        |

{% hint style="info" %}
模型合并的效果出人意料地好。合并后的模型通常会通过结合互补知识，在基准测试中超越其父模型。HuggingFace 上的 MergeKit 社区托管了数千个合并模型。
{% endhint %}

***

## 服务器要求

| 组件     | 最低              | 推荐                   |
| ------ | --------------- | -------------------- |
| GPU    | 不需要（可使用 CPU 合并） | 大型模型需要 A100 40 GB    |
| 显存     | —               | 70B 模型合并需要 80 GB     |
| 内存     | 32 GB           | 64 GB+（模型会加载到 RAM 中） |
| CPU    | 8 核             | 16 核以上               |
| 存储     | 100 GB          | 500 GB+              |
| 操作系统   | Ubuntu 20.04+   | Ubuntu 22.04         |
| Python | 3.10+           | 3.11                 |

{% hint style="warning" %}
对于纯 CPU 合并（最常见的模式），RAM 是瓶颈。以 bf16 合并两个 7B 模型至少需要约 28 GB RAM。使用 `--lazy-unpickle` 以降低内存占用。
{% endhint %}

***

## 端口

| 端口 | 服务  | 备注        |
| -- | --- | --------- |
| 22 | SSH | 终端访问和文件传输 |

Mergekit 作为命令行工具运行——无需 Web 服务器。

***

## 在 Clore.ai 上安装

### 第 1 步——租用服务器

1. 前往 [Clore.ai 市场](https://clore.ai/marketplace)
2. 筛选条件： **RAM ≥ 64 GB** （对大型模型合并至关重要）
3. 选择 **存储空间 ≥ 500 GB** （合并模型需要容纳 2–4 个输入模型加输出模型的空间）
4. GPU 是可选的，但如果你想在之后测试合并模型，它会很有用
5. 开放端口 **22** 即可

### 第 2 步 — 通过 SSH 连接

```bash
ssh root@<server-ip> -p <ssh-port>
```

### 第 3 步——安装 Python 环境

```bash
# 安装 Python 3.11
apt-get update
apt-get install -y python3.11 python3.11-venv python3.11-pip git

# 创建虚拟环境
python3.11 -m venv /opt/mergekit
source /opt/mergekit/bin/activate
```

### 第 4 步——安装 Mergekit

```bash
# 从 PyPI 安装
pip install mergekit

# 或从源代码安装（推荐以获取最新功能）
git clone https://github.com/arcee-ai/mergekit.git
cd mergekit
pip install -e '.[everything]'
```

### 第 5 步——安装 HuggingFace CLI

```bash
pip install huggingface_hub
huggingface-cli login  # 输入你的 HF 令牌
```

### 第 6 步——验证安装

```bash
mergekit --help
mergekit-yaml --help
```

***

## 下载要合并的模型

```bash
# 下载你想要合并的模型
# 使用 huggingface_hub

python3 << 'EOF'
from huggingface_hub import snapshot_download

# 下载模型 1
snapshot_download(
    repo_id="mistralai/Mistral-7B-Instruct-v0.3",
    local_dir="models/Mistral-7B-Instruct-v0.3"
)

# 下载模型 2
snapshot_download(
    repo_id="meta-llama/Llama-3.2-8B-Instruct",
    local_dir="models/Llama-3.2-8B-Instruct",
    token="hf_your-token"  # 受限模型需要此项
)
EOF

# 或使用 huggingface_hub CLI
huggingface-cli download mistralai/Mistral-7B-Instruct-v0.3 \
  --local-dir models/Mistral-7B-Instruct-v0.3
```

***

## 合并配置

Mergekit 使用 YAML 配置文件定义合并。

### 示例 1：SLERP 合并（两个模型）

SLERP 沿球面弧线融合两个模型——最适合同一架构的模型：

```yaml
# slerp_merge.yaml
models:
  - model: models/Mistral-7B-Instruct-v0.3
  - model: models/OpenHermes-2.5-Mistral-7B

merge_method: slerp
base_model: models/Mistral-7B-Instruct-v0.3

slices:
  - sources:
    - model: models/Mistral-7B-Instruct-v0.3
      layer_range: [0, 32]
    - model: models/OpenHermes-2.5-Mistral-7B
      layer_range: [0, 32]

parameters:
  t:
    - filter: self_attn
      value: 0.5  # 注意力层采用 50/50 融合
    - filter: mlp
      value: 0.3  # MLP 层有 30% 来自模型 2
    - value: 0.5  # 其他所有内容的默认值

dtype: bfloat16
```

```bash
mergekit-yaml slerp_merge.yaml merged-model/ --lazy-unpickle
```

### 示例 2：TIES 合并（多个模型）

TIES 可处理多个合并模型之间的干扰：

```yaml
# ties_merge.yaml
models:
  - model: models/Mistral-7B-v0.3
    parameters:
      weight: 1.0    # 基础模型，完整权重
      density: 1.0

  - model: models/Mistral-7B-coding
    parameters:
      weight: 0.7    # 编码能力
      density: 0.5   # 保留 50% 的已更改参数

  - model: models/Mistral-7B-math
    parameters:
      weight: 0.5    # 数学能力
      density: 0.3   # 保留 30% 的已更改参数

merge_method: ties
base_model: models/Mistral-7B-v0.3

parameters:
  normalize: true
  int8_mask: true

dtype: bfloat16
```

```bash
mergekit-yaml ties_merge.yaml merged-ties/ --lazy-unpickle
```

### 示例 3：DARE-TIES 合并（最佳全能方案）

```yaml
# dare_ties_merge.yaml
models:
  - model: models/Llama-3.2-8B-Instruct
    parameters:
      weight: 1.0
      density: 0.7
      dare_linear: true

  - model: models/Llama-3.2-8B-code
    parameters:
      weight: 0.8
      density: 0.5
      dare_linear: true

  - model: models/Llama-3.2-8B-math
    parameters:
      weight: 0.6
      density: 0.4
      dare_linear: true

merge_method: dare_ties
base_model: models/Llama-3.2-8B-Instruct

parameters:
  normalize: true
  dare_density: 0.5
  dare_epsilon: 0.08

dtype: bfloat16
```

```bash
mergekit-yaml dare_ties_merge.yaml merged-dare-ties/ --lazy-unpickle
```

### 示例 4：任务算术（添加能力）

向基础模型添加“技能增量”：

```yaml
# task_arithmetic.yaml
# 将数学调优模型中的数学技能添加到通用基础模型
models:
  - model: models/Llama-3.2-8B-Instruct
    parameters:
      weight: 1.0
  
  - model: models/Llama-3.2-8B-math
    parameters:
      weight: 0.7   # 正值 = 添加此能力
  
  # 要移除一项能力，请使用负权重：
  # - model: models/Llama-3.2-8B-harmful
  #   parameters:
  #     weight: -0.5

merge_method: task_arithmetic
base_model: models/Llama-3.2-8B-Instruct

dtype: bfloat16
```

### 示例 5：MoE（专家混合）

将模型组合为稀疏 MoE 架构：

```yaml
# moe_merge.yaml
base_model: models/Llama-3.2-8B-Instruct

gate_mode: hidden  # 使用隐藏状态将请求路由到专家
dtype: bfloat16
experts:
  - source_model: models/Llama-3.2-8B-coding
    positive_prompts:
      - "编写代码"
      - "调试此函数"
      - "实现一个算法"
    negative_prompts:
      - "给我讲个故事"
      - "解释历史"
  
  - source_model: models/Llama-3.2-8B-creative
    positive_prompts:
      - "写一个故事"
      - "发挥创意"
      - "想象"
    negative_prompts:
      - "编写代码"
      - "计算"
```

```bash
mergekit-moe moe_merge.yaml merged-moe/ --lazy-unpickle
```

***

## 运行合并

### 基本命令

```bash
# 激活环境
source /opt/mergekit/bin/activate

# 使用延迟反序列化运行合并（节省 RAM）
mergekit-yaml your_config.yaml output_model/ --lazy-unpickle

# 使用 CUDA 加速（如果 GPU 可用）
mergekit-yaml your_config.yaml output_model/ \
  --lazy-unpickle \
  --cuda \
  --copy-tokenizer

# 低内存模式（更慢，但可在较小的服务器上运行）
mergekit-yaml your_config.yaml output_model/ \
  --lazy-unpickle \
  --low-cpu-memory
```

### 监控进度

```bash
# Mergekit 显示每一层的进度
# 典型输出：
# 正在加载模型 1...
# 正在加载模型 2...
# 正在合并第 0/32 层：embed_tokens
# 正在合并第 1/32 层：layers.0.self_attn
# ...
# 正在保存合并后的模型...
# 完成！已保存至 output_model/
```

***

## 测试合并后的模型

```bash
# 使用 transformers 快速测试
python3 << 'EOF'
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

model_path = "output_model"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    torch_dtype=torch.bfloat16,
    device_map="auto"
)

prompt = "解释 LoRA 与全量微调之间的区别："
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model.generate(**inputs, max_new_tokens=200, temperature=0.7)

print(tokenizer.decode(outputs[0], skip_special_tokens=True))
EOF
```

***

## 发布到 HuggingFace

```bash
# 登录
huggingface-cli login

# 创建并推送仓库
python3 << 'EOF'
from huggingface_hub import HfApi
api = HfApi()

# 创建仓库
api.create_repo("my-merged-model-7b", private=False)

# 上传合并后的模型
api.upload_folder(
    folder_path="output_model/",
    repo_id="your-username/my-merged-model-7b",
    repo_type="model"
)
print("已上传！")
EOF
```

***

## 高级：进化合并

使用 Mergekit 的进化优化器寻找最佳合并权重：

```bash
# 安装进化优化器
pip install 'mergekit[evo]'

# 运行进化搜索
mergekit-evolve evolve_config.yaml \
  --storage-path ./evolve-workspace \
  --n-iterations 100 \
  --task mmlu  # 针对 MMLU 基准进行优化
```

***

## 故障排查

### 合并期间内存不足（OOM）

```bash
# 对大型模型始终使用 --lazy-unpickle
mergekit-yaml config.yaml out/ --lazy-unpickle

# 添加 --low-cpu-memory 标志
mergekit-yaml config.yaml out/ --lazy-unpickle --low-cpu-memory

# 合并前检查可用 RAM
free -h

# 对于 7B 模型，至少需要约 30 GB RAM
# 对于 13B 模型：约 60 GB RAM
# 对于 70B 模型：约 280 GB RAM（或使用高 RAM CPU 服务器）
```

### `ValueError：模型不兼容`

```bash
# 模型必须具有相同的架构
# 不能直接合并 Llama-3 与 Mistral
# 检查模型配置
python3 -c "
import json
for path in ['models/model1/config.json', 'models/model2/config.json']:
    with open(path) as f:
        cfg = json.load(f)
    print(path, ':', cfg.get('model_type'), cfg.get('hidden_size'), cfg.get('num_hidden_layers'))
"
```

### 合并速度非常慢

```bash
# 使用 GPU 加速张量操作
mergekit-yaml config.yaml out/ --lazy-unpickle --cuda

# 确保已安装支持 CUDA 的 PyTorch
python3 -c "import torch; print(torch.cuda.is_available())"

# 如果 CUDA 不可用，请安装它：
pip install torch --index-url https://download.pytorch.org/whl/cu128
```

### 合并后的模型输出乱码

```bash
# 常见原因：
# 1. 合并了不兼容的模型家族（例如，Llama + Mistral）
# 2. 权重过于极端（SLERP 中使用 t=0 或 t=1，而非 0.3–0.7）
# 3. TIES 中的密度过高（尝试 density: 0.3–0.5）

# 诊断：先测试每个父模型
# 然后尝试以 50/50 SLERP 合并作为基准

# 检查合并后的模型配置
cat output_model/config.json | python3 -m json.tool
```

### `FileNotFoundError` 针对模型文件

```bash
# 列出已下载的内容
ls -la models/your-model/

# 必需文件：
# config.json、tokenizer.json、*.safetensors（或 *.bin）

# 使用强制选项重新下载
huggingface-cli download <repo_id> --local-dir models/<name> --force-download
```

***

## 热门合并配方

### 通用助手 + 编码

```yaml
# 非常适合同时需要通用能力的开发者
models:
  - model: mistralai/Mistral-7B-Instruct-v0.3
    parameters: {weight: 1.0, density: 0.7}
  - model: mistralai/Codestral-7B  
    parameters: {weight: 0.8, density: 0.5}

merge_method: dare_ties
base_model: mistralai/Mistral-7B-Instruct-v0.3
dtype: bfloat16
```

### 多语言增强

```yaml
# 为英文模型添加多语言能力
models:
  - model: meta-llama/Llama-3.2-8B-Instruct
    parameters: {weight: 1.0, density: 0.8}
  - model: utter-project/EuroLLM-9B-Instruct
    parameters: {weight: 0.6, density: 0.4}

merge_method: ties
base_model: meta-llama/Llama-3.2-8B-Instruct
dtype: bfloat16
```

***

## 有用链接

* **GitHub**: <https://github.com/arcee-ai/mergekit> ⭐ 5K+
* **文档**: <https://github.com/arcee-ai/mergekit/wiki>
* **HuggingFace 上的 MergeKit 模型**: <https://huggingface.co/models?other=mergekit>
* **Arcee.ai Discord**: <https://discord.gg/arcee>
* **TIES 论文**: <https://arxiv.org/abs/2306.01708>
* **DARE 论文**: <https://arxiv.org/abs/2311.03099>
* **Clore.ai 市场**: <https://clore.ai/marketplace>

***

## Clore.ai GPU 推荐

{% hint style="warning" %}
**Clore.ai 市场上未列出多 GPU 的 80GB 级机型。** 目前列出的最大配置是 4× RTX PRO 6000 Blackwell（每张 96GB，共 380GB）以及 8–11× RTX 5090（每张 32GB）。A100 / H200 / B200 容量可按 [裸机](https://clore.ai/bare-metal) 需求提供。部署前请查看 [GPU 价格与可用性](/guides/guides_v2-zh/ru-men-zhi-nan/pricing.md) 。
{% endhint %}

| 使用场景         | 推荐 GPU         | Clore.ai 预计成本                     |
| ------------ | -------------- | --------------------------------- |
| 开发/测试        | RTX 3090（24GB） | $0.07–0.21/gpu/hr                 |
| 模型合并（7B–13B） | RTX 4090（24GB） | $0.14–0.42/gpu/hr                 |
| 大模型（70B+）    | A100 80GB      | [裸机](https://clore.ai/bare-metal) |
| 多 GPU 合并     | 2–4× A100 80GB | [裸机](https://clore.ai/bare-metal) |

> 💡 本指南中的所有示例都可以部署在 [Clore.ai](https://clore.ai/marketplace) GPU 服务器上。浏览可用 GPU 并按小时租用——无需承诺，拥有完整 root 访问权限。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/xun-lian/mergekit.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
