Spaces:
Paused
Paused
File size: 12,241 Bytes
2f5127c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 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 |
# Copyright 2020-2025 The HuggingFace Team. All rights reserved.
#
# 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 os
import sys
from dataclasses import dataclass, field
from typing import Optional
from transformers import is_bitsandbytes_available
from ..core import flatten_dict
@dataclass
class DDPOConfig:
r"""
Configuration class for the [`DDPOTrainer`].
Using [`~transformers.HfArgumentParser`] we can turn this class into
[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
command line.
Parameters:
exp_name (`str`, *optional*, defaults to `os.path.basename(sys.argv[0])[: -len(".py")]`):
Name of this experiment (by default is the file name without the extension name).
run_name (`str`, *optional*, defaults to `""`):
Name of this run.
seed (`int`, *optional*, defaults to `0`):
Random seed.
log_with (`Literal["wandb", "tensorboard"]]` or `None`, *optional*, defaults to `None`):
Log with either 'wandb' or 'tensorboard', check
https://huggingface.co/docs/accelerate/usage_guides/tracking for more details.
tracker_kwargs (`Dict`, *optional*, defaults to `{}`):
Keyword arguments for the tracker (e.g. wandb_project).
accelerator_kwargs (`Dict`, *optional*, defaults to `{}`):
Keyword arguments for the accelerator.
project_kwargs (`Dict`, *optional*, defaults to `{}`):
Keyword arguments for the accelerator project config (e.g. `logging_dir`).
tracker_project_name (`str`, *optional*, defaults to `"trl"`):
Name of project to use for tracking.
logdir (`str`, *optional*, defaults to `"logs"`):
Top-level logging directory for checkpoint saving.
num_epochs (`int`, *optional*, defaults to `100`):
Number of epochs to train.
save_freq (`int`, *optional*, defaults to `1`):
Number of epochs between saving model checkpoints.
num_checkpoint_limit (`int`, *optional*, defaults to `5`):
Number of checkpoints to keep before overwriting old ones.
mixed_precision (`str`, *optional*, defaults to `"fp16"`):
Mixed precision training.
allow_tf32 (`bool`, *optional*, defaults to `True`):
Allow `tf32` on Ampere GPUs.
resume_from (`str`, *optional*, defaults to `""`):
Resume training from a checkpoint.
sample_num_steps (`int`, *optional*, defaults to `50`):
Number of sampler inference steps.
sample_eta (`float`, *optional*, defaults to `1.0`):
Eta parameter for the DDIM sampler.
sample_guidance_scale (`float`, *optional*, defaults to `5.0`):
Classifier-free guidance weight.
sample_batch_size (`int`, *optional*, defaults to `1`):
Batch size (per GPU) to use for sampling.
sample_num_batches_per_epoch (`int`, *optional*, defaults to `2`):
Number of batches to sample per epoch.
train_batch_size (`int`, *optional*, defaults to `1`):
Batch size (per GPU) to use for training.
train_use_8bit_adam (`bool`, *optional*, defaults to `False`):
Use 8bit Adam optimizer from bitsandbytes.
train_learning_rate (`float`, *optional*, defaults to `3e-4`):
Learning rate.
train_adam_beta1 (`float`, *optional*, defaults to `0.9`):
Adam beta1.
train_adam_beta2 (`float`, *optional*, defaults to `0.999`):
Adam beta2.
train_adam_weight_decay (`float`, *optional*, defaults to `1e-4`):
Adam weight decay.
train_adam_epsilon (`float`, *optional*, defaults to `1e-8`):
Adam epsilon.
train_gradient_accumulation_steps (`int`, *optional*, defaults to `1`):
Number of gradient accumulation steps.
train_max_grad_norm (`float`, *optional*, defaults to `1.0`):
Maximum gradient norm for gradient clipping.
train_num_inner_epochs (`int`, *optional*, defaults to `1`):
Number of inner epochs per outer epoch.
train_cfg (`bool`, *optional*, defaults to `True`):
Whether to use classifier-free guidance during training.
train_adv_clip_max (`float`, *optional*, defaults to `5.0`):
Clip advantages to the range.
train_clip_range (`float`, *optional*, defaults to `1e-4`):
PPO clip range.
train_timestep_fraction (`float`, *optional*, defaults to `1.0`):
Fraction of timesteps to train on.
per_prompt_stat_tracking (`bool`, *optional*, defaults to `False`):
Whether to track statistics for each prompt separately.
per_prompt_stat_tracking_buffer_size (`int`, *optional*, defaults to `16`):
Number of reward values to store in the buffer for each prompt.
per_prompt_stat_tracking_min_count (`int`, *optional*, defaults to `16`):
Minimum number of reward values to store in the buffer.
async_reward_computation (`bool`, *optional*, defaults to `False`):
Whether to compute rewards asynchronously.
max_workers (`int`, *optional*, defaults to `2`):
Maximum number of workers to use for async reward computation.
negative_prompts (`str`, *optional*, defaults to `""`):
Comma-separated list of prompts to use as negative examples.
push_to_hub (`bool`, *optional*, defaults to `False`):
Whether to push the final model checkpoint to the Hub.
"""
exp_name: str = field(
default=os.path.basename(sys.argv[0])[: -len(".py")],
metadata={"help": "Name of this experiment (by default is the file name without the extension name)."},
)
run_name: str = field(
default="",
metadata={"help": "Name of this run."},
)
seed: int = field(
default=0,
metadata={"help": "Random seed."},
)
log_with: Optional[str] = field(
default=None,
metadata={
"help": "Log with either 'wandb' or 'tensorboard'.",
"choices": ["wandb", "tensorboard"],
},
)
tracker_kwargs: dict = field(
default_factory=dict,
metadata={"help": "Keyword arguments for the tracker (e.g. wandb_project)."},
)
accelerator_kwargs: dict = field(
default_factory=dict,
metadata={"help": "Keyword arguments for the accelerator."},
)
project_kwargs: dict = field(
default_factory=dict,
metadata={"help": "Keyword arguments for the accelerator project config (e.g. `logging_dir`)."},
)
tracker_project_name: str = field(
default="trl",
metadata={"help": "Name of project to use for tracking."},
)
logdir: str = field(
default="logs",
metadata={"help": "Top-level logging directory for checkpoint saving."},
)
num_epochs: int = field(
default=100,
metadata={"help": "Number of epochs to train."},
)
save_freq: int = field(
default=1,
metadata={"help": "Number of epochs between saving model checkpoints."},
)
num_checkpoint_limit: int = field(
default=5,
metadata={"help": "Number of checkpoints to keep before overwriting old ones."},
)
mixed_precision: str = field(
default="fp16",
metadata={"help": "Mixed precision training."},
)
allow_tf32: bool = field(
default=True,
metadata={"help": "Allow `tf32` on Ampere GPUs."},
)
resume_from: str = field(
default="",
metadata={"help": "Resume training from a checkpoint."},
)
sample_num_steps: int = field(
default=50,
metadata={"help": "Number of sampler inference steps."},
)
sample_eta: float = field(
default=1.0,
metadata={"help": "Eta parameter for the DDIM sampler."},
)
sample_guidance_scale: float = field(
default=5.0,
metadata={"help": "Classifier-free guidance weight."},
)
sample_batch_size: int = field(
default=1,
metadata={"help": "Batch size (per GPU) to use for sampling."},
)
sample_num_batches_per_epoch: int = field(
default=2,
metadata={"help": "Number of batches to sample per epoch."},
)
train_batch_size: int = field(
default=1,
metadata={"help": "Batch size (per GPU) to use for training."},
)
train_use_8bit_adam: bool = field(
default=False,
metadata={"help": "Use 8bit Adam optimizer from bitsandbytes."},
)
train_learning_rate: float = field(
default=3e-4,
metadata={"help": "Learning rate."},
)
train_adam_beta1: float = field(
default=0.9,
metadata={"help": "Adam beta1."},
)
train_adam_beta2: float = field(
default=0.999,
metadata={"help": "Adam beta2."},
)
train_adam_weight_decay: float = field(
default=1e-4,
metadata={"help": "Adam weight decay."},
)
train_adam_epsilon: float = field(
default=1e-8,
metadata={"help": "Adam epsilon."},
)
train_gradient_accumulation_steps: int = field(
default=1,
metadata={"help": "Number of gradient accumulation steps."},
)
train_max_grad_norm: float = field(
default=1.0,
metadata={"help": "Maximum gradient norm for gradient clipping."},
)
train_num_inner_epochs: int = field(
default=1,
metadata={"help": "Number of inner epochs per outer epoch."},
)
train_cfg: bool = field(
default=True,
metadata={"help": "Whether to use classifier-free guidance during training."},
)
train_adv_clip_max: float = field(
default=5.0,
metadata={"help": "Clip advantages to the range."},
)
train_clip_range: float = field(
default=1e-4,
metadata={"help": "PPO clip range."},
)
train_timestep_fraction: float = field(
default=1.0,
metadata={"help": "Fraction of timesteps to train on."},
)
per_prompt_stat_tracking: bool = field(
default=False,
metadata={"help": "Whether to track statistics for each prompt separately."},
)
per_prompt_stat_tracking_buffer_size: int = field(
default=16,
metadata={"help": "Number of reward values to store in the buffer for each prompt."},
)
per_prompt_stat_tracking_min_count: int = field(
default=16,
metadata={"help": "Minimum number of reward values to store in the buffer."},
)
async_reward_computation: bool = field(
default=False,
metadata={"help": "Whether to compute rewards asynchronously."},
)
max_workers: int = field(
default=2,
metadata={"help": "Maximum number of workers to use for async reward computation."},
)
negative_prompts: str = field(
default="",
metadata={"help": "Comma-separated list of prompts to use as negative examples."},
)
push_to_hub: bool = field(
default=False,
metadata={"help": "Whether to push the final model checkpoint to the Hub."},
)
def to_dict(self):
output_dict = {}
for key, value in self.__dict__.items():
output_dict[key] = value
return flatten_dict(output_dict)
def __post_init__(self):
if self.train_use_8bit_adam and not is_bitsandbytes_available():
raise ImportError(
"You need to install bitsandbytes to use 8bit Adam. "
"You can install it with `pip install bitsandbytes`."
)
|