Elffuss BraidHub

kikocis/SpatialLM public

main · 8.2 KiBRawPermalink
1# Copyright 2025 HuggingFace Inc. and the LlamaFactory team.
2#
3# This code is inspired by the HuggingFace's transformers library.
4# https://github.com/huggingface/transformers/blob/v4.40.0/examples/pytorch/language-modeling/run_clm.py
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18import json
19import os
20import sys
21from pathlib import Path
22from typing import Any, Optional, Union
23
24import torch
25import transformers
26import yaml
27from omegaconf import OmegaConf
28from transformers import HfArgumentParser
29from transformers.integrations import is_deepspeed_zero3_enabled
30from transformers.trainer_utils import get_last_checkpoint
31from transformers.training_args import ParallelMode
32from transformers.utils import is_torch_bf16_gpu_available, is_torch_npu_available
33from transformers.utils import (
34 SAFE_WEIGHTS_INDEX_NAME,
35 SAFE_WEIGHTS_NAME,
36 WEIGHTS_INDEX_NAME,
37 WEIGHTS_NAME,
38)
39
40from ..framework import logging
41from ..framework.utils import (
42 check_dependencies,
43 get_current_device,
44 is_env_enabled,
45)
46from .data_args import DataArguments
47from .finetuning_args import FinetuningArguments
48from .generating_args import GeneratingArguments
49from .model_args import ModelArguments
50from .training_args import TrainingArguments
51
52CHECKPOINT_NAMES = {
53 SAFE_WEIGHTS_INDEX_NAME,
54 SAFE_WEIGHTS_NAME,
55 WEIGHTS_INDEX_NAME,
56 WEIGHTS_NAME,
57}
58logger = logging.get_logger(__name__)
59
60check_dependencies()
61
62
63_TRAIN_ARGS = [
64 ModelArguments,
65 DataArguments,
66 TrainingArguments,
67 FinetuningArguments,
68 GeneratingArguments,
69]
70_TRAIN_CLS = tuple[
71 ModelArguments,
72 DataArguments,
73 TrainingArguments,
74 FinetuningArguments,
75 GeneratingArguments,
76]
77
78
79def read_args(
80 args: Optional[Union[dict[str, Any], list[str]]] = None,
81) -> Union[dict[str, Any], list[str]]:
82 r"""Get arguments from the command line or a config file."""
83 if args is not None:
84 return args
85
86 if sys.argv[1].endswith(".yaml") or sys.argv[1].endswith(".yml"):
87 override_config = OmegaConf.from_cli(sys.argv[2:])
88 dict_config = yaml.safe_load(Path(sys.argv[1]).absolute().read_text())
89 return OmegaConf.to_container(OmegaConf.merge(dict_config, override_config))
90 elif sys.argv[1].endswith(".json"):
91 override_config = OmegaConf.from_cli(sys.argv[2:])
92 dict_config = json.loads(Path(sys.argv[1]).absolute().read_text())
93 return OmegaConf.to_container(OmegaConf.merge(dict_config, override_config))
94 else:
95 return sys.argv[1:]
96
97
98def _parse_args(
99 parser: "HfArgumentParser",
100 args: Optional[Union[dict[str, Any], list[str]]] = None,
101 allow_extra_keys: bool = False,
102) -> tuple[Any]:
103 args = read_args(args)
104 if isinstance(args, dict):
105 return parser.parse_dict(args, allow_extra_keys=allow_extra_keys)
106
107 (*parsed_args, unknown_args) = parser.parse_args_into_dataclasses(
108 args=args, return_remaining_strings=True
109 )
110
111 if unknown_args and not allow_extra_keys:
112 print(parser.format_help())
113 print(f"Got unknown args, potentially deprecated arguments: {unknown_args}")
114 raise ValueError(
115 f"Some specified arguments are not used by the HfArgumentParser: {unknown_args}"
116 )
117
118 return tuple(parsed_args)
119
120
121def _set_transformers_logging() -> None:
122 if os.getenv("LLAMAFACTORY_VERBOSITY", "INFO") in ["DEBUG", "INFO"]:
123 transformers.utils.logging.set_verbosity_info()
124 transformers.utils.logging.enable_default_handler()
125 transformers.utils.logging.enable_explicit_format()
126
127
128def _set_env_vars() -> None:
129 if is_torch_npu_available():
130 # avoid JIT compile on NPU devices, see https://zhuanlan.zhihu.com/p/660875458
131 torch.npu.set_compile_mode(jit_compile=is_env_enabled("NPU_JIT_COMPILE"))
132
133
134def _parse_train_args(
135 args: Optional[Union[dict[str, Any], list[str]]] = None,
136) -> _TRAIN_CLS:
137 parser = HfArgumentParser(_TRAIN_ARGS)
138 allow_extra_keys = is_env_enabled("ALLOW_EXTRA_ARGS")
139 return _parse_args(parser, args, allow_extra_keys=allow_extra_keys)
140
141
142def get_train_args(
143 args: Optional[Union[dict[str, Any], list[str]]] = None,
144) -> _TRAIN_CLS:
145 model_args, data_args, training_args, finetuning_args, generating_args = (
146 _parse_train_args(args)
147 )
148
149 # Setup logging
150 if training_args.should_log:
151 _set_transformers_logging()
152
153 if training_args.parallel_mode == ParallelMode.NOT_DISTRIBUTED:
154 raise ValueError(
155 "Please launch distributed training with `llamafactory-cli` or `torchrun`."
156 )
157
158 if (
159 training_args.deepspeed
160 and training_args.parallel_mode != ParallelMode.DISTRIBUTED
161 ):
162 raise ValueError("Please use `FORCE_TORCHRUN=1` to launch DeepSpeed training.")
163
164 if training_args.do_train and data_args.dataset is None:
165 raise ValueError("Please specify dataset for training.")
166
167 if training_args.do_eval and (
168 data_args.eval_dataset is None and data_args.val_size < 1e-6
169 ):
170 raise ValueError("Please specify dataset for evaluation.")
171
172 if finetuning_args.pure_bf16:
173 if not (
174 is_torch_bf16_gpu_available()
175 or (is_torch_npu_available() and torch.npu.is_bf16_supported())
176 ):
177 raise ValueError("This device does not support `pure_bf16`.")
178
179 if is_deepspeed_zero3_enabled():
180 raise ValueError("`pure_bf16` is incompatible with DeepSpeed ZeRO-3.")
181
182 _set_env_vars()
183
184 if training_args.do_train and (not training_args.fp16) and (not training_args.bf16):
185 logger.warning_rank0("We recommend enable mixed precision training.")
186
187 # Post-process training arguments
188 training_args.generation_max_length = (
189 training_args.generation_max_length or data_args.cutoff_len
190 )
191 training_args.generation_num_beams = (
192 data_args.eval_num_beams or training_args.generation_num_beams
193 )
194 training_args.remove_unused_columns = False # important for multimodal dataset
195 can_resume_from_checkpoint = True
196
197 if (
198 training_args.resume_from_checkpoint is None
199 and training_args.do_train
200 and os.path.isdir(training_args.output_dir)
201 and not training_args.overwrite_output_dir
202 and can_resume_from_checkpoint
203 ):
204 last_checkpoint = get_last_checkpoint(training_args.output_dir)
205 if last_checkpoint is None and any(
206 os.path.isfile(os.path.join(training_args.output_dir, name))
207 for name in CHECKPOINT_NAMES
208 ):
209 raise ValueError(
210 "Output directory already exists and is not empty. Please set `overwrite_output_dir`."
211 )
212
213 if last_checkpoint is not None:
214 training_args.resume_from_checkpoint = last_checkpoint
215 logger.info_rank0(
216 f"Resuming training from {training_args.resume_from_checkpoint}."
217 )
218 logger.info_rank0(
219 "Change `output_dir` or use `overwrite_output_dir` to avoid."
220 )
221
222 # Post-process model arguments
223 if training_args.bf16 or finetuning_args.pure_bf16:
224 model_args.compute_dtype = torch.bfloat16
225 elif training_args.fp16:
226 model_args.compute_dtype = torch.float16
227
228 model_args.device_map = {"": get_current_device()}
229 model_args.model_max_length = data_args.cutoff_len
230
231 # Log on each process the small summary
232 logger.info(
233 f"Process rank: {training_args.process_index}, "
234 f"world size: {training_args.world_size}, device: {training_args.device}, "
235 f"distributed training: {training_args.parallel_mode == ParallelMode.DISTRIBUTED}, "
236 f"compute dtype: {str(model_args.compute_dtype)}"
237 )
238 transformers.set_seed(training_args.seed)
239
240 return model_args, data_args, training_args, finetuning_args, generating_args