common.py 8.81 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
from datetime import datetime
chenych's avatar
chenych committed
20
from typing import Any, 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


def abort_process(pid: int) -> None:
chenych's avatar
chenych committed
47
    r"""Abort the processes recursively in a bottom-up way."""
chenych's avatar
chenych committed
48
49
50
51
52
53
54
55
56
    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
57
58
59


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

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


chenych's avatar
chenych committed
69
def _get_config_path() -> os.PathLike:
chenych's avatar
chenych committed
70
    r"""Get the path to user config."""
chenych's avatar
chenych committed
71
72
73
    return os.path.join(DEFAULT_CACHE_DIR, USER_CONFIG)


chenych's avatar
chenych committed
74
75
def load_config() -> dict[str, Union[str, dict[str, Any]]]:
    r"""Load user config if exists."""
chenych's avatar
chenych committed
76
    try:
chenych's avatar
chenych committed
77
        with open(_get_config_path(), encoding="utf-8") as f:
chenych's avatar
chenych committed
78
79
80
81
82
83
            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:
chenych's avatar
chenych committed
84
    r"""Save user config."""
chenych's avatar
chenych committed
85
86
87
88
89
90
91
92
93
    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
94
    with open(_get_config_path(), "w", encoding="utf-8") as f:
chenych's avatar
chenych committed
95
96
97
98
        safe_dump(user_config, f)


def get_model_path(model_name: str) -> str:
chenych's avatar
chenych committed
99
    r"""Get the model path according to the model name."""
chenych's avatar
chenych committed
100
    user_config = load_config()
chenych's avatar
chenych committed
101
    path_dict: dict[DownloadSource, str] = SUPPORTED_MODELS.get(model_name, defaultdict(str))
chenych's avatar
chenych committed
102
103
104
105
106
    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
107
    ):  # replace hf path with ms path
chenych's avatar
chenych committed
108
109
        model_path = path_dict.get(DownloadSource.MODELSCOPE)

luopl's avatar
luopl committed
110
111
112
113
114
115
116
    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
117
118
119
120
    return model_path


def get_template(model_name: str) -> str:
chenych's avatar
chenych committed
121
    r"""Get the template name if the model is a chat/distill/instruct model."""
luopl's avatar
luopl committed
122
    return DEFAULT_TEMPLATE.get(model_name, "default")
chenych's avatar
chenych committed
123
124


chenych's avatar
chenych committed
125
def get_time() -> str:
chenych's avatar
chenych committed
126
    r"""Get current date and time."""
chenych's avatar
chenych committed
127
    return datetime.now().strftime(r"%Y-%m-%d-%H-%M-%S")
chenych's avatar
chenych committed
128
129


chenych's avatar
chenych committed
130
def is_multimodal(model_name: str) -> bool:
chenych's avatar
chenych committed
131
    r"""Judge if the model is a vision language model."""
chenych's avatar
chenych committed
132
    return model_name in MULTIMODAL_SUPPORTED_MODELS
chenych's avatar
chenych committed
133
134


chenych's avatar
chenych committed
135
136
def load_dataset_info(dataset_dir: str) -> dict[str, dict[str, Any]]:
    r"""Load dataset_info.json."""
chenych's avatar
chenych committed
137
    if dataset_dir == "ONLINE" or dataset_dir.startswith("REMOTE:"):
luopl's avatar
luopl committed
138
        logger.info_rank0(f"dataset_dir is {dataset_dir}, using online dataset.")
chenych's avatar
chenych committed
139
140
141
        return {}

    try:
luopl's avatar
luopl committed
142
        with open(os.path.join(dataset_dir, DATA_CONFIG), encoding="utf-8") as f:
chenych's avatar
chenych committed
143
144
            return json.load(f)
    except Exception as err:
luopl's avatar
luopl committed
145
        logger.warning_rank0(f"Cannot open {os.path.join(dataset_dir, DATA_CONFIG)} due to {str(err)}.")
chenych's avatar
chenych committed
146
147
148
        return {}


chenych's avatar
chenych committed
149
150
def load_args(config_path: str) -> Optional[dict[str, Any]]:
    r"""Load the training configuration from config path."""
chenych's avatar
chenych committed
151
152
153
154
155
156
157
    try:
        with open(config_path, encoding="utf-8") as f:
            return safe_load(f)
    except Exception:
        return None


chenych's avatar
chenych committed
158
159
def save_args(config_path: str, config_dict: dict[str, Any]) -> None:
    r"""Save the training configuration to config path."""
chenych's avatar
chenych committed
160
161
162
163
    with open(config_path, "w", encoding="utf-8") as f:
        safe_dump(config_dict, f)


chenych's avatar
chenych committed
164
165
def _clean_cmd(args: dict[str, Any]) -> dict[str, Any]:
    r"""Remove args with NoneType or False or empty string value."""
chenych's avatar
chenych committed
166
167
168
169
    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 != "")}


chenych's avatar
chenych committed
170
171
def gen_cmd(args: dict[str, Any]) -> str:
    r"""Generate CLI commands for previewing."""
chenych's avatar
chenych committed
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
    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


chenych's avatar
chenych committed
190
191
def save_cmd(args: dict[str, Any]) -> str:
    r"""Save CLI commands to launch training."""
chenych's avatar
chenych committed
192
193
194
195
196
197
198
199
200
    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:
chenych's avatar
chenych committed
201
    r"""Get scores after evaluation."""
chenych's avatar
chenych committed
202
203
204
205
206
207
208
    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:
chenych's avatar
chenych committed
209
    r"""Create deepspeed config in the current directory."""
chenych's avatar
chenych committed
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
    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)