|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import os |
|
import textwrap |
|
import warnings |
|
from collections import defaultdict, deque |
|
from collections.abc import Sized |
|
from contextlib import nullcontext |
|
from typing import Any, Callable, Optional, Union |
|
|
|
import datasets |
|
import torch |
|
import torch.utils.data |
|
import transformers |
|
from accelerate.utils import broadcast_object_list, gather, gather_object, is_peft_model, set_seed |
|
from datasets import Dataset, IterableDataset |
|
from packaging import version |
|
from torch import nn |
|
from torch.utils.data import DataLoader, Sampler |
|
from transformers import ( |
|
AutoModelForCausalLM, |
|
AutoModelForSequenceClassification, |
|
AutoTokenizer, |
|
GenerationConfig, |
|
PreTrainedModel, |
|
PreTrainedTokenizerBase, |
|
Trainer, |
|
TrainerCallback, |
|
is_wandb_available, |
|
) |
|
from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled |
|
from transformers.trainer_utils import seed_worker |
|
from transformers.utils import is_datasets_available, is_peft_available |
|
|
|
from ..data_utils import apply_chat_template, is_conversational, maybe_apply_chat_template |
|
from ..extras.profiling import profiling_context, profiling_decorator |
|
from ..extras.vllm_client import VLLMClient |
|
from ..import_utils import is_deepspeed_available, is_liger_kernel_available, is_rich_available, is_vllm_available |
|
from ..models import create_reference_model, prepare_deepspeed, unwrap_model_for_generation |
|
from .callbacks import SyncRefModelCallback |
|
from .grpo_config import GRPOConfig |
|
from .utils import ( |
|
disable_dropout_in_model, |
|
generate_model_card, |
|
get_comet_experiment_url, |
|
pad, |
|
print_prompt_completions_sample, |
|
selective_log_softmax, |
|
) |
|
|
|
|
|
if is_deepspeed_available(): |
|
import deepspeed |
|
|
|
if is_peft_available(): |
|
from peft import PeftConfig, get_peft_model |
|
|
|
if is_liger_kernel_available(): |
|
from liger_kernel.chunked_loss import LigerFusedLinearGRPOLoss |
|
|
|
if is_wandb_available(): |
|
import wandb |
|
|
|
|
|
|
|
RewardFunc = Union[str, PreTrainedModel, Callable[[list, list], list[float]]] |
|
|
|
|
|
class RepeatSampler(Sampler): |
|
""" |
|
Sampler that repeats the indices of a dataset in a structured manner. |
|
|
|
Args: |
|
data_source (`Sized`): |
|
Dataset to sample from. |
|
mini_repeat_count (`int`): |
|
Number of times to repeat each index per batch. |
|
batch_size (`int`, *optional*, defaults to `1`): |
|
Number of unique indices per batch. |
|
repeat_count (`int`, *optional*, defaults to `1`): |
|
Number of times to repeat the full sampling process. |
|
shuffle (`bool`, *optional*, defaults to `True`): |
|
Whether to shuffle the dataset. |
|
seed (`int` or `None`, *optional*, defaults to `None`): |
|
Random seed for reproducibility (only affects this sampler). |
|
|
|
Example: |
|
```python |
|
>>> sampler = RepeatRandomSampler(["a", "b", "c", "d", "e", "f", "g"], mini_repeat_count=2, batch_size=3, repeat_count=4) |
|
>>> list(sampler) |
|
[4, 4, 3, 3, 0, 0, |
|
4, 4, 3, 3, 0, 0, |
|
4, 4, 3, 3, 0, 0, |
|
4, 4, 3, 3, 0, 0, |
|
|
|
1, 1, 2, 2, 6, 6, |
|
1, 1, 2, 2, 6, 6, |
|
1, 1, 2, 2, 6, 6, |
|
1, 1, 2, 2, 6, 6] |
|
``` |
|
|
|
```txt |
|
mini_repeat_count = 3 |
|
- - - |
|
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, | |
|
4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, | |
|
8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, | |
|
repeat_count = 2 |
|
0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, | |
|
4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, | |
|
8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, ...] | |
|
--------- --------- --------- --------- |
|
--------- --------- --------- --------- |
|
--------- --------- --------- --------- |
|
batch_size = 12 |
|
``` |
|
""" |
|
|
|
def __init__( |
|
self, |
|
data_source: Sized, |
|
mini_repeat_count: int, |
|
batch_size: int = 1, |
|
repeat_count: int = 1, |
|
shuffle: bool = True, |
|
seed: Optional[int] = None, |
|
): |
|
self.data_source = data_source |
|
self.mini_repeat_count = mini_repeat_count |
|
self.batch_size = batch_size |
|
self.repeat_count = repeat_count |
|
self.num_samples = len(data_source) |
|
self.shuffle = shuffle |
|
self.seed = seed |
|
|
|
if shuffle: |
|
self.generator = torch.Generator() |
|
if seed is not None: |
|
self.generator.manual_seed(seed) |
|
|
|
def __iter__(self): |
|
if self.shuffle: |
|
|
|
indexes = torch.randperm(self.num_samples, generator=self.generator).tolist() |
|
else: |
|
indexes = list(range(self.num_samples)) |
|
|
|
|
|
|
|
indexes = [indexes[i : i + self.batch_size] for i in range(0, len(indexes), self.batch_size)] |
|
|
|
|
|
|
|
indexes = [chunk for chunk in indexes if len(chunk) == self.batch_size] |
|
|
|
for chunk in indexes: |
|
for _ in range(self.repeat_count): |
|
for index in chunk: |
|
for _ in range(self.mini_repeat_count): |
|
yield index |
|
|
|
def __len__(self) -> int: |
|
return self.num_samples * self.mini_repeat_count * self.repeat_count |
|
|
|
|
|
class RepeatRandomSampler(RepeatSampler): |
|
def __init__(self, *args, **kwargs): |
|
warnings.warn( |
|
"RepeatRandomSampler is deprecated and will be removed in version 0.18. Use RepeatSampler instead.", |
|
DeprecationWarning, |
|
) |
|
super().__init__(*args, **kwargs) |
|
|
|
|
|
|
|
def nanstd(tensor: torch.Tensor) -> torch.Tensor: |
|
""" |
|
Compute the standard deviation of a tensor, ignoring NaNs. This function only supports 1D tensors. |
|
|
|
Args: |
|
tensor (`torch.Tensor`): |
|
Input tensor of shape `(N,)`. |
|
|
|
Returns: |
|
`torch.Tensor`: |
|
Standard deviation of the tensor, ignoring NaNs. |
|
""" |
|
variance = torch.nanmean((tensor - torch.nanmean(tensor, keepdim=True)) ** 2) |
|
count = torch.sum(~torch.isnan(tensor)) |
|
variance *= count / (count - 1) |
|
return torch.sqrt(variance) |
|
|
|
|
|
def split_tensor_dict( |
|
tensor_dict: dict[str, Optional[torch.Tensor]], num_chunks: int |
|
) -> list[dict[str, Optional[torch.Tensor]]]: |
|
""" |
|
Splits a dictionary of tensors along the first dimension into `num_chunks` equal parts. |
|
|
|
Example: |
|
>>> x = torch.arange(12).reshape(6, 2) |
|
>>> y = torch.arange(6).reshape(6, 1) |
|
>>> tensor_dict = {"x": x, "y": y} |
|
>>> split_tensor_dict(tensor_dict, 3) |
|
[ |
|
{"x": tensor([[0, 1], [2, 3]]), "y": tensor([[0], [1]])}, |
|
{"x": tensor([[4, 5], [6, 7]]), "y": tensor([[2], [3]])}, |
|
{"x": tensor([[ 8, 9], [10, 11]]), "y": tensor([[4], [5]])} |
|
] |
|
""" |
|
first_tensor = next(tensor for tensor in tensor_dict.values() if tensor is not None) |
|
chunk_size = first_tensor.shape[0] // num_chunks |
|
return [ |
|
{ |
|
key: tensor[i * chunk_size : (i + 1) * chunk_size] if tensor is not None else None |
|
for key, tensor in tensor_dict.items() |
|
} |
|
for i in range(num_chunks) |
|
] |
|
|
|
|
|
def nanmin(tensor: torch.Tensor) -> torch.Tensor: |
|
""" |
|
Compute the minimum value of a tensor, ignoring NaNs. This function only supports 1D tensors. |
|
|
|
Args: |
|
tensor (`torch.Tensor`): Input tensor of shape `(N,)`. |
|
|
|
Returns: |
|
`torch.Tensor`: Minimum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN. |
|
""" |
|
if torch.isnan(tensor).all(): |
|
return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device) |
|
return torch.min(tensor[~torch.isnan(tensor)]) |
|
|
|
|
|
def nanmax(tensor: torch.Tensor) -> torch.Tensor: |
|
""" |
|
Compute the maximum value of a tensor, ignoring NaNs. This function only supports 1D tensors. |
|
|
|
Args: |
|
tensor (`torch.Tensor`): Input tensor of shape `(N,)`. |
|
|
|
Returns: |
|
`torch.Tensor`: Maximum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN. |
|
""" |
|
if torch.isnan(tensor).all(): |
|
return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device) |
|
return torch.max(tensor[~torch.isnan(tensor)]) |
|
|
|
|
|
class GRPOTrainer(Trainer): |
|
""" |
|
Trainer for the Group Relative Policy Optimization (GRPO) method. This algorithm was initially proposed in the |
|
paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://huggingface.co/papers/2402.03300). |
|
|
|
Example: |
|
|
|
```python |
|
from datasets import load_dataset |
|
from trl import GRPOTrainer |
|
|
|
dataset = load_dataset("trl-lib/tldr", split="train") |
|
|
|
def reward_func(completions, **kwargs): |
|
# Dummy reward function that rewards completions with more unique letters. |
|
return [float(len(set(completion))) for completion in completions] |
|
|
|
trainer = GRPOTrainer( |
|
model="Qwen/Qwen2-0.5B-Instruct", |
|
reward_funcs=reward_func, |
|
train_dataset=dataset, |
|
) |
|
|
|
trainer.train() |
|
``` |
|
|
|
Args: |
|
model (`Union[str, PreTrainedModel]`): |
|
Model to be trained. Can be either: |
|
|
|
- A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or |
|
a path to a *directory* containing model weights saved using |
|
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is |
|
loaded using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keywork arguments |
|
in `args.model_init_kwargs`. |
|
- A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. |
|
reward_funcs (`Union[RewardFunc, list[RewardFunc]]`): |
|
Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward |
|
functions with the prompts and completions and sum the rewards. Can be either: |
|
|
|
- A single reward function, such as: |
|
- A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a |
|
path to a *directory* containing model weights saved using |
|
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded |
|
using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the |
|
keyword arguments in `args.model_init_kwargs`. |
|
- A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported. |
|
- A custom reward function: The function is provided with the prompts and the generated completions, |
|
plus any additional columns in the dataset. It should return a list of rewards. Custom reward |
|
functions can also return None when the reward is not applicable to those samples. This is useful for |
|
multi-task training where different reward functions apply to different types of samples. When a |
|
reward function returns None for a sample, that reward function is excluded from the reward |
|
calculation for that sample. For more details, see |
|
[Using a custom reward function](#using-a-custom-reward-function). |
|
- A list of reward functions, where each item can independently be any of the above types. Mixing different |
|
types within the list (e.g., a string model ID and a custom reward function) is allowed. |
|
args ([`GRPOConfig`], *optional*, defaults to `None`): |
|
Configuration for this trainer. If `None`, a default configuration is used. |
|
train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]): |
|
Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is |
|
ignored. The format of the samples can be either: |
|
|
|
- [Standard](dataset_formats#standard): Each sample contains plain text. |
|
- [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role |
|
and content). |
|
eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Union[Dataset, IterableDataset]]`): |
|
Dataset to use for evaluation. It must meet the same requirements as `train_dataset`. |
|
processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*, defaults to `None`): |
|
Processing class used to process the data. The padding side must be set to "left". If `None`, the |
|
processing class is loaded from the model's name with [`~transformers.AutoTokenizer.from_pretrained`]. A |
|
padding token, `processing_class.pad_token`, must be set. If the processing class has not set a padding |
|
token, `processing_class.eos_token` will be used as the default. |
|
reward_processing_classes (`Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]`, *optional*, defaults to `None`): |
|
Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either: |
|
|
|
- A single processing class: Used when `reward_funcs` contains only one reward function. |
|
- A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`. |
|
If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is |
|
`None`, the tokenizer for the model is automatically loaded using [`~transformers.AutoTokenizer.from_pretrained`]. |
|
For elements in `reward_funcs` that are custom reward functions (not [`~transformers.PreTrainedModel`]), |
|
the corresponding entries in `reward_processing_classes` are ignored. |
|
callbacks (list of [`~transformers.TrainerCallback`], *optional*, defaults to `None`): |
|
List of callbacks to customize the training loop. Will add those to the list of default callbacks |
|
detailed in [here](https://huggingface.co/docs/transformers/main_classes/callback). |
|
|
|
If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`] |
|
method. |
|
optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`): |
|
A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your |
|
model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`. |
|
peft_config ([`~peft.PeftConfig`], *optional*, defaults to `None`): |
|
PEFT configuration used to wrap the model. If `None`, the model is not wrapped. |
|
""" |
|
|
|
_tag_names = ["trl", "grpo"] |
|
|
|
def __init__( |
|
self, |
|
model: Union[str, PreTrainedModel], |
|
reward_funcs: Union[RewardFunc, list[RewardFunc]], |
|
args: Optional[GRPOConfig] = None, |
|
train_dataset: Optional[Union[Dataset, IterableDataset]] = None, |
|
eval_dataset: Optional[Union[Dataset, IterableDataset, dict[str, Union[Dataset, IterableDataset]]]] = None, |
|
processing_class: Optional[PreTrainedTokenizerBase] = None, |
|
reward_processing_classes: Optional[Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]] = None, |
|
callbacks: Optional[list[TrainerCallback]] = None, |
|
optimizers: tuple[Optional[torch.optim.Optimizer], Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None), |
|
peft_config: Optional["PeftConfig"] = None, |
|
): |
|
|
|
if args is None: |
|
model_name = model if isinstance(model, str) else model.config._name_or_path |
|
model_name = model_name.split("/")[-1] |
|
args = GRPOConfig(f"{model_name}-GRPO") |
|
|
|
|
|
|
|
model_init_kwargs = args.model_init_kwargs or {} |
|
if isinstance(model, str): |
|
model_id = model |
|
torch_dtype = model_init_kwargs.get("torch_dtype") |
|
if isinstance(torch_dtype, torch.dtype) or torch_dtype == "auto" or torch_dtype is None: |
|
pass |
|
elif isinstance(torch_dtype, str): |
|
torch_dtype = getattr(torch, torch_dtype) |
|
model_init_kwargs["torch_dtype"] = torch_dtype |
|
else: |
|
raise ValueError( |
|
"Invalid `torch_dtype` passed to `GRPOConfig`. Expected either 'auto' or a string representing " |
|
f"a `torch.dtype` (e.g., 'float32'), but got {torch_dtype}." |
|
) |
|
|
|
model_init_kwargs["use_cache"] = ( |
|
False if args.gradient_checkpointing else model_init_kwargs.get("use_cache") |
|
) |
|
model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) |
|
else: |
|
model_id = model.config._name_or_path |
|
if args.model_init_kwargs is not None: |
|
raise ValueError( |
|
"You passed `model_init_kwargs` to the `GRPOConfig`, but your model is already instantiated. " |
|
"This argument can only be used when the `model` argument is a string." |
|
) |
|
|
|
if peft_config is not None: |
|
if not is_peft_available(): |
|
raise ImportError("PEFT is required to use `peft_config`. Run `pip install peft`.") |
|
model = get_peft_model(model, peft_config) |
|
|
|
|
|
if args.gradient_checkpointing: |
|
model = self._enable_gradient_checkpointing(model, args) |
|
|
|
|
|
self.beta = args.beta |
|
if self.beta == 0.0: |
|
|
|
self.ref_model = None |
|
elif is_deepspeed_zero3_enabled(): |
|
self.ref_model = AutoModelForCausalLM.from_pretrained(model_id, **model_init_kwargs) |
|
elif is_peft_model(model): |
|
|
|
|
|
self.ref_model = None |
|
else: |
|
|
|
self.ref_model = create_reference_model(model) |
|
|
|
|
|
if args.disable_dropout: |
|
disable_dropout_in_model(model) |
|
if self.ref_model is not None: |
|
disable_dropout_in_model(self.ref_model) |
|
|
|
|
|
if processing_class is None: |
|
processing_class = AutoTokenizer.from_pretrained(model.config._name_or_path, padding_side="left") |
|
if processing_class.pad_token is None: |
|
processing_class.pad_token = processing_class.eos_token |
|
|
|
|
|
if not isinstance(reward_funcs, list): |
|
reward_funcs = [reward_funcs] |
|
self.reward_func_names = [] |
|
for i, reward_func in enumerate(reward_funcs): |
|
if isinstance(reward_func, str): |
|
reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained( |
|
reward_func, num_labels=1, **model_init_kwargs |
|
) |
|
if isinstance(reward_funcs[i], nn.Module): |
|
self.reward_func_names.append(reward_funcs[i].config._name_or_path.split("/")[-1]) |
|
else: |
|
self.reward_func_names.append(reward_funcs[i].__name__) |
|
self.reward_funcs = reward_funcs |
|
|
|
|
|
if args.reward_weights is not None: |
|
if len(args.reward_weights) != len(reward_funcs): |
|
raise ValueError( |
|
f"Number of reward weights ({len(args.reward_weights)}) must match number of reward " |
|
f"functions ({len(reward_funcs)})" |
|
) |
|
self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32) |
|
else: |
|
self.reward_weights = torch.ones(len(reward_funcs), dtype=torch.float32) |
|
|
|
|
|
if reward_processing_classes is None: |
|
reward_processing_classes = [None] * len(reward_funcs) |
|
elif not isinstance(reward_processing_classes, list): |
|
reward_processing_classes = [reward_processing_classes] |
|
else: |
|
if len(reward_processing_classes) != len(reward_funcs): |
|
raise ValueError("The number of reward processing classes must match the number of reward functions.") |
|
|
|
for i, (reward_processing_class, reward_func) in enumerate(zip(reward_processing_classes, reward_funcs)): |
|
if isinstance(reward_func, PreTrainedModel): |
|
if reward_processing_class is None: |
|
reward_processing_class = AutoTokenizer.from_pretrained(reward_func.config._name_or_path) |
|
if reward_processing_class.pad_token_id is None: |
|
reward_processing_class.pad_token = reward_processing_class.eos_token |
|
|
|
|
|
reward_func.config.pad_token_id = reward_processing_class.pad_token_id |
|
reward_processing_classes[i] = reward_processing_class |
|
self.reward_processing_classes = reward_processing_classes |
|
|
|
|
|
def data_collator(features): |
|
return features |
|
|
|
|
|
self.max_prompt_length = args.max_prompt_length |
|
self.max_completion_length = args.max_completion_length |
|
self.num_generations = args.num_generations |
|
self.temperature = args.temperature |
|
self.top_p = args.top_p |
|
self.top_k = args.top_k |
|
self.min_p = args.min_p |
|
self.repetition_penalty = args.repetition_penalty |
|
self.use_vllm = args.use_vllm |
|
self.use_liger_loss = args.use_liger_loss |
|
self.loss_type = args.loss_type |
|
self.scale_rewards = args.scale_rewards |
|
self.mask_truncated_completions = args.mask_truncated_completions |
|
|
|
|
|
self.shuffle_dataset = args.shuffle_dataset |
|
|
|
if ( |
|
isinstance(train_dataset, IterableDataset) |
|
or isinstance(eval_dataset, IterableDataset) |
|
or ( |
|
isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values()) |
|
) |
|
): |
|
|
|
raise NotImplementedError( |
|
"Iterable datasets are not yet supported in GRPOTrainer. Please use a standard dataset instead." |
|
) |
|
|
|
|
|
self.num_iterations = args.num_iterations |
|
self.epsilon_low = args.epsilon |
|
self.epsilon_high = args.epsilon_high if args.epsilon_high is not None else args.epsilon |
|
|
|
self._step = 0 |
|
|
|
|
|
self._buffered_inputs = None |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model.warnings_issued["estimate_tokens"] = True |
|
|
|
if self.use_liger_loss: |
|
if not is_liger_kernel_available(): |
|
raise ImportError( |
|
"Liger is required to use `liger_loss` as the GRPO loss. Run `pip install liger-kernel`." |
|
) |
|
if is_peft_model(model): |
|
raise TypeError("Liger loss is not supported with a PEFT model.") |
|
|
|
if self.loss_type != "bnpo": |
|
raise ValueError( |
|
f"The provided loss type (`{self.loss_type}`) is not supported with `use_liger_loss`. Liger loss " |
|
"only supports `bnpo` for now." |
|
) |
|
|
|
self.liger_grpo_loss = LigerFusedLinearGRPOLoss( |
|
beta=self.beta, |
|
epsilon_low=self.epsilon_low, |
|
epsilon_high=self.epsilon_high, |
|
temperature=self.temperature, |
|
use_ref_model=self.ref_model is not None, |
|
) |
|
|
|
super().__init__( |
|
model=model, |
|
args=args, |
|
data_collator=data_collator, |
|
train_dataset=train_dataset, |
|
eval_dataset=eval_dataset, |
|
processing_class=processing_class, |
|
callbacks=callbacks, |
|
optimizers=optimizers, |
|
) |
|
|
|
|
|
self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)} |
|
self._total_train_tokens = 0 |
|
self.log_completions = args.log_completions |
|
self.wandb_log_unique_prompts = args.wandb_log_unique_prompts |
|
self.num_completions_to_print = args.num_completions_to_print |
|
|
|
|
|
maxlen = self.accelerator.num_processes * args.per_device_train_batch_size * args.gradient_accumulation_steps |
|
self._textual_logs = { |
|
"prompt": deque(maxlen=maxlen), |
|
"completion": deque(maxlen=maxlen), |
|
"rewards": defaultdict(lambda: deque(maxlen=maxlen)), |
|
} |
|
|
|
|
|
if self.num_generations < 2: |
|
raise ValueError( |
|
"GRPO requires at least 2 generations per prompt to calculate the advantages. You provided " |
|
f"{self.num_generations}, which is less than the minimum required." |
|
) |
|
num_processes = self.accelerator.num_processes |
|
effective_batch_size = args.per_device_train_batch_size * num_processes * args.gradient_accumulation_steps |
|
possible_values = [ |
|
n_gen for n_gen in range(2, effective_batch_size + 1) if (effective_batch_size) % n_gen == 0 |
|
] |
|
if self.num_generations not in possible_values: |
|
raise ValueError( |
|
f"The effective train batch size ({num_processes} x {args.per_device_train_batch_size} x " |
|
f"{args.gradient_accumulation_steps}) must be evenly divisible by the number of generations per " |
|
f"prompt ({self.num_generations}). Given the current effective train batch size, the valid values for " |
|
f"the number of generations are: {possible_values}." |
|
) |
|
if self.args.eval_strategy != "no": |
|
effective_batch_size = args.per_device_eval_batch_size * num_processes |
|
possible_values = [ |
|
n_gen for n_gen in range(2, effective_batch_size + 1) if (effective_batch_size) % n_gen == 0 |
|
] |
|
if self.num_generations not in possible_values: |
|
raise ValueError( |
|
f"The effective eval batch size ({num_processes} x {args.per_device_eval_batch_size}) must be " |
|
f"evenly divisible by the number of generations per prompt ({self.num_generations}). Given the " |
|
"current effective eval batch size, the valid values for the number of generations are: " |
|
f"{possible_values}." |
|
) |
|
|
|
|
|
|
|
|
|
set_seed(args.seed, device_specific=True) |
|
|
|
if self.use_vllm: |
|
if not is_vllm_available(): |
|
raise ImportError( |
|
"vLLM is not available and `use_vllm` is set to True. Please install vLLM with " |
|
"`pip install vllm` to use it." |
|
) |
|
|
|
if self.accelerator.is_main_process: |
|
self.vllm_client = VLLMClient( |
|
args.vllm_server_host, args.vllm_server_port, connection_timeout=args.vllm_server_timeout |
|
) |
|
self.vllm_client.init_communicator() |
|
|
|
|
|
self.guided_decoding_regex = args.vllm_guided_decoding_regex |
|
|
|
self._last_loaded_step = -1 |
|
|
|
|
|
|
|
|
|
self.accelerator.wait_for_everyone() |
|
else: |
|
self.generation_config = GenerationConfig( |
|
max_new_tokens=self.max_completion_length, |
|
do_sample=True, |
|
pad_token_id=processing_class.pad_token_id, |
|
bos_token_id=processing_class.bos_token_id, |
|
eos_token_id=processing_class.eos_token_id, |
|
temperature=self.temperature, |
|
top_p=self.top_p, |
|
top_k=self.top_k, |
|
min_p=self.min_p, |
|
repetition_penalty=self.repetition_penalty, |
|
cache_implementation=args.cache_implementation, |
|
) |
|
|
|
|
|
|
|
|
|
self.model_accepts_loss_kwargs = False |
|
|
|
|
|
self.model.add_model_tags(self._tag_names) |
|
|
|
if self.ref_model is not None: |
|
if self.is_deepspeed_enabled: |
|
self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) |
|
else: |
|
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) |
|
|
|
if args.sync_ref_model: |
|
self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator)) |
|
|
|
for i, reward_func in enumerate(self.reward_funcs): |
|
if isinstance(reward_func, PreTrainedModel): |
|
if self.is_deepspeed_enabled: |
|
self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator) |
|
else: |
|
self.reward_funcs[i] = self.accelerator.prepare_model(reward_func, evaluation_mode=True) |
|
|
|
def _set_signature_columns_if_needed(self): |
|
|
|
|
|
|
|
|
|
if self._signature_columns is None: |
|
self._signature_columns = ["prompt"] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_train_dataloader(self): |
|
if self.train_dataset is None: |
|
raise ValueError("Trainer: training requires a train_dataset.") |
|
|
|
train_dataset = self.train_dataset |
|
data_collator = self.data_collator |
|
if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): |
|
train_dataset = self._remove_unused_columns(train_dataset, description="training") |
|
else: |
|
data_collator = self._get_collator_with_removed_columns(data_collator, description="training") |
|
|
|
dataloader_params = { |
|
"batch_size": self._train_batch_size * self.args.gradient_accumulation_steps, |
|
"collate_fn": data_collator, |
|
"num_workers": self.args.dataloader_num_workers, |
|
"pin_memory": self.args.dataloader_pin_memory, |
|
"persistent_workers": self.args.dataloader_persistent_workers, |
|
} |
|
|
|
if not isinstance(train_dataset, torch.utils.data.IterableDataset): |
|
dataloader_params["sampler"] = self._get_train_sampler() |
|
dataloader_params["drop_last"] = self.args.dataloader_drop_last |
|
dataloader_params["worker_init_fn"] = seed_worker |
|
dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor |
|
|
|
return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) |
|
|
|
def _get_train_sampler(self) -> Sampler: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
effective_batch_size = ( |
|
self.args.per_device_train_batch_size |
|
* self.accelerator.num_processes |
|
* self.args.gradient_accumulation_steps |
|
) |
|
return RepeatSampler( |
|
data_source=self.train_dataset, |
|
mini_repeat_count=self.num_generations, |
|
batch_size=effective_batch_size // self.num_generations, |
|
repeat_count=self.num_iterations * self.args.gradient_accumulation_steps, |
|
shuffle=self.shuffle_dataset, |
|
seed=self.args.seed, |
|
) |
|
|
|
def _get_eval_sampler(self, eval_dataset) -> Sampler: |
|
|
|
return RepeatSampler( |
|
data_source=eval_dataset, |
|
mini_repeat_count=self.num_generations, |
|
seed=self.args.seed, |
|
) |
|
|
|
def _enable_gradient_checkpointing(self, model: PreTrainedModel, args: GRPOConfig) -> PreTrainedModel: |
|
"""Enables gradient checkpointing for the model.""" |
|
|
|
model.config.use_cache = False |
|
|
|
|
|
if is_peft_model(model): |
|
model.base_model.gradient_checkpointing_enable() |
|
|
|
else: |
|
model.gradient_checkpointing_enable() |
|
|
|
gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {} |
|
use_reentrant = ( |
|
"use_reentrant" not in gradient_checkpointing_kwargs or gradient_checkpointing_kwargs["use_reentrant"] |
|
) |
|
|
|
if use_reentrant: |
|
model.enable_input_require_grads() |
|
|
|
return model |
|
|
|
@profiling_decorator |
|
def _get_last_hidden_state(self, model, input_ids, attention_mask, logits_to_keep=None): |
|
|
|
unwrapped_model = self.accelerator.unwrap_model(model) |
|
last_hidden_state = unwrapped_model.model(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state |
|
last_hidden_state = last_hidden_state[:, :-1, :] |
|
if logits_to_keep is not None: |
|
last_hidden_state = last_hidden_state[:, -logits_to_keep:, :] |
|
return last_hidden_state |
|
|
|
|
|
@profiling_decorator |
|
def _get_per_token_logps(self, model, input_ids, attention_mask, logits_to_keep, batch_size=None) -> torch.Tensor: |
|
batch_size = batch_size or input_ids.size(0) |
|
all_logps = [] |
|
for i in range(0, input_ids.size(0), batch_size): |
|
input_ids_batch = input_ids[i : i + batch_size] |
|
attention_mask_batch = attention_mask[i : i + batch_size] |
|
|
|
|
|
logits = model( |
|
input_ids=input_ids_batch, attention_mask=attention_mask_batch, logits_to_keep=logits_to_keep + 1 |
|
).logits |
|
logits = logits[:, :-1, :] |
|
input_ids_batch = input_ids_batch[:, -logits_to_keep:] |
|
|
|
|
|
logits = logits[:, -logits_to_keep:] |
|
|
|
|
|
logits = logits / self.temperature |
|
logps = selective_log_softmax(logits, input_ids_batch) |
|
all_logps.append(logps) |
|
return torch.cat(all_logps, dim=0) |
|
|
|
@profiling_decorator |
|
def _move_model_to_vllm(self): |
|
|
|
deepspeed_plugin = self.accelerator.state.deepspeed_plugin |
|
zero_stage_3 = deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3 |
|
gather_if_zero3 = deepspeed.zero.GatheredParameters if zero_stage_3 else nullcontext |
|
|
|
if is_peft_model(self.model): |
|
|
|
|
|
with gather_if_zero3(list(self.model.parameters())): |
|
self.model.merge_adapter() |
|
|
|
|
|
for name, param in self.model.named_parameters(): |
|
|
|
name = name.removeprefix("base_model.model.").replace(".base_layer", "") |
|
if self.model.prefix in name: |
|
continue |
|
|
|
if "original_module" in name: |
|
continue |
|
name = name.replace("modules_to_save.default.", "") |
|
|
|
if self.accelerator.is_main_process: |
|
self.vllm_client.update_named_param(name, param.data) |
|
|
|
|
|
self.model.unmerge_adapter() |
|
|
|
else: |
|
|
|
for name, param in self.model.named_parameters(): |
|
with gather_if_zero3([param]): |
|
if self.accelerator.is_main_process: |
|
self.vllm_client.update_named_param(name, param.data) |
|
|
|
|
|
if self.accelerator.is_main_process: |
|
self.vllm_client.reset_prefix_cache() |
|
|
|
@profiling_decorator |
|
def _prepare_inputs( |
|
self, accumulated_local_batch: dict[str, Union[torch.Tensor, Any]] |
|
) -> dict[str, Union[torch.Tensor, Any]]: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
mode = "eval" if self.control.should_evaluate else "train" |
|
if mode == "train": |
|
generate_every = self.args.gradient_accumulation_steps * self.num_iterations |
|
if self._step % generate_every == 0 or self._buffered_inputs is None: |
|
|
|
accumulated_local_batch = self._generate_and_score_completions(accumulated_local_batch) |
|
self._buffered_inputs = split_tensor_dict( |
|
accumulated_local_batch, self.args.gradient_accumulation_steps |
|
) |
|
inputs = self._buffered_inputs[self._step % self.args.gradient_accumulation_steps] |
|
self._step += 1 |
|
else: |
|
|
|
inputs = self._generate_and_score_completions(accumulated_local_batch) |
|
return inputs |
|
|
|
def _generate_and_score_completions( |
|
self, inputs: list[dict[str, Union[torch.Tensor, Any]]] |
|
) -> dict[str, Union[torch.Tensor, Any]]: |
|
device = self.accelerator.device |
|
mode = "eval" if self.control.should_evaluate else "train" |
|
|
|
prompts = [x["prompt"] for x in inputs] |
|
prompts_text = [maybe_apply_chat_template(example, self.processing_class)["prompt"] for example in inputs] |
|
prompt_inputs = self.processing_class( |
|
text=prompts_text, return_tensors="pt", padding=True, padding_side="left", add_special_tokens=False |
|
) |
|
prompt_inputs = super()._prepare_inputs(prompt_inputs) |
|
prompt_ids, prompt_mask = prompt_inputs["input_ids"], prompt_inputs["attention_mask"] |
|
|
|
if self.max_prompt_length is not None: |
|
prompt_ids = prompt_ids[:, -self.max_prompt_length :] |
|
prompt_mask = prompt_mask[:, -self.max_prompt_length :] |
|
|
|
|
|
if self.use_vllm: |
|
|
|
if self.state.global_step != self._last_loaded_step: |
|
self._move_model_to_vllm() |
|
self._last_loaded_step = self.state.global_step |
|
|
|
|
|
all_prompts_text = gather_object(prompts_text) |
|
if self.accelerator.is_main_process: |
|
|
|
|
|
|
|
ordered_set_of_prompts = all_prompts_text[:: self.num_generations] |
|
with profiling_context(self, "vLLM.generate"): |
|
completion_ids = self.vllm_client.generate( |
|
prompts=ordered_set_of_prompts, |
|
n=self.num_generations, |
|
repetition_penalty=self.repetition_penalty, |
|
temperature=self.temperature, |
|
top_p=self.top_p, |
|
top_k=-1 if self.top_k is None else self.top_k, |
|
min_p=0.0 if self.min_p is None else self.min_p, |
|
max_tokens=self.max_completion_length, |
|
guided_decoding_regex=self.guided_decoding_regex, |
|
) |
|
else: |
|
completion_ids = [None] * len(all_prompts_text) |
|
|
|
|
|
completion_ids = broadcast_object_list(completion_ids, from_process=0) |
|
process_slice = slice( |
|
self.accelerator.process_index * len(prompts), |
|
(self.accelerator.process_index + 1) * len(prompts), |
|
) |
|
completion_ids = completion_ids[process_slice] |
|
|
|
|
|
completion_ids = [torch.tensor(ids, device=device) for ids in completion_ids] |
|
completion_ids = pad(completion_ids, padding_value=self.processing_class.pad_token_id) |
|
prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) |
|
else: |
|
|
|
with unwrap_model_for_generation( |
|
self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation |
|
) as unwrapped_model: |
|
prompt_completion_ids = unwrapped_model.generate( |
|
prompt_ids, attention_mask=prompt_mask, generation_config=self.generation_config |
|
) |
|
|
|
|
|
prompt_length = prompt_ids.size(1) |
|
prompt_ids = prompt_completion_ids[:, :prompt_length] |
|
completion_ids = prompt_completion_ids[:, prompt_length:] |
|
|
|
|
|
is_eos = completion_ids == self.processing_class.eos_token_id |
|
eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device) |
|
eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)] |
|
sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1) |
|
completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int() |
|
|
|
|
|
if self.mask_truncated_completions: |
|
truncated_completions = ~is_eos.any(dim=1) |
|
completion_mask = completion_mask * (~truncated_completions).unsqueeze(1).int() |
|
|
|
|
|
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) |
|
|
|
logits_to_keep = completion_ids.size(1) |
|
batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size |
|
|
|
with torch.no_grad(): |
|
|
|
|
|
if self.num_iterations > 1: |
|
old_per_token_logps = self._get_per_token_logps( |
|
self.model, prompt_completion_ids, attention_mask, logits_to_keep, batch_size |
|
) |
|
else: |
|
old_per_token_logps = None |
|
|
|
if self.beta == 0.0: |
|
ref_per_token_logps = None |
|
elif self.ref_model is not None: |
|
ref_per_token_logps = self._get_per_token_logps( |
|
self.ref_model, prompt_completion_ids, attention_mask, logits_to_keep, batch_size |
|
) |
|
else: |
|
with self.accelerator.unwrap_model(self.model).disable_adapter(): |
|
ref_per_token_logps = self._get_per_token_logps( |
|
self.model, prompt_completion_ids, attention_mask, logits_to_keep, batch_size |
|
) |
|
|
|
|
|
completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) |
|
if is_conversational(inputs[0]): |
|
completions = [] |
|
for prompt, completion in zip(prompts, completions_text): |
|
bootstrap = prompt.pop()["content"] if prompt[-1]["role"] == "assistant" else "" |
|
completions.append([{"role": "assistant", "content": bootstrap + completion}]) |
|
else: |
|
completions = completions_text |
|
|
|
rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device) |
|
for i, (reward_func, reward_processing_class, reward_func_name) in enumerate( |
|
zip(self.reward_funcs, self.reward_processing_classes, self.reward_func_names) |
|
): |
|
with profiling_context(self, reward_func_name): |
|
if isinstance( |
|
reward_func, nn.Module |
|
): |
|
if is_conversational(inputs[0]): |
|
messages = [{"messages": p + c} for p, c in zip(prompts, completions)] |
|
texts = [apply_chat_template(x, reward_processing_class)["text"] for x in messages] |
|
else: |
|
texts = [p + c for p, c in zip(prompts, completions)] |
|
reward_inputs = reward_processing_class( |
|
text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False |
|
) |
|
reward_inputs = super()._prepare_inputs(reward_inputs) |
|
with torch.inference_mode(): |
|
rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] |
|
else: |
|
|
|
keys = [key for key in inputs[0] if key not in ["prompt", "completion"]] |
|
reward_kwargs = {key: [example[key] for example in inputs] for key in keys} |
|
output_reward_func = reward_func(prompts=prompts, completions=completions, **reward_kwargs) |
|
|
|
output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func] |
|
|
|
rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device) |
|
|
|
|
|
if torch.isnan(rewards_per_func).all(dim=1).any(): |
|
nan_row_idx = torch.isnan(rewards_per_func).all(dim=1).nonzero(as_tuple=True)[0][0] |
|
row_reward_kwargs = {key: value[nan_row_idx] for key, value in reward_kwargs.items()} |
|
row_reward_kwargs["prompt"] = prompts[nan_row_idx] |
|
row_reward_kwargs["completion"] = completions[nan_row_idx] |
|
warnings.warn( |
|
f"All reward functions returned None for the following kwargs: {row_reward_kwargs}. " |
|
"Please ensure that at least one reward function returns a valid reward." |
|
) |
|
|
|
|
|
|
|
rewards_per_func = gather(rewards_per_func) |
|
|
|
|
|
rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1) |
|
|
|
|
|
mean_grouped_rewards = rewards.view(-1, self.num_generations).mean(dim=1) |
|
std_grouped_rewards = rewards.view(-1, self.num_generations).std(dim=1) |
|
|
|
|
|
mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(self.num_generations, dim=0) |
|
std_grouped_rewards = std_grouped_rewards.repeat_interleave(self.num_generations, dim=0) |
|
advantages = rewards - mean_grouped_rewards |
|
if self.scale_rewards: |
|
advantages = advantages / (std_grouped_rewards + 1e-4) |
|
|
|
|
|
process_slice = slice( |
|
self.accelerator.process_index * len(prompts), |
|
(self.accelerator.process_index + 1) * len(prompts), |
|
) |
|
advantages = advantages[process_slice] |
|
|
|
|
|
if mode == "train": |
|
self.state.num_input_tokens_seen += self.accelerator.gather_for_metrics(attention_mask.sum()).sum().item() |
|
self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen] |
|
|
|
|
|
agg_completion_mask = self.accelerator.gather_for_metrics(completion_mask.sum(1)) |
|
self._metrics[mode]["completions/mean_length"].append(agg_completion_mask.float().mean().item()) |
|
self._metrics[mode]["completions/min_length"].append(agg_completion_mask.float().min().item()) |
|
self._metrics[mode]["completions/max_length"].append(agg_completion_mask.float().max().item()) |
|
|
|
|
|
agg_terminated_with_eos = self.accelerator.gather_for_metrics(is_eos.any(dim=1)) |
|
term_completion_mask = agg_completion_mask[agg_terminated_with_eos] |
|
clipped_completions_ratio = 1 - len(term_completion_mask) / len(agg_completion_mask) |
|
self._metrics[mode]["completions/clipped_ratio"].append(clipped_completions_ratio) |
|
if len(term_completion_mask) == 0: |
|
|
|
term_completion_mask = torch.zeros(1, device=device) |
|
self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_mask.float().mean().item()) |
|
self._metrics[mode]["completions/min_terminated_length"].append(term_completion_mask.float().min().item()) |
|
self._metrics[mode]["completions/max_terminated_length"].append(term_completion_mask.float().max().item()) |
|
|
|
|
|
for i, reward_func_name in enumerate(self.reward_func_names): |
|
mean_rewards = torch.nanmean(rewards_per_func[:, i]).item() |
|
self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards) |
|
std_rewards = nanstd(rewards_per_func[:, i]).item() |
|
self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_rewards) |
|
self._metrics[mode]["reward"].append(mean_grouped_rewards.mean().item()) |
|
self._metrics[mode]["reward_std"].append(std_grouped_rewards.mean().item()) |
|
|
|
|
|
self._textual_logs["prompt"].extend(gather_object(prompts_text)) |
|
self._textual_logs["completion"].extend(gather_object(completions_text)) |
|
for i, name in enumerate(self.reward_func_names): |
|
self._textual_logs["rewards"][name].extend(rewards_per_func[:, i].tolist()) |
|
|
|
return { |
|
"prompt_ids": prompt_ids, |
|
"prompt_mask": prompt_mask, |
|
"completion_ids": completion_ids, |
|
"completion_mask": completion_mask, |
|
"advantages": advantages, |
|
"old_per_token_logps": old_per_token_logps, |
|
"ref_per_token_logps": ref_per_token_logps, |
|
} |
|
|
|
def compute_liger_loss(self, model, inputs): |
|
|
|
prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] |
|
completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] |
|
input_ids = torch.cat([prompt_ids, completion_ids], dim=1) |
|
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) |
|
logits_to_keep = completion_ids.size(1) |
|
|
|
|
|
last_hidden_state = self._get_last_hidden_state(model, input_ids, attention_mask, logits_to_keep) |
|
unwrapped_model = self.accelerator.unwrap_model(model) |
|
|
|
loss, metrics = self.liger_grpo_loss( |
|
_input=last_hidden_state, |
|
lin_weight=unwrapped_model.lm_head.weight, |
|
selected_token_ids=completion_ids, |
|
attention_mask=completion_mask, |
|
advantages=inputs["advantages"], |
|
bias=unwrapped_model.lm_head.bias, |
|
ref_per_token_logps=inputs["ref_per_token_logps"], |
|
old_per_token_logps=inputs["old_per_token_logps"], |
|
) |
|
|
|
|
|
mean_kl = metrics[0] if self.beta != 0.0 else None |
|
clip_ratio = metrics[-1] |
|
|
|
mode = "eval" if self.control.should_evaluate else "train" |
|
if self.beta != 0.0: |
|
self._metrics[mode]["kl"].append(self.accelerator.gather_for_metrics(mean_kl).mean().item()) |
|
self._metrics[mode]["clip_ratio"].append(self.accelerator.gather_for_metrics(clip_ratio).mean().item()) |
|
return loss |
|
|
|
@profiling_decorator |
|
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): |
|
if return_outputs: |
|
raise ValueError("The GRPOTrainer does not support returning outputs") |
|
if self.use_liger_loss: |
|
|
|
return self.compute_liger_loss(model, inputs) |
|
else: |
|
return self._compute_loss(model, inputs) |
|
|
|
def _compute_loss(self, model, inputs): |
|
|
|
prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"] |
|
completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"] |
|
input_ids = torch.cat([prompt_ids, completion_ids], dim=1) |
|
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) |
|
logits_to_keep = completion_ids.size(1) |
|
|
|
per_token_logps = self._get_per_token_logps(model, input_ids, attention_mask, logits_to_keep) |
|
|
|
|
|
if self.beta != 0.0: |
|
ref_per_token_logps = inputs["ref_per_token_logps"] |
|
per_token_kl = ( |
|
torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1 |
|
) |
|
|
|
|
|
advantages = inputs["advantages"] |
|
|
|
|
|
old_per_token_logps = inputs["old_per_token_logps"] if self.num_iterations > 1 else per_token_logps.detach() |
|
coef_1 = torch.exp(per_token_logps - old_per_token_logps) |
|
coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high) |
|
per_token_loss1 = coef_1 * advantages.unsqueeze(1) |
|
per_token_loss2 = coef_2 * advantages.unsqueeze(1) |
|
per_token_loss = -torch.min(per_token_loss1, per_token_loss2) |
|
if self.beta != 0.0: |
|
per_token_loss = per_token_loss + self.beta * per_token_kl |
|
|
|
if self.loss_type == "grpo": |
|
loss = ((per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)).mean() |
|
elif self.loss_type == "bnpo": |
|
loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0) |
|
elif self.loss_type == "dr_grpo": |
|
loss = (per_token_loss * completion_mask).sum() / (per_token_loss.size(0) * self.max_completion_length) |
|
else: |
|
raise ValueError(f"Unknown loss type: {self.loss_type}") |
|
|
|
|
|
mode = "eval" if self.control.should_evaluate else "train" |
|
|
|
if self.beta != 0.0: |
|
mean_kl = (per_token_kl * completion_mask).sum() / completion_mask.sum() |
|
self._metrics[mode]["kl"].append(self.accelerator.gather_for_metrics(mean_kl).nanmean().item()) |
|
|
|
|
|
is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages.unsqueeze(1) < 0) |
|
is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages.unsqueeze(1) > 0) |
|
is_region_clipped = is_low_clipped | is_high_clipped |
|
|
|
low_clip = (is_low_clipped * completion_mask).sum() / completion_mask.sum() |
|
high_clip = (is_high_clipped * completion_mask).sum() / completion_mask.sum() |
|
clip_ratio = (is_region_clipped * completion_mask).sum() / completion_mask.sum() |
|
|
|
gathered_low_clip = self.accelerator.gather_for_metrics(low_clip) |
|
self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item()) |
|
self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item()) |
|
gathered_high_clip = self.accelerator.gather_for_metrics(high_clip) |
|
self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item()) |
|
self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item()) |
|
gathered_clip_ratio = self.accelerator.gather_for_metrics(clip_ratio) |
|
self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item()) |
|
return loss |
|
|
|
def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: Optional[list[str]] = None): |
|
inputs = self._prepare_inputs(inputs) |
|
with torch.no_grad(): |
|
with self.compute_loss_context_manager(): |
|
loss = self.compute_loss(model, inputs) |
|
loss = loss.mean().detach() |
|
return loss, None, None |
|
|
|
def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None: |
|
mode = "eval" if self.control.should_evaluate else "train" |
|
metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} |
|
|
|
|
|
|
|
if mode == "eval": |
|
metrics = {f"eval_{key}": val for key, val in metrics.items()} |
|
|
|
logs = {**logs, **metrics} |
|
if version.parse(transformers.__version__) >= version.parse("4.47.0.dev0"): |
|
super().log(logs, start_time) |
|
else: |
|
super().log(logs) |
|
self._metrics[mode].clear() |
|
|
|
if self.accelerator.is_main_process and self.log_completions: |
|
if is_rich_available(): |
|
print_prompt_completions_sample( |
|
self._textual_logs["prompt"], |
|
self._textual_logs["completion"], |
|
self._textual_logs["rewards"], |
|
self.state.global_step, |
|
self.num_completions_to_print, |
|
) |
|
|
|
if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None: |
|
import pandas as pd |
|
|
|
table = { |
|
"step": [str(self.state.global_step)] * len(self._textual_logs["prompt"]), |
|
"prompt": self._textual_logs["prompt"], |
|
"completion": self._textual_logs["completion"], |
|
**self._textual_logs["rewards"], |
|
} |
|
df = pd.DataFrame(table) |
|
if self.wandb_log_unique_prompts: |
|
df = df.drop_duplicates(subset=["prompt"]) |
|
wandb.log({"completions": wandb.Table(dataframe=df)}) |
|
|
|
def create_model_card( |
|
self, |
|
model_name: Optional[str] = None, |
|
dataset_name: Optional[str] = None, |
|
tags: Union[str, list[str], None] = None, |
|
): |
|
""" |
|
Creates a draft of a model card using the information available to the `Trainer`. |
|
|
|
Args: |
|
model_name (`str` or `None`, *optional*, defaults to `None`): |
|
Name of the model. |
|
dataset_name (`str` or `None`, *optional*, defaults to `None`): |
|
Name of the dataset used for training. |
|
tags (`str`, `list[str]` or `None`, *optional*, defaults to `None`): |
|
Tags to be associated with the model card. |
|
""" |
|
if not self.is_world_process_zero(): |
|
return |
|
|
|
if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): |
|
base_model = self.model.config._name_or_path |
|
else: |
|
base_model = None |
|
|
|
tags = tags or [] |
|
if isinstance(tags, str): |
|
tags = [tags] |
|
|
|
if hasattr(self.model.config, "unsloth_version"): |
|
tags.append("unsloth") |
|
|
|
citation = textwrap.dedent( |
|
"""\ |
|
@article{zhihong2024deepseekmath, |
|
title = {{DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models}}, |
|
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}, |
|
year = 2024, |
|
eprint = {arXiv:2402.03300}, |
|
} |
|
""" |
|
) |
|
|
|
model_card = generate_model_card( |
|
base_model=base_model, |
|
model_name=model_name, |
|
hub_model_id=self.hub_model_id, |
|
dataset_name=dataset_name, |
|
tags=tags, |
|
wandb_url=wandb.run.get_url() if is_wandb_available() and wandb.run is not None else None, |
|
comet_url=get_comet_experiment_url(), |
|
trainer_name="GRPO", |
|
trainer_citation=citation, |
|
paper_title="DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models", |
|
paper_id="2402.03300", |
|
) |
|
|
|
model_card.save(os.path.join(self.args.output_dir, "README.md")) |
|
|