common.py 9 KB
Newer Older
chenych's avatar
chenych committed
1
# Copyright 2025 the LlamaFactory team.
chenych's avatar
chenych committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#
# 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 json
import os
chenych's avatar
chenych committed
17
import signal
chenych's avatar
chenych committed
18
from collections import defaultdict
chenych's avatar
chenych committed
19
20
from datetime import datetime
from typing import Any, Dict, Optional, Union
chenych's avatar
chenych committed
21

chenych's avatar
chenych committed
22
from psutil import Process
chenych's avatar
chenych committed
23
24
from yaml import safe_dump, safe_load

luopl's avatar
luopl committed
25
from ..extras import logging
chenych's avatar
chenych committed
26
27
28
from ..extras.constants import (
    DATA_CONFIG,
    DEFAULT_TEMPLATE,
chenych's avatar
chenych committed
29
    MULTIMODAL_SUPPORTED_MODELS,
chenych's avatar
chenych committed
30
    SUPPORTED_MODELS,
chenych's avatar
chenych committed
31
    TRAINING_ARGS,
chenych's avatar
chenych committed
32
33
    DownloadSource,
)
luopl's avatar
luopl committed
34
from ..extras.misc import use_modelscope, use_openmind
chenych's avatar
chenych committed
35
36


luopl's avatar
luopl committed
37
logger = logging.get_logger(__name__)
chenych's avatar
chenych committed
38
39
40
41
42
43

DEFAULT_CACHE_DIR = "cache"
DEFAULT_CONFIG_DIR = "config"
DEFAULT_DATA_DIR = "data"
DEFAULT_SAVE_DIR = "saves"
USER_CONFIG = "user_config.yaml"
chenych's avatar
chenych committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58


def abort_process(pid: int) -> None:
    r"""
    Aborts the processes recursively in a bottom-up way.
    """
    try:
        children = Process(pid).children()
        if children:
            for child in children:
                abort_process(child.pid)

        os.kill(pid, signal.SIGABRT)
    except Exception:
        pass
chenych's avatar
chenych committed
59
60
61
62
63
64
65


def get_save_dir(*paths: str) -> os.PathLike:
    r"""
    Gets the path to saved model checkpoints.
    """
    if os.path.sep in paths[-1]:
luopl's avatar
luopl committed
66
        logger.warning_rank0("Found complex path, some features may be not available.")
chenych's avatar
chenych committed
67
68
69
70
71
72
        return paths[-1]

    paths = (path.replace(" ", "").strip() for path in paths)
    return os.path.join(DEFAULT_SAVE_DIR, *paths)


chenych's avatar
chenych committed
73
def _get_config_path() -> os.PathLike:
chenych's avatar
chenych committed
74
75
76
77
78
79
    r"""
    Gets the path to user config.
    """
    return os.path.join(DEFAULT_CACHE_DIR, USER_CONFIG)


chenych's avatar
chenych committed
80
def load_config() -> Dict[str, Union[str, Dict[str, Any]]]:
chenych's avatar
chenych committed
81
82
83
84
    r"""
    Loads user config if exists.
    """
    try:
chenych's avatar
chenych committed
85
        with open(_get_config_path(), encoding="utf-8") as f:
chenych's avatar
chenych committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
            return safe_load(f)
    except Exception:
        return {"lang": None, "last_model": None, "path_dict": {}, "cache_dir": None}


def save_config(lang: str, model_name: Optional[str] = None, model_path: Optional[str] = None) -> None:
    r"""
    Saves user config.
    """
    os.makedirs(DEFAULT_CACHE_DIR, exist_ok=True)
    user_config = load_config()
    user_config["lang"] = lang or user_config["lang"]
    if model_name:
        user_config["last_model"] = model_name

    if model_name and model_path:
        user_config["path_dict"][model_name] = model_path

chenych's avatar
chenych committed
104
    with open(_get_config_path(), "w", encoding="utf-8") as f:
chenych's avatar
chenych committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
        safe_dump(user_config, f)


