|
| 1 | +# Copyright 2025 Bytedance Ltd. and/or its affiliates |
| 2 | + |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +""" |
| 15 | +Merge individual MoE expert weights into stacked tensors for efficient loading. |
| 16 | +
|
| 17 | +This script takes a HuggingFace checkpoint with individual expert weights |
| 18 | +(e.g., model.layers.{i}.mlp.experts.{j}.gate_proj.weight) and merges them |
| 19 | +into stacked tensors (e.g., model.layers.{i}.mlp.experts.gate_proj) for |
| 20 | +faster loading and better memory efficiency in VeOmni. |
| 21 | +
|
| 22 | +The merging process: |
| 23 | +1. Loads individual expert weights from the HF checkpoint |
| 24 | +2. Stacks them into single tensors for each projection type |
| 25 | +3. Handles all three projection types: gate_proj, up_proj, down_proj |
| 26 | +4. Supports both Qwen3-MoE (num_experts) and DeepSeek (n_routed_experts) formats |
| 27 | +5. Handles models with initial dense layers (first_k_dense_replace) |
| 28 | +
|
| 29 | +Usage: python moe_merge.py --raw_hf_path <input_checkpoint> --merge_hf_path <output_dir> |
| 30 | +""" |
| 31 | + |
| 32 | +import os |
| 33 | +from argparse import ArgumentParser |
| 34 | +from dataclasses import dataclass |
| 35 | +from glob import glob |
| 36 | +from typing import Generator |
| 37 | + |
| 38 | +import torch |
| 39 | +from safetensors.torch import safe_open |
| 40 | +from tqdm import tqdm |
| 41 | +from transformers import AutoConfig |
| 42 | +from veomni.models import build_tokenizer, save_model_weights |
| 43 | + |
| 44 | + |
| 45 | +@dataclass |
| 46 | +class StateDictIterator: |
| 47 | + filepath: str |
| 48 | + |
| 49 | + def __iter__(self) -> Generator[tuple[str, "torch.Tensor"], None, None]: |
| 50 | + if self.filepath.endswith(".safetensors"): |
| 51 | + with safe_open(self.filepath, framework="pt", device="cpu") as f: |
| 52 | + for key in f.keys(): |
| 53 | + yield key, f.get_tensor(key) |
| 54 | + |
| 55 | + else: |
| 56 | + state_dict = torch.load(self.filepath, map_location="cpu", weights_only=True, mmap=True) |
| 57 | + for key in state_dict.keys(): |
| 58 | + yield key, state_dict[key] |
| 59 | + |
| 60 | + |
| 61 | +def main(raw_hf_path, merge_hf_path): |
| 62 | + torch.set_default_dtype(torch.bfloat16) |
| 63 | + os.makedirs(merge_hf_path, exist_ok=True) |
| 64 | + |
| 65 | + config = AutoConfig.from_pretrained(raw_hf_path) |
| 66 | + tokenizer = build_tokenizer(raw_hf_path) |
| 67 | + |
| 68 | + safetensor_files = list(glob(os.path.join(raw_hf_path, "*.safetensors"))) |
| 69 | + safetensor_files.sort() |
| 70 | + state_dict_iterators = [StateDictIterator(shard_file) for shard_file in safetensor_files] |
| 71 | + new_state_dict = {} |
| 72 | + for state_dict_iterator in tqdm(state_dict_iterators, desc="Loading checkpoint shards"): |
| 73 | + for name, tensor in state_dict_iterator: |
| 74 | + new_state_dict[name] = tensor.cpu() |
| 75 | + |
| 76 | + print(new_state_dict.keys()) |
| 77 | + |
| 78 | + if hasattr(config, "num_experts"): |
| 79 | + # qwen3moe |
| 80 | + num_experts = config.num_experts |
| 81 | + elif hasattr(config, "n_routed_experts"): |
| 82 | + # deepseek |
| 83 | + num_experts = config.n_routed_experts |
| 84 | + else: |
| 85 | + raise RuntimeError("could not find how many experts to assign") |
| 86 | + num_hidden_layers = config.num_hidden_layers |
| 87 | + |
| 88 | + if hasattr(config, "first_k_dense_replace"): |
| 89 | + # deepseek first k dense layer |
| 90 | + moe_layer_start_idx = config.first_k_dense_replace |
| 91 | + else: |
| 92 | + # moe layer only in the model |
| 93 | + moe_layer_start_idx = 0 |
| 94 | + |
| 95 | + for i in range(moe_layer_start_idx, num_hidden_layers): |
| 96 | + gate_proj = [] |
| 97 | + for j in range(num_experts): |
| 98 | + gate_proj.append(new_state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight")) |
| 99 | + |
| 100 | + new_state_dict[f"model.layers.{i}.mlp.experts.gate_proj"] = torch.stack(gate_proj) |
| 101 | + up_proj = [] |
| 102 | + for j in range(num_experts): |
| 103 | + up_proj.append(new_state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.up_proj.weight")) |
| 104 | + |
| 105 | + new_state_dict[f"model.layers.{i}.mlp.experts.up_proj"] = torch.stack(up_proj) |
| 106 | + down_proj = [] |
| 107 | + for j in range(num_experts): |
| 108 | + down_proj.append(new_state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.down_proj.weight")) |
| 109 | + |
| 110 | + new_state_dict[f"model.layers.{i}.mlp.experts.down_proj"] = torch.stack(down_proj) |
| 111 | + |
| 112 | + model_assets = [config, tokenizer] |
| 113 | + save_model_weights(merge_hf_path, new_state_dict, model_assets=model_assets) |
| 114 | + |
| 115 | + |
| 116 | +if __name__ == "__main__": |
| 117 | + parser = ArgumentParser() |
| 118 | + parser.add_argument("--raw_hf_path", type=str, required=True) |
| 119 | + parser.add_argument("--merge_hf_path", type=str, required=True) |
| 120 | + args = parser.parse_args() |
| 121 | + main(args.raw_hf_path, args.merge_hf_path) |
0 commit comments