kyr commited on
Delete grpo_trainer.py
Browse files- grpo_trainer.py +0 -863
grpo_trainer.py
DELETED
|
@@ -1,863 +0,0 @@
|
|
| 1 |
-
# Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 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 |
-
import os
|
| 16 |
-
import textwrap
|
| 17 |
-
from collections import defaultdict
|
| 18 |
-
from typing import Any, Callable, Optional, Union, Sized
|
| 19 |
-
|
| 20 |
-
import torch
|
| 21 |
-
import torch.utils.data
|
| 22 |
-
import transformers
|
| 23 |
-
from datasets import Dataset, IterableDataset
|
| 24 |
-
from packaging import version
|
| 25 |
-
from transformers import (
|
| 26 |
-
AriaForConditionalGeneration,
|
| 27 |
-
AriaProcessor,
|
| 28 |
-
AutoModelForCausalLM,
|
| 29 |
-
AutoModelForSequenceClassification,
|
| 30 |
-
AutoProcessor,
|
| 31 |
-
AutoTokenizer,
|
| 32 |
-
GenerationConfig,
|
| 33 |
-
PreTrainedModel,
|
| 34 |
-
PreTrainedTokenizerBase,
|
| 35 |
-
Qwen2VLForConditionalGeneration,
|
| 36 |
-
Qwen2_5_VLForConditionalGeneration,
|
| 37 |
-
Trainer,
|
| 38 |
-
TrainerCallback,
|
| 39 |
-
is_wandb_available,
|
| 40 |
-
)
|
| 41 |
-
from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
|
| 42 |
-
from transformers.utils import is_peft_available
|
| 43 |
-
|
| 44 |
-
from trl.data_utils import apply_chat_template, is_conversational, maybe_apply_chat_template
|
| 45 |
-
from trl.models import create_reference_model, prepare_deepspeed, unwrap_model_for_generation
|
| 46 |
-
from trl.trainer.grpo_config import GRPOConfig
|
| 47 |
-
from trl.trainer.utils import generate_model_card, get_comet_experiment_url
|
| 48 |
-
# from trl import GRPOTrainer
|
| 49 |
-
|
| 50 |
-
from accelerate.utils import is_peft_model, set_seed
|
| 51 |
-
import PIL.Image
|
| 52 |
-
|
| 53 |
-
import copy
|
| 54 |
-
from torch.utils.data import Sampler
|
| 55 |
-
import warnings
|
| 56 |
-
|
| 57 |
-
if is_peft_available():
|
| 58 |
-
from peft import PeftConfig, get_peft_model
|
| 59 |
-
|
| 60 |
-
if is_wandb_available():
|
| 61 |
-
import wandb
|
| 62 |
-
|
| 63 |
-
from open_r1.vlm_modules.vlm_module import VLMBaseModule
|
| 64 |
-
# What we call a reward function is a callable that takes a list of prompts and completions and returns a list of
|
| 65 |
-
# rewards. When it's a string, it's a model ID, so it's loaded as a pretrained model.
|
| 66 |
-
RewardFunc = Union[str, PreTrainedModel, Callable[[list, list], list[float]]]
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
class RepeatRandomSampler(Sampler):
|
| 70 |
-
"""
|
| 71 |
-
Sampler that repeats the indices of a dataset in a structured manner.
|
| 72 |
-
|
| 73 |
-
Args:
|
| 74 |
-
data_source (`Sized`):
|
| 75 |
-
Dataset to sample from.
|
| 76 |
-
mini_repeat_count (`int`):
|
| 77 |
-
Number of times to repeat each index per batch.
|
| 78 |
-
batch_size (`int`, *optional*, defaults to `1`):
|
| 79 |
-
Number of unique indices per batch.
|
| 80 |
-
repeat_count (`int`, *optional*, defaults to `1`):
|
| 81 |
-
Number of times to repeat the full sampling process.
|
| 82 |
-
seed (`int` or `None`, *optional*, defaults to `None`):
|
| 83 |
-
Random seed for reproducibility.
|
| 84 |
-
"""
|
| 85 |
-
|
| 86 |
-
def __init__(
|
| 87 |
-
self,
|
| 88 |
-
data_source: Sized,
|
| 89 |
-
mini_repeat_count: int,
|
| 90 |
-
batch_size: int = 1,
|
| 91 |
-
repeat_count: int = 1,
|
| 92 |
-
seed: Optional[int] = None,
|
| 93 |
-
):
|
| 94 |
-
self.data_source = data_source
|
| 95 |
-
self.mini_repeat_count = mini_repeat_count
|
| 96 |
-
self.batch_size = batch_size
|
| 97 |
-
self.repeat_count = repeat_count
|
| 98 |
-
self.num_samples = len(data_source)
|
| 99 |
-
self.seed = seed
|
| 100 |
-
self.generator = torch.Generator()
|
| 101 |
-
if seed is not None:
|
| 102 |
-
self.generator.manual_seed(seed)
|
| 103 |
-
|
| 104 |
-
def __iter__(self):
|
| 105 |
-
indexes = torch.randperm(self.num_samples, generator=self.generator).tolist()
|
| 106 |
-
indexes = [indexes[i : i + self.batch_size] for i in range(0, len(indexes), self.batch_size)]
|
| 107 |
-
indexes = [chunk for chunk in indexes if len(chunk) == self.batch_size]
|
| 108 |
-
|
| 109 |
-
for chunk in indexes:
|
| 110 |
-
for _ in range(self.repeat_count):
|
| 111 |
-
for index in chunk:
|
| 112 |
-
for _ in range(self.mini_repeat_count):
|
| 113 |
-
yield index
|
| 114 |
-
|
| 115 |
-
def __len__(self) -> int:
|
| 116 |
-
return self.num_samples * self.mini_repeat_count * self.repeat_count
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
class VLMGRPOTrainer(Trainer):
|
| 120 |
-
"""
|
| 121 |
-
Trainer for the Group Relative Policy Optimization (GRPO) method. This algorithm was initially proposed in the
|
| 122 |
-
paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300).
|
| 123 |
-
|
| 124 |
-
Example:
|
| 125 |
-
|
| 126 |
-
```python
|
| 127 |
-
from datasets import load_dataset
|
| 128 |
-
from trl import GRPOTrainer
|
| 129 |
-
|
| 130 |
-
dataset = load_dataset("trl-lib/tldr", split="train")
|
| 131 |
-
|
| 132 |
-
trainer = GRPOTrainer(
|
| 133 |
-
model="Qwen/Qwen2-0.5B-Instruct",
|
| 134 |
-
reward_funcs="weqweasdas/RM-Gemma-2B",
|
| 135 |
-
train_dataset=dataset,
|
| 136 |
-
)
|
| 137 |
-
|
| 138 |
-
trainer.train()
|
| 139 |
-
```
|
| 140 |
-
|
| 141 |
-
Args:
|
| 142 |
-
model (`Union[str, PreTrainedModel]`):
|
| 143 |
-
Model to be trained. Can be either:
|
| 144 |
-
|
| 145 |
-
- A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or
|
| 146 |
-
a path to a *directory* containing model weights saved using
|
| 147 |
-
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is
|
| 148 |
-
loaded using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keywork arguments
|
| 149 |
-
in `args.model_init_kwargs`.
|
| 150 |
-
- A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
|
| 151 |
-
reward_funcs (`Union[RewardFunc, list[RewardFunc]]`):
|
| 152 |
-
Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
|
| 153 |
-
functions with the prompts and completions and sum the rewards. Can be either:
|
| 154 |
-
|
| 155 |
-
- A single reward function, such as:
|
| 156 |
-
- A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a
|
| 157 |
-
path to a *directory* containing model weights saved using
|
| 158 |
-
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
| 159 |
-
using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the
|
| 160 |
-
keyword arguments in `args.model_init_kwargs`.
|
| 161 |
-
- A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported.
|
| 162 |
-
- A custom reward function: The function is provided with the prompts and the generated completions,
|
| 163 |
-
plus any additional columns in the dataset. It should return a list of rewards. For more details, see
|
| 164 |
-
[Using a custom reward function](#using-a-custom-reward-function).
|
| 165 |
-
- A list of reward functions, where each item can independently be any of the above types. Mixing different
|
| 166 |
-
types within the list (e.g., a string model ID and a custom reward function) is allowed.
|
| 167 |
-
args ([`GRPOConfig`], *optional*, defaults to `None`):
|
| 168 |
-
Configuration for this trainer. If `None`, a default configuration is used.
|
| 169 |
-
train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
|
| 170 |
-
Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is
|
| 171 |
-
ignored. The format of the samples can be either:
|
| 172 |
-
|
| 173 |
-
- [Standard](dataset_formats#standard): Each sample contains plain text.
|
| 174 |
-
- [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
|
| 175 |
-
and content).
|
| 176 |
-
eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Union[Dataset, IterableDataset]]`):
|
| 177 |
-
Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
|
| 178 |
-
processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*, defaults to `None`):
|
| 179 |
-
Processing class used to process the data. The padding side must be set to "left". If `None`, the
|
| 180 |
-
processing class is loaded from the model's name with [`~transformers.AutoTokenizer.from_pretrained`].
|
| 181 |
-
reward_processing_classes (`Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]`, *optional*, defaults to `None`):
|
| 182 |
-
Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
|
| 183 |
-
|
| 184 |
-
- A single processing class: Used when `reward_funcs` contains only one reward function.
|
| 185 |
-
- A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
|
| 186 |
-
If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is
|
| 187 |
-
`None`, the tokenizer for the model is automatically loaded using [`~transformers.AutoTokenizer.from_pretrained`].
|
| 188 |
-
For elements in `reward_funcs` that are custom reward functions (not [`~transformers.PreTrainedModel`]),
|
| 189 |
-
the corresponding entries in `reward_processing_classes` are ignored.
|
| 190 |
-
callbacks (list of [`~transformers.TrainerCallback`], *optional*, defaults to `None`):
|
| 191 |
-
List of callbacks to customize the training loop. Will add those to the list of default callbacks
|
| 192 |
-
detailed in [here](https://huggingface.co/docs/transformers/main_classes/callback).
|
| 193 |
-
|
| 194 |
-
If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
|
| 195 |
-
method.
|
| 196 |
-
optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`):
|
| 197 |
-
A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your
|
| 198 |
-
model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`.
|
| 199 |
-
peft_config ([`~peft.PeftConfig`], *optional*, defaults to `None`):
|
| 200 |
-
PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
|
| 201 |
-
"""
|
| 202 |
-
|
| 203 |
-
def __init__(
|
| 204 |
-
self,
|
| 205 |
-
model: Union[str, PreTrainedModel],
|
| 206 |
-
reward_funcs: Union[RewardFunc, list[RewardFunc]],
|
| 207 |
-
args: GRPOConfig = None,
|
| 208 |
-
vlm_module: VLMBaseModule = None,
|
| 209 |
-
train_dataset: Optional[Union[Dataset, IterableDataset]] = None,
|
| 210 |
-
eval_dataset: Optional[Union[Dataset, IterableDataset, dict[str, Union[Dataset, IterableDataset]]]] = None,
|
| 211 |
-
processing_class: Optional[PreTrainedTokenizerBase] = None,
|
| 212 |
-
reward_processing_classes: Optional[Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]] = None,
|
| 213 |
-
callbacks: Optional[list[TrainerCallback]] = None,
|
| 214 |
-
optimizers: tuple[Optional[torch.optim.Optimizer], Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None),
|
| 215 |
-
peft_config: Optional["PeftConfig"] = None,
|
| 216 |
-
freeze_vision_modules: Optional[bool] = False,
|
| 217 |
-
attn_implementation: str = "flash_attention_2",
|
| 218 |
-
torch_dtype: str = "bfloat16",
|
| 219 |
-
**kwargs,
|
| 220 |
-
):
|
| 221 |
-
# Args
|
| 222 |
-
if args is None:
|
| 223 |
-
model_name = model if isinstance(model, str) else model.config._name_or_path
|
| 224 |
-
model_name = model_name.split("/")[-1]
|
| 225 |
-
args = GRPOConfig(f"{model_name}-GRPO")
|
| 226 |
-
|
| 227 |
-
self.vlm_module = vlm_module
|
| 228 |
-
|
| 229 |
-
# Models
|
| 230 |
-
# Trained model
|
| 231 |
-
model_init_kwargs = args.model_init_kwargs or {}
|
| 232 |
-
# FIXME
|
| 233 |
-
# Remember to modify it in the invernvl
|
| 234 |
-
model_init_kwargs["attn_implementation"] = attn_implementation
|
| 235 |
-
if model_init_kwargs.get("torch_dtype") is None:
|
| 236 |
-
model_init_kwargs["torch_dtype"] = torch_dtype
|
| 237 |
-
|
| 238 |
-
assert isinstance(model, str), "model must be a string in the current implementation"
|
| 239 |
-
model_id = model
|
| 240 |
-
torch_dtype = model_init_kwargs.get("torch_dtype")
|
| 241 |
-
if isinstance(torch_dtype, torch.dtype) or torch_dtype == "auto" or torch_dtype is None:
|
| 242 |
-
pass # torch_dtype is already a torch.dtype or "auto" or None
|
| 243 |
-
elif isinstance(torch_dtype, str): # it's a str, but not "auto"
|
| 244 |
-
torch_dtype = getattr(torch, torch_dtype)
|
| 245 |
-
else:
|
| 246 |
-
raise ValueError(
|
| 247 |
-
"Invalid `torch_dtype` passed to `GRPOConfig`. Expected either 'auto' or a string representing "
|
| 248 |
-
f"a `torch.dtype` (e.g., 'float32'), but got {torch_dtype}."
|
| 249 |
-
)
|
| 250 |
-
# Disable caching if gradient checkpointing is enabled (not supported)
|
| 251 |
-
model_init_kwargs["use_cache"] = (
|
| 252 |
-
False if args.gradient_checkpointing else model_init_kwargs.get("use_cache")
|
| 253 |
-
)
|
| 254 |
-
model_cls = self.vlm_module.get_model_class(model_id, model_init_kwargs)
|
| 255 |
-
model = model_cls.from_pretrained(model_id, **model_init_kwargs)
|
| 256 |
-
|
| 257 |
-
# LoRA
|
| 258 |
-
self.vision_modules_keywords = self.vlm_module.get_vision_modules_keywords()
|
| 259 |
-
if peft_config is not None:
|
| 260 |
-
print("Applying LoRA...")
|
| 261 |
-
def find_all_linear_names(model, multimodal_keywords):
|
| 262 |
-
cls = torch.nn.Linear
|
| 263 |
-
lora_module_names = set()
|
| 264 |
-
for name, module in model.named_modules():
|
| 265 |
-
# LoRA is not applied to the vision modules
|
| 266 |
-
if any(mm_keyword in name for mm_keyword in multimodal_keywords):
|
| 267 |
-
continue
|
| 268 |
-
if isinstance(module, cls):
|
| 269 |
-
lora_module_names.add(name)
|
| 270 |
-
for m in lora_module_names: # needed for 16-bit
|
| 271 |
-
if "embed_tokens" in m:
|
| 272 |
-
lora_module_names.remove(m)
|
| 273 |
-
return list(lora_module_names)
|
| 274 |
-
target_modules = find_all_linear_names(model, self.vision_modules_keywords)
|
| 275 |
-
peft_config.target_modules = target_modules
|
| 276 |
-
model = get_peft_model(model, peft_config)
|
| 277 |
-
|
| 278 |
-
# Freeze vision modules
|
| 279 |
-
if freeze_vision_modules:
|
| 280 |
-
print("Freezing vision modules...")
|
| 281 |
-
for n, p in model.named_parameters():
|
| 282 |
-
if any(keyword in n for keyword in self.vision_modules_keywords):
|
| 283 |
-
p.requires_grad = False
|
| 284 |
-
# Compute the number of trainable parameters and print the parameter that is trainable
|
| 285 |
-
trainable_params = [p for p in model.parameters() if p.requires_grad]
|
| 286 |
-
total_params = sum(p.numel() for p in trainable_params)
|
| 287 |
-
# for n, p in model.named_parameters():
|
| 288 |
-
# if p.requires_grad:
|
| 289 |
-
# print(n, p.shape)
|
| 290 |
-
print(f"Total trainable parameters: {total_params}")
|
| 291 |
-
|
| 292 |
-
# Enable gradient checkpointing if requested
|
| 293 |
-
if args.gradient_checkpointing:
|
| 294 |
-
model = self._enable_gradient_checkpointing(model, args)
|
| 295 |
-
|
| 296 |
-
# Reference model
|
| 297 |
-
self.beta = args.beta
|
| 298 |
-
if self.beta == 0.0:
|
| 299 |
-
# If beta is 0.0, the reference model is not needed
|
| 300 |
-
self.ref_model = None
|
| 301 |
-
elif is_deepspeed_zero3_enabled():
|
| 302 |
-
self.ref_model = model_cls.from_pretrained(model_id, **model_init_kwargs)
|
| 303 |
-
elif is_peft_model(model):
|
| 304 |
-
# If PEFT is used, the reference model is not needed since the adapter can be disabled
|
| 305 |
-
# to revert to the initial model.
|
| 306 |
-
self.ref_model = None
|
| 307 |
-
else:
|
| 308 |
-
# If PEFT configuration is not provided, create a reference model based on the initial model.
|
| 309 |
-
self.ref_model = create_reference_model(model)
|
| 310 |
-
|
| 311 |
-
# Processing class
|
| 312 |
-
if processing_class is None:
|
| 313 |
-
processing_cls = self.vlm_module.get_processing_class()
|
| 314 |
-
processing_class = processing_cls.from_pretrained(model_id, trust_remote_code=model_init_kwargs.get("trust_remote_code", None))
|
| 315 |
-
for component, processing_keyword in self.vlm_module.get_custom_processing_keywords():
|
| 316 |
-
if processing_keyword in kwargs:
|
| 317 |
-
# If we cannot find component in processing_class, return the processing_class itself
|
| 318 |
-
processing_component = getattr(processing_class, component, processing_class)
|
| 319 |
-
setattr(processing_component, processing_keyword, kwargs[processing_keyword])
|
| 320 |
-
if getattr(processing_class, "tokenizer", None) is not None:
|
| 321 |
-
pad_token_id = processing_class.tokenizer.pad_token_id
|
| 322 |
-
processing_class.pad_token_id = pad_token_id
|
| 323 |
-
processing_class.eos_token_id = processing_class.tokenizer.eos_token_id
|
| 324 |
-
else:
|
| 325 |
-
assert isinstance(processing_class, PreTrainedTokenizerBase), "processing_class must be an instance of PreTrainedTokenizerBase if it has no tokenizer attribute"
|
| 326 |
-
pad_token_id = processing_class.pad_token_id
|
| 327 |
-
|
| 328 |
-
self.vlm_module.post_model_init(model, processing_class)
|
| 329 |
-
self.vlm_module.post_model_init(self.ref_model, processing_class)
|
| 330 |
-
|
| 331 |
-
# Reward functions
|
| 332 |
-
if not isinstance(reward_funcs, list):
|
| 333 |
-
reward_funcs = [reward_funcs]
|
| 334 |
-
for i, reward_func in enumerate(reward_funcs):
|
| 335 |
-
if isinstance(reward_func, str):
|
| 336 |
-
reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained(
|
| 337 |
-
reward_func, num_labels=1, **model_init_kwargs
|
| 338 |
-
)
|
| 339 |
-
self.reward_funcs = reward_funcs
|
| 340 |
-
|
| 341 |
-
# Reward processing class
|
| 342 |
-
if reward_processing_classes is None:
|
| 343 |
-
reward_processing_classes = [None] * len(reward_funcs)
|
| 344 |
-
elif not isinstance(reward_processing_classes, list):
|
| 345 |
-
reward_processing_classes = [reward_processing_classes]
|
| 346 |
-
else:
|
| 347 |
-
if len(reward_processing_classes) != len(reward_funcs):
|
| 348 |
-
raise ValueError("The number of reward processing classes must match the number of reward functions.")
|
| 349 |
-
|
| 350 |
-
for i, (reward_processing_class, reward_func) in enumerate(zip(reward_processing_classes, reward_funcs)):
|
| 351 |
-
if isinstance(reward_func, PreTrainedModel):
|
| 352 |
-
if reward_processing_class is None:
|
| 353 |
-
reward_processing_class = AutoTokenizer.from_pretrained(reward_func.config._name_or_path)
|
| 354 |
-
if reward_processing_class.pad_token_id is None:
|
| 355 |
-
reward_processing_class.pad_token = reward_processing_class.eos_token
|
| 356 |
-
# The reward model computes the reward for the latest non-padded token in the input sequence.
|
| 357 |
-
# So it's important to set the pad token ID to the padding token ID of the processing class.
|
| 358 |
-
reward_func.config.pad_token_id = reward_processing_class.pad_token_id
|
| 359 |
-
reward_processing_classes[i] = reward_processing_class
|
| 360 |
-
self.reward_processing_classes = reward_processing_classes
|
| 361 |
-
|
| 362 |
-
# Data collator
|
| 363 |
-
def data_collator(features): # No data collation is needed in GRPO
|
| 364 |
-
return features
|
| 365 |
-
|
| 366 |
-
# Training arguments
|
| 367 |
-
self.max_prompt_length = args.max_prompt_length
|
| 368 |
-
self.max_prompt_length = None
|
| 369 |
-
if args.max_prompt_length is not None:
|
| 370 |
-
warnings.warn("Setting max_prompt_length is currently not supported, it has been set to None")
|
| 371 |
-
|
| 372 |
-
self.max_completion_length = args.max_completion_length # = |o_i| in the GRPO paper
|
| 373 |
-
self.num_generations = args.num_generations # = G in the GRPO paper
|
| 374 |
-
self.generation_config = GenerationConfig(
|
| 375 |
-
max_new_tokens=self.max_completion_length,
|
| 376 |
-
do_sample=True,
|
| 377 |
-
temperature=1,
|
| 378 |
-
pad_token_id=pad_token_id,
|
| 379 |
-
)
|
| 380 |
-
if hasattr(self.vlm_module, "get_eos_token_id"): # For InternVL
|
| 381 |
-
self.generation_config.eos_token_id = self.vlm_module.get_eos_token_id(processing_class)
|
| 382 |
-
self.beta = args.beta
|
| 383 |
-
self.epsilon_low = args.epsilon
|
| 384 |
-
self.epsilon_high = args.epsilon_high if args.epsilon_high is not None else args.epsilon
|
| 385 |
-
|
| 386 |
-
# Multi-step
|
| 387 |
-
self.num_iterations = args.num_iterations # = 𝜇 in the GRPO paper
|
| 388 |
-
# Tracks the number of iterations (forward + backward passes), including those within a gradient accumulation cycle
|
| 389 |
-
self._step = 0
|
| 390 |
-
# Buffer the batch to reuse generated outputs across multiple updates
|
| 391 |
-
self._buffered_inputs = [None] * args.gradient_accumulation_steps
|
| 392 |
-
|
| 393 |
-
# The trainer estimates the number of FLOPs (floating-point operations) using the number of elements in the
|
| 394 |
-
# input tensor associated with the key "input_ids". However, in GRPO, the sampled data does not include the
|
| 395 |
-
# "input_ids" key. Instead, the available keys is "prompt". As a result, the trainer issues the warning:
|
| 396 |
-
# "Could not estimate the number of tokens of the input, floating-point operations will not be computed." To
|
| 397 |
-
# suppress this warning, we set the "estimate_tokens" key in the model's "warnings_issued" dictionary to True.
|
| 398 |
-
# This acts as a flag to indicate that the warning has already been issued.
|
| 399 |
-
model.warnings_issued["estimate_tokens"] = True
|
| 400 |
-
|
| 401 |
-
# Initialize the metrics
|
| 402 |
-
self._metrics = defaultdict(list)
|
| 403 |
-
|
| 404 |
-
super().__init__(
|
| 405 |
-
model=model,
|
| 406 |
-
args=args,
|
| 407 |
-
data_collator=data_collator,
|
| 408 |
-
train_dataset=train_dataset,
|
| 409 |
-
eval_dataset=eval_dataset,
|
| 410 |
-
processing_class=processing_class,
|
| 411 |
-
callbacks=callbacks,
|
| 412 |
-
optimizers=optimizers,
|
| 413 |
-
)
|
| 414 |
-
|
| 415 |
-
# Check if the per_device_train/eval_batch_size * num processes can be divided by the number of generations
|
| 416 |
-
num_processes = self.accelerator.num_processes
|
| 417 |
-
global_batch_size = args.per_device_train_batch_size * num_processes
|
| 418 |
-
possible_values = [n_gen for n_gen in range(2, global_batch_size + 1) if (global_batch_size) % n_gen == 0]
|
| 419 |
-
if self.num_generations not in possible_values:
|
| 420 |
-
raise ValueError(
|
| 421 |
-
f"The global train batch size ({num_processes} x {args.per_device_train_batch_size}) must be evenly "
|
| 422 |
-
f"divisible by the number of generations per prompt ({self.num_generations}). Given the current train "
|
| 423 |
-
f"batch size, the valid values for the number of generations are: {possible_values}."
|
| 424 |
-
)
|
| 425 |
-
if self.args.eval_strategy != "no":
|
| 426 |
-
global_batch_size = args.per_device_eval_batch_size * num_processes
|
| 427 |
-
possible_values = [n_gen for n_gen in range(2, global_batch_size + 1) if (global_batch_size) % n_gen == 0]
|
| 428 |
-
if self.num_generations not in possible_values:
|
| 429 |
-
raise ValueError(
|
| 430 |
-
f"The global eval batch size ({num_processes} x {args.per_device_eval_batch_size}) must be evenly "
|
| 431 |
-
f"divisible by the number of generations per prompt ({self.num_generations}). Given the current "
|
| 432 |
-
f"eval batch size, the valid values for the number of generations are: {possible_values}."
|
| 433 |
-
)
|
| 434 |
-
|
| 435 |
-
# Ensure each process receives a unique seed to prevent duplicate completions when generating with
|
| 436 |
-
# transformers if num_generations exceeds per_device_train_batch_size. We could skip it if we use vLLM, but
|
| 437 |
-
# it's safer to set it in all cases.
|
| 438 |
-
set_seed(args.seed, device_specific=True)
|
| 439 |
-
|
| 440 |
-
# Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
|
| 441 |
-
# model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
|
| 442 |
-
# self.model_accepts_loss_kwargs to False to enable scaling.
|
| 443 |
-
self.model_accepts_loss_kwargs = False
|
| 444 |
-
|
| 445 |
-
if self.ref_model is not None:
|
| 446 |
-
# if self.is_deepspeed_enabled:
|
| 447 |
-
if is_deepspeed_zero3_enabled():
|
| 448 |
-
self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
|
| 449 |
-
else:
|
| 450 |
-
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
|
| 451 |
-
|
| 452 |
-
for i, reward_func in enumerate(self.reward_funcs):
|
| 453 |
-
if isinstance(reward_func, PreTrainedModel):
|
| 454 |
-
self.reward_funcs[i] = self.accelerator.prepare_model(reward_func, evaluation_mode=True)
|
| 455 |
-
|
| 456 |
-
def _enable_gradient_checkpointing(self, model: PreTrainedModel, args: GRPOConfig) -> PreTrainedModel:
|
| 457 |
-
"""Enables gradient checkpointing for the model."""
|
| 458 |
-
# Ensure use_cache is disabled
|
| 459 |
-
model.config.use_cache = False
|
| 460 |
-
|
| 461 |
-
# Enable gradient checkpointing on the base model for PEFT
|
| 462 |
-
if is_peft_model(model):
|
| 463 |
-
model.base_model.gradient_checkpointing_enable()
|
| 464 |
-
# Enable gradient checkpointing for non-PEFT models
|
| 465 |
-
else:
|
| 466 |
-
if getattr(model, "language_model", None) is not None:
|
| 467 |
-
# For InternVL; these operations are copied from the original training script of InternVL
|
| 468 |
-
model.language_model.config.use_cache = False
|
| 469 |
-
model.vision_model.gradient_checkpointing = True
|
| 470 |
-
model.vision_model.encoder.gradient_checkpointing = True
|
| 471 |
-
model.language_model._set_gradient_checkpointing()
|
| 472 |
-
# This line is necessary, otherwise the `model.gradient_checkpointing_enable()` will be executed during the training process, leading to an error since InternVL does not support this operation.
|
| 473 |
-
args.gradient_checkpointing = False
|
| 474 |
-
else:
|
| 475 |
-
model.gradient_checkpointing_enable()
|
| 476 |
-
|
| 477 |
-
gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
|
| 478 |
-
use_reentrant = (
|
| 479 |
-
"use_reentrant" not in gradient_checkpointing_kwargs or gradient_checkpointing_kwargs["use_reentrant"]
|
| 480 |
-
)
|
| 481 |
-
|
| 482 |
-
if use_reentrant:
|
| 483 |
-
model.enable_input_require_grads()
|
| 484 |
-
|
| 485 |
-
return model
|
| 486 |
-
|
| 487 |
-
def _set_signature_columns_if_needed(self):
|
| 488 |
-
# If `self.args.remove_unused_columns` is True, non-signature columns are removed.
|
| 489 |
-
# By default, this method sets `self._signature_columns` to the model's expected inputs.
|
| 490 |
-
# In GRPOTrainer, we preprocess data, so using the model's signature columns doesn't work.
|
| 491 |
-
# Instead, we set them to the columns expected by the `training_step` method, hence the override.
|
| 492 |
-
if self._signature_columns is None:
|
| 493 |
-
self._signature_columns = ["prompt"]
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
# Get the per-token log probabilities for the completions for the model and the reference model
|
| 497 |
-
def _get_per_token_logps(self, model, input_ids, attention_mask, **custom_multimodal_inputs):
|
| 498 |
-
logits = model(input_ids=input_ids, attention_mask=attention_mask, **custom_multimodal_inputs).logits # (B, L, V)
|
| 499 |
-
logits = logits[:, :-1, :] # (B, L-1, V), exclude the last logit: it corresponds to the next token pred
|
| 500 |
-
input_ids = input_ids[:, 1:] # (B, L-1), exclude the first input ID since we don't have logits for it
|
| 501 |
-
# Compute the log probabilities for the input tokens. Use a loop to reduce memory peak.
|
| 502 |
-
per_token_logps = []
|
| 503 |
-
for logits_row, input_ids_row in zip(logits, input_ids):
|
| 504 |
-
log_probs = logits_row.log_softmax(dim=-1)
|
| 505 |
-
token_log_prob = torch.gather(log_probs, dim=1, index=input_ids_row.unsqueeze(1)).squeeze(1)
|
| 506 |
-
per_token_logps.append(token_log_prob)
|
| 507 |
-
return torch.stack(per_token_logps)
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
def _prepare_inputs(self, inputs):
|
| 511 |
-
# Simple pass-through, just like original
|
| 512 |
-
return inputs
|
| 513 |
-
|
| 514 |
-
def _get_key_from_inputs(self, x, key):
|
| 515 |
-
ele = x.get(key, None)
|
| 516 |
-
assert ele is not None, f"The key {key} is not found in the input"
|
| 517 |
-
if isinstance(ele, list):
|
| 518 |
-
return [e for e in ele]
|
| 519 |
-
else:
|
| 520 |
-
return [ele]
|
| 521 |
-
|
| 522 |
-
def _generate_and_score_completions(self, inputs: dict[str, Union[torch.Tensor, Any]], model) -> dict[str, Union[torch.Tensor, Any]]:
|
| 523 |
-
device = self.accelerator.device
|
| 524 |
-
prompts = [x["prompt"] for x in inputs]
|
| 525 |
-
prompts_text = self.vlm_module.prepare_prompt(self.processing_class, inputs)
|
| 526 |
-
# Handle both pre-loaded images and image paths
|
| 527 |
-
images = []
|
| 528 |
-
for x in inputs:
|
| 529 |
-
if "image" in x:
|
| 530 |
-
imgs = self._get_key_from_inputs(x, "image")
|
| 531 |
-
elif "image_path" in x and x["image_path"] is not None:
|
| 532 |
-
imgs = [PIL.Image.open(p) for p in self._get_key_from_inputs(x, "image_path")]
|
| 533 |
-
else:
|
| 534 |
-
imgs = []
|
| 535 |
-
|
| 536 |
-
for img in imgs:
|
| 537 |
-
try:
|
| 538 |
-
# Ensure minimum dimensions of 28 pixels
|
| 539 |
-
w, h = img.size
|
| 540 |
-
if w < 28 or h < 28:
|
| 541 |
-
# Calculate new dimensions maintaining aspect ratio
|
| 542 |
-
if w < h:
|
| 543 |
-
new_w = 28
|
| 544 |
-
new_h = int(h * (28/w))
|
| 545 |
-
else:
|
| 546 |
-
new_h = 28
|
| 547 |
-
new_w = int(w * (28/h))
|
| 548 |
-
img = img.resize((new_w, new_h), PIL.Image.Resampling.LANCZOS)
|
| 549 |
-
except:
|
| 550 |
-
pass
|
| 551 |
-
images.append(img)
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
prompt_inputs = self.vlm_module.prepare_model_inputs(
|
| 555 |
-
self.processing_class,
|
| 556 |
-
prompts_text,
|
| 557 |
-
images,
|
| 558 |
-
return_tensors="pt",
|
| 559 |
-
padding=True,
|
| 560 |
-
padding_side="left",
|
| 561 |
-
add_special_tokens=False,
|
| 562 |
-
)
|
| 563 |
-
prompt_inputs = super()._prepare_inputs(prompt_inputs)
|
| 564 |
-
prompt_ids, prompt_mask = prompt_inputs["input_ids"], prompt_inputs["attention_mask"]
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
# max_prompt_length is not supported yet
|
| 568 |
-
# if self.max_prompt_length is not None:
|
| 569 |
-
# prompt_ids = prompt_ids[:, -self.max_prompt_length :]
|
| 570 |
-
# prompt_inputs["input_ids"] = prompt_ids
|
| 571 |
-
# prompt_mask = prompt_mask[:, -self.max_prompt_length :]
|
| 572 |
-
# prompt_inputs["attention_mask"] = prompt_mask
|
| 573 |
-
|
| 574 |
-
# Generate completions
|
| 575 |
-
with unwrap_model_for_generation(model, self.accelerator) as unwrapped_model:
|
| 576 |
-
generate_returned_result = unwrapped_model.generate(
|
| 577 |
-
**{k: v for k, v in prompt_inputs.items() if k not in self.vlm_module.get_non_generate_params()},
|
| 578 |
-
generation_config=self.generation_config
|
| 579 |
-
)
|
| 580 |
-
prompt_length = prompt_ids.size(1)
|
| 581 |
-
if not self.vlm_module.is_embeds_input():
|
| 582 |
-
prompt_completion_ids = generate_returned_result
|
| 583 |
-
prompt_ids = prompt_completion_ids[:, :prompt_length]
|
| 584 |
-
completion_ids = prompt_completion_ids[:, prompt_length:]
|
| 585 |
-
else:
|
| 586 |
-
# In this case, the input of the LLM backbone is the embedding of the combination of the image and text prompt
|
| 587 |
-
# So the returned result of the `generate` method only contains the completion ids
|
| 588 |
-
completion_ids = generate_returned_result
|
| 589 |
-
prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1)
|
| 590 |
-
|
| 591 |
-
# Mask everything after the first EOS token
|
| 592 |
-
is_eos = completion_ids == self.processing_class.eos_token_id
|
| 593 |
-
eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device)
|
| 594 |
-
eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)]
|
| 595 |
-
sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1)
|
| 596 |
-
completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int()
|
| 597 |
-
|
| 598 |
-
# Concatenate prompt_mask with completion_mask for logit computation
|
| 599 |
-
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C)
|
| 600 |
-
|
| 601 |
-
# Get the multimodal inputs
|
| 602 |
-
multimodal_keywords = self.vlm_module.get_custom_multimodal_keywords()
|
| 603 |
-
multimodal_inputs = {k: prompt_inputs[k] if k in prompt_inputs else None for k in multimodal_keywords}
|
| 604 |
-
with torch.no_grad():
|
| 605 |
-
# When using num_iterations == 1, old_per_token_logps == per_token_logps, so we can skip its
|
| 606 |
-
# computation here, and use per_token_logps.detach() instead.
|
| 607 |
-
if self.num_iterations > 1:
|
| 608 |
-
old_per_token_logps = self._get_per_token_logps(
|
| 609 |
-
model, prompt_completion_ids, attention_mask, **multimodal_inputs
|
| 610 |
-
)
|
| 611 |
-
old_per_token_logps = old_per_token_logps[:, prompt_length - 1:]
|
| 612 |
-
else:
|
| 613 |
-
old_per_token_logps = None
|
| 614 |
-
|
| 615 |
-
if self.beta == 0.0:
|
| 616 |
-
ref_per_token_logps = None
|
| 617 |
-
elif self.ref_model is not None:
|
| 618 |
-
ref_per_token_logps = self._get_per_token_logps(
|
| 619 |
-
self.ref_model, prompt_completion_ids, attention_mask, **multimodal_inputs
|
| 620 |
-
)
|
| 621 |
-
else:
|
| 622 |
-
with self.accelerator.unwrap_model(model).disable_adapter():
|
| 623 |
-
ref_per_token_logps = self._get_per_token_logps(
|
| 624 |
-
model, prompt_completion_ids, attention_mask, **multimodal_inputs
|
| 625 |
-
)
|
| 626 |
-
if ref_per_token_logps is not None:
|
| 627 |
-
ref_per_token_logps = ref_per_token_logps[:, prompt_length - 1:]
|
| 628 |
-
|
| 629 |
-
# Decode the generated completions
|
| 630 |
-
completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
|
| 631 |
-
if is_conversational(inputs[0]):
|
| 632 |
-
completions = [[{"role": "assistant", "content": completion}] for completion in completions]
|
| 633 |
-
|
| 634 |
-
# Compute the rewards
|
| 635 |
-
# No need to duplicate prompts as we're not generating multiple completions per prompt
|
| 636 |
-
|
| 637 |
-
rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device)
|
| 638 |
-
for i, (reward_func, reward_processing_class) in enumerate(
|
| 639 |
-
zip(self.reward_funcs, self.reward_processing_classes)
|
| 640 |
-
):
|
| 641 |
-
if isinstance(reward_func, PreTrainedModel):
|
| 642 |
-
if is_conversational(inputs[0]):
|
| 643 |
-
messages = [{"messages": p + c} for p, c in zip(prompts, completions)]
|
| 644 |
-
texts = [apply_chat_template(x, reward_processing_class)["text"] for x in messages]
|
| 645 |
-
else:
|
| 646 |
-
texts = [p + c for p, c in zip(prompts, completions)]
|
| 647 |
-
reward_inputs = reward_processing_class(
|
| 648 |
-
texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False
|
| 649 |
-
)
|
| 650 |
-
reward_inputs = super()._prepare_inputs(reward_inputs)
|
| 651 |
-
with torch.inference_mode():
|
| 652 |
-
rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,)
|
| 653 |
-
else:
|
| 654 |
-
# Repeat all input columns (but "prompt" and "completion") to match the number of generations
|
| 655 |
-
reward_kwargs = {key: [] for key in inputs[0].keys() if key not in ["prompt", "completion"]}
|
| 656 |
-
for key in reward_kwargs:
|
| 657 |
-
for example in inputs:
|
| 658 |
-
# No need to duplicate prompts as we're not generating multiple completions per prompt
|
| 659 |
-
# reward_kwargs[key].extend([example[key]] * self.num_generations)
|
| 660 |
-
reward_kwargs[key].extend([example[key]])
|
| 661 |
-
output_reward_func = reward_func(prompts=prompts, completions=completions, **reward_kwargs)
|
| 662 |
-
rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device)
|
| 663 |
-
|
| 664 |
-
# Gather rewards across processes
|
| 665 |
-
rewards_per_func = self.accelerator.gather(rewards_per_func)
|
| 666 |
-
|
| 667 |
-
# Sum the rewards from all reward functions
|
| 668 |
-
rewards = rewards_per_func.sum(dim=1)
|
| 669 |
-
|
| 670 |
-
# Compute grouped-wise rewards
|
| 671 |
-
# Each group consists of num_generations completions for the same prompt
|
| 672 |
-
mean_grouped_rewards = rewards.view(-1, self.num_generations).mean(dim=1)
|
| 673 |
-
std_grouped_rewards = rewards.view(-1, self.num_generations).std(dim=1)
|
| 674 |
-
|
| 675 |
-
# Normalize the rewards to compute the advantages
|
| 676 |
-
mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
|
| 677 |
-
std_grouped_rewards = std_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
|
| 678 |
-
advantages = (rewards - mean_grouped_rewards) / (std_grouped_rewards + 1e-4)
|
| 679 |
-
|
| 680 |
-
# Get only the local slice of advantages
|
| 681 |
-
process_slice = slice(
|
| 682 |
-
self.accelerator.process_index * len(prompts),
|
| 683 |
-
(self.accelerator.process_index + 1) * len(prompts),
|
| 684 |
-
)
|
| 685 |
-
advantages = advantages[process_slice]
|
| 686 |
-
|
| 687 |
-
# Log the metrics
|
| 688 |
-
completion_length = self.accelerator.gather_for_metrics(completion_mask.sum(1)).float().mean().item()
|
| 689 |
-
self._metrics["completion_length"].append(completion_length)
|
| 690 |
-
|
| 691 |
-
reward_per_func = self.accelerator.gather_for_metrics(rewards_per_func).mean(0)
|
| 692 |
-
for i, reward_func in enumerate(self.reward_funcs):
|
| 693 |
-
if isinstance(reward_func, PreTrainedModel):
|
| 694 |
-
reward_func_name = reward_func.config._name_or_path.split("/")[-1]
|
| 695 |
-
else:
|
| 696 |
-
reward_func_name = reward_func.__name__
|
| 697 |
-
self._metrics[f"rewards/{reward_func_name}"].append(reward_per_func[i].item())
|
| 698 |
-
|
| 699 |
-
self._metrics["reward"].append(self.accelerator.gather_for_metrics(rewards).mean().item())
|
| 700 |
-
|
| 701 |
-
self._metrics["reward_std"].append(self.accelerator.gather_for_metrics(std_grouped_rewards).mean().item())
|
| 702 |
-
|
| 703 |
-
return {
|
| 704 |
-
"prompt_ids": prompt_ids,
|
| 705 |
-
"prompt_mask": prompt_mask,
|
| 706 |
-
"completion_ids": completion_ids,
|
| 707 |
-
"completion_mask": completion_mask,
|
| 708 |
-
"old_per_token_logps": old_per_token_logps,
|
| 709 |
-
"ref_per_token_logps": ref_per_token_logps,
|
| 710 |
-
"advantages": advantages,
|
| 711 |
-
"multimodal_inputs": multimodal_inputs
|
| 712 |
-
}
|
| 713 |
-
|
| 714 |
-
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 715 |
-
if return_outputs:
|
| 716 |
-
raise ValueError("The GRPOTrainer does not support returning outputs")
|
| 717 |
-
|
| 718 |
-
# Check if we need to generate new completions or use buffered ones
|
| 719 |
-
if self.state.global_step % self.num_iterations == 0:
|
| 720 |
-
inputs = self._generate_and_score_completions(inputs, model)
|
| 721 |
-
self._buffered_inputs[self._step % self.args.gradient_accumulation_steps] = inputs
|
| 722 |
-
else:
|
| 723 |
-
inputs = self._buffered_inputs[self._step % self.args.gradient_accumulation_steps]
|
| 724 |
-
self._step += 1
|
| 725 |
-
|
| 726 |
-
# Get the prepared inputs
|
| 727 |
-
prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
|
| 728 |
-
completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
|
| 729 |
-
multimodal_inputs = inputs["multimodal_inputs"]
|
| 730 |
-
|
| 731 |
-
# Concatenate for full sequence
|
| 732 |
-
input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
|
| 733 |
-
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
|
| 734 |
-
|
| 735 |
-
# Get the current policy's log probabilities
|
| 736 |
-
per_token_logps = self._get_per_token_logps(model, input_ids, attention_mask, **multimodal_inputs)
|
| 737 |
-
# Get rid of the prompt (-1 because of the shift done in get_per_token_logps)
|
| 738 |
-
per_token_logps = per_token_logps[:, prompt_ids.size(1) - 1:]
|
| 739 |
-
|
| 740 |
-
# Get the advantages from inputs
|
| 741 |
-
advantages = inputs["advantages"]
|
| 742 |
-
|
| 743 |
-
# When using num_iterations == 1, old_per_token_logps == per_token_logps, so we can skip its computation
|
| 744 |
-
# and use per_token_logps.detach() instead
|
| 745 |
-
old_per_token_logps = inputs["old_per_token_logps"] if self.num_iterations > 1 else per_token_logps.detach()
|
| 746 |
-
|
| 747 |
-
# Compute the policy ratio and clipped version
|
| 748 |
-
coef_1 = torch.exp(per_token_logps - old_per_token_logps)
|
| 749 |
-
coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
|
| 750 |
-
per_token_loss1 = coef_1 * advantages.unsqueeze(1)
|
| 751 |
-
per_token_loss2 = coef_2 * advantages.unsqueeze(1)
|
| 752 |
-
per_token_loss = -torch.min(per_token_loss1, per_token_loss2)
|
| 753 |
-
|
| 754 |
-
# Add KL penalty if beta > 0
|
| 755 |
-
if self.beta > 0:
|
| 756 |
-
ref_per_token_logps = inputs["ref_per_token_logps"]
|
| 757 |
-
per_token_kl = torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
|
| 758 |
-
per_token_loss = per_token_loss + self.beta * per_token_kl
|
| 759 |
-
|
| 760 |
-
# Log KL divergence
|
| 761 |
-
mean_kl = ((per_token_kl * completion_mask).sum(dim=1) / completion_mask.sum(dim=1)).mean()
|
| 762 |
-
self._metrics["kl"].append(self.accelerator.gather_for_metrics(mean_kl).mean().item())
|
| 763 |
-
|
| 764 |
-
# Compute final loss
|
| 765 |
-
loss = ((per_token_loss * completion_mask).sum(dim=1) / completion_mask.sum(dim=1)).mean()
|
| 766 |
-
|
| 767 |
-
# Log clip ratio
|
| 768 |
-
is_clipped = (per_token_loss1 < per_token_loss2).float()
|
| 769 |
-
clip_ratio = (is_clipped * completion_mask).sum() / completion_mask.sum()
|
| 770 |
-
self._metrics["clip_ratio"].append(self.accelerator.gather_for_metrics(clip_ratio).mean().item())
|
| 771 |
-
|
| 772 |
-
return loss
|
| 773 |
-
|
| 774 |
-
def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None:
|
| 775 |
-
metrics = {key: sum(val) / len(val) for key, val in self._metrics.items()} # average the metrics
|
| 776 |
-
logs = {**logs, **metrics}
|
| 777 |
-
if version.parse(transformers.__version__) >= version.parse("4.47.0.dev0"):
|
| 778 |
-
super().log(logs, start_time)
|
| 779 |
-
else: # transformers<=4.46
|
| 780 |
-
super().log(logs)
|
| 781 |
-
self._metrics.clear()
|
| 782 |
-
|
| 783 |
-
def create_model_card(
|
| 784 |
-
self,
|
| 785 |
-
model_name: Optional[str] = None,
|
| 786 |
-
dataset_name: Optional[str] = None,
|
| 787 |
-
tags: Union[str, list[str], None] = None,
|
| 788 |
-
):
|
| 789 |
-
"""
|
| 790 |
-
Creates a draft of a model card using the information available to the `Trainer`.
|
| 791 |
-
|
| 792 |
-
Args:
|
| 793 |
-
model_name (`str` or `None`, *optional*, defaults to `None`):
|
| 794 |
-
Name of the model.
|
| 795 |
-
dataset_name (`str` or `None`, *optional*, defaults to `None`):
|
| 796 |
-
Name of the dataset used for training.
|
| 797 |
-
tags (`str`, `list[str]` or `None`, *optional*, defaults to `None`):
|
| 798 |
-
Tags to be associated with the model card.
|
| 799 |
-
"""
|
| 800 |
-
if not self.is_world_process_zero():
|
| 801 |
-
return
|
| 802 |
-
|
| 803 |
-
if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path):
|
| 804 |
-
base_model = self.model.config._name_or_path
|
| 805 |
-
else:
|
| 806 |
-
base_model = None
|
| 807 |
-
|
| 808 |
-
tags = tags or []
|
| 809 |
-
if isinstance(tags, str):
|
| 810 |
-
tags = [tags]
|
| 811 |
-
|
| 812 |
-
if hasattr(self.model.config, "unsloth_version"):
|
| 813 |
-
tags.append("unsloth")
|
| 814 |
-
|
| 815 |
-
citation = textwrap.dedent(
|
| 816 |
-
"""\
|
| 817 |
-
@article{zhihong2024deepseekmath,
|
| 818 |
-
title = {{DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models}},
|
| 819 |
-
author = {Zhihong Shao and Peiyi Wang and Qihao Zhu and Runxin Xu and Junxiao Song and Mingchuan Zhang and Y. K. Li and Y. Wu and Daya Guo},
|
| 820 |
-
year = 2024,
|
| 821 |
-
eprint = {arXiv:2402.03300},
|
| 822 |
-
"""
|
| 823 |
-
)
|
| 824 |
-
|
| 825 |
-
model_card = generate_model_card(
|
| 826 |
-
base_model=base_model,
|
| 827 |
-
model_name=model_name,
|
| 828 |
-
hub_model_id=self.hub_model_id,
|
| 829 |
-
dataset_name=dataset_name,
|
| 830 |
-
tags=tags,
|
| 831 |
-
wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None,
|
| 832 |
-
comet_url=get_comet_experiment_url(),
|
| 833 |
-
trainer_name="GRPO",
|
| 834 |
-
trainer_citation=citation,
|
| 835 |
-
paper_title="DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models",
|
| 836 |
-
paper_id="2402.03300",
|
| 837 |
-
)
|
| 838 |
-
|
| 839 |
-
model_card.save(os.path.join(self.args.output_dir, "README.md"))
|
| 840 |
-
|
| 841 |
-
def _get_train_sampler(self) -> Sampler:
|
| 842 |
-
"""Returns a sampler that ensures proper data sampling for GRPO training."""
|
| 843 |
-
effective_batch_size = (
|
| 844 |
-
self.args.per_device_train_batch_size
|
| 845 |
-
* self.accelerator.num_processes
|
| 846 |
-
* self.args.gradient_accumulation_steps
|
| 847 |
-
)
|
| 848 |
-
|
| 849 |
-
return RepeatRandomSampler(
|
| 850 |
-
data_source=self.train_dataset,
|
| 851 |
-
mini_repeat_count=self.num_generations,
|
| 852 |
-
batch_size=effective_batch_size // self.num_generations,
|
| 853 |
-
repeat_count=self.num_iterations,
|
| 854 |
-
seed=self.args.seed,
|
| 855 |
-
)
|
| 856 |
-
|
| 857 |
-
def _get_eval_sampler(self, eval_dataset) -> Sampler:
|
| 858 |
-
"""Returns a sampler for evaluation."""
|
| 859 |
-
return RepeatRandomSampler(
|
| 860 |
-
data_source=eval_dataset,
|
| 861 |
-
mini_repeat_count=self.num_generations,
|
| 862 |
-
seed=self.args.seed,
|
| 863 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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