def get_model_path(model_name: str) -> str:
    r"""
    Gets the model path according to the model name.
    """
    user_config = load_config()
    path_dict: Dict["DownloadSource", str] = SUPPORTED_MODELS.get(model_name, defaultdict(str))
    model_path = user_config["path_dict"].get(model_name, "") or path_dict.get(DownloadSource.DEFAULT, "")
    if (
        use_modelscope()
        and path_dict.get(DownloadSource.MODELSCOPE)
        and model_path == path_dict.get(DownloadSource.DEFAULT)
luopl's avatar
luopl committed
119
    ):  # replace hf path with ms path
chenych's avatar
chenych committed
120
121
        model_path = path_dict.get(DownloadSource.MODELSCOPE)

luopl's avatar
luopl committed
122
123
124
125
126
127
128
    if (
        use_openmind()
        and path_dict.get(DownloadSource.OPENMIND)
        and model_path == path_dict.get(DownloadSource.DEFAULT)
    ):  # replace hf path with om path
        model_path = path_dict.get(DownloadSource.OPENMIND)

chenych's avatar
chenych committed
129
130
131
132
133
    return model_path


def get_template(model_name: str) -> str:
    r"""
chenych's avatar
chenych committed
134
    Gets the template name if the model is a chat/distill/instruct model.
chenych's avatar
chenych committed
135
    """
luopl's avatar
luopl committed
136
    return DEFAULT_TEMPLATE.get(model_name, "default")
chenych's avatar
chenych committed
137
138


chenych's avatar
chenych committed
139
def get_time() -> str:
chenych's avatar
chenych committed
140
    r"""
chenych's avatar
chenych committed
141
    Gets current date and time.
chenych's avatar
chenych committed
142
    """
chenych's avatar
chenych committed
143
    return datetime.now().strftime(r"%Y-%m-%d-%H-%M-%S")
chenych's avatar
chenych committed
144
145


chenych's avatar
chenych committed
146
def is_multimodal(model_name: str) -> bool:
chenych's avatar
chenych committed
147
    r"""
chenych's avatar
chenych committed
148
    Judges if the model is a vision language model.
chenych's avatar
chenych committed
149
    """
chenych's avatar
chenych committed
150
    return model_name in MULTIMODAL_SUPPORTED_MODELS
chenych's avatar
chenych committed
151
152
153
154
155
156
157


def load_dataset_info(dataset_dir: str) -> Dict[str, Dict[str, Any]]:
    r"""
    Loads dataset_info.json.
    """
    if dataset_dir == "ONLINE" or dataset_dir.startswith("REMOTE:"):
luopl's avatar
luopl committed
158
        logger.info_rank0(f"dataset_dir is {dataset_dir}, using online dataset.")
chenych's avatar
chenych committed
159
160
161
        return {}

    try:
luopl's avatar
luopl committed
162
        with open(os.path.join(dataset_dir, DATA_CONFIG), encoding="utf-8") as f:
chenych's avatar
chenych committed
163
164
            return json.load(f)
    except Exception as err:
luopl's avatar
luopl committed
165
        logger.warning_rank0(f"Cannot open {os.path.join(dataset_dir, DATA_CONFIG)} due to {str(err)}.")
chenych's avatar
chenych committed
166
167
168
        return {}


chenych's avatar
chenych committed
169
170
171
172
173
174
175
176
177
178
179
180
def load_args(config_path: str) -> Optional[Dict[str, Any]]:
    r"""
    Loads the training configuration from config path.
    """
    try:
        with open(config_path, encoding="utf-8") as f:
            return safe_load(f)
    except Exception:
        return None


def save_args(config_path: str, config_dict: Dict[str, Any]) -> None:
chenych's avatar
chenych committed
181
    r"""
chenych's avatar
chenych committed
182
    Saves the training configuration to config path.
chenych's avatar
chenych committed
183
    """
chenych's avatar
chenych committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
    with open(config_path, "w", encoding="utf-8") as f:
        safe_dump(config_dict, f)


def _clean_cmd(args: Dict[str, Any]) -> Dict[str, Any]:
    r"""
    Removes args with NoneType or False or empty string value.
    """
    no_skip_keys = ["packing"]
    return {k: v for k, v in args.items() if (k in no_skip_keys) or (v is not None and v is not False and v != "")}


