| 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 | |
| 18 | from dataclasses import asdict, dataclass, field, fields |
| 19 | from typing import Any, Literal, Optional, Union |
| 20 | |
| 21 | import torch |
| 22 | from typing_extensions import Self |
| 23 | |
| 24 | from ..network import AttentionFunction, RopeScaling |
| 25 | |
| 26 | |
| 27 | @dataclass |
| 28 | class BaseModelArguments: |
| 29 | r"""Arguments pertaining to the model.""" |
| 30 | |
| 31 | model_name_or_path: Optional[str] = field( |
| 32 | default=None, |
| 33 | metadata={ |
| 34 | "help": "Path to the model weight or identifier from huggingface.co/models or modelscope.cn/models." |
| 35 | }, |
| 36 | ) |
| 37 | cache_dir: Optional[str] = field( |
| 38 | default=None, |
| 39 | metadata={ |
| 40 | "help": "Where to store the pre-trained models downloaded from huggingface.co or modelscope.cn." |
| 41 | }, |
| 42 | ) |
| 43 | use_fast_tokenizer: bool = field( |
| 44 | default=True, |
| 45 | metadata={ |
| 46 | "help": "Whether or not to use one of the fast tokenizer (backed by the tokenizers library)." |
| 47 | }, |
| 48 | ) |
| 49 | resize_vocab: bool = field( |
| 50 | default=False, |
| 51 | metadata={ |
| 52 | "help": "Whether or not to resize the tokenizer vocab and the embedding layers." |
| 53 | }, |
| 54 | ) |
| 55 | split_special_tokens: bool = field( |
| 56 | default=False, |
| 57 | metadata={ |
| 58 | "help": "Whether or not the special tokens should be split during the tokenization process." |
| 59 | }, |
| 60 | ) |
| 61 | add_tokens: Optional[str] = field( |
| 62 | default=None, |
| 63 | metadata={ |
| 64 | "help": "Non-special tokens to be added into the tokenizer. Use commas to separate multiple tokens." |
| 65 | }, |
| 66 | ) |
| 67 | add_special_tokens: Optional[str] = field( |
| 68 | default=None, |
| 69 | metadata={ |
| 70 | "help": "Special tokens to be added into the tokenizer. Use commas to separate multiple tokens." |
| 71 | }, |
| 72 | ) |
| 73 | model_revision: str = field( |
| 74 | default="main", |
| 75 | metadata={ |
| 76 | "help": "The specific model version to use (can be a branch name, tag name or commit id)." |
| 77 | }, |
| 78 | ) |
| 79 | low_cpu_mem_usage: bool = field( |
| 80 | default=True, |
| 81 | metadata={"help": "Whether or not to use memory-efficient model loading."}, |
| 82 | ) |
| 83 | rope_scaling: Optional[RopeScaling] = field( |
| 84 | default=None, |
| 85 | metadata={ |
| 86 | "help": "Which scaling strategy should be adopted for the RoPE embeddings." |
| 87 | }, |
| 88 | ) |
| 89 | flash_attn: AttentionFunction = field( |
| 90 | default=AttentionFunction.AUTO, |
| 91 | metadata={"help": "Enable FlashAttention for faster training and inference."}, |
| 92 | ) |
| 93 | disable_gradient_checkpointing: bool = field( |
| 94 | default=False, |
| 95 | metadata={"help": "Whether or not to disable gradient checkpointing."}, |
| 96 | ) |
| 97 | use_reentrant_gc: bool = field( |
| 98 | default=True, |
| 99 | metadata={"help": "Whether or not to use reentrant gradient checkpointing."}, |
| 100 | ) |
| 101 | train_from_scratch: bool = field( |
| 102 | default=False, |
| 103 | metadata={"help": "Whether or not to randomly initialize the model weights."}, |
| 104 | ) |
| 105 | offload_folder: str = field( |
| 106 | default="offload", |
| 107 | metadata={"help": "Path to offload model weights."}, |
| 108 | ) |
| 109 | use_cache: bool = field( |
| 110 | default=True, |
| 111 | metadata={"help": "Whether or not to use KV cache in generation."}, |
| 112 | ) |
| 113 | infer_dtype: Literal["auto", "float16", "bfloat16", "float32"] = field( |
| 114 | default="auto", |
| 115 | metadata={"help": "Data type for model weights and activations at inference."}, |
| 116 | ) |
| 117 | hf_hub_token: Optional[str] = field( |
| 118 | default=None, |
| 119 | metadata={"help": "Auth token to log in with Hugging Face Hub."}, |
| 120 | ) |
| 121 | ms_hub_token: Optional[str] = field( |
| 122 | default=None, |
| 123 | metadata={"help": "Auth token to log in with ModelScope Hub."}, |
| 124 | ) |
| 125 | print_param_status: bool = field( |
| 126 | default=False, |
| 127 | metadata={ |
| 128 | "help": "For debugging purposes, print the status of the parameters in the model." |
| 129 | }, |
| 130 | ) |
| 131 | trust_remote_code: bool = field( |
| 132 | default=False, |
| 133 | metadata={ |
| 134 | "help": "Whether to trust the execution of code from datasets/models defined on the Hub or not." |
| 135 | }, |
| 136 | ) |
| 137 | |
| 138 | def __post_init__(self): |
| 139 | if self.model_name_or_path is None: |
| 140 | raise ValueError("Please provide `model_name_or_path`.") |
| 141 | |
| 142 | if self.split_special_tokens and self.use_fast_tokenizer: |
| 143 | raise ValueError( |
| 144 | "`split_special_tokens` is only supported for slow tokenizers." |
| 145 | ) |
| 146 | |
| 147 | if self.add_tokens is not None: # support multiple tokens |
| 148 | self.add_tokens = [token.strip() for token in self.add_tokens.split(",")] |
| 149 | |
| 150 | if self.add_special_tokens is not None: # support multiple special tokens |
| 151 | self.add_special_tokens = [ |
| 152 | token.strip() for token in self.add_special_tokens.split(",") |
| 153 | ] |
| 154 | |
| 155 | |
| 156 | @dataclass |
| 157 | class ExportArguments: |
| 158 | r"""Arguments pertaining to the model export.""" |
| 159 | |
| 160 | export_dir: Optional[str] = field( |
| 161 | default=None, |
| 162 | metadata={"help": "Path to the directory to save the exported model."}, |
| 163 | ) |
| 164 | export_size: int = field( |
| 165 | default=5, |
| 166 | metadata={"help": "The file shard size (in GB) of the exported model."}, |
| 167 | ) |
| 168 | export_device: Literal["cpu", "auto"] = field( |
| 169 | default="cpu", |
| 170 | metadata={ |
| 171 | "help": "The device used in model export, use `auto` to accelerate exporting." |
| 172 | }, |
| 173 | ) |
| 174 | |
| 175 | |
| 176 | @dataclass |
| 177 | class ModelArguments( |
| 178 | ExportArguments, |
| 179 | BaseModelArguments, |
| 180 | ): |
| 181 | r"""Arguments pertaining to which model/config/tokenizer we are going to fine-tune or infer. |
| 182 | |
| 183 | The class on the most right will be displayed first. |
| 184 | """ |
| 185 | |
| 186 | compute_dtype: Optional[torch.dtype] = field( |
| 187 | default=None, |
| 188 | init=False, |
| 189 | metadata={ |
| 190 | "help": "Torch data type for computing model outputs, derived from `fp/bf16`. Do not specify it." |
| 191 | }, |
| 192 | ) |
| 193 | device_map: Optional[Union[str, dict[str, Any]]] = field( |
| 194 | default=None, |
| 195 | init=False, |
| 196 | metadata={ |
| 197 | "help": "Device map for model placement, derived from training stage. Do not specify it." |
| 198 | }, |
| 199 | ) |
| 200 | model_max_length: Optional[int] = field( |
| 201 | default=None, |
| 202 | init=False, |
| 203 | metadata={ |
| 204 | "help": "The maximum input length for model, derived from `cutoff_len`. Do not specify it." |
| 205 | }, |
| 206 | ) |
| 207 | block_diag_attn: bool = field( |
| 208 | default=False, |
| 209 | init=False, |
| 210 | metadata={ |
| 211 | "help": "Whether use block diag attention or not, derived from `neat_packing`. Do not specify it." |
| 212 | }, |
| 213 | ) |
| 214 | |
| 215 | def __post_init__(self): |
| 216 | BaseModelArguments.__post_init__(self) |
| 217 | |
| 218 | @classmethod |
| 219 | def copyfrom(cls, source: "Self", **kwargs) -> "Self": |
| 220 | init_args, lazy_args = {}, {} |
| 221 | for attr in fields(source): |
| 222 | if attr.init: |
| 223 | init_args[attr.name] = getattr(source, attr.name) |
| 224 | else: |
| 225 | lazy_args[attr.name] = getattr(source, attr.name) |
| 226 | |
| 227 | init_args.update(kwargs) |
| 228 | result = cls(**init_args) |
| 229 | for name, value in lazy_args.items(): |
| 230 | setattr(result, name, value) |
| 231 | |
| 232 | return result |
| 233 | |
| 234 | def to_dict(self) -> dict[str, Any]: |
| 235 | args = asdict(self) |
| 236 | args = { |
| 237 | k: f"<{k.upper()}>" if k.endswith("token") else v for k, v in args.items() |
| 238 | } |
| 239 | return args |