model_merger.py 6.24 KB
Newer Older
chenych's avatar
chenych committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os
import re
from concurrent.futures import ThreadPoolExecutor
from typing import Dict, List, Tuple

import torch
from torch.distributed._tensor import DTensor, Placement, Shard
chenych's avatar
v0.3.0  
chenych committed
23
from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForTokenClassification, AutoModelForVision2Seq
chenych's avatar
chenych committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42


def merge_by_placement(tensors: List[torch.Tensor], placement: Placement):
    if placement.is_replicate():
        return tensors[0]
    elif placement.is_partial():
        raise NotImplementedError("Partial placement is not supported yet")
    elif placement.is_shard():
        return torch.cat(tensors, dim=placement.dim).contiguous()
    else:
        raise ValueError(f"Unsupported placement: {placement}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--local_dir", required=True, type=str, help="The path for your saved model")
    parser.add_argument("--hf_upload_path", default=False, type=str, help="The path of the huggingface repo to upload")
    args = parser.parse_args()

chenych's avatar
v0.3.0  
chenych committed
43
44
    assert not args.local_dir.endswith("huggingface"), "The local_dir should not end with huggingface"
    local_dir = args.local_dir
chenych's avatar
chenych committed
45
46
47
48
49
50
51
52
53

    # copy rank zero to find the shape of (dp, fsdp)
    rank = 0
    world_size = 0
    for filename in os.listdir(local_dir):
        match = re.match(r"model_world_size_(\d+)_rank_0\.pt", filename)
        if match:
            world_size = match.group(1)
            break
chenych's avatar
v0.3.0  
chenych committed
54
    assert world_size, "No model file with the proper format"
chenych's avatar
chenych committed
55

chenych's avatar
v0.3.0  
chenych committed
56
57
58
    state_dict = torch.load(
        os.path.join(local_dir, f"model_world_size_{world_size}_rank_{rank}.pt"), map_location="cpu"
    )
chenych's avatar
chenych committed
59
60
    pivot_key = sorted(state_dict.keys())[0]
    weight = state_dict[pivot_key]
chenych's avatar
v0.3.0  
chenych committed
61
62
63
64
65
    assert isinstance(weight, torch.distributed._tensor.DTensor)
    # get sharding info
    device_mesh = weight.device_mesh
    mesh = device_mesh.mesh
    mesh_dim_names = device_mesh.mesh_dim_names
chenych's avatar
chenych committed
66
67
68

    print(f"Got device mesh {mesh}, mesh_dim_names {mesh_dim_names}")

chenych's avatar
v0.3.0  
chenych committed
69
    assert mesh_dim_names in (("fsdp",), ("ddp", "fsdp")), f"Unsupported mesh_dim_names {mesh_dim_names}"
chenych's avatar
chenych committed
70
71
72
73
74
75
76
77
78
79

    if "tp" in mesh_dim_names:
        # fsdp * tp
        total_shards = mesh.shape[-1] * mesh.shape[-2]
        mesh_shape = (mesh.shape[-2], mesh.shape[-1])
    else:
        # fsdp
        total_shards = mesh.shape[-1]
        mesh_shape = (mesh.shape[-1],)

chenych's avatar
v0.3.0  
chenych committed
80
81
    print(f"Processing model shards with {total_shards} {mesh_shape} in total")

chenych's avatar
chenych committed
82
83
84
85
    model_state_dict_lst = []
    model_state_dict_lst.append(state_dict)
    model_state_dict_lst.extend([""] * (total_shards - 1))

chenych's avatar
v0.3.0  
chenych committed
86
    def process_one_shard(rank):
chenych's avatar
chenych committed
87
88
89
90
91
92
93
        model_path = os.path.join(local_dir, f"model_world_size_{world_size}_rank_{rank}.pt")
        state_dict = torch.load(model_path, map_location="cpu", weights_only=False)
        model_state_dict_lst[rank] = state_dict
        return state_dict

    with ThreadPoolExecutor(max_workers=min(32, os.cpu_count())) as executor:
        for rank in range(1, total_shards):
chenych's avatar
v0.3.0  
chenych committed
94
95
            executor.submit(process_one_shard, rank)
    state_dict = {}
chenych's avatar
chenych committed
96
97
98
99
100
101
102
103
    param_placements: Dict[str, List[Placement]] = {}
    keys = set(model_state_dict_lst[0].keys())
    for key in keys:
        state_dict[key] = []
        for model_state_dict in model_state_dict_lst:
            try:
                tensor = model_state_dict.pop(key)
            except Exception:
chenych's avatar
v0.3.0  
chenych committed
104
105
                print("-" * 30)
                print(model_state_dict)
chenych's avatar
chenych committed
106
107
108
            if isinstance(tensor, DTensor):
                state_dict[key].append(tensor._local_tensor.bfloat16())
                placements = tuple(tensor.placements)
chenych's avatar
Update  
chenych committed
109
110
                # replicated placement at ddp dimension can be discarded
                if mesh_dim_names[0] == "ddp":
chenych's avatar
chenych committed
111
                    placements = placements[1:]
chenych's avatar
Update  
chenych committed
112

chenych's avatar
chenych committed
113
114
115
116
117
                if key not in param_placements:
                    param_placements[key] = placements
                else:
                    assert param_placements[key] == placements
            else:
chenych's avatar
v0.3.0  
chenych committed
118
                state_dict[key] = tensor.bfloat16()
chenych's avatar
chenych committed
119
120
121
122
123
124
125

    del model_state_dict_lst

    for key in sorted(state_dict):
        if not isinstance(state_dict[key], list):
            print(f"No need to merge key {key}")
            continue
chenych's avatar
v0.3.0  
chenych committed
126
127
128
129
130
131
132
        # merge shards
        placements: Tuple[Shard] = param_placements[key]
        if len(mesh_shape) == 1:
            # 1-D list, FSDP without TP
            assert len(placements) == 1
            shards = state_dict[key]
            state_dict[key] = merge_by_placement(shards, placements[0])
chenych's avatar
chenych committed
133
        else:
chenych's avatar
v0.3.0  
chenych committed
134
135
            # 2-D list, FSDP + TP
            raise NotImplementedError("FSDP + TP is not supported yet")
chenych's avatar
chenych committed
136

chenych's avatar
v0.3.0  
chenych committed
137
    print("Writing to local disk")
chenych's avatar
chenych committed
138
    hf_path = os.path.join(local_dir, "huggingface")
chenych's avatar
v0.3.0  
chenych committed
139
140
141
142
143
144
145
146
    config = AutoConfig.from_pretrained(hf_path)

    if "ForTokenClassification" in config.architectures[0]:
        auto_model = AutoModelForTokenClassification
    elif "ForCausalLM" in config.architectures[0]:
        auto_model = AutoModelForCausalLM
    elif "ForConditionalGeneration" in config.architectures[0]:
        auto_model = AutoModelForVision2Seq
chenych's avatar
chenych committed
147
    else:
chenych's avatar
v0.3.0  
chenych committed
148
        raise NotImplementedError(f"Unknown architecture {config.architectures}")
chenych's avatar
chenych committed
149
150

    with torch.device("meta"):
chenych's avatar
v0.3.0  
chenych committed
151
        model = auto_model.from_config(config, torch_dtype=torch.bfloat16)
chenych's avatar
chenych committed
152
153
154

    model.to_empty(device="cpu")

chenych's avatar
v0.3.0  
chenych committed
155
    print(f"Saving model to {hf_path}")
chenych's avatar
chenych committed
156
    model.save_pretrained(hf_path, state_dict=state_dict)
chenych's avatar
v0.3.0  
chenych committed
157
158
    del state_dict
    del model
chenych's avatar
chenych committed
159
    if args.hf_upload_path:
chenych's avatar
v0.3.0  
chenych committed
160
161
162
163
164
165
        # Push to hugging face
        from huggingface_hub import HfApi

        api = HfApi()
        api.create_repo(repo_id=args.hf_upload_path, private=False, exist_ok=True)
        api.upload_folder(folder_path=hf_path, repo_id=args.hf_upload_path, repo_type="model")