Upload 3 files
Browse files- launcher.py +26 -0
- misc.py +372 -0
- train.py +34 -0
launcher.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the LlamaFactory team.
|
| 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 |
+
from llamafactory.extras.misc import init_distributed_runtime
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def launch():
|
| 19 |
+
init_distributed_runtime()
|
| 20 |
+
from llamafactory.train.tuner import run_exp # use absolute import
|
| 21 |
+
|
| 22 |
+
run_exp()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if __name__ == "__main__":
|
| 26 |
+
launch()
|
misc.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team.
|
| 2 |
+
#
|
| 3 |
+
# This code is inspired by the HuggingFace's PEFT library.
|
| 4 |
+
# https://github.com/huggingface/peft/blob/v0.10.0/src/peft/peft_model.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 |
+
|
| 18 |
+
import gc
|
| 19 |
+
import os
|
| 20 |
+
import socket
|
| 21 |
+
from typing import TYPE_CHECKING, Any, Literal, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.distributed as dist
|
| 25 |
+
import transformers.dynamic_module_utils
|
| 26 |
+
from transformers import InfNanRemoveLogitsProcessor, LogitsProcessorList
|
| 27 |
+
from transformers.dynamic_module_utils import get_relative_imports
|
| 28 |
+
from transformers.utils import (
|
| 29 |
+
is_torch_bf16_gpu_available,
|
| 30 |
+
is_torch_cuda_available,
|
| 31 |
+
is_torch_mps_available,
|
| 32 |
+
is_torch_npu_available,
|
| 33 |
+
is_torch_xpu_available,
|
| 34 |
+
)
|
| 35 |
+
from transformers.utils.versions import require_version
|
| 36 |
+
|
| 37 |
+
from . import logging
|
| 38 |
+
from .packages import is_transformers_version_greater_than
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
_is_fp16_available = is_torch_npu_available() or is_torch_cuda_available()
|
| 42 |
+
try:
|
| 43 |
+
_is_bf16_available = is_torch_bf16_gpu_available() or (is_torch_npu_available() and torch.npu.is_bf16_supported())
|
| 44 |
+
except Exception:
|
| 45 |
+
_is_bf16_available = False
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if TYPE_CHECKING:
|
| 49 |
+
from numpy.typing import NDArray
|
| 50 |
+
|
| 51 |
+
from ..hparams import ModelArguments
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
logger = logging.get_logger(__name__)
|
| 55 |
+
_DIST_BARRIER_PATCHED = False
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class AverageMeter:
|
| 59 |
+
r"""Compute and store the average and current value."""
|
| 60 |
+
|
| 61 |
+
def __init__(self):
|
| 62 |
+
self.reset()
|
| 63 |
+
|
| 64 |
+
def reset(self):
|
| 65 |
+
self.val = 0
|
| 66 |
+
self.avg = 0
|
| 67 |
+
self.sum = 0
|
| 68 |
+
self.count = 0
|
| 69 |
+
|
| 70 |
+
def update(self, val, n=1):
|
| 71 |
+
self.val = val
|
| 72 |
+
self.sum += val * n
|
| 73 |
+
self.count += n
|
| 74 |
+
self.avg = self.sum / self.count
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def check_version(requirement: str, mandatory: bool = False) -> None:
|
| 78 |
+
r"""Optionally check the package version."""
|
| 79 |
+
if is_env_enabled("DISABLE_VERSION_CHECK") and not mandatory:
|
| 80 |
+
logger.warning_rank0_once("Version checking has been disabled, may lead to unexpected behaviors.")
|
| 81 |
+
return
|
| 82 |
+
|
| 83 |
+
if "gptmodel" in requirement or "autoawq" in requirement:
|
| 84 |
+
pip_command = f"pip install {requirement} --no-build-isolation"
|
| 85 |
+
else:
|
| 86 |
+
pip_command = f"pip install {requirement}"
|
| 87 |
+
|
| 88 |
+
if mandatory:
|
| 89 |
+
hint = f"To fix: run `{pip_command}`."
|
| 90 |
+
else:
|
| 91 |
+
hint = f"To fix: run `{pip_command}` or set `DISABLE_VERSION_CHECK=1` to skip this check."
|
| 92 |
+
|
| 93 |
+
require_version(requirement, hint)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def check_dependencies() -> None:
|
| 97 |
+
r"""Check the version of the required packages."""
|
| 98 |
+
check_version(
|
| 99 |
+
"transformers>=4.45.0,<=4.52.3,!=4.46.0,!=4.46.1,!=4.46.2,!=4.46.3,!=4.47.0,!=4.47.1,!=4.48.0,!=4.52.0"
|
| 100 |
+
)
|
| 101 |
+
check_version("datasets>=2.16.0,<=3.6.0")
|
| 102 |
+
check_version("accelerate>=0.34.0,<=1.7.0")
|
| 103 |
+
check_version("peft>=0.14.0,<=0.15.2")
|
| 104 |
+
check_version("trl>=0.8.6,<=0.9.6")
|
| 105 |
+
if is_transformers_version_greater_than("4.46.0") and not is_transformers_version_greater_than("4.48.1"):
|
| 106 |
+
logger.warning_rank0_once("There are known bugs in transformers v4.46.0-v4.48.0, please use other versions.")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def calculate_tps(dataset: list[dict[str, Any]], metrics: dict[str, float], stage: Literal["sft", "rm"]) -> float:
|
| 110 |
+
r"""Calculate effective tokens per second."""
|
| 111 |
+
effective_token_num = 0
|
| 112 |
+
for data in dataset:
|
| 113 |
+
if stage == "sft":
|
| 114 |
+
effective_token_num += len(data["input_ids"])
|
| 115 |
+
elif stage == "rm":
|
| 116 |
+
effective_token_num += len(data["chosen_input_ids"]) + len(data["rejected_input_ids"])
|
| 117 |
+
|
| 118 |
+
result = effective_token_num * metrics["epoch"] / metrics["train_runtime"]
|
| 119 |
+
return result / dist.get_world_size() if dist.is_initialized() else result
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def count_parameters(model: "torch.nn.Module") -> tuple[int, int]:
|
| 123 |
+
r"""Return the number of trainable parameters and number of all parameters in the model."""
|
| 124 |
+
trainable_params, all_param = 0, 0
|
| 125 |
+
for param in model.parameters():
|
| 126 |
+
num_params = param.numel()
|
| 127 |
+
# if using DS Zero 3 and the weights are initialized empty
|
| 128 |
+
if num_params == 0 and hasattr(param, "ds_numel"):
|
| 129 |
+
num_params = param.ds_numel
|
| 130 |
+
|
| 131 |
+
# Due to the design of 4bit linear layers from bitsandbytes, multiply the number of parameters by itemsize
|
| 132 |
+
if param.__class__.__name__ == "Params4bit":
|
| 133 |
+
if hasattr(param, "quant_storage") and hasattr(param.quant_storage, "itemsize"):
|
| 134 |
+
num_bytes = param.quant_storage.itemsize
|
| 135 |
+
elif hasattr(param, "element_size"): # for older pytorch version
|
| 136 |
+
num_bytes = param.element_size()
|
| 137 |
+
else:
|
| 138 |
+
num_bytes = 1
|
| 139 |
+
|
| 140 |
+
num_params = num_params * 2 * num_bytes
|
| 141 |
+
|
| 142 |
+
all_param += num_params
|
| 143 |
+
if param.requires_grad:
|
| 144 |
+
trainable_params += num_params
|
| 145 |
+
|
| 146 |
+
return trainable_params, all_param
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def get_current_device() -> "torch.device":
|
| 150 |
+
r"""Get the current available device."""
|
| 151 |
+
if is_torch_xpu_available():
|
| 152 |
+
device = "xpu:{}".format(os.getenv("LOCAL_RANK", "0"))
|
| 153 |
+
elif is_torch_npu_available():
|
| 154 |
+
device = "npu:{}".format(os.getenv("LOCAL_RANK", "0"))
|
| 155 |
+
elif is_torch_mps_available():
|
| 156 |
+
device = "mps:{}".format(os.getenv("LOCAL_RANK", "0"))
|
| 157 |
+
elif is_torch_cuda_available():
|
| 158 |
+
device = "cuda:{}".format(os.getenv("LOCAL_RANK", "0"))
|
| 159 |
+
else:
|
| 160 |
+
device = "cpu"
|
| 161 |
+
|
| 162 |
+
return torch.device(device)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def get_device_count() -> int:
|
| 166 |
+
r"""Get the number of available devices."""
|
| 167 |
+
if is_torch_xpu_available():
|
| 168 |
+
return torch.xpu.device_count()
|
| 169 |
+
elif is_torch_npu_available():
|
| 170 |
+
return torch.npu.device_count()
|
| 171 |
+
elif is_torch_mps_available():
|
| 172 |
+
return torch.mps.device_count()
|
| 173 |
+
elif is_torch_cuda_available():
|
| 174 |
+
return torch.cuda.device_count()
|
| 175 |
+
else:
|
| 176 |
+
return 0
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def patch_dist_barrier() -> None:
|
| 180 |
+
r"""Patch dist.barrier to use current CUDA device for NCCL backend."""
|
| 181 |
+
global _DIST_BARRIER_PATCHED
|
| 182 |
+
if is_env_enabled("DISABLE_DIST_BARRIER_PATCH"):
|
| 183 |
+
return
|
| 184 |
+
|
| 185 |
+
if _DIST_BARRIER_PATCHED or not dist.is_available() or not hasattr(dist, "barrier"):
|
| 186 |
+
return
|
| 187 |
+
|
| 188 |
+
original_barrier = dist.barrier
|
| 189 |
+
|
| 190 |
+
def _patched_barrier(*args, **kwargs):
|
| 191 |
+
if "device_ids" not in kwargs and dist.is_initialized():
|
| 192 |
+
try:
|
| 193 |
+
backend = dist.get_backend()
|
| 194 |
+
except Exception:
|
| 195 |
+
backend = None
|
| 196 |
+
|
| 197 |
+
if backend == "nccl" and is_torch_cuda_available():
|
| 198 |
+
try:
|
| 199 |
+
kwargs["device_ids"] = [torch.cuda.current_device()]
|
| 200 |
+
except Exception:
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
return original_barrier(*args, **kwargs)
|
| 204 |
+
|
| 205 |
+
dist.barrier = _patched_barrier
|
| 206 |
+
_DIST_BARRIER_PATCHED = True
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def set_device_by_local_rank() -> None:
|
| 210 |
+
r"""Bind current CUDA device to LOCAL_RANK as early as possible."""
|
| 211 |
+
if not is_torch_cuda_available():
|
| 212 |
+
return
|
| 213 |
+
|
| 214 |
+
local_rank = os.getenv("LOCAL_RANK")
|
| 215 |
+
if local_rank is None:
|
| 216 |
+
return
|
| 217 |
+
|
| 218 |
+
try:
|
| 219 |
+
local_rank_id = int(local_rank)
|
| 220 |
+
except ValueError:
|
| 221 |
+
logger.warning_rank0(f"Invalid LOCAL_RANK: {local_rank}.")
|
| 222 |
+
return
|
| 223 |
+
|
| 224 |
+
if local_rank_id < 0 or local_rank_id >= torch.cuda.device_count():
|
| 225 |
+
logger.warning_rank0(f"LOCAL_RANK {local_rank_id} is out of CUDA device range.")
|
| 226 |
+
return
|
| 227 |
+
|
| 228 |
+
try:
|
| 229 |
+
if torch.cuda.current_device() != local_rank_id:
|
| 230 |
+
torch.cuda.set_device(local_rank_id)
|
| 231 |
+
except Exception as e:
|
| 232 |
+
logger.warning_rank0(f"Failed to set CUDA device by LOCAL_RANK={local_rank_id}: {e}.")
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def init_distributed_runtime() -> None:
|
| 236 |
+
r"""Initialize distributed runtime before entering the training workflow."""
|
| 237 |
+
set_device_by_local_rank()
|
| 238 |
+
patch_dist_barrier()
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def get_logits_processor() -> "LogitsProcessorList":
|
| 242 |
+
r"""Get logits processor that removes NaN and Inf logits."""
|
| 243 |
+
logits_processor = LogitsProcessorList()
|
| 244 |
+
logits_processor.append(InfNanRemoveLogitsProcessor())
|
| 245 |
+
return logits_processor
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def get_peak_memory() -> tuple[int, int]:
|
| 249 |
+
r"""Get the peak memory usage for the current device (in Bytes)."""
|
| 250 |
+
if is_torch_xpu_available():
|
| 251 |
+
return torch.xpu.max_memory_allocated(), torch.xpu.max_memory_reserved()
|
| 252 |
+
elif is_torch_npu_available():
|
| 253 |
+
return torch.npu.max_memory_allocated(), torch.npu.max_memory_reserved()
|
| 254 |
+
elif is_torch_mps_available():
|
| 255 |
+
return torch.mps.current_allocated_memory(), -1
|
| 256 |
+
elif is_torch_cuda_available():
|
| 257 |
+
return torch.cuda.max_memory_allocated(), torch.cuda.max_memory_reserved()
|
| 258 |
+
else:
|
| 259 |
+
return 0, 0
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def has_tokenized_data(path: "os.PathLike") -> bool:
|
| 263 |
+
r"""Check if the path has a tokenized dataset."""
|
| 264 |
+
return os.path.isdir(path) and len(os.listdir(path)) > 0
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def infer_optim_dtype(model_dtype: "torch.dtype") -> "torch.dtype":
|
| 268 |
+
r"""Infer the optimal dtype according to the model_dtype and device compatibility."""
|
| 269 |
+
if _is_bf16_available and model_dtype == torch.bfloat16:
|
| 270 |
+
return torch.bfloat16
|
| 271 |
+
elif _is_fp16_available:
|
| 272 |
+
return torch.float16
|
| 273 |
+
else:
|
| 274 |
+
return torch.float32
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def is_accelerator_available() -> bool:
|
| 278 |
+
r"""Check if the accelerator is available."""
|
| 279 |
+
return (
|
| 280 |
+
is_torch_xpu_available() or is_torch_npu_available() or is_torch_mps_available() or is_torch_cuda_available()
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def is_env_enabled(env_var: str, default: str = "0") -> bool:
|
| 285 |
+
r"""Check if the environment variable is enabled."""
|
| 286 |
+
return os.getenv(env_var, default).lower() in ["true", "y", "1"]
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def numpify(inputs: Union["NDArray", "torch.Tensor"]) -> "NDArray":
|
| 290 |
+
r"""Cast a torch tensor or a numpy array to a numpy array."""
|
| 291 |
+
if isinstance(inputs, torch.Tensor):
|
| 292 |
+
inputs = inputs.cpu()
|
| 293 |
+
if inputs.dtype == torch.bfloat16: # numpy does not support bfloat16 until 1.21.4
|
| 294 |
+
inputs = inputs.to(torch.float32)
|
| 295 |
+
|
| 296 |
+
inputs = inputs.numpy()
|
| 297 |
+
|
| 298 |
+
return inputs
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def skip_check_imports() -> None:
|
| 302 |
+
r"""Avoid flash attention import error in custom model files."""
|
| 303 |
+
if not is_env_enabled("FORCE_CHECK_IMPORTS"):
|
| 304 |
+
transformers.dynamic_module_utils.check_imports = get_relative_imports
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def torch_gc() -> None:
|
| 308 |
+
r"""Collect the device memory."""
|
| 309 |
+
gc.collect()
|
| 310 |
+
if is_torch_xpu_available():
|
| 311 |
+
torch.xpu.empty_cache()
|
| 312 |
+
elif is_torch_npu_available():
|
| 313 |
+
torch.npu.empty_cache()
|
| 314 |
+
elif is_torch_mps_available():
|
| 315 |
+
torch.mps.empty_cache()
|
| 316 |
+
elif is_torch_cuda_available():
|
| 317 |
+
torch.cuda.empty_cache()
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def try_download_model_from_other_hub(model_args: "ModelArguments") -> str:
|
| 321 |
+
if (not use_modelscope() and not use_openmind()) or os.path.exists(model_args.model_name_or_path):
|
| 322 |
+
return model_args.model_name_or_path
|
| 323 |
+
|
| 324 |
+
if use_modelscope():
|
| 325 |
+
check_version("modelscope>=1.11.0", mandatory=True)
|
| 326 |
+
from modelscope import snapshot_download # type: ignore
|
| 327 |
+
|
| 328 |
+
revision = "master" if model_args.model_revision == "main" else model_args.model_revision
|
| 329 |
+
return snapshot_download(
|
| 330 |
+
model_args.model_name_or_path,
|
| 331 |
+
revision=revision,
|
| 332 |
+
cache_dir=model_args.cache_dir,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
if use_openmind():
|
| 336 |
+
check_version("openmind>=0.8.0", mandatory=True)
|
| 337 |
+
from openmind.utils.hub import snapshot_download # type: ignore
|
| 338 |
+
|
| 339 |
+
return snapshot_download(
|
| 340 |
+
model_args.model_name_or_path,
|
| 341 |
+
revision=model_args.model_revision,
|
| 342 |
+
cache_dir=model_args.cache_dir,
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def use_modelscope() -> bool:
|
| 347 |
+
return is_env_enabled("USE_MODELSCOPE_HUB")
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def use_openmind() -> bool:
|
| 351 |
+
return is_env_enabled("USE_OPENMIND_HUB")
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def use_ray() -> bool:
|
| 355 |
+
return is_env_enabled("USE_RAY")
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def find_available_port() -> int:
|
| 359 |
+
r"""Find an available port on the local machine."""
|
| 360 |
+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
| 361 |
+
sock.bind(("", 0))
|
| 362 |
+
port = sock.getsockname()[1]
|
| 363 |
+
sock.close()
|
| 364 |
+
return port
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def fix_proxy(ipv6_enabled: bool = False) -> None:
|
| 368 |
+
r"""Fix proxy settings for gradio ui."""
|
| 369 |
+
os.environ["no_proxy"] = "localhost,127.0.0.1,0.0.0.0"
|
| 370 |
+
if ipv6_enabled:
|
| 371 |
+
for name in ("http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY"):
|
| 372 |
+
os.environ.pop(name, None)
|
train.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 the LlamaFactory team.
|
| 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 |
+
from llamafactory.extras.misc import init_distributed_runtime
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
init_distributed_runtime()
|
| 20 |
+
from llamafactory.train.tuner import run_exp
|
| 21 |
+
|
| 22 |
+
run_exp()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _mp_fn(index):
|
| 26 |
+
# For xla_spawn (TPUs)
|
| 27 |
+
init_distributed_runtime()
|
| 28 |
+
from llamafactory.train.tuner import run_exp
|
| 29 |
+
|
| 30 |
+
run_exp()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == "__main__":
|
| 34 |
+
main()
|