def gen_cmd(args: Dict[str, Any]) -> str:
    r"""
    Generates CLI commands for previewing.
    """
    cmd_lines = ["llamafactory-cli train "]
    for k, v in _clean_cmd(args).items():
        if isinstance(v, dict):
            cmd_lines.append(f"    --{k} {json.dumps(v, ensure_ascii=False)} ")
        elif isinstance(v, list):
            cmd_lines.append(f"    --{k} {' '.join(map(str, v))} ")
        else:
            cmd_lines.append(f"    --{k} {str(v)} ")

    if os.name == "nt":
        cmd_text = "`\n".join(cmd_lines)
    else:
        cmd_text = "\\\n".join(cmd_lines)

    cmd_text = f"```bash\n{cmd_text}\n```"
    return cmd_text


def save_cmd(args: Dict[str, Any]) -> str:
    r"""
    Saves CLI commands to launch training.
    """
    output_dir = args["output_dir"]
    os.makedirs(output_dir, exist_ok=True)
    with open(os.path.join(output_dir, TRAINING_ARGS), "w", encoding="utf-8") as f:
        safe_dump(_clean_cmd(args), f)

    return os.path.join(output_dir, TRAINING_ARGS)


def load_eval_results(path: os.PathLike) -> str:
    r"""
    Gets scores after evaluation.
    """
    with open(path, encoding="utf-8") as f:
        result = json.dumps(json.load(f), indent=4)

    return f"```json\n{result}\n```\n"


def create_ds_config() -> None:
    r"""
    Creates deepspeed config in the current directory.
    """
    os.makedirs(DEFAULT_CACHE_DIR, exist_ok=True)
    ds_config = {
        "train_batch_size": "auto",
        "train_micro_batch_size_per_gpu": "auto",
        "gradient_accumulation_steps": "auto",
        "gradient_clipping": "auto",
        "zero_allow_untested_optimizer": True,
        "fp16": {
            "enabled": "auto",
            "loss_scale": 0,
            "loss_scale_window": 1000,
            "initial_scale_power": 16,
            "hysteresis": 2,
            "min_loss_scale": 1,
        },
        "bf16": {"enabled": "auto"},
    }
    offload_config = {
        "device": "cpu",
        "pin_memory": True,
    }
    ds_config["zero_optimization"] = {
        "stage": 2,
        "allgather_partitions": True,
        "allgather_bucket_size": 5e8,
        "overlap_comm": True,
        "reduce_scatter": True,
        "reduce_bucket_size": 5e8,
        "contiguous_gradients": True,
        "round_robin_gradients": True,
    }
    with open(os.path.join(DEFAULT_CACHE_DIR, "ds_z2_config.json"), "w", encoding="utf-8") as f:
        json.dump(ds_config, f, indent=2)

    ds_config["zero_optimization"]["offload_optimizer"] = offload_config
    with open(os.path.join(DEFAULT_CACHE_DIR, "ds_z2_offload_config.json"), "w", encoding="utf-8") as f:
        json.dump(ds_config, f, indent=2)

    ds_config["zero_optimization"] = {
        "stage": 3,
        "overlap_comm": True,
        "contiguous_gradients": True,
        "sub_group_size": 1e9,
        "reduce_bucket_size": "auto",
        "stage3_prefetch_bucket_size": "auto",
        "stage3_param_persistence_threshold": "auto",
        "stage3_max_live_parameters": 1e9,
        "stage3_max_reuse_distance": 1e9,
        "stage3_gather_16bit_weights_on_model_save": True,
    }
    with open(os.path.join(DEFAULT_CACHE_DIR, "ds_z3_config.json"), "w", encoding="utf-8") as f:
        json.dump(ds_config, f, indent=2)

    ds_config["zero_optimization"]["offload_optimizer"] = offload_config
    ds_config["zero_optimization"]["offload_param"] = offload_config
    with open(os.path.join(DEFAULT_CACHE_DIR, "ds_z3_offload_config.json"), "w", encoding="utf-8") as f:
        json.dump(ds_config, f, indent=2)