cciwon-code-review-cli 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/bin/code-review.js +1 -1
  2. package/lib/chat-mode.js +7 -2
  3. package/package.json +1 -1
  4. package/unsloth_compiled_cache/.locks/.lock.AqlmLoraLinear_peft_forward.py +0 -0
  5. package/unsloth_compiled_cache/.locks/.lock.AwqLoraLinear_peft_forward.py +0 -0
  6. package/unsloth_compiled_cache/.locks/.lock.BatchNorm1d.py +0 -0
  7. package/unsloth_compiled_cache/.locks/.lock.BatchNorm2d.py +0 -0
  8. package/unsloth_compiled_cache/.locks/.lock.BatchNorm3d.py +0 -0
  9. package/unsloth_compiled_cache/.locks/.lock.Conv1d.py +0 -0
  10. package/unsloth_compiled_cache/.locks/.lock.Conv2d.py +0 -0
  11. package/unsloth_compiled_cache/.locks/.lock.Conv3d.py +0 -0
  12. package/unsloth_compiled_cache/.locks/.lock.ConvTranspose1d.py +0 -0
  13. package/unsloth_compiled_cache/.locks/.lock.ConvTranspose2d.py +0 -0
  14. package/unsloth_compiled_cache/.locks/.lock.ConvTranspose3d.py +0 -0
  15. package/unsloth_compiled_cache/.locks/.lock.GPTQLoraLinear_peft_forward.py +0 -0
  16. package/unsloth_compiled_cache/.locks/.lock.GroupNorm.py +0 -0
  17. package/unsloth_compiled_cache/.locks/.lock.LayerNorm.py +0 -0
  18. package/unsloth_compiled_cache/.locks/.lock.Linear4bit_peft_forward.py +0 -0
  19. package/unsloth_compiled_cache/.locks/.lock.Linear8bitLt_peft_forward.py +0 -0
  20. package/unsloth_compiled_cache/.locks/.lock.Linear_peft_forward.py +0 -0
  21. package/unsloth_compiled_cache/.locks/.lock.LoraParallelLinear_peft_forward.py +0 -0
  22. package/unsloth_compiled_cache/.locks/.lock.RMSNorm.py +0 -0
  23. package/unsloth_compiled_cache/.locks/.lock.UnslothBCOTrainer.py +0 -0
  24. package/unsloth_compiled_cache/.locks/.lock.UnslothCPOTrainer.py +0 -0
  25. package/unsloth_compiled_cache/.locks/.lock.UnslothDPOTrainer.py +0 -0
  26. package/unsloth_compiled_cache/.locks/.lock.UnslothGKDTrainer.py +0 -0
  27. package/unsloth_compiled_cache/.locks/.lock.UnslothGRPOTrainer.py +0 -0
  28. package/unsloth_compiled_cache/.locks/.lock.UnslothKTOTrainer.py +0 -0
  29. package/unsloth_compiled_cache/.locks/.lock.UnslothNashMDTrainer.py +0 -0
  30. package/unsloth_compiled_cache/.locks/.lock.UnslothORPOTrainer.py +0 -0
  31. package/unsloth_compiled_cache/.locks/.lock.UnslothOnlineDPOTrainer.py +0 -0
  32. package/unsloth_compiled_cache/.locks/.lock.UnslothPPOTrainer.py +0 -0
  33. package/unsloth_compiled_cache/.locks/.lock.UnslothPRMTrainer.py +0 -0
  34. package/unsloth_compiled_cache/.locks/.lock.UnslothRLOOTrainer.py +0 -0
  35. package/unsloth_compiled_cache/.locks/.lock.UnslothRewardTrainer.py +0 -0
  36. package/unsloth_compiled_cache/.locks/.lock.UnslothSFTTrainer.py +0 -0
  37. package/unsloth_compiled_cache/.locks/.lock.UnslothXPOTrainer.py +0 -0
  38. package/unsloth_compiled_cache/.locks/.lock.unsloth_compiled_module_qwen3_moe.py +0 -0
  39. package/unsloth_compiled_cache/.locks/.lock.unsloth_compiled_module_siglip.py +0 -0
  40. package/unsloth_compiled_cache/AqlmLoraLinear_peft_forward.py +88 -0
  41. package/unsloth_compiled_cache/AwqLoraLinear_peft_forward.py +87 -0
  42. package/unsloth_compiled_cache/BatchNorm1d.py +117 -0
  43. package/unsloth_compiled_cache/BatchNorm2d.py +117 -0
  44. package/unsloth_compiled_cache/BatchNorm3d.py +117 -0
  45. package/unsloth_compiled_cache/Conv1d.py +70 -0
  46. package/unsloth_compiled_cache/Conv2d.py +70 -0
  47. package/unsloth_compiled_cache/Conv3d.py +70 -0
  48. package/unsloth_compiled_cache/ConvTranspose1d.py +97 -0
  49. package/unsloth_compiled_cache/ConvTranspose2d.py +106 -0
  50. package/unsloth_compiled_cache/ConvTranspose3d.py +98 -0
  51. package/unsloth_compiled_cache/GPTQLoraLinear_peft_forward.py +95 -0
  52. package/unsloth_compiled_cache/GroupNorm.py +70 -0
  53. package/unsloth_compiled_cache/LayerNorm.py +72 -0
  54. package/unsloth_compiled_cache/Linear4bit_peft_forward.py +115 -0
  55. package/unsloth_compiled_cache/Linear8bitLt_peft_forward.py +113 -0
  56. package/unsloth_compiled_cache/Linear_peft_forward.py +104 -0
  57. package/unsloth_compiled_cache/LoraParallelLinear_peft_forward.py +91 -0
  58. package/unsloth_compiled_cache/RMSNorm.py +73 -0
  59. package/unsloth_compiled_cache/UnslothBCOTrainer.py +2026 -0
  60. package/unsloth_compiled_cache/UnslothCPOTrainer.py +1806 -0
  61. package/unsloth_compiled_cache/UnslothDPOTrainer.py +2750 -0
  62. package/unsloth_compiled_cache/UnslothGKDTrainer.py +1157 -0
  63. package/unsloth_compiled_cache/UnslothGRPOTrainer.py +3607 -0
  64. package/unsloth_compiled_cache/UnslothKTOTrainer.py +2220 -0
  65. package/unsloth_compiled_cache/UnslothNashMDTrainer.py +1210 -0
  66. package/unsloth_compiled_cache/UnslothORPOTrainer.py +1730 -0
  67. package/unsloth_compiled_cache/UnslothOnlineDPOTrainer.py +2313 -0
  68. package/unsloth_compiled_cache/UnslothPPOTrainer.py +1504 -0
  69. package/unsloth_compiled_cache/UnslothPRMTrainer.py +979 -0
  70. package/unsloth_compiled_cache/UnslothRLOOTrainer.py +2674 -0
  71. package/unsloth_compiled_cache/UnslothRewardTrainer.py +1197 -0
  72. package/unsloth_compiled_cache/UnslothSFTTrainer.py +1416 -0
  73. package/unsloth_compiled_cache/UnslothXPOTrainer.py +1255 -0
  74. package/unsloth_compiled_cache/__pycache__/AqlmLoraLinear_peft_forward.cpython-312.pyc +0 -0
  75. package/unsloth_compiled_cache/__pycache__/AwqLoraLinear_peft_forward.cpython-312.pyc +0 -0
  76. package/unsloth_compiled_cache/__pycache__/BatchNorm1d.cpython-312.pyc +0 -0
  77. package/unsloth_compiled_cache/__pycache__/BatchNorm2d.cpython-312.pyc +0 -0
  78. package/unsloth_compiled_cache/__pycache__/BatchNorm3d.cpython-312.pyc +0 -0
  79. package/unsloth_compiled_cache/__pycache__/Conv1d.cpython-312.pyc +0 -0
  80. package/unsloth_compiled_cache/__pycache__/Conv2d.cpython-312.pyc +0 -0
  81. package/unsloth_compiled_cache/__pycache__/Conv3d.cpython-312.pyc +0 -0
  82. package/unsloth_compiled_cache/__pycache__/ConvTranspose1d.cpython-312.pyc +0 -0
  83. package/unsloth_compiled_cache/__pycache__/ConvTranspose2d.cpython-312.pyc +0 -0
  84. package/unsloth_compiled_cache/__pycache__/ConvTranspose3d.cpython-312.pyc +0 -0
  85. package/unsloth_compiled_cache/__pycache__/GPTQLoraLinear_peft_forward.cpython-312.pyc +0 -0
  86. package/unsloth_compiled_cache/__pycache__/GroupNorm.cpython-312.pyc +0 -0
  87. package/unsloth_compiled_cache/__pycache__/LayerNorm.cpython-312.pyc +0 -0
  88. package/unsloth_compiled_cache/__pycache__/Linear4bit_peft_forward.cpython-312.pyc +0 -0
  89. package/unsloth_compiled_cache/__pycache__/Linear8bitLt_peft_forward.cpython-312.pyc +0 -0
  90. package/unsloth_compiled_cache/__pycache__/Linear_peft_forward.cpython-312.pyc +0 -0
  91. package/unsloth_compiled_cache/__pycache__/LoraParallelLinear_peft_forward.cpython-312.pyc +0 -0
  92. package/unsloth_compiled_cache/__pycache__/RMSNorm.cpython-312.pyc +0 -0
  93. package/unsloth_compiled_cache/__pycache__/UnslothBCOTrainer.cpython-312.pyc +0 -0
  94. package/unsloth_compiled_cache/__pycache__/UnslothCPOTrainer.cpython-312.pyc +0 -0
  95. package/unsloth_compiled_cache/__pycache__/UnslothDPOTrainer.cpython-312.pyc +0 -0
  96. package/unsloth_compiled_cache/__pycache__/UnslothGKDTrainer.cpython-312.pyc +0 -0
  97. package/unsloth_compiled_cache/__pycache__/UnslothGRPOTrainer.cpython-312.pyc +0 -0
  98. package/unsloth_compiled_cache/__pycache__/UnslothKTOTrainer.cpython-312.pyc +0 -0
  99. package/unsloth_compiled_cache/__pycache__/UnslothNashMDTrainer.cpython-312.pyc +0 -0
  100. package/unsloth_compiled_cache/__pycache__/UnslothORPOTrainer.cpython-312.pyc +0 -0
  101. package/unsloth_compiled_cache/__pycache__/UnslothOnlineDPOTrainer.cpython-312.pyc +0 -0
  102. package/unsloth_compiled_cache/__pycache__/UnslothPPOTrainer.cpython-312.pyc +0 -0
  103. package/unsloth_compiled_cache/__pycache__/UnslothPRMTrainer.cpython-312.pyc +0 -0
  104. package/unsloth_compiled_cache/__pycache__/UnslothRLOOTrainer.cpython-312.pyc +0 -0
  105. package/unsloth_compiled_cache/__pycache__/UnslothRewardTrainer.cpython-312.pyc +0 -0
  106. package/unsloth_compiled_cache/__pycache__/UnslothSFTTrainer.cpython-312.pyc +0 -0
  107. package/unsloth_compiled_cache/__pycache__/UnslothXPOTrainer.cpython-312.pyc +0 -0
  108. package/unsloth_compiled_cache/__pycache__/unsloth_compiled_module_qwen3_moe.cpython-312.pyc +0 -0
  109. package/unsloth_compiled_cache/__pycache__/unsloth_compiled_module_siglip.cpython-312.pyc +0 -0
  110. package/unsloth_compiled_cache/unsloth_compiled_module_qwen3_moe.py +726 -0
  111. package/unsloth_compiled_cache/unsloth_compiled_module_siglip.py +534 -0
@@ -0,0 +1,2674 @@
1
+ """
2
+ 2025.12.6
3
+ 2025.12.7
4
+ 4.57.1
5
+ 0.24.0
6
+ __UNSLOTH_VERSIONING__
7
+ """
8
+
9
+ # Unsloth auto generated code
10
+ # Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.
11
+ #
12
+ # This program is free software: you can redistribute it and/or modify
13
+ # it under the terms of the GNU Lesser General Public License as published by
14
+ # the Free Software Foundation, either version 3 of the License, or
15
+ # (at your option) any later version.
16
+ #
17
+ # This program is distributed in the hope that it will be useful,
18
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
19
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20
+ # GNU General Public License for more details.
21
+ #
22
+ # You should have received a copy of the GNU Lesser General Public License
23
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
24
+
25
+ from torch import Tensor
26
+ import torch
27
+ import torch.nn as nn
28
+ from torch.nn import functional as F
29
+ from typing import Any, List, Optional, Tuple, Union, Dict, Set, Callable
30
+ from trl.trainer.rloo_trainer import (Any, AutoConfig, AutoModelForSequenceClassification, AutoProcessor, AutoTokenizer, BaseTrainer, DataLoader, Dataset, FSDP, GenerationConfig, GuidedDecodingParams, IterableDataset, LLM, Optional, Path, PeftConfig, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, RLOOConfig, RLOOTrainer, RepeatSampler, RewardFunc, Sampler, SamplingParams, SyncRefModelCallback, TrainerCallback, Union, VLLMClient, apply_chat_template, broadcast_object_list, datasets, defaultdict, deque, disable_dropout_in_model, ensure_master_addr_port, entropy_from_logits, gather, gather_object, identity, inspect, is_conversational, is_datasets_available, is_flash_attn_2_available, is_peft_model, is_rich_available, is_vllm_available, logger, logging, maybe_apply_chat_template, nanmax, nanmin, nanstd, nn, nullcontext, os, pad, partial, prepare_deepspeed, prepare_fsdp, prepare_multimodal_messages, prepare_peft_model, print_prompt_completions_sample, profiling_context, profiling_decorator, seed_worker, selective_log_softmax, set_seed, shuffle_sequence_dict, split_pixel_values_by_grid, split_tensor_dict, textwrap, torch, transformers, unsplit_pixel_values_by_grid, unwrap_model_for_generation, warnings, FSDP, GuidedDecodingParams, LLM, Optional, SamplingParams, apply_chat_template, broadcast_object_list, gather, gather_object, is_flash_attn_2_available, maybe_apply_chat_template, nullcontext, os, pad, prepare_multimodal_messages, profiling_context, torch, transformers, unwrap_model_for_generation, FSDP, LLM, gather, is_peft_model, nn, nullcontext, os, profiling_decorator, Any, Union, profiling_decorator, shuffle_sequence_dict, split_pixel_values_by_grid, split_tensor_dict, torch, unsplit_pixel_values_by_grid, Optional, PreTrainedModel, logger, os, torch, FSDP, LLM, nn, os, FSDP, nn, torch)
31
+
32
+
33
+ import os
34
+ from typing import *
35
+ from dataclasses import dataclass, field
36
+ from packaging.version import Version
37
+ import torch
38
+ import numpy as np
39
+ from contextlib import nullcontext
40
+ from torch.nn import functional as F
41
+ import inspect
42
+ from transformers import DataCollatorForSeq2Seq, DataCollatorForLanguageModeling as TransformersDataCollatorForLanguageModeling
43
+ from transformers.training_args import ParallelMode
44
+
45
+ # Wrap trainer with padding to right and enable training mode
46
+ # Also patches W&B since multiple runs must use wandb.finish()
47
+ import functools
48
+ from types import MethodType
49
+ def prepare_for_training_mode(f):
50
+ @functools.wraps(f)
51
+ def wrapper(self, *args, **kwargs):
52
+ # Enable training mode
53
+ if hasattr(self, 'model') and hasattr(self.model, "for_training"):
54
+ self.model.for_training()
55
+ output = f(self, *args, **kwargs)
56
+ # Return inference mode
57
+ if hasattr(self, 'model') and hasattr(self.model, "for_inference"):
58
+ self.model.for_inference()
59
+ # Patch W&B to enable logging on future runs, otherwise it'll overwrite the first run
60
+ try:
61
+ import wandb
62
+ wandb.finish()
63
+ except:
64
+ pass
65
+ return output
66
+ return wrapper
67
+ pass
68
+
69
+ torch_compile_options = {
70
+ "epilogue_fusion" : True,
71
+ "max_autotune" : False,
72
+ "shape_padding" : True,
73
+ "trace.enabled" : False,
74
+ "triton.cudagraphs" : False,
75
+ }
76
+
77
+ @torch.compile(dynamic = True, fullgraph = True, options = torch_compile_options,)
78
+ def chunked_selective_log_softmax(logits, index):
79
+ # Split into 4 chunks only
80
+ chunked_logits = torch.chunk(logits.reshape(-1, logits.shape[-1]), chunks = 4, dim = 0)
81
+ chunked_index = torch.chunk(index.reshape(-1), chunks = 4, dim = 0)
82
+ all_per_token_logps = []
83
+ # Below loop does the same as selective_log_softmax(chunk_logits, chunk_index)
84
+ for chunk_logits, chunk_index in zip(chunked_logits, chunked_index):
85
+ chunk_logits = chunk_logits.to(torch.float32)
86
+ selected_logits = torch.gather(chunk_logits, dim = -1, index = chunk_index.unsqueeze(-1)).squeeze(-1)
87
+ logsumexp_values = torch.logsumexp(chunk_logits, dim = -1)
88
+ per_token_logps = selected_logits - logsumexp_values
89
+ all_per_token_logps.append(per_token_logps)
90
+ pass
91
+ all_per_token_logps = torch.concat(all_per_token_logps)
92
+ all_per_token_logps = all_per_token_logps.reshape((logits.shape[0], logits.shape[1]))
93
+ return all_per_token_logps
94
+
95
+ def calculate_pad_tokens_in_prompt(
96
+ input_ids: torch.Tensor,
97
+ logits_to_keep: int,
98
+ pad_token_id: int
99
+ ) -> torch.Tensor:
100
+ """
101
+ Given prompt tensor, it returns all the left padded tokens in that sequence. so [pad, pad, pad, cat] = 3 tokens
102
+ """
103
+ if logits_to_keep >= input_ids.shape[1]:
104
+ raise ValueError("logits_to_keep must be smaller than the sequence length.")
105
+
106
+ prompt_section = input_ids[:, :-logits_to_keep]
107
+
108
+ padding_mask = (prompt_section == pad_token_id)
109
+
110
+ pad_token_counts = padding_mask.sum(dim=1)
111
+
112
+ return pad_token_counts
113
+
114
+ def create_completion_attention_mask(
115
+ completion_input_ids: torch.Tensor,
116
+ left_pad_tokens_per_prompt: torch.Tensor,
117
+ max_left_pad: int,
118
+ pad_token_id: int
119
+ ) -> torch.Tensor:
120
+ """
121
+ Given that we have a sequence, [p,p,p,c,c,c,pad,pad,pad]
122
+
123
+ Where p are extra prompt tokens we got from slicing the torch tensor, c is completion tokens
124
+ and pad are pad tokens, this function would make a completion mask that would 0 out the pad
125
+ and p tokens. so in this example [0,0,0,1,1,1,0,0,0]
126
+ """
127
+ batch_size, completion_len = completion_input_ids.shape
128
+ device = completion_input_ids.device
129
+
130
+ num_tokens_to_mask = max_left_pad - left_pad_tokens_per_prompt
131
+
132
+ indices = torch.arange(completion_len, device=device).unsqueeze(0)
133
+ shift_mask = indices >= num_tokens_to_mask.unsqueeze(1)
134
+
135
+ non_padding_mask = (completion_input_ids != pad_token_id)
136
+
137
+ final_mask = shift_mask & non_padding_mask
138
+
139
+ return final_mask
140
+
141
+ def left_pack_padding(tensor: torch.Tensor, pad_id: int) -> torch.Tensor:
142
+ """
143
+ Moves all padding tokens in each sequence of a batch to the right.
144
+ """
145
+ mask = (tensor != pad_id)
146
+ # Must do stable=True since binary mark is unordered
147
+ sorted_indices = torch.argsort(mask, dim=1, descending=True, stable=True)
148
+ packed_tensor = torch.gather(tensor, 1, sorted_indices)
149
+ return packed_tensor
150
+
151
+ def align_logprobs_with_mask(
152
+ logprob_tensor: torch.Tensor,
153
+ attention_mask: torch.Tensor,
154
+ pad_value: float = 0.0
155
+ ) -> torch.Tensor:
156
+ """
157
+ Aligns a log probability tensor with a given attention mask.
158
+ """
159
+
160
+ device = logprob_tensor.device
161
+ batch_size, logprob_seq_len = logprob_tensor.shape
162
+ mask_seq_len = attention_mask.shape[1]
163
+
164
+ padded_logprobs = torch.full(
165
+ attention_mask.shape,
166
+ fill_value=pad_value,
167
+ dtype=logprob_tensor.dtype,
168
+ device=device
169
+ )
170
+
171
+ left_pad_counts = torch.argmax(attention_mask, dim=1)
172
+
173
+ cols = torch.arange(logprob_seq_len, device=device)
174
+ dest_indices = left_pad_counts.unsqueeze(1) + cols
175
+
176
+ # Create destination row indices
177
+ # Shape: [batch_size, logprob_seq_len]
178
+ row_indices = torch.arange(batch_size, device=device).unsqueeze(1).expand_as(dest_indices)
179
+
180
+ # --- 4. Filter out-of-bounds indices and perform assignment ---
181
+ # Create a mask to identify only the indices that are within the bounds
182
+ # of the target tensor's sequence length.
183
+ valid_mask = dest_indices < mask_seq_len
184
+
185
+ # Use this mask to select only the valid row indices, column indices,
186
+ # and the corresponding values from the logprob tensor.
187
+ # This flattens the selected elements into 1D tensors.
188
+ valid_rows = row_indices[valid_mask]
189
+ valid_cols = dest_indices[valid_mask]
190
+ valid_vals = logprob_tensor[valid_mask]
191
+
192
+ # Place the valid values into their correct positions in the padded tensor
193
+ # using a single, efficient advanced indexing operation.
194
+ padded_logprobs[valid_rows, valid_cols] = valid_vals
195
+
196
+ return padded_logprobs
197
+ def vLLMSamplingParams(**kwargs):
198
+ from vllm import SamplingParams
199
+
200
+ sampling_params = SamplingParams(**kwargs)
201
+ sampling_params._set_kwargs = kwargs
202
+ return sampling_params
203
+ @dataclass
204
+ class UnslothRLOOConfig(RLOOConfig):
205
+ """
206
+
207
+ Configuration class for the [`RLOOTrainer`].
208
+
209
+ This class includes only the parameters that are specific to RLOO training. For a full list of training arguments,
210
+ please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
211
+ differ from those in [`~transformers.TrainingArguments`].
212
+
213
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
214
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
215
+ command line.
216
+
217
+ Parameters:
218
+ > Parameters that control the model and reference model
219
+
220
+ model_init_kwargs (`str`, `dict[str, Any]`, *optional*):
221
+ Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
222
+ argument of the [`RLOOTrainer`] is provided as a string.
223
+ disable_dropout (`bool`, *optional*, defaults to `False`):
224
+ Whether to disable dropout in the model. This is useful for training with a reference model, as it prevents
225
+ the model from generating different logprobs for the same input.
226
+
227
+ > Parameters that control the data preprocessing
228
+
229
+ remove_unused_columns (`bool`, *optional*, defaults to `False`):
230
+ Whether to only keep the column `"prompt"` in the dataset. If you use a custom reward function that
231
+ requires any column other than `"prompts"` and `"completions"`, you should keep this to `False`.
232
+ max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
233
+ Maximum length of the prompt. If the prompt is longer than this value, it will be truncated left.
234
+ num_generations (`int` or `None`, *optional*, defaults to `2`):
235
+ Number of generations per prompt to sample. The effective batch size (num_processes * per_device_batch_size
236
+ * gradient_accumulation_steps) must be evenly divisible by this value.
237
+ max_completion_length (`int` or `None`, *optional*, defaults to `256`):
238
+ Maximum length of the generated completion.
239
+ ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
240
+ This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
241
+ improving generation speed. However, disabling this option allows training models that exceed the VRAM
242
+ capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible
243
+ with vLLM generation.
244
+ shuffle_dataset (`bool`, *optional*, defaults to `True`):
245
+ Whether to shuffle the training dataset.
246
+
247
+ > Parameters that control generation
248
+
249
+ generation_batch_size: (`int`, *optional*):
250
+ Batch size to use for generation. If `None`, it defaults to the effective training batch size:
251
+ `per_device_train_batch_size * num_processes * steps_per_generation`. In other words, there is one
252
+ generation batch processed per optimization step. Mutually exclusive with `steps_per_generation`.
253
+ steps_per_generation: (`int`, *optional*):
254
+ Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`. Mutually exclusive
255
+ with `generation_batch_size`.
256
+ temperature (`float`, defaults to `1.0`):
257
+ Temperature for sampling. The higher the temperature, the more random the completions.
258
+ top_p (`float`, *optional*, defaults to `1.0`):
259
+ Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to
260
+ `1.0` to consider all tokens.
261
+ top_k (`int`, *optional*):
262
+ Number of highest probability vocabulary tokens to keep for top-k-filtering. If `None`, top-k-filtering is
263
+ disabled and all tokens are considered.
264
+ min_p (`float`, *optional*):
265
+ Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
266
+ value between `0.0` and `1.0`. Typical values are in the `0.01-0.2` range.
267
+ repetition_penalty (`float`, *optional*, defaults to `1.0`):
268
+ Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far.
269
+ Values > `1.0` encourage the model to use new tokens, while values < `1.0` encourage the model to repeat
270
+ tokens.
271
+ use_transformers_paged (`bool`, *optional*, defaults to `False`):
272
+ Whether to use the `transformers` paged implementation for generation. If set to `True`, the `transformers`
273
+ paged implementation will be used for generation instead of the default padded implementation. This
274
+ parameter is only effective when `use_vllm` is set to `False`.
275
+ cache_implementation (`str`, *optional*):
276
+ Implementation of the cache method for faster generation when `use_vllm` is set to `False`.
277
+ generation_kwargs (`dict[str, Any]`, *optional*):
278
+ Additional keyword arguments to pass to [`~transformers.GenerationConfig`] (if using transformers) or
279
+ `SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the
280
+ generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict
281
+ with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them.
282
+
283
+ > Parameters that control generation acceleration powered by vLLM
284
+
285
+ use_vllm (`bool`, *optional*, defaults to `False`):
286
+ Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation
287
+ instead of the default model.generate(). Requires `vllm` to be installed.
288
+ vllm_mode (`str`, *optional*, defaults to `"server"`):
289
+ Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `"server"` or
290
+ `"colocate"`.
291
+
292
+ - `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM
293
+ server is running (start with `trl vllm-serve`).
294
+ - `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a
295
+ separate server but may cause resource contention with training.
296
+ vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
297
+ Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use
298
+ the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model
299
+ implementation.
300
+ vllm_guided_decoding_regex (`str`, *optional*):
301
+ Regex for vLLM guided decoding. If `None` (default), guided decoding is disabled.
302
+
303
+ > Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`)
304
+
305
+ vllm_server_base_url (`str`, *optional*):
306
+ Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `vllm_server_host` and
307
+ `vllm_server_port` are ignored.
308
+ vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
309
+ Host of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
310
+ vllm_server_port (`int`, *optional*, defaults to `8000`):
311
+ Port of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
312
+ vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
313
+ Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the
314
+ timeout, a `ConnectionError` is raised.
315
+
316
+ > Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`)
317
+
318
+ vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`):
319
+ Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to
320
+ `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
321
+ launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.
322
+ vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
323
+ Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to
324
+ `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
325
+ launching the vLLM server via the `--vllm_tensor_parallel_size` flag.
326
+ vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
327
+ Whether to enable sleep mode for vLLM. If `True`, vLLM will sleep during the optimization step and woken
328
+ for weight sync and generation.
329
+
330
+ > Parameters that control the training
331
+
332
+ beta (`float`, *optional*, defaults to `0.05`):
333
+ KL coefficient. If `0.0`, the reference model is not loaded, reducing memory usage and improving training
334
+ speed.
335
+ num_iterations (`int`, *optional*, defaults to `1`):
336
+ Number of iterations per batch (denoted as μ in the algorithm).
337
+ epsilon (`float`, *optional*, defaults to `0.2`):
338
+ Epsilon value for clipping.
339
+ epsilon_high (`float`, *optional*):
340
+ Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound
341
+ specified in argument `epsilon`. Paper [DAPO](https://huggingface.co/papers/2503.14476) recommends `0.28`.
342
+ reward_weights (`list[float]`, *optional*):
343
+ Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are
344
+ weighted equally with weight `1.0`.
345
+ normalize_advantages (`bool`, *optional*, defaults to `False`):
346
+ Whether to normalize advantages. Normalization is done per generation batch to have mean `0.0` and standard
347
+ deviation of `1.0`.
348
+ reward_clip_range (`tuple[float, float]`, *optional*):
349
+ Clip range for rewards as (min, max). If `None`, no clipping is applied.
350
+ mask_truncated_completions (`bool`, *optional*, defaults to `False`):
351
+ When enabled, truncated completions are excluded from the loss calculation, preventing them from being
352
+ incorrectly penalized and introducing noise during training. According to the
353
+ [DAPO](https://huggingface.co/papers/2503.14476) paper, this is a good practice for training stability.
354
+ sync_ref_model (`bool`, *optional*, defaults to `False`):
355
+ Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using
356
+ the `ref_model_mixup_alpha` parameter. This synchronization originates from the
357
+ [TR-DPO](https://huggingface.co/papers/2404.09656) paper.
358
+ ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`):
359
+ α parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which controls the mix
360
+ between the current policy and the previous reference policy during updates. The reference policy is
361
+ updated according to the equation: `π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you
362
+ must set `sync_ref_model=True`.
363
+ ref_model_sync_steps (`int`, *optional*, defaults to `512`):
364
+ τ parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which determines how
365
+ frequently the current policy is synchronized with the reference policy. To use this parameter, you must
366
+ set `sync_ref_model=True`.
367
+
368
+ > Parameters that control the logging
369
+
370
+ log_completions (`bool`, *optional*, defaults to `False`):
371
+ Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is installed,
372
+ it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`.
373
+ num_completions_to_print (`int`, *optional*):
374
+ Number of completions to print with `rich`. If `None`, all completions are logged.
375
+ wandb_log_unique_prompts (`bool`, *optional*, defaults to `False`):
376
+ Whether to log unique prompts in wandb. If `True`, only unique prompts are logged. If `False`, all prompts
377
+ are logged.
378
+
379
+ > Deprecated parameters
380
+
381
+ rloo_k:
382
+
383
+ <Deprecated version="0.22.0">
384
+
385
+ This parameter is deprecated and will be removed in version 0.25.0. Use `num_generations` instead.
386
+
387
+ </Deprecated>
388
+
389
+ cliprange:
390
+
391
+ <Deprecated version="0.22.0">
392
+
393
+ This parameter is deprecated and will be removed in version 0.25.0. Use `epsilon` instead.
394
+
395
+ </Deprecated>
396
+
397
+ kl_coef:
398
+
399
+ <Deprecated version="0.22.0">
400
+
401
+ This parameter is deprecated and will be removed in version 0.25.0. Use `beta` instead.
402
+
403
+ </Deprecated>
404
+
405
+ exp_name:
406
+
407
+ <Deprecated version="0.22.0">
408
+
409
+ This parameter is deprecated and will be removed in version 0.25.0. Use `run_name` instead.
410
+
411
+ </Deprecated>
412
+
413
+ normalize_reward:
414
+
415
+ <Deprecated version="0.22.0">
416
+
417
+ This parameter is deprecated and will be removed in version 0.25.0. Use `normalize_advantages` instead.
418
+
419
+ </Deprecated>
420
+
421
+ num_ppo_epochs:
422
+
423
+ <Deprecated version="0.22.0">
424
+
425
+ This parameter is deprecated and will be removed in version 0.25.0. Use `num_iterations` instead.
426
+
427
+ </Deprecated>
428
+
429
+ num_mini_batches:
430
+
431
+ <Deprecated version="0.22.0">
432
+
433
+ This parameter is deprecated and will be removed in version 0.25.0. Use `steps_per_generation` instead.
434
+
435
+ </Deprecated>
436
+
437
+ total_episodes:
438
+
439
+ <Deprecated version="0.22.0">
440
+
441
+ This parameter is deprecated and will be removed in version 0.25.0. Use `max_steps` instead.
442
+
443
+ </Deprecated>
444
+
445
+ response_length:
446
+
447
+ <Deprecated version="0.22.0">
448
+
449
+ This parameter is deprecated and will be removed in version 0.25.0. Use `max_completion_length` instead.
450
+
451
+ </Deprecated>
452
+
453
+ token_level_kl:
454
+
455
+ <Deprecated version="0.22.0">
456
+
457
+ This parameter is deprecated and will be removed in version 0.25.0. KL is now computed only at the sequence
458
+ level.
459
+
460
+ </Deprecated>
461
+
462
+ dataset_num_proc:
463
+
464
+ <Deprecated version="0.22.0">
465
+
466
+ This parameter is deprecated and will be removed in version 0.25.0. This parameter was unused, you can
467
+ safely remove it from your scripts.
468
+
469
+ </Deprecated>
470
+
471
+ local_rollout_forward_batch_size:
472
+
473
+ <Deprecated version="0.22.0">
474
+
475
+ This parameter is deprecated and will be removed in version 0.25.0. Now it is automatically set to
476
+ `per_device_train_batch_size` (or `per_device_eval_batch_size` during evaluation).
477
+
478
+ </Deprecated>
479
+
480
+ num_sample_generations:
481
+
482
+ <Deprecated version="0.22.0">
483
+
484
+ This parameter is deprecated and will be removed in version 0.25.0. Use `logging_steps` to control
485
+ generation logging frequency.
486
+
487
+ </Deprecated>
488
+
489
+ stop_token:
490
+
491
+ <Deprecated version="0.22.0">
492
+
493
+ This parameter is deprecated and will be removed in version 0.25.0.
494
+
495
+ </Deprecated>
496
+
497
+ stop_token_id:
498
+
499
+ <Deprecated version="0.22.0">
500
+
501
+ This parameter is deprecated and will be removed in version 0.25.0. Use `processing_class.eos_token_id`
502
+ instead.
503
+
504
+ </Deprecated>
505
+
506
+ missing_eos_penalty:
507
+
508
+ <Deprecated version="0.22.0">
509
+
510
+ This parameter is deprecated and will be removed in version 0.25.0. Replicate with a custom reward function
511
+ checking if `eos_token_id` is in `completion_ids`.
512
+
513
+ </Deprecated>
514
+
515
+ """
516
+ vllm_sampling_params: Optional[Any] = field(
517
+ default = None,
518
+ metadata = {'help': 'vLLM SamplingParams'},
519
+ )
520
+ unsloth_num_chunks : Optional[int] = field(
521
+ default = -1,
522
+ metadata = {'help': 'Chunk size to reduce memory usage. -1 is most efficient.'},
523
+ )
524
+
525
+ def __init__(
526
+ self,
527
+ output_dir = None,
528
+ overwrite_output_dir = None,
529
+ do_train = False,
530
+ do_eval = False,
531
+ do_predict = False,
532
+ eval_strategy = 'no',
533
+ prediction_loss_only = False,
534
+ per_device_train_batch_size = 4,
535
+ per_device_eval_batch_size = 4,
536
+ per_gpu_train_batch_size = None,
537
+ per_gpu_eval_batch_size = None,
538
+ gradient_accumulation_steps = 2,
539
+ eval_accumulation_steps = 2,
540
+ eval_delay = 0,
541
+ torch_empty_cache_steps = 250,
542
+ learning_rate = 5e-05,
543
+ weight_decay = 0.01,
544
+ adam_beta1 = 0.9,
545
+ adam_beta2 = 0.999,
546
+ adam_epsilon = 1e-08,
547
+ max_grad_norm = 1.0,
548
+ num_train_epochs = 3.0,
549
+ max_steps = -1,
550
+ lr_scheduler_type = 'linear',
551
+ warmup_ratio = 0.1,
552
+ warmup_steps = 0,
553
+ log_level = 'passive',
554
+ log_level_replica = 'warning',
555
+ log_on_each_node = True,
556
+ logging_dir = None,
557
+ logging_strategy = 'steps',
558
+ logging_first_step = False,
559
+ logging_steps = 1,
560
+ logging_nan_inf_filter = False,
561
+ save_strategy = 'steps',
562
+ save_steps = 500,
563
+ save_total_limit = None,
564
+ save_safetensors = True,
565
+ save_on_each_node = False,
566
+ save_only_model = False,
567
+ restore_callback_states_from_checkpoint = False,
568
+ no_cuda = False,
569
+ use_cpu = False,
570
+ use_mps_device = False,
571
+ seed = 3407,
572
+ data_seed = 3407,
573
+ jit_mode_eval = False,
574
+ bf16 = False,
575
+ fp16 = False,
576
+ fp16_opt_level = 'O1',
577
+ half_precision_backend = 'auto',
578
+ bf16_full_eval = False,
579
+ fp16_full_eval = False,
580
+ tf32 = None,
581
+ local_rank = -1,
582
+ ddp_backend = None,
583
+ tpu_num_cores = None,
584
+ tpu_metrics_debug = False,
585
+ debug = '',
586
+ dataloader_drop_last = False,
587
+ eval_steps = None,
588
+ dataloader_num_workers = 0,
589
+ dataloader_prefetch_factor = None,
590
+ past_index = -1,
591
+ run_name = None,
592
+ disable_tqdm = None,
593
+ remove_unused_columns = False,
594
+ label_names = None,
595
+ load_best_model_at_end = False,
596
+ metric_for_best_model = None,
597
+ greater_is_better = None,
598
+ ignore_data_skip = False,
599
+ fsdp = None,
600
+ fsdp_min_num_params = 0,
601
+ fsdp_config = None,
602
+ fsdp_transformer_layer_cls_to_wrap = None,
603
+ accelerator_config = None,
604
+ parallelism_config = None,
605
+ deepspeed = None,
606
+ label_smoothing_factor = 0.0,
607
+ optim = 'adamw_8bit',
608
+ optim_args = None,
609
+ adafactor = False,
610
+ group_by_length = False,
611
+ length_column_name = 'length',
612
+ report_to = 'none',
613
+ project = 'huggingface',
614
+ trackio_space_id = 'trackio',
615
+ ddp_find_unused_parameters = None,
616
+ ddp_bucket_cap_mb = None,
617
+ ddp_broadcast_buffers = None,
618
+ dataloader_pin_memory = True,
619
+ dataloader_persistent_workers = False,
620
+ skip_memory_metrics = True,
621
+ use_legacy_prediction_loop = False,
622
+ push_to_hub = False,
623
+ resume_from_checkpoint = None,
624
+ hub_model_id = None,
625
+ hub_strategy = 'every_save',
626
+ hub_token = None,
627
+ hub_private_repo = None,
628
+ hub_always_push = False,
629
+ hub_revision = None,
630
+ gradient_checkpointing = True,
631
+ gradient_checkpointing_kwargs = None,
632
+ include_inputs_for_metrics = False,
633
+ eval_do_concat_batches = True,
634
+ fp16_backend = 'auto',
635
+ push_to_hub_model_id = None,
636
+ push_to_hub_organization = None,
637
+ push_to_hub_token = None,
638
+ mp_parameters = '',
639
+ auto_find_batch_size = False,
640
+ full_determinism = False,
641
+ torchdynamo = None,
642
+ ray_scope = 'last',
643
+ ddp_timeout = 1800,
644
+ torch_compile = False,
645
+ torch_compile_backend = None,
646
+ torch_compile_mode = None,
647
+ include_tokens_per_second = False,
648
+ include_num_input_tokens_seen = False,
649
+ neftune_noise_alpha = None,
650
+ optim_target_modules = None,
651
+ batch_eval_metrics = False,
652
+ eval_on_start = False,
653
+ use_liger_kernel = False,
654
+ liger_kernel_config = None,
655
+ eval_use_gather_object = False,
656
+ average_tokens_across_devices = True,
657
+ model_init_kwargs = None,
658
+ disable_dropout = False,
659
+ max_prompt_length = 512,
660
+ num_generations = 8,
661
+ max_completion_length = 256,
662
+ ds3_gather_for_generation = True,
663
+ shuffle_dataset = True,
664
+ generation_batch_size = None,
665
+ steps_per_generation = None,
666
+ temperature = 1.0,
667
+ top_p = 1.0,
668
+ top_k = None,
669
+ min_p = None,
670
+ generation_kwargs = {},
671
+ repetition_penalty = 1.0,
672
+ use_transformers_paged = False,
673
+ cache_implementation = None,
674
+ use_vllm = False,
675
+ vllm_mode = 'colocate',
676
+ vllm_model_impl = 'vllm',
677
+ vllm_enable_sleep_mode = False,
678
+ vllm_guided_decoding_regex = None,
679
+ vllm_server_base_url = None,
680
+ vllm_server_host = '0.0.0.0',
681
+ vllm_server_port = 8000,
682
+ vllm_server_timeout = 240.0,
683
+ vllm_gpu_memory_utilization = 0.3,
684
+ vllm_tensor_parallel_size = 1,
685
+ beta = 0.05,
686
+ num_iterations = 1,
687
+ epsilon = 0.2,
688
+ epsilon_high = None,
689
+ reward_weights = None,
690
+ normalize_advantages = False,
691
+ reward_clip_range = None,
692
+ mask_truncated_completions = False,
693
+ sync_ref_model = False,
694
+ ref_model_mixup_alpha = 0.6,
695
+ ref_model_sync_steps = 512,
696
+ log_completions = False,
697
+ num_completions_to_print = None,
698
+ wandb_log_unique_prompts = False,
699
+ rloo_k = None,
700
+ cliprange = None,
701
+ kl_coef = None,
702
+ exp_name = None,
703
+ normalize_reward = None,
704
+ num_ppo_epochs = None,
705
+ num_mini_batches = None,
706
+ total_episodes = None,
707
+ response_length = None,
708
+ token_level_kl = None,
709
+ dataset_num_proc = None,
710
+ local_rollout_forward_batch_size = None,
711
+ num_sample_generations = None,
712
+ stop_token = None,
713
+ stop_token_id = None,
714
+ missing_eos_penalty = None,
715
+ vllm_sampling_params = None,
716
+ unsloth_num_chunks = -1,
717
+
718
+ **kwargs,
719
+ ):
720
+ if learning_rate < 1e-7: print(f'Unsloth: Your learning rate of `{learning_rate}` is too small and less than 1e-7! Consider increasing it, otherwise gradient updates will be close to 0!')
721
+ if learning_rate > 1: print(f'Unsloth: Your learning rate of `{learning_rate}` is way too larger > 1! Consider decreasing it to 1e-1, otherwise gradient updates will explode!')
722
+ if output_dir is None and save_strategy == 'steps' and save_steps == 500:
723
+ output_dir = 'unsloth_training_checkpoints'
724
+ save_strategy = 'no'
725
+ if dataset_num_proc is None:
726
+ from multiprocessing import cpu_count
727
+ dataset_num_proc = min(max(cpu_count()+4, 2), 64)
728
+ if steps_per_generation is None and generation_batch_size is None:
729
+ ga = gradient_accumulation_steps
730
+ world_size = int(os.environ.get('WORLD_SIZE', '1'))
731
+ if (ga * world_size * per_device_train_batch_size) % num_generations != 0:
732
+ print('Unsloth: We now expect `per_device_train_batch_size` * `gradient_accumulation_steps` * `world_size` to be a multiple of `num_generations`.\nWe will change the batch size of ' + str(per_device_train_batch_size) + ' to the `num_generations` of ' + str(num_generations))
733
+ per_device_train_batch_size = num_generations
734
+
735
+ if temperature <= 0:
736
+ raise MathError('Unsloth: Please set a positive non-zero temperature since your results will be wrong.')
737
+ elif temperature >= 10:
738
+ raise MathError('Unsloth: Please set a positive non-zero temperature less than 10, since sampling will be quite erratic.')
739
+
740
+
741
+ super().__init__(
742
+ output_dir = output_dir,
743
+ overwrite_output_dir = overwrite_output_dir,
744
+ do_train = do_train,
745
+ do_eval = do_eval,
746
+ do_predict = do_predict,
747
+ eval_strategy = eval_strategy,
748
+ prediction_loss_only = prediction_loss_only,
749
+ per_device_train_batch_size = per_device_train_batch_size,
750
+ per_device_eval_batch_size = per_device_eval_batch_size,
751
+ per_gpu_train_batch_size = per_gpu_train_batch_size,
752
+ per_gpu_eval_batch_size = per_gpu_eval_batch_size,
753
+ gradient_accumulation_steps = gradient_accumulation_steps,
754
+ eval_accumulation_steps = eval_accumulation_steps,
755
+ eval_delay = eval_delay,
756
+ torch_empty_cache_steps = torch_empty_cache_steps,
757
+ learning_rate = learning_rate,
758
+ weight_decay = weight_decay,
759
+ adam_beta1 = adam_beta1,
760
+ adam_beta2 = adam_beta2,
761
+ adam_epsilon = adam_epsilon,
762
+ max_grad_norm = max_grad_norm,
763
+ num_train_epochs = num_train_epochs,
764
+ max_steps = max_steps,
765
+ lr_scheduler_type = lr_scheduler_type,
766
+ warmup_ratio = warmup_ratio,
767
+ warmup_steps = warmup_steps,
768
+ log_level = log_level,
769
+ log_level_replica = log_level_replica,
770
+ log_on_each_node = log_on_each_node,
771
+ logging_dir = logging_dir,
772
+ logging_strategy = logging_strategy,
773
+ logging_first_step = logging_first_step,
774
+ logging_steps = logging_steps,
775
+ logging_nan_inf_filter = logging_nan_inf_filter,
776
+ save_strategy = save_strategy,
777
+ save_steps = save_steps,
778
+ save_total_limit = save_total_limit,
779
+ save_safetensors = save_safetensors,
780
+ save_on_each_node = save_on_each_node,
781
+ save_only_model = save_only_model,
782
+ restore_callback_states_from_checkpoint = restore_callback_states_from_checkpoint,
783
+ no_cuda = no_cuda,
784
+ use_cpu = use_cpu,
785
+ use_mps_device = use_mps_device,
786
+ seed = seed,
787
+ data_seed = data_seed,
788
+ jit_mode_eval = jit_mode_eval,
789
+ bf16 = bf16,
790
+ fp16 = fp16,
791
+ fp16_opt_level = fp16_opt_level,
792
+ half_precision_backend = half_precision_backend,
793
+ bf16_full_eval = bf16_full_eval,
794
+ fp16_full_eval = fp16_full_eval,
795
+ tf32 = tf32,
796
+ local_rank = local_rank,
797
+ ddp_backend = ddp_backend,
798
+ tpu_num_cores = tpu_num_cores,
799
+ tpu_metrics_debug = tpu_metrics_debug,
800
+ debug = debug,
801
+ dataloader_drop_last = dataloader_drop_last,
802
+ eval_steps = eval_steps,
803
+ dataloader_num_workers = dataloader_num_workers,
804
+ dataloader_prefetch_factor = dataloader_prefetch_factor,
805
+ past_index = past_index,
806
+ run_name = run_name,
807
+ disable_tqdm = disable_tqdm,
808
+ remove_unused_columns = remove_unused_columns,
809
+ label_names = label_names,
810
+ load_best_model_at_end = load_best_model_at_end,
811
+ metric_for_best_model = metric_for_best_model,
812
+ greater_is_better = greater_is_better,
813
+ ignore_data_skip = ignore_data_skip,
814
+ fsdp = fsdp,
815
+ fsdp_min_num_params = fsdp_min_num_params,
816
+ fsdp_config = fsdp_config,
817
+ fsdp_transformer_layer_cls_to_wrap = fsdp_transformer_layer_cls_to_wrap,
818
+ accelerator_config = accelerator_config,
819
+ parallelism_config = parallelism_config,
820
+ deepspeed = deepspeed,
821
+ label_smoothing_factor = label_smoothing_factor,
822
+ optim = optim,
823
+ optim_args = optim_args,
824
+ adafactor = adafactor,
825
+ group_by_length = group_by_length,
826
+ length_column_name = length_column_name,
827
+ report_to = report_to,
828
+ project = project,
829
+ trackio_space_id = trackio_space_id,
830
+ ddp_find_unused_parameters = ddp_find_unused_parameters,
831
+ ddp_bucket_cap_mb = ddp_bucket_cap_mb,
832
+ ddp_broadcast_buffers = ddp_broadcast_buffers,
833
+ dataloader_pin_memory = dataloader_pin_memory,
834
+ dataloader_persistent_workers = dataloader_persistent_workers,
835
+ skip_memory_metrics = skip_memory_metrics,
836
+ use_legacy_prediction_loop = use_legacy_prediction_loop,
837
+ push_to_hub = push_to_hub,
838
+ resume_from_checkpoint = resume_from_checkpoint,
839
+ hub_model_id = hub_model_id,
840
+ hub_strategy = hub_strategy,
841
+ hub_token = hub_token,
842
+ hub_private_repo = hub_private_repo,
843
+ hub_always_push = hub_always_push,
844
+ hub_revision = hub_revision,
845
+ gradient_checkpointing = gradient_checkpointing,
846
+ gradient_checkpointing_kwargs = gradient_checkpointing_kwargs,
847
+ include_inputs_for_metrics = include_inputs_for_metrics,
848
+ eval_do_concat_batches = eval_do_concat_batches,
849
+ fp16_backend = fp16_backend,
850
+ push_to_hub_model_id = push_to_hub_model_id,
851
+ push_to_hub_organization = push_to_hub_organization,
852
+ push_to_hub_token = push_to_hub_token,
853
+ mp_parameters = mp_parameters,
854
+ auto_find_batch_size = auto_find_batch_size,
855
+ full_determinism = full_determinism,
856
+ torchdynamo = torchdynamo,
857
+ ray_scope = ray_scope,
858
+ ddp_timeout = ddp_timeout,
859
+ torch_compile = torch_compile,
860
+ torch_compile_backend = torch_compile_backend,
861
+ torch_compile_mode = torch_compile_mode,
862
+ include_tokens_per_second = include_tokens_per_second,
863
+ include_num_input_tokens_seen = include_num_input_tokens_seen,
864
+ neftune_noise_alpha = neftune_noise_alpha,
865
+ optim_target_modules = optim_target_modules,
866
+ batch_eval_metrics = batch_eval_metrics,
867
+ eval_on_start = eval_on_start,
868
+ use_liger_kernel = use_liger_kernel,
869
+ liger_kernel_config = liger_kernel_config,
870
+ eval_use_gather_object = eval_use_gather_object,
871
+ average_tokens_across_devices = average_tokens_across_devices,
872
+ model_init_kwargs = model_init_kwargs,
873
+ disable_dropout = disable_dropout,
874
+ max_prompt_length = max_prompt_length,
875
+ num_generations = num_generations,
876
+ max_completion_length = max_completion_length,
877
+ ds3_gather_for_generation = ds3_gather_for_generation,
878
+ shuffle_dataset = shuffle_dataset,
879
+ generation_batch_size = generation_batch_size,
880
+ steps_per_generation = steps_per_generation,
881
+ temperature = temperature,
882
+ top_p = top_p,
883
+ top_k = top_k,
884
+ min_p = min_p,
885
+ generation_kwargs = generation_kwargs,
886
+ repetition_penalty = repetition_penalty,
887
+ use_transformers_paged = use_transformers_paged,
888
+ cache_implementation = cache_implementation,
889
+ use_vllm = use_vllm,
890
+ vllm_mode = vllm_mode,
891
+ vllm_model_impl = vllm_model_impl,
892
+ vllm_enable_sleep_mode = vllm_enable_sleep_mode,
893
+ vllm_guided_decoding_regex = vllm_guided_decoding_regex,
894
+ vllm_server_base_url = vllm_server_base_url,
895
+ vllm_server_host = vllm_server_host,
896
+ vllm_server_port = vllm_server_port,
897
+ vllm_server_timeout = vllm_server_timeout,
898
+ vllm_gpu_memory_utilization = vllm_gpu_memory_utilization,
899
+ vllm_tensor_parallel_size = vllm_tensor_parallel_size,
900
+ beta = beta,
901
+ num_iterations = num_iterations,
902
+ epsilon = epsilon,
903
+ epsilon_high = epsilon_high,
904
+ reward_weights = reward_weights,
905
+ normalize_advantages = normalize_advantages,
906
+ reward_clip_range = reward_clip_range,
907
+ mask_truncated_completions = mask_truncated_completions,
908
+ sync_ref_model = sync_ref_model,
909
+ ref_model_mixup_alpha = ref_model_mixup_alpha,
910
+ ref_model_sync_steps = ref_model_sync_steps,
911
+ log_completions = log_completions,
912
+ num_completions_to_print = num_completions_to_print,
913
+ wandb_log_unique_prompts = wandb_log_unique_prompts,
914
+ rloo_k = rloo_k,
915
+ cliprange = cliprange,
916
+ kl_coef = kl_coef,
917
+ exp_name = exp_name,
918
+ normalize_reward = normalize_reward,
919
+ num_ppo_epochs = num_ppo_epochs,
920
+ num_mini_batches = num_mini_batches,
921
+ total_episodes = total_episodes,
922
+ response_length = response_length,
923
+ token_level_kl = token_level_kl,
924
+ dataset_num_proc = dataset_num_proc,
925
+ local_rollout_forward_batch_size = local_rollout_forward_batch_size,
926
+ num_sample_generations = num_sample_generations,
927
+ stop_token = stop_token,
928
+ stop_token_id = stop_token_id,
929
+ missing_eos_penalty = missing_eos_penalty,**kwargs)
930
+ self.vllm_sampling_params = vllm_sampling_params
931
+ self.unsloth_num_chunks = unsloth_num_chunks
932
+
933
+ pass
934
+
935
+ class _UnslothRLOOTrainer(BaseTrainer):
936
+ """"""
937
+
938
+ _tag_names = ["trl", "rloo"]
939
+ _name = "RLOO"
940
+ _paper = {
941
+ "title": "Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs",
942
+ "id": "2402.14740",
943
+ # docstyle-ignore
944
+ "citation": textwrap.dedent("""\
945
+ @inproceedings{ahmadian2024back,
946
+ title = {{Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs}},
947
+ author = {Arash Ahmadian and Chris Cremer and Matthias Gall{\'{e}} and Marzieh Fadaee and Julia Kreutzer and Olivier Pietquin and Ahmet {\"{U}}st{\"{u}}n and Sara Hooker},
948
+ year = 2024,
949
+ booktitle = {Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), {ACL} 2024, Bangkok, Thailand, August 11-16, 2024},
950
+ pages = {12248--12267},
951
+ publisher = {Association for Computational Linguistics},
952
+ editor = {Lun{-}Wei Ku and Andre Martins and Vivek Srikumar},
953
+ }"""),
954
+ }
955
+
956
+ def __init__(
957
+ self,
958
+ # Note for dev: we can remove the default None when we remove the deprecated model parameter in version 0.25.0
959
+ model: Union[str, PreTrainedModel] = None,
960
+ reward_funcs: Union[RewardFunc, list[RewardFunc]] = None,
961
+ args: Optional[RLOOConfig] = None,
962
+ train_dataset: Optional[Union[Dataset, IterableDataset]] = None,
963
+ eval_dataset: Optional[Union[Dataset, IterableDataset, dict[str, Union[Dataset, IterableDataset]]]] = None,
964
+ processing_class: Optional[Union[PreTrainedTokenizerBase, ProcessorMixin]] = None,
965
+ reward_processing_classes: Optional[Union[PreTrainedTokenizerBase, list[PreTrainedTokenizerBase]]] = None,
966
+ callbacks: Optional[list[TrainerCallback]] = None,
967
+ optimizers: tuple[Optional[torch.optim.Optimizer], Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None),
968
+ peft_config: Optional["PeftConfig"] = None,
969
+ # Deprecated parameters
970
+ config=None,
971
+ reward_model=None,
972
+ policy=None,
973
+ ref_policy=None,
974
+ data_collator=None,
975
+ ):
976
+
977
+ if hasattr(model, 'vllm_engine') and hasattr(args, 'use_vllm'):
978
+ if (getattr(args, 'use_vllm', False) == False):
979
+ args.use_vllm = True
980
+ if not os.environ.get("TRL_EXPERIMENTAL_SILENCE"):
981
+ warnings.warn(
982
+ "This trainer will soon be moved to trl.experimental and is a candidate for removal. If you rely on "
983
+ "it and want it to remain, please share your comments here: "
984
+ "https://github.com/huggingface/trl/issues/4223. Silence this warning by setting environment variable "
985
+ "TRL_EXPERIMENTAL_SILENCE=1."
986
+ )
987
+ # Handle deprecated parameters
988
+ if config is not None:
989
+ warnings.warn(
990
+ "Parameter 'config' is deprecated and will be removed in version 0.25.0. Please use 'args' instead. "
991
+ "We are setting args=config"
992
+ )
993
+ if args is None:
994
+ args = config
995
+ else:
996
+ raise ValueError("Cannot specify both 'config' (deprecated) and 'args'. Please use 'args' only.")
997
+
998
+ if reward_model is not None:
999
+ warnings.warn(
1000
+ "Parameter 'reward_model' is deprecated and will be removed in version 0.25.0. Please use "
1001
+ "'reward_funcs' instead. We are setting reward_funcs=reward_model"
1002
+ )
1003
+ if reward_funcs is None:
1004
+ reward_funcs = reward_model
1005
+ else:
1006
+ raise ValueError(
1007
+ "Cannot specify both 'reward_model' (deprecated) and 'reward_funcs'. Please use 'reward_funcs' "
1008
+ "only."
1009
+ )
1010
+ if policy is not None:
1011
+ warnings.warn(
1012
+ "Parameter 'policy' is deprecated and will be removed in version 0.25.0. Please use 'model' instead. "
1013
+ "We are setting model=policy"
1014
+ )
1015
+ if model is None:
1016
+ model = policy
1017
+ else:
1018
+ raise ValueError("Cannot specify both 'policy' (deprecated) and 'model'. Please use 'model' only.")
1019
+ if ref_policy is not None:
1020
+ warnings.warn(
1021
+ "Parameter 'ref_policy' is deprecated and will be removed in version 0.25.0. To use the initial model "
1022
+ "as the reference model, simply omit this parameter. The parameter is ignored."
1023
+ )
1024
+ if data_collator is not None:
1025
+ warnings.warn(
1026
+ "Parameter 'data_collator' is deprecated and will be removed in version 0.25.0. The RLOOTrainer does "
1027
+ "not use a data collator, so this parameter is ignored."
1028
+ )
1029
+ if "input_ids" in train_dataset.column_names:
1030
+ warnings.warn(
1031
+ "The training dataset contains a column named 'input_ids', indicating that it is pre-tokenized. "
1032
+ "Support for pre-tokenized datasets is deprecated and will be removed in version 0.25. Please provide "
1033
+ "the raw dataset (conversational or standard) with a 'prompt' column instead."
1034
+ )
1035
+
1036
+ def decode(example, tokenizer):
1037
+ return {"prompt": tokenizer.decode(example["input_ids"])}
1038
+
1039
+ train_dataset = train_dataset.map(decode, fn_kwargs={"tokenizer": processing_class})
1040
+ if eval_dataset is not None and "input_ids" in eval_dataset.column_names:
1041
+ warnings.warn(
1042
+ "The evaluation dataset contains a column named 'input_ids', indicating that it is pre-tokenized. "
1043
+ "Support for pre-tokenized datasets is deprecated and will be removed in version 0.25. Please provide "
1044
+ "the raw dataset (conversational or standard) with a 'prompt' column instead."
1045
+ )
1046
+
1047
+ def decode(example, tokenizer):
1048
+ return {"prompt": tokenizer.decode(example["input_ids"])}
1049
+
1050
+ eval_dataset = eval_dataset.map(decode, fn_kwargs={"tokenizer": processing_class})
1051
+
1052
+ # Args
1053
+ if args is None:
1054
+ model_name = model if isinstance(model, str) else model.config._name_or_path
1055
+ model_name = model_name.split("/")[-1]
1056
+ args = RLOOConfig(f"{model_name}-RLOO")
1057
+
1058
+ # Models
1059
+ # Trained model
1060
+ model_init_kwargs = args.model_init_kwargs or {}
1061
+ if isinstance(model, str):
1062
+ model_id = model
1063
+ dtype = model_init_kwargs.get("dtype")
1064
+ if isinstance(dtype, torch.dtype) or dtype == "auto" or dtype is None:
1065
+ pass # dtype is already a torch.dtype or "auto" or None
1066
+ elif isinstance(dtype, str): # it's a str, but not "auto"
1067
+ dtype = getattr(torch, dtype)
1068
+ model_init_kwargs["dtype"] = dtype
1069
+ else:
1070
+ raise ValueError(
1071
+ "Invalid `dtype` passed to `RLOOConfig`. Expected either 'auto' or a string representing "
1072
+ f"a `torch.dtype` (e.g., 'float32'), but got {dtype}."
1073
+ )
1074
+ # Disable caching if gradient checkpointing is enabled [not supported]
1075
+ config = AutoConfig.from_pretrained(model_id)
1076
+ architecture = getattr(transformers, config.architectures[0])
1077
+ model = architecture.from_pretrained(model_id, **model_init_kwargs)
1078
+ else:
1079
+ model_id = model.config._name_or_path
1080
+ if args.model_init_kwargs is not None:
1081
+ logger.warning(
1082
+ "You passed `model_init_kwargs` to the `RLOOConfig`, but your model is already instantiated. "
1083
+ "The `model_init_kwargs` will be ignored."
1084
+ )
1085
+
1086
+ # Some models [SmolVLM/Idefics3] don't support `logits_to_keep` argument and error out if we pass it
1087
+ # Inspect the forward method before we wrap the model with PEFT
1088
+ self.model_kwarg_keys = (
1089
+ inspect.signature(model.forward).parameters.keys()
1090
+ if not hasattr(model, "get_base_model")
1091
+ else inspect.signature(model.get_base_model().forward).parameters.keys()
1092
+ )
1093
+
1094
+ if False:
1095
+ model = prepare_peft_model(model, peft_config, args)
1096
+
1097
+ # Processing class
1098
+ if processing_class is None:
1099
+ processing_class = AutoProcessor.from_pretrained(model.config._name_or_path, truncation_side="left")
1100
+
1101
+ # Handle pad token for processors or tokenizers
1102
+ if isinstance(processing_class, ProcessorMixin):
1103
+ tokenizer = processing_class.tokenizer
1104
+ elif isinstance(processing_class, PreTrainedTokenizerBase):
1105
+ tokenizer = processing_class
1106
+ else:
1107
+ raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
1108
+
1109
+ if tokenizer.pad_token is None:
1110
+ tokenizer.pad_token = tokenizer.eos_token
1111
+
1112
+ self.pad_token = tokenizer.pad_token
1113
+ self.pad_token_id = tokenizer.pad_token_id
1114
+ self.eos_token_id = tokenizer.eos_token_id
1115
+
1116
+ # Reward functions
1117
+ if not isinstance(reward_funcs, list):
1118
+ reward_funcs = [reward_funcs]
1119
+ self.reward_func_names = []
1120
+ for i, reward_func in enumerate(reward_funcs):
1121
+ if isinstance(reward_func, str):
1122
+ reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained(
1123
+ reward_func, num_labels=1, **model_init_kwargs
1124
+ )
1125
+ if isinstance(reward_funcs[i], nn.Module): # Use Module over PretrainedModel for compat w/ compiled models
1126
+ self.reward_func_names.append(reward_funcs[i].config._name_or_path.split("/")[-1])
1127
+ else:
1128
+ self.reward_func_names.append(reward_funcs[i].__name__)
1129
+ self.reward_funcs = reward_funcs
1130
+
1131
+ # Reward weights
1132
+ if args.reward_weights is not None:
1133
+ if len(args.reward_weights) != len(reward_funcs):
1134
+ raise ValueError(
1135
+ f"Number of reward weights ({len(args.reward_weights)}) must match number of reward "
1136
+ f"functions ({len(reward_funcs)})"
1137
+ )
1138
+ self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32)
1139
+ else:
1140
+ self.reward_weights = torch.ones(len(reward_funcs), dtype=torch.float32)
1141
+
1142
+ # Reward processing class
1143
+ if reward_processing_classes is None:
1144
+ reward_processing_classes = [None] * len(reward_funcs)
1145
+ elif not isinstance(reward_processing_classes, list):
1146
+ reward_processing_classes = [reward_processing_classes]
1147
+ if len(reward_processing_classes) != len(reward_funcs):
1148
+ raise ValueError(
1149
+ f"The number of reward processing classes ({len(reward_processing_classes)}) must match the number of "
1150
+ f"reward functions ({len(reward_funcs)})."
1151
+ )
1152
+
1153
+ for i, (reward_processing_class, reward_func) in enumerate(zip(reward_processing_classes, reward_funcs)):
1154
+ if isinstance(reward_func, PreTrainedModel):
1155
+ if reward_processing_class is None:
1156
+ reward_processing_class = AutoTokenizer.from_pretrained(reward_func.config._name_or_path)
1157
+ if reward_processing_class.pad_token_id is None:
1158
+ reward_processing_class.pad_token = reward_processing_class.eos_token
1159
+ # The reward model computes the reward for the latest non-padded token in the input sequence.
1160
+ # So it's important to set the pad token ID to the padding token ID of the processing class.
1161
+ reward_func.config.pad_token_id = reward_processing_class.pad_token_id
1162
+ reward_processing_classes[i] = reward_processing_class
1163
+
1164
+ self.reward_processing_classes = reward_processing_classes
1165
+
1166
+ # Training arguments
1167
+ self.max_prompt_length = args.max_prompt_length
1168
+ self.max_completion_length = args.max_completion_length
1169
+ self.num_generations = args.num_generations
1170
+ self.temperature = args.temperature
1171
+ self.top_p = args.top_p
1172
+ self.top_k = args.top_k
1173
+ self.min_p = args.min_p
1174
+ self.repetition_penalty = args.repetition_penalty
1175
+ self.use_transformers_paged = args.use_transformers_paged
1176
+ self.use_vllm = args.use_vllm
1177
+ self.vllm_mode = args.vllm_mode
1178
+ self.vllm_gpu_memory_utilization = args.vllm_gpu_memory_utilization # only applies to colocation mode
1179
+ self.vllm_tensor_parallel_size = args.vllm_tensor_parallel_size # only applies to colocation mode
1180
+ self.normalize_advantages = args.normalize_advantages
1181
+ self.mask_truncated_completions = args.mask_truncated_completions
1182
+ self.reward_clip_range = args.reward_clip_range
1183
+
1184
+ # Datasets
1185
+ self.shuffle_dataset = args.shuffle_dataset
1186
+
1187
+ if (
1188
+ isinstance(train_dataset, IterableDataset)
1189
+ or isinstance(eval_dataset, IterableDataset)
1190
+ or (
1191
+ isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values())
1192
+ )
1193
+ ):
1194
+ # See https://github.com/huggingface/trl/issues/3213
1195
+ raise NotImplementedError(
1196
+ "Iterable datasets are not yet supported in RLOOTrainer. Please use a standard dataset instead."
1197
+ )
1198
+
1199
+ # Multi-step
1200
+ self.num_iterations = args.num_iterations
1201
+ self.epsilon_low = args.epsilon
1202
+ self.epsilon_high = args.epsilon_high if args.epsilon_high is not None else args.epsilon
1203
+ # Tracks the number of iterations [forward + backward passes], including those within a grad accum cycle
1204
+ self._step = 0
1205
+ # Buffer the batch to reuse generated outputs across multiple updates. For more details, see
1206
+ # `_get_train_sampler` and `_prepare_inputs`.
1207
+ self._buffered_inputs = None
1208
+
1209
+ # The trainer estimates the number of FLOPs [floating-point operations] using the number of elements in the
1210
+ # input tensor associated with the key "input_ids". However, in RLOO, the sampled data does not include the
1211
+ # "input_ids" key. Instead, the available keys is "prompt". As a result, the trainer issues the warning:
1212
+ # "Could not estimate the number of tokens of the input, floating-point operations will not be computed." To
1213
+ # suppress this warning, we set the "estimate_tokens" key in the model's "warnings_issued" dictionary to True.
1214
+ # This acts as a flag to indicate that the warning has already been issued.
1215
+ model.warnings_issued["estimate_tokens"] = True
1216
+
1217
+ super().__init__(
1218
+ model=model,
1219
+ args=args,
1220
+ data_collator=identity, # No data collation is needed in RLOO
1221
+ train_dataset=train_dataset,
1222
+ eval_dataset=eval_dataset,
1223
+ processing_class=processing_class,
1224
+ callbacks=callbacks,
1225
+ optimizers=optimizers,
1226
+ )
1227
+
1228
+ # Reference model
1229
+ self.beta = args.beta
1230
+ if self.beta == 0.0:
1231
+ # If beta is 0.0, the reference model is not needed
1232
+ self.ref_model = None
1233
+ elif is_peft_model(model):
1234
+ # If PEFT is used, the reference model is not needed since the adapter can be disabled
1235
+ # to revert to the initial model.
1236
+ self.ref_model = None
1237
+ else:
1238
+ # For deepspeed, fsdp or non-distributed models, create a reference model from scratch
1239
+ config = AutoConfig.from_pretrained(model_id)
1240
+ architecture = getattr(transformers, config.architectures[0])
1241
+ self.ref_model = architecture.from_pretrained(model_id, **model_init_kwargs)
1242
+
1243
+ # Disable dropout in the models
1244
+ if args.disable_dropout:
1245
+ disable_dropout_in_model(model)
1246
+ if self.ref_model is not None:
1247
+ disable_dropout_in_model(self.ref_model)
1248
+
1249
+ # Initialize the metrics
1250
+ self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
1251
+ self._total_train_tokens = 0
1252
+ self.log_completions = args.log_completions
1253
+ self.wandb_log_unique_prompts = args.wandb_log_unique_prompts
1254
+ self.num_completions_to_print = args.num_completions_to_print
1255
+ # Keep logs sized to the generation batch to record only outputs from the latest model update.
1256
+ self._logs = {
1257
+ "images": deque(maxlen=args.generation_batch_size),
1258
+ "prompt": deque(maxlen=args.generation_batch_size),
1259
+ "completion": deque(maxlen=args.generation_batch_size),
1260
+ "rewards": defaultdict(lambda: deque(maxlen=args.generation_batch_size)),
1261
+ "advantages": deque(maxlen=args.generation_batch_size),
1262
+ }
1263
+
1264
+ # Ensure each process receives a unique seed to prevent duplicate completions when generating with
1265
+ # transformers if num_generations exceeds per_device_train_batch_size. We could skip it if we use vLLM, but
1266
+ # it's safer to set it in all cases.
1267
+ set_seed(args.seed, device_specific=True)
1268
+
1269
+ if self.use_vllm:
1270
+ if not is_vllm_available():
1271
+ raise ImportError(
1272
+ "vLLM is not available and `use_vllm` is set to True. Please install vLLM with "
1273
+ "`pip install trl[vllm]` to use it."
1274
+ )
1275
+
1276
+ if self.vllm_mode == "server":
1277
+ if self.accelerator.is_main_process:
1278
+ if args.vllm_server_base_url is not None:
1279
+ base_url = args.vllm_server_base_url
1280
+ else:
1281
+ base_url = f"http://{args.vllm_server_host}:{args.vllm_server_port}"
1282
+ self.vllm_client = VLLMClient(base_url=base_url, connection_timeout=args.vllm_server_timeout)
1283
+ self.vllm_client.init_communicator(device=torch.cuda.current_device())
1284
+
1285
+ elif self.vllm_mode == "colocate":
1286
+ if not self.accelerator.num_processes % self.vllm_tensor_parallel_size == 0:
1287
+ raise ValueError(
1288
+ f"vllm_tensor_parallel_size ({self.vllm_tensor_parallel_size}) must divide world size "
1289
+ f"({self.accelerator.num_processes}) evenly."
1290
+ )
1291
+
1292
+ if self.vllm_tensor_parallel_size > 1:
1293
+ self.tp_group, _ = torch.distributed.new_subgroups_by_enumeration(
1294
+ [
1295
+ list(range(i * self.vllm_tensor_parallel_size, (i + 1) * self.vllm_tensor_parallel_size))
1296
+ for i in range(self.accelerator.num_processes // self.vllm_tensor_parallel_size)
1297
+ ]
1298
+ )
1299
+ os.environ["RANK"] = str(self.accelerator.process_index)
1300
+ os.environ["LOCAL_RANK"] = str(self.accelerator.local_process_index)
1301
+ os.environ["WORLD_SIZE"] = str(self.accelerator.num_processes)
1302
+ ensure_master_addr_port()
1303
+
1304
+ if self.max_prompt_length is not None and self.max_completion_length is not None:
1305
+ max_model_len = self.max_prompt_length + self.max_completion_length
1306
+ else:
1307
+ max_model_len = None
1308
+ self.llm = model.vllm_engine
1309
+ if self.args.vllm_enable_sleep_mode:
1310
+ self.llm.sleep(level=1)
1311
+ else:
1312
+ raise ValueError(f"vllm_mode must be either 'server' or 'colocate', got '{self.vllm_mode}'.")
1313
+ self.guided_decoding_regex = args.vllm_guided_decoding_regex
1314
+
1315
+ self._last_loaded_step = -1
1316
+ self.accelerator.wait_for_everyone()
1317
+ else:
1318
+ generation_kwargs = {
1319
+ "max_new_tokens": self.max_completion_length,
1320
+ "do_sample": True,
1321
+ "pad_token_id": tokenizer.pad_token_id,
1322
+ "bos_token_id": tokenizer.bos_token_id,
1323
+ "eos_token_id": tokenizer.eos_token_id,
1324
+ "temperature": self.temperature,
1325
+ "top_p": self.top_p,
1326
+ "top_k": self.top_k,
1327
+ "min_p": self.min_p,
1328
+ "repetition_penalty": self.repetition_penalty,
1329
+ "cache_implementation": args.cache_implementation,
1330
+ }
1331
+ if args.generation_kwargs is not None:
1332
+ generation_kwargs.update(args.generation_kwargs)
1333
+ self.generation_config = GenerationConfig(**generation_kwargs)
1334
+
1335
+ # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
1336
+ # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
1337
+ # self.model_accepts_loss_kwargs to False to enable scaling.
1338
+ self.model_accepts_loss_kwargs = False
1339
+
1340
+ # Add tags to the model
1341
+ self.model.add_model_tags(self._tag_names)
1342
+
1343
+ if self.ref_model is not None:
1344
+ if self.is_deepspeed_enabled:
1345
+ self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
1346
+ elif self.is_fsdp_enabled:
1347
+ self.ref_model = prepare_fsdp(self.ref_model, self.accelerator)
1348
+ else:
1349
+ self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
1350
+
1351
+ if args.sync_ref_model:
1352
+ self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator))
1353
+
1354
+ for i, reward_func in enumerate(self.reward_funcs):
1355
+ if isinstance(reward_func, PreTrainedModel):
1356
+ if self.is_deepspeed_enabled:
1357
+ self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator)
1358
+ else:
1359
+ # set device placement to True to make `prepare_model` move `reward_func` to device when using fsdp
1360
+ self.reward_funcs[i] = self.accelerator.prepare_model(
1361
+ reward_func, evaluation_mode=True, device_placement=True
1362
+ )
1363
+
1364
+ def _set_signature_columns_if_needed(self):
1365
+ # If `self.args.remove_unused_columns` is True, non-signature columns are removed.
1366
+ # By default, this method sets `self._signature_columns` to the model's expected inputs.
1367
+ # In RLOOTrainer, we preprocess data, so using the model's signature columns doesn't work.
1368
+ # Instead, we set them to the columns expected by the `training_step` method, hence the override.
1369
+ if self._signature_columns is None:
1370
+ self._signature_columns = ["prompt", "image", "images"]
1371
+
1372
+ # This method overrides `Trainer.get_train_dataloader` to support our custom batching strategy.
1373
+ # Instead of returning a standard per-step batch (i.e., `per_device_batch_size), our dataloader loads an
1374
+ # *generation* batch (i.e., `per_device_batch_size × steps_per_generation`). This allows us to generate completions
1375
+ # once every steps_per_generation step—rather than once per accumulation step—which is significantly more
1376
+ # efficient. The only change from the original implementation is multiplying the batch size by
1377
+ # `steps_per_generation`. Thus, `_prepare_inputs` is called with this *generation* batch, and it handles the
1378
+ # splitting internally.
1379
+ # Maintenance note: This method is a copy-paste of the original `Trainer.get_train_dataloader` with only one line
1380
+ # modification. As a result, some parts of the method aren't relevant to RLOO, but we keep them to stay one line
1381
+ # apart from the super method, ensuring easier maintenance in the future.
1382
+ def get_train_dataloader(self):
1383
+ if self.train_dataset is None:
1384
+ raise ValueError("Trainer: training requires a train_dataset.")
1385
+
1386
+ train_dataset = self.train_dataset
1387
+ data_collator = self.data_collator
1388
+ if is_datasets_available() and isinstance(train_dataset, datasets.Dataset):
1389
+ train_dataset = self._remove_unused_columns(train_dataset, description="training")
1390
+ else:
1391
+ data_collator = self._get_collator_with_removed_columns(data_collator, description="training")
1392
+
1393
+ dataloader_params = {
1394
+ "batch_size": self._train_batch_size * self.args.steps_per_generation, # < this is the change
1395
+ "collate_fn": data_collator,
1396
+ "num_workers": self.args.dataloader_num_workers,
1397
+ "pin_memory": self.args.dataloader_pin_memory,
1398
+ "persistent_workers": self.args.dataloader_persistent_workers,
1399
+ }
1400
+
1401
+ if not isinstance(train_dataset, torch.utils.data.IterableDataset):
1402
+ dataloader_params["sampler"] = self._get_train_sampler()
1403
+ dataloader_params["drop_last"] = self.args.dataloader_drop_last
1404
+ dataloader_params["worker_init_fn"] = partial(
1405
+ seed_worker, num_workers=self.args.dataloader_num_workers, rank=self.args.process_index
1406
+ )
1407
+
1408
+ dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor
1409
+
1410
+ return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params))
1411
+
1412
+ def _get_train_sampler(self, dataset: Optional[Dataset] = None) -> Sampler:
1413
+ # Returns a sampler that
1414
+ # 1. ensures each prompt is repeated across multiple processes. This guarantees that identical prompts are
1415
+ # distributed to different GPUs, allowing rewards to be computed and normalized correctly within each prompt
1416
+ # group. Using the same seed across processes ensures consistent prompt assignment, preventing discrepancies
1417
+ # in group formation.
1418
+ # 2. repeats the batch multiple times to allow reusing generations across multiple updates. Refer to
1419
+ # _prepare_inputs to see how the generations are stored and reused.
1420
+
1421
+ # In the following figure, the values are the prompt indices. The first row shows the first sampled batch, the
1422
+ # second row shows the second sampled batch, and so on.
1423
+ #
1424
+ # | GPU 0 | GPU 1 |
1425
+ #
1426
+ # global_step step <-───> num_generations=2
1427
+ # <-───────> per_device_train_batch_size=3
1428
+ # grad_accum ▲ ▲ 0 0 0 0 1 1 2 2 <- Generate for the first `steps_per_generation` (prompts 0 to 11); store the completions; use the first slice to compute the loss
1429
+ # =2 ▼ | 0 1 3 3 4 4 5 5 <- Take the stored generations and use the second slice to compute the loss
1430
+ # |
1431
+ # | 1 2 6 6 7 7 8 8 <- Take the stored generations and use the third slice to compute the loss
1432
+ # steps_per_gen=4 ▼ 1 3 9 9 10 10 11 11 <- Take the stored generations and use the fourth slice to compute the loss
1433
+ #
1434
+ # 2 4 12 12 13 13 14 14 <- Generate for the second `steps_per_generation` (prompts 12 to 23); store the completions; use the first slice to compute the loss
1435
+ # 2 5 15 15 16 16 17 17 <- Take the stored generations and use the second slice to compute the loss
1436
+ # ...
1437
+ if dataset is None:
1438
+ dataset = self.train_dataset
1439
+ return RepeatSampler(
1440
+ data_source=dataset,
1441
+ mini_repeat_count=self.num_generations,
1442
+ batch_size=self.args.generation_batch_size // self.num_generations,
1443
+ repeat_count=self.num_iterations * self.args.steps_per_generation,
1444
+ shuffle=self.shuffle_dataset,
1445
+ seed=self.args.seed,
1446
+ )
1447
+
1448
+ def _get_eval_sampler(self, eval_dataset) -> Sampler:
1449
+ # See _get_train_sampler for an explanation of the sampler.
1450
+ return RepeatSampler(
1451
+ data_source=eval_dataset,
1452
+ mini_repeat_count=self.num_generations,
1453
+ seed=self.args.seed,
1454
+ )
1455
+
1456
+ @profiling_decorator
1457
+ def _get_per_token_logps_and_entropies(
1458
+ self,
1459
+ model,
1460
+ input_ids,
1461
+ attention_mask,
1462
+ logits_to_keep,
1463
+ batch_size=None,
1464
+ compute_entropy=False,
1465
+ pixel_values=None,
1466
+ image_grid_thw=None,
1467
+ num_images=None,
1468
+ pixel_attention_mask=None,
1469
+ image_sizes=None,
1470
+ token_type_ids=None,
1471
+ ) -> dict[str, Optional[torch.Tensor]]:
1472
+ """Compute log-probs and (optionally) entropies for each token."""
1473
+ batch_size = batch_size or input_ids.size(0) # Chunk inputs into smaller batches to reduce memory peak
1474
+ all_logps = []
1475
+ all_entropies = []
1476
+ for start in range(0, input_ids.size(0), batch_size):
1477
+ input_ids_batch = input_ids[start : start + batch_size]
1478
+ attention_mask_batch = attention_mask[start : start + batch_size]
1479
+
1480
+ # Build model inputs - check if the model supports logits_to_keep (some models and VLMs don't)
1481
+ model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch}
1482
+
1483
+ if image_grid_thw is not None and pixel_values is not None:
1484
+ rows_per_image = image_grid_thw.prod(dim=-1)
1485
+ rows_per_sample = torch.split(rows_per_image, num_images)
1486
+ rows_per_sample = torch.stack([s.sum() for s in rows_per_sample])
1487
+ cum_rows = torch.cat([torch.tensor([0], device=rows_per_sample.device), rows_per_sample.cumsum(0)])
1488
+ row_start, row_end = cum_rows[start].item(), cum_rows[start + batch_size].item()
1489
+ model_inputs["pixel_values"] = pixel_values[row_start:row_end]
1490
+ cum_imgs = torch.tensor([0] + num_images).cumsum(0)
1491
+ img_start, img_end = cum_imgs[start], cum_imgs[start + batch_size]
1492
+ model_inputs["image_grid_thw"] = image_grid_thw[img_start:img_end]
1493
+ elif pixel_values is not None:
1494
+ model_inputs["pixel_values"] = pixel_values[start : start + batch_size]
1495
+ if pixel_attention_mask is not None:
1496
+ model_inputs["pixel_attention_mask"] = pixel_attention_mask[start : start + batch_size]
1497
+ if image_sizes is not None:
1498
+ model_inputs["image_sizes"] = image_sizes[start : start + batch_size]
1499
+ if token_type_ids is not None:
1500
+ model_inputs["token_type_ids"] = token_type_ids[start : start + batch_size]
1501
+
1502
+ # Only add logits_to_keep if the model supports it
1503
+ if "logits_to_keep" in self.model_kwarg_keys:
1504
+ # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded
1505
+ model_inputs["logits_to_keep"] = logits_to_keep + 1
1506
+
1507
+ model_inputs["use_cache"] = False # only used in generation; set False to suppress warnings
1508
+
1509
+ logits = model(**model_inputs).logits
1510
+ # Exclude the last value: it corresponds to the next token pred
1511
+ logits = logits[:, :-1, :] # (B, L-1, H)
1512
+ # Only keep the last logits_to_keep. For model that support logits_to_keep, this is a no-op.
1513
+ logits = logits[:, -logits_to_keep:, :] # (B, logits_to_keep, H)
1514
+ # Divide logits by sampling temperature.
1515
+ # See https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo#policy-training-implementation-details
1516
+ logits = logits / self.temperature
1517
+
1518
+ completion_ids = input_ids_batch[:, -logits_to_keep:]
1519
+ logps = selective_log_softmax(logits, completion_ids) # compute logprobs
1520
+ all_logps.append(logps)
1521
+
1522
+ if compute_entropy:
1523
+ with torch.no_grad():
1524
+ entropies = entropy_from_logits(logits)
1525
+ all_entropies.append(entropies)
1526
+
1527
+ logps = torch.cat(all_logps, dim=0)
1528
+ entropies = torch.cat(all_entropies, dim=0) if compute_entropy else None
1529
+ return logps, entropies
1530
+
1531
+ def _fix_param_name_to_vllm(self, name, extra_prefixes: Optional[list[str]] = None):
1532
+ extra_prefixes = extra_prefixes or []
1533
+ prefixes = ["_checkpoint_wrapped_module."] + extra_prefixes
1534
+ for prefix in prefixes:
1535
+ name = name.replace(prefix, "")
1536
+ return name
1537
+
1538
+ def _sync_fsdp1_params_to_vllm(self, module: nn.Module, prefix: str = "", visited=None):
1539
+ """Memory-efficient post-order traversal of FSDP modules to extract full parameters and sync with vLLM."""
1540
+ # For FSDP1, we need to recurse into children and also use summon_full_params
1541
+ if visited is None:
1542
+ visited = set()
1543
+ for child_name, child_module in module.named_children():
1544
+ child_prefix = f"{prefix}.{child_name}" if prefix else child_name
1545
+ self._sync_fsdp1_params_to_vllm(
1546
+ child_module, prefix=child_prefix, visited=visited
1547
+ ) # recurse into the child
1548
+
1549
+ if isinstance(module, FSDP):
1550
+ with FSDP.summon_full_params(module, recurse=False, writeback=False):
1551
+ for param_name, param in module.named_parameters():
1552
+ full_name = f"{prefix}.{param_name}" if prefix else param_name
1553
+ full_name = self._fix_param_name_to_vllm(full_name, extra_prefixes=["_fsdp_wrapped_module."])
1554
+
1555
+ if full_name in visited:
1556
+ continue # skip FSDP subtrees already traversed
1557
+ visited.add(full_name)
1558
+
1559
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
1560
+ self.vllm_client.update_named_param(full_name, param.data)
1561
+ elif self.vllm_mode == "colocate":
1562
+
1563
+ pass
1564
+
1565
+ pass
1566
+
1567
+ def _sync_fsdp2_params_to_vllm(self, module: nn.Module):
1568
+ # For FSDP2, module already covers all parameters, so no need for recursion
1569
+ for name, param in module.items():
1570
+ if param.is_cpu:
1571
+ param = param.to(torch.device("cuda"))
1572
+ param = param.full_tensor()
1573
+
1574
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
1575
+ self.vllm_client.update_named_param(name, param)
1576
+ elif self.vllm_mode == "colocate":
1577
+
1578
+ pass
1579
+
1580
+ pass
1581
+
1582
+ @profiling_decorator
1583
+ def _move_model_to_vllm(self):
1584
+ # For DeepSpeed ZeRO-3 and FSDP, we need to gather all parameters before operations
1585
+ deepspeed_plugin = self.accelerator.state.deepspeed_plugin
1586
+ zero_stage_3 = deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3
1587
+ if zero_stage_3:
1588
+ import deepspeed
1589
+
1590
+ gather_if_zero3 = deepspeed.zero.GatheredParameters
1591
+ else:
1592
+ gather_if_zero3 = nullcontext
1593
+
1594
+ if is_peft_model(self.model):
1595
+ # With PEFT and FSDP/DeepSpeed ZeRO Stage 3, we must gather the full model at once before merging, as
1596
+ # merging adapters in a sharded manner is not supported.
1597
+ # TODO: does this work with FSDP?
1598
+ with gather_if_zero3(list(self.model.parameters())):
1599
+ self.model.merge_adapter()
1600
+
1601
+ # Update vLLM weights while parameters are gathered
1602
+ if self.is_fsdp_enabled: # note if using FSDP, gather_if_zero3 is nullcontext
1603
+ # Update vLLM weights while parameters are gathered
1604
+ # For PEFT with FSDP we need to use the memory efficient post-order traversal
1605
+ fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None)
1606
+ fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1
1607
+ if fsdp_version == 1:
1608
+ self._sync_fsdp1_params_to_vllm(
1609
+ self.model
1610
+ ) # use memory-efficient post-order traversal for FSDP
1611
+ elif fsdp_version == 2:
1612
+ self._sync_fsdp2_params_to_vllm(self.model)
1613
+ else:
1614
+ # DeepSpeed ZeRO-3 with PEFT
1615
+ for name, param in self.model.named_parameters():
1616
+ # When using PEFT, we need to recover the original parameter name and discard some parameters
1617
+ name = name.removeprefix("base_model.model.").replace(".base_layer", "")
1618
+ if self.model.prefix in name:
1619
+ continue
1620
+ # When module to save, remove its prefix and discard the original module
1621
+ if "original_module" in name:
1622
+ continue
1623
+ name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."])
1624
+
1625
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
1626
+ self.vllm_client.update_named_param(name, param.data)
1627
+ elif self.vllm_mode == "colocate":
1628
+
1629
+ pass
1630
+
1631
+ pass
1632
+ # Unmerge adapters while parameters are still gathered
1633
+ self.model.unmerge_adapter()
1634
+ # Parameters will automatically be repartitioned when exiting the context
1635
+ else:
1636
+ # For non-PEFT models, simply gather (if needed) and update each parameter individually.
1637
+ if self.is_fsdp_enabled:
1638
+ fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None)
1639
+ fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1
1640
+ if fsdp_version == 1:
1641
+ self._sync_fsdp1_params_to_vllm(self.model) # use memory-efficient post-order traversal for FSDP
1642
+ elif fsdp_version == 2:
1643
+ self._sync_fsdp2_params_to_vllm(self.model)
1644
+ else:
1645
+ for name, param in self.model.named_parameters():
1646
+ name = self._fix_param_name_to_vllm(name)
1647
+ with gather_if_zero3([param]):
1648
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
1649
+ self.vllm_client.update_named_param(name, param.data)
1650
+ elif self.vllm_mode == "colocate":
1651
+
1652
+ pass
1653
+
1654
+ pass
1655
+
1656
+ # Reset cache on vLLM
1657
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
1658
+ self.vllm_client.reset_prefix_cache()
1659
+ elif self.vllm_mode == "colocate":
1660
+ self.llm.reset_prefix_cache()
1661
+
1662
+ @profiling_decorator
1663
+ def _prepare_inputs(
1664
+ self, generation_batch: dict[str, Union[torch.Tensor, Any]]
1665
+ ) -> dict[str, Union[torch.Tensor, Any]]:
1666
+ # Prepares inputs for model training/evaluation by managing completion generation and batch handling.
1667
+ # During training:
1668
+ # - Receives the local generation batch (Per-GPU batch size × steps per generation)
1669
+ # from the modified training dataloader instead of the standard local batch
1670
+ # - Generates completions once for the entire generation batch and splits it into batches of size
1671
+ # `per_device_train_batch_size`
1672
+ # - Buffers these completions and returns the appropriate slice for the current accumulation step
1673
+ # - Optimizes by regenerating completions only periodically (every steps_per_generation * num_iterations)
1674
+ # During evaluation:
1675
+ # - The input is treated as a standard local batch (no accumulation, no multiple iterations)
1676
+ # - Completions are generated for each batch without buffering or reuse
1677
+ # Returns a single local batch in both cases.
1678
+
1679
+ mode = "train" if self.model.training else "eval"
1680
+ if mode == "train":
1681
+ generate_every = self.args.steps_per_generation * self.num_iterations
1682
+ if self._step % generate_every == 0 or self._buffered_inputs is None:
1683
+ # self._buffered_inputs=None can occur when resuming from a checkpoint
1684
+ generation_batch = self._generate_and_score_completions(generation_batch)
1685
+ generation_batch = split_pixel_values_by_grid(generation_batch)
1686
+
1687
+ try: generation_batch = shuffle_sequence_dict(generation_batch)
1688
+
1689
+ except: pass
1690
+ generation_batches = split_tensor_dict(generation_batch, self.args.steps_per_generation)
1691
+ self._buffered_inputs = [unsplit_pixel_values_by_grid(batch) for batch in generation_batches]
1692
+ inputs = self._buffered_inputs[self._step % self.args.steps_per_generation]
1693
+ self._step += 1
1694
+ else:
1695
+ # In evaluation, there is neither batch grouping for generation, nor multiple iterations, hence
1696
+ # local generation batch == local eval batch
1697
+ inputs = self._generate_and_score_completions(generation_batch)
1698
+ return inputs
1699
+
1700
+ @profiling_decorator
1701
+ def _calculate_rewards(self, inputs, prompts, completions, completion_ids_list):
1702
+ device = self.accelerator.device
1703
+ rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device)
1704
+
1705
+ # Repeat all input columns (but "prompt", "completion", and "completion_ids") to match the num of generations
1706
+ keys = [key for key in inputs[0] if key not in ["prompt", "completion", "completion_ids"]]
1707
+ reward_kwargs = {key: [example[key] for example in inputs] for key in keys}
1708
+
1709
+ # This allows for dynamic reward shaping based on training progress.
1710
+ reward_kwargs["trainer_state"] = self.state
1711
+
1712
+ for i, (reward_func, reward_processing_class, reward_func_name) in enumerate(
1713
+ zip(self.reward_funcs, self.reward_processing_classes, self.reward_func_names)
1714
+ ):
1715
+ with profiling_context(self, reward_func_name):
1716
+ if isinstance(reward_func, nn.Module): # Module (no PretrainedModel) for compat with compiled models
1717
+ if is_conversational(inputs[0]):
1718
+ messages = [{"messages": p + c} for p, c in zip(prompts, completions)]
1719
+ texts = [apply_chat_template(x, reward_processing_class)["text"] for x in messages]
1720
+ else:
1721
+ texts = [p + c for p, c in zip(prompts, completions)]
1722
+ reward_inputs = reward_processing_class(
1723
+ text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False
1724
+ )
1725
+ reward_inputs = super()._prepare_inputs(reward_inputs)
1726
+ with torch.inference_mode():
1727
+ rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,)
1728
+ else:
1729
+ output_reward_func = reward_func(
1730
+ prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs
1731
+ )
1732
+ # Convert None values to NaN
1733
+ output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func]
1734
+
1735
+ rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device)
1736
+
1737
+ # If all reward functions return None for a given row, issue a detailed warning
1738
+ if torch.isnan(rewards_per_func).all(dim=1).any():
1739
+ nan_row_idx = torch.isnan(rewards_per_func).all(dim=1).nonzero(as_tuple=True)[0][0]
1740
+ row_reward_kwargs = {
1741
+ key: value[nan_row_idx] for key, value in reward_kwargs.items() if key != "trainer_state"
1742
+ }
1743
+ row_reward_kwargs["prompt"] = prompts[nan_row_idx]
1744
+ row_reward_kwargs["completion"] = completions[nan_row_idx]
1745
+ logger.warning(
1746
+ f"All reward functions returned None for the following kwargs:\n{row_reward_kwargs}\n"
1747
+ "Please ensure that at least one reward function returns a valid reward."
1748
+ )
1749
+
1750
+ # Gather the reward per function: this part is crucial, because the rewards are normalized per group and the
1751
+ # completions may be distributed across processes
1752
+ rewards_per_func = gather(rewards_per_func)
1753
+ return rewards_per_func
1754
+
1755
+ def _generate_single_turn(self, prompts: list[str], images: Optional[list]):
1756
+ device = self.accelerator.device
1757
+
1758
+ # If the prompts are conversational and the inputs contain images, we need to convert the prompts from
1759
+ # [{"role": "user", "content": "What color is the sky?"}] to
1760
+ # [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What color is the sky?"}]}]
1761
+ kwargs = {}
1762
+ if images is not None:
1763
+ kwargs = {"images": images}
1764
+ for prompt, image_list in zip(prompts, images):
1765
+ if isinstance(prompt, list): # i.e., when using conversational data
1766
+ prepare_multimodal_messages(prompt, num_images=len(image_list))
1767
+
1768
+ prompts_text = [
1769
+ maybe_apply_chat_template({"prompt": prompt}, self.processing_class)["prompt"] for prompt in prompts
1770
+ ]
1771
+
1772
+ if images is not None:
1773
+ prompt_inputs = self.processing_class(text=prompts_text, padding=True, return_tensors="pt", **kwargs)
1774
+ prompt_inputs = super()._prepare_inputs(prompt_inputs)
1775
+ forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]}
1776
+ else:
1777
+ forward_kwargs = {}
1778
+
1779
+ # Generate completions using either vLLM or regular generation
1780
+ if self.use_vllm:
1781
+ if self.vllm_mode == "colocate" and self.args.vllm_enable_sleep_mode:
1782
+ # wake up colocated vLLM instances if needed
1783
+ torch.cuda.empty_cache() # required to avoid OOM in some cases
1784
+ self.llm.wake_up()
1785
+
1786
+ # First, update the vLLM weights if needed
1787
+ if self.state.global_step != self._last_loaded_step:
1788
+ self._move_model_to_vllm()
1789
+ self._last_loaded_step = self.state.global_step
1790
+
1791
+ # Generate completions using vLLM: gather all prompts and use them in a single call in the main process
1792
+ if self.vllm_mode == "server":
1793
+ all_prompts_text = gather_object(prompts_text)
1794
+ if images is not None:
1795
+ all_images = gather_object(images)
1796
+
1797
+ if self.accelerator.is_main_process:
1798
+ # Since 'prompts' contains 'num_generations' duplicates, we first take unique prompts, and generate
1799
+ # num_generations outputs for each one. This is faster than generating outputs for each duplicate
1800
+ # prompt individually.
1801
+ ordered_set_of_prompts = all_prompts_text[:: self.num_generations]
1802
+
1803
+ if images is not None:
1804
+ ordered_set_of_images = all_images[:: self.num_generations]
1805
+ else:
1806
+ ordered_set_of_images = None
1807
+
1808
+ with profiling_context(self, "vLLM.generate"):
1809
+ output = self.vllm_client.generate(
1810
+ prompts=ordered_set_of_prompts,
1811
+ images=ordered_set_of_images,
1812
+ n=self.num_generations,
1813
+ repetition_penalty=self.repetition_penalty,
1814
+ temperature=self.temperature,
1815
+ top_p=self.top_p,
1816
+ top_k=-1 if self.top_k is None else self.top_k,
1817
+ min_p=0.0 if self.min_p is None else self.min_p,
1818
+ max_tokens=self.max_completion_length,
1819
+ truncate_prompt_tokens=self.max_prompt_length,
1820
+ guided_decoding_regex=self.guided_decoding_regex,
1821
+ generation_kwargs=self.args.generation_kwargs,
1822
+ )
1823
+ payload = (output["prompt_ids"], output["completion_ids"], output["logprobs"])
1824
+ else:
1825
+ payload = None
1826
+
1827
+ # Broadcast the completions from the main process to all processes, ensuring each process receives its corresponding slice.
1828
+ obj_list = [payload]
1829
+ broadcast_object_list(obj_list, from_process=0)
1830
+ all_prompt_ids, all_completion_ids, _ = obj_list[0]
1831
+
1832
+ # At this point, we only get 1 copy of each prompt, so we need to repeat them num_generations times
1833
+ all_prompt_ids = [ids for ids in all_prompt_ids for _ in range(self.num_generations)]
1834
+
1835
+ process_slice = slice(
1836
+ self.accelerator.process_index * len(prompts),
1837
+ (self.accelerator.process_index + 1) * len(prompts),
1838
+ )
1839
+ prompt_ids = all_prompt_ids[process_slice]
1840
+ completion_ids = all_completion_ids[process_slice]
1841
+
1842
+ # Generate completions using colocated vLLM instances: each device holds vLLM copy and work on their own batch of prompts
1843
+ elif self.vllm_mode == "colocate":
1844
+ if self.guided_decoding_regex:
1845
+ guided_decoding = GuidedDecodingParams(regex=self.guided_decoding_regex)
1846
+ else:
1847
+ guided_decoding = None
1848
+
1849
+ generation_kwargs = {
1850
+ "n": 1, # vLLM on each GPU generates only 1 in colocate mode
1851
+ "repetition_penalty": self.repetition_penalty,
1852
+ "temperature": self.temperature,
1853
+ "top_p": self.top_p,
1854
+ "top_k": -1 if self.top_k is None else self.top_k,
1855
+ "min_p": 0.0 if self.min_p is None else self.min_p,
1856
+ "max_tokens": self.max_completion_length,
1857
+ "truncate_prompt_tokens": self.max_prompt_length,
1858
+ "guided_decoding": guided_decoding,
1859
+ }
1860
+ if self.args.generation_kwargs is not None:
1861
+ generation_kwargs.update(self.args.generation_kwargs)
1862
+ sampling_params = SamplingParams(**grpo_update_SamplingParams(SamplingParams, generation_kwargs, getattr(self.args, 'vllm_sampling_params', None)))
1863
+
1864
+ if self.vllm_tensor_parallel_size > 1:
1865
+ # Gather prompts from all ranks in the TP group and flatten.
1866
+ # Each rank starts with its own prompts; after gathering, all ranks see the full group set.
1867
+ orig_size = len(prompts_text)
1868
+ gathered_prompts = [None for _ in range(self.vllm_tensor_parallel_size)]
1869
+ torch.distributed.all_gather_object(gathered_prompts, prompts_text, group=self.tp_group)
1870
+ all_prompts_text = [p for sublist in gathered_prompts for p in sublist]
1871
+
1872
+ if images is not None:
1873
+ gathered_images = [None for _ in range(self.vllm_tensor_parallel_size)]
1874
+ torch.distributed.all_gather_object(gathered_images, images, group=self.tp_group)
1875
+ all_images = [img for sublist in gathered_images for img in sublist]
1876
+ else:
1877
+ all_images = None
1878
+ else:
1879
+ all_prompts_text = prompts_text
1880
+ all_images = images
1881
+
1882
+ if images is not None and all_images:
1883
+ vllm_inputs = []
1884
+ for prompt, image_list in zip(all_prompts_text, all_images):
1885
+ vllm_inputs.append({"prompt": prompt, "multi_modal_data": {"image": image_list}})
1886
+
1887
+ else:
1888
+ vllm_inputs = all_prompts_text
1889
+
1890
+ with profiling_context(self, "vLLM.generate"):
1891
+ all_outputs = self.llm.generate(vllm_inputs, sampling_params=sampling_params, use_tqdm=False, lora_request = self.model.load_lora('rloo_trainer_lora_model_' + (os.environ.get('CUDA_VISIBLE_DEVICES', '0').replace(',','')), load_tensors = True))
1892
+
1893
+ all_prompt_ids = [output.prompt_token_ids for output in all_outputs]
1894
+ all_completion_ids = [output.token_ids for outputs in all_outputs for output in outputs.outputs]
1895
+
1896
+ if self.vllm_tensor_parallel_size > 1:
1897
+ # Slice completions for this rank within its TP group.
1898
+ # Each rank generates all outputs — we keep only our share.
1899
+ local_rank_in_group = torch.distributed.get_rank(group=self.tp_group)
1900
+ tp_slice = slice(local_rank_in_group * orig_size, (local_rank_in_group + 1) * orig_size)
1901
+ prompt_ids = all_prompt_ids[tp_slice]
1902
+ completion_ids = all_completion_ids[tp_slice]
1903
+ else:
1904
+ prompt_ids = all_prompt_ids
1905
+ completion_ids = all_completion_ids
1906
+
1907
+ if self.args.vllm_enable_sleep_mode:
1908
+ self.llm.sleep(level=1)
1909
+
1910
+ elif self.use_transformers_paged:
1911
+ # Re-process inputs for paged generation if needed
1912
+ # Note: images are already validated and preprocessed above
1913
+ paged_prompt_inputs = self.processing_class(text=prompts_text, **kwargs)
1914
+ previous_attn = self.model_wrapped.config._attn_implementation
1915
+
1916
+ if is_flash_attn_2_available():
1917
+ self.model_wrapped.config._attn_implementation = "paged_attention"
1918
+ else:
1919
+ self.model_wrapped.config._attn_implementation = "sdpa_paged"
1920
+ with (
1921
+ profiling_context(self, "transformers.generate_batch"),
1922
+ unwrap_model_for_generation(
1923
+ self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation
1924
+ ) as unwrapped_model,
1925
+ torch.no_grad(),
1926
+ FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(),
1927
+ ):
1928
+ # Cast to the appropriate dtype based on training configuration
1929
+ if self.args.bf16:
1930
+ unwrapped_model.to(torch.bfloat16)
1931
+ elif self.args.fp16:
1932
+ unwrapped_model.to(torch.float16)
1933
+ with torch.inference_mode():
1934
+ all_outputs = unwrapped_model.generate_batch(
1935
+ paged_prompt_inputs.input_ids, generation_config=self.generation_config, progress_bar=False
1936
+ )
1937
+ unwrapped_model.train() # restore training mode, as generate_batch forces eval mode
1938
+ completion_ids = [output.generated_tokens for output in all_outputs.values()]
1939
+ prompt_ids = paged_prompt_inputs.input_ids
1940
+ # Restore the original attention implementation, training mode
1941
+ self.model_wrapped.config._attn_implementation = previous_attn
1942
+
1943
+ else:
1944
+ # Regular generation path
1945
+ generate_inputs = self.processing_class(
1946
+ text=prompts_text,
1947
+ return_tensors="pt",
1948
+ padding=True,
1949
+ padding_side="left",
1950
+ max_length=self.max_prompt_length,
1951
+ truncation=True,
1952
+ add_special_tokens=False,
1953
+ **kwargs,
1954
+ )
1955
+ generate_inputs = super()._prepare_inputs(generate_inputs)
1956
+
1957
+ with (
1958
+ profiling_context(self, "transformers.generate"),
1959
+ unwrap_model_for_generation(
1960
+ self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation
1961
+ ) as unwrapped_model,
1962
+ torch.no_grad(),
1963
+ FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(),
1964
+ ):
1965
+ prompt_completion_ids = unwrapped_model.generate(
1966
+ **generate_inputs, generation_config=self.generation_config, disable_compile=True
1967
+ )
1968
+ # Compute prompt length and extract completion ids
1969
+ prompt_ids, prompt_mask = generate_inputs["input_ids"], generate_inputs["attention_mask"]
1970
+ prompt_length = prompt_ids.size(1)
1971
+ completion_ids = prompt_completion_ids[:, prompt_length:]
1972
+
1973
+ # Mask everything after the first EOS token
1974
+ is_eos = completion_ids == self.eos_token_id
1975
+ eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device)
1976
+ eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)]
1977
+ sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1)
1978
+ completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int()
1979
+ prompt_ids = [p[m].tolist() for p, m in zip(prompt_ids, prompt_mask.bool())]
1980
+ completion_ids = [c[m].tolist() for c, m in zip(completion_ids, completion_mask.bool())]
1981
+
1982
+ return prompt_ids, completion_ids, forward_kwargs
1983
+
1984
+ def _generate(self, prompts: list[str], images: Optional[list]):
1985
+ device = self.accelerator.device
1986
+ mode = "train" if self.model.training else "eval"
1987
+
1988
+ prompt_ids, completion_ids, forward_kwargs = self._generate_single_turn(prompts, images)
1989
+
1990
+ # Get completion length per sequence, used for logging
1991
+ prompt_lengths = torch.tensor([len(ids) for ids in prompt_ids], device=device)
1992
+ completion_lengths = torch.tensor([len(ids) for ids in completion_ids], device=device)
1993
+ agg_prompt_lengths = self.accelerator.gather(prompt_lengths)
1994
+ agg_completion_lengths = self.accelerator.gather(completion_lengths)
1995
+ total_prompt_tokens = agg_prompt_lengths.sum()
1996
+ total_completion_tokens = agg_completion_lengths.sum() # = num_items_in_batch, required for the DAPO loss
1997
+
1998
+ # Log the metrics
1999
+ if mode == "train":
2000
+ self.state.num_input_tokens_seen += (total_prompt_tokens + total_completion_tokens).item()
2001
+ self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen]
2002
+
2003
+ # Log completion lengths, mean, min, max
2004
+ agg_completion_lengths = self.accelerator.gather(completion_lengths)
2005
+ self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item())
2006
+ self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item())
2007
+ self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item())
2008
+
2009
+ # Identify sequences that terminated with EOS and log their lengths
2010
+ eos_and_pad = [self.eos_token_id, self.pad_token_id]
2011
+ is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids], device=device)
2012
+ agg_is_truncated = self.accelerator.gather(is_truncated)
2013
+ self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item())
2014
+ term_completion_lengths = agg_completion_lengths[~agg_is_truncated]
2015
+ if len(term_completion_lengths) == 0: # edge case where no terminated sequences are found
2016
+ term_completion_lengths = torch.zeros(1, device=device)
2017
+ self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item())
2018
+ self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item())
2019
+ self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item())
2020
+
2021
+ return prompt_ids, completion_ids, forward_kwargs
2022
+
2023
+ def _generate_and_score_completions(
2024
+ self, inputs: list[dict[str, Union[torch.Tensor, Any]]]
2025
+ ) -> dict[str, Union[torch.Tensor, Any]]:
2026
+ device = self.accelerator.device
2027
+ mode = "train" if self.model.training else "eval"
2028
+
2029
+ prompts = [x["prompt"] for x in inputs]
2030
+
2031
+ if "images" in inputs[0]:
2032
+ images = [example.get("images") for example in inputs]
2033
+ elif "image" in inputs[0]:
2034
+ images = [[example.get("image")] if example.get("image") is not None else None for example in inputs]
2035
+ else:
2036
+ images = None
2037
+ # Transformers requires at least one image in the batch, otherwise it throws an error
2038
+ if images is not None and all(img_list == [] for img_list in images):
2039
+ images = None
2040
+
2041
+ prompt_ids_list, completion_ids_list, forward_kwargs = self._generate(prompts, images)
2042
+
2043
+ # Convert lists of token IDs to padded tensors
2044
+ prompt_ids = [torch.tensor(ids, device=device) for ids in prompt_ids_list]
2045
+ prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids]
2046
+ prompt_ids = pad(prompt_ids, padding_value=self.pad_token_id, padding_side="left")
2047
+ prompt_mask = pad(prompt_mask, padding_value=0, padding_side="left")
2048
+ completion_ids = [torch.tensor(ids, device=device) for ids in completion_ids_list]
2049
+ completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids]
2050
+ completion_ids = pad(completion_ids, padding_value=self.pad_token_id, padding_side="right")
2051
+ completion_mask = pad(completion_mask, padding_value=0, padding_side="right")
2052
+
2053
+ # If mask_truncated_completions is enabled, zero out truncated completions in completion_mask
2054
+ if self.mask_truncated_completions:
2055
+ eos_and_pad = [self.eos_token_id, self.pad_token_id]
2056
+ is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device)
2057
+ completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int()
2058
+
2059
+ # Concatenate prompt_mask with completion_mask for logit computation
2060
+ prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C)
2061
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C)
2062
+ # If token_type_ids are used, extend them with zeros for the completion part
2063
+ if "token_type_ids" in forward_kwargs:
2064
+ token_type_ids = forward_kwargs["token_type_ids"]
2065
+ forward_kwargs["token_type_ids"] = torch.cat(
2066
+ [token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1
2067
+ )
2068
+
2069
+ logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
2070
+ batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size
2071
+
2072
+ num_images = [len(img_list) for img_list in images] if images is not None else None
2073
+
2074
+ with torch.no_grad():
2075
+ # Compute the per-token log probabilities for the current model
2076
+ old_per_token_logps, _ = self._get_per_token_logps_and_entropies(
2077
+ self.model,
2078
+ prompt_completion_ids,
2079
+ attention_mask,
2080
+ logits_to_keep,
2081
+ batch_size,
2082
+ num_images=num_images,
2083
+ **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
2084
+ )
2085
+ old_logps = (old_per_token_logps * completion_mask).sum(1) # mask out padding and tokens after EOS
2086
+
2087
+ # Compute the per-token log probabilities for the reference model
2088
+ if self.beta != 0.0:
2089
+ if self.ref_model is not None:
2090
+ ref_per_token_logps, _ = self._get_per_token_logps_and_entropies(
2091
+ self.ref_model,
2092
+ prompt_completion_ids,
2093
+ attention_mask,
2094
+ logits_to_keep,
2095
+ batch_size=batch_size,
2096
+ num_images=num_images,
2097
+ **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
2098
+ )
2099
+ else:
2100
+ with self.accelerator.unwrap_model(self.model).disable_adapter():
2101
+ ref_per_token_logps, _ = self._get_per_token_logps_and_entropies(
2102
+ self.model,
2103
+ prompt_completion_ids,
2104
+ attention_mask,
2105
+ logits_to_keep,
2106
+ batch_size=batch_size,
2107
+ num_images=num_images,
2108
+ **forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
2109
+ )
2110
+ else:
2111
+ ref_per_token_logps = None
2112
+
2113
+ # Decode
2114
+ prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True)
2115
+ completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
2116
+ if is_conversational(inputs[0]):
2117
+ completions = []
2118
+ for prompt, completion in zip(prompts, completions_text):
2119
+ bootstrap = prompt.pop()["content"] if prompt[-1]["role"] == "assistant" else ""
2120
+ completions.append([{"role": "assistant", "content": bootstrap + completion}])
2121
+ else:
2122
+ completions = completions_text
2123
+
2124
+ # Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is
2125
+ # important because rewards will be normalized per group, and completions are distributed. We will later slice
2126
+ # rewards_per_func to extract each process's subset.
2127
+ rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
2128
+
2129
+ # Apply weights to each reward function's output and sum
2130
+ rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
2131
+
2132
+ # Apply reward clipping if specified
2133
+ if self.reward_clip_range:
2134
+ rewards = rewards.clamp(min=self.reward_clip_range[0], max=self.reward_clip_range[1])
2135
+
2136
+ # Include the KL penalty in the reward
2137
+ if self.beta != 0.0:
2138
+ per_token_kl = old_per_token_logps - ref_per_token_logps
2139
+ # Apply sequence-level KL penalty to rewards (sum KL across tokens first, then apply to each sequence)
2140
+ kl = (per_token_kl * completion_mask).sum(-1)
2141
+ kl = gather(kl) # rewards are gathered, so kl must be too
2142
+ rewards = rewards - self.beta * kl
2143
+
2144
+ grouped_rewards = rewards.view(-1, self.num_generations)
2145
+ mean_grouped_rewards = grouped_rewards.mean(dim=1)
2146
+ std_rewards = grouped_rewards.std(dim=1)
2147
+ is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards))
2148
+
2149
+ # RLOO advantages computation
2150
+ grouped_sum = grouped_rewards.sum(dim=1, keepdim=True) # (num_prompts, 1)
2151
+ baselines = (grouped_sum - grouped_rewards) / (self.num_generations - 1) # (num_prompts, num_generations)
2152
+ baselines = baselines.view(-1) # Flatten back to match rewards shape
2153
+ advantages = rewards - baselines
2154
+
2155
+ # Normalize advantages
2156
+ if self.normalize_advantages:
2157
+ advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-4)
2158
+
2159
+ # Slice to keep only the local part of the data
2160
+ process_slice = slice(
2161
+ self.accelerator.process_index * len(prompts),
2162
+ (self.accelerator.process_index + 1) * len(prompts),
2163
+ )
2164
+ all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
2165
+ advantages = advantages[process_slice]
2166
+
2167
+ # Calculate and log the mean KL divergence between current and reference model
2168
+ if self.beta != 0.0:
2169
+ mean_kl = (per_token_kl * completion_mask).sum() / completion_mask.sum().clamp(min=1.0)
2170
+ self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
2171
+
2172
+ # Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
2173
+ for i, reward_func_name in enumerate(self.reward_func_names):
2174
+ mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
2175
+ self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
2176
+ std_func_rewards = nanstd(rewards_per_func[:, i]).item()
2177
+ self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards)
2178
+ self._metrics[mode]["reward"].append(mean_grouped_rewards.mean().item())
2179
+ self._metrics[mode]["reward_std"].append(std_rewards.mean().item())
2180
+ self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
2181
+
2182
+ # Log prompt and completion texts
2183
+ self._logs["prompt"].extend(gather_object(prompts_text))
2184
+ self._logs["completion"].extend(gather_object(completions_text))
2185
+ for i, name in enumerate(self.reward_func_names):
2186
+ self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
2187
+ self._logs["advantages"].extend(all_process_advantages.tolist())
2188
+
2189
+ if images is not None:
2190
+ self._logs["images"].extend(gather_object(images))
2191
+
2192
+ output = {
2193
+ "prompt_ids": prompt_ids,
2194
+ "prompt_mask": prompt_mask,
2195
+ "completion_ids": completion_ids,
2196
+ "completion_mask": completion_mask,
2197
+ "old_logps": old_logps,
2198
+ "advantages": advantages,
2199
+ }
2200
+ if "pixel_values" in forward_kwargs:
2201
+ output["pixel_values"] = forward_kwargs["pixel_values"]
2202
+ if "image_grid_thw" in forward_kwargs:
2203
+ output["image_grid_thw"] = forward_kwargs["image_grid_thw"]
2204
+ if "pixel_attention_mask" in forward_kwargs:
2205
+ output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"]
2206
+ if "image_sizes" in forward_kwargs:
2207
+ output["image_sizes"] = forward_kwargs["image_sizes"]
2208
+ if "token_type_ids" in forward_kwargs:
2209
+ output["token_type_ids"] = forward_kwargs["token_type_ids"]
2210
+ if images is not None:
2211
+ output["num_images"] = num_images
2212
+ return output
2213
+
2214
+ @profiling_decorator
2215
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
2216
+ if return_outputs:
2217
+ raise ValueError("The RLOOTrainer does not support returning outputs")
2218
+ return self._compute_loss(model, inputs)
2219
+
2220
+ def _compute_loss(self, model, inputs):
2221
+ # Compute the per-token log probabilities for the model
2222
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
2223
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
2224
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
2225
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
2226
+ logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
2227
+
2228
+ # Compute the per_token_logps and the entropy at each position in the completion
2229
+ per_token_logps, entropies = self._get_per_token_logps_and_entropies(
2230
+ model,
2231
+ input_ids,
2232
+ attention_mask,
2233
+ logits_to_keep,
2234
+ compute_entropy=True,
2235
+ pixel_values=inputs.get("pixel_values"),
2236
+ image_grid_thw=inputs.get("image_grid_thw"),
2237
+ num_images=inputs.get("num_images"),
2238
+ pixel_attention_mask=inputs.get("pixel_attention_mask"),
2239
+ image_sizes=inputs.get("image_sizes"),
2240
+ token_type_ids=inputs.get("token_type_ids"),
2241
+ )
2242
+
2243
+ logps = (per_token_logps * completion_mask).sum(1) # mask out padding and tokens after EOS
2244
+ old_logps = inputs["old_logps"]
2245
+ log_ratio = logps - old_logps
2246
+
2247
+ # Compute the loss
2248
+ advantages = inputs["advantages"]
2249
+ coef_1 = torch.exp(log_ratio)
2250
+ coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
2251
+ per_sequence_loss1 = coef_1 * advantages
2252
+ per_sequence_loss2 = coef_2 * advantages
2253
+ per_sequence_loss = -torch.min(per_sequence_loss1, per_sequence_loss2)
2254
+ loss = per_sequence_loss.mean()
2255
+
2256
+ # Log the metrics
2257
+ mode = "train" if self.model.training else "eval"
2258
+
2259
+ # Entropy
2260
+ mean_entropy = (entropies * completion_mask).sum() / completion_mask.sum().clamp(min=1.0)
2261
+ self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item())
2262
+
2263
+ # Compute the clipped probability ratios
2264
+ is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages < 0)
2265
+ is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages > 0)
2266
+ is_region_clipped = is_low_clipped | is_high_clipped
2267
+ gathered_low_clip = self.accelerator.gather(is_low_clipped.float().mean())
2268
+ self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item())
2269
+ self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item())
2270
+ gathered_high_clip = self.accelerator.gather(is_high_clipped.float().mean())
2271
+ self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item())
2272
+ self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item())
2273
+ gathered_clip_ratio = self.accelerator.gather(is_region_clipped.float().mean())
2274
+ self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item())
2275
+ return loss
2276
+
2277
+ def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: Optional[list[str]] = None):
2278
+ inputs = self._prepare_inputs(inputs)
2279
+ with torch.no_grad():
2280
+ with self.compute_loss_context_manager():
2281
+ loss = self.compute_loss(model, inputs)
2282
+ loss = loss.mean().detach()
2283
+ return loss, None, None
2284
+
2285
+ def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None:
2286
+ mode = "train" if self.model.training else "eval"
2287
+ metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics
2288
+
2289
+ # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
2290
+ # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
2291
+ if mode == "eval":
2292
+ metrics = {f"eval_{key}": val for key, val in metrics.items()}
2293
+
2294
+ logs = {**logs, **metrics}
2295
+ super().log(logs, start_time)
2296
+ self._metrics[mode].clear()
2297
+
2298
+ if self.accelerator.is_main_process and self.log_completions:
2299
+ if is_rich_available():
2300
+ print_prompt_completions_sample(
2301
+ self._logs["prompt"],
2302
+ self._logs["completion"],
2303
+ self._logs["rewards"],
2304
+ self._logs["advantages"],
2305
+ self.state.global_step,
2306
+ self.num_completions_to_print,
2307
+ )
2308
+
2309
+ if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None:
2310
+ import pandas as pd
2311
+
2312
+ table = {
2313
+ "step": [str(self.state.global_step)] * len(self._logs["prompt"]),
2314
+ "prompt": self._logs["prompt"],
2315
+ "completion": self._logs["completion"],
2316
+ **self._logs["rewards"],
2317
+ "advantage": self._logs["advantages"],
2318
+ }
2319
+
2320
+ if self._logs["images"]:
2321
+ table["images"] = []
2322
+ for image_list in self._logs["images"]:
2323
+ # Convert images to wandb Image objects for proper visualization
2324
+ table["images"].append([wandb.Image(image) for image in image_list])
2325
+
2326
+ df = pd.DataFrame(table)
2327
+ if self.wandb_log_unique_prompts:
2328
+ df = df.drop_duplicates(subset=["prompt"])
2329
+ wandb.log({"completions": wandb.Table(dataframe=df)})
2330
+
2331
+ # Ensure the model card is saved along with the checkpoint
2332
+ def _save_checkpoint(self, model, trial):
2333
+ if self.args.hub_model_id is None:
2334
+ model_name = Path(self.args.output_dir).name
2335
+ else:
2336
+ model_name = self.args.hub_model_id.split("/")[-1]
2337
+ self.create_model_card(model_name=model_name)
2338
+ super()._save_checkpoint(model, trial)
2339
+ class UnslothRLOOTrainer(_UnslothRLOOTrainer):
2340
+ """
2341
+
2342
+ Trainer for the Reinforce Leave One Out (RLOO) method. This algorithm was initially proposed in the paper [Back to
2343
+ Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in
2344
+ LLMs](https://huggingface.co/papers/2402.14740).
2345
+
2346
+ Example:
2347
+
2348
+ ```python
2349
+ from datasets import load_dataset
2350
+ from trl import RLOOTrainer
2351
+
2352
+ dataset = load_dataset("trl-lib/tldr", split="train")
2353
+ def reward_func(completions, **kwargs):
2354
+ # Dummy reward function that rewards completions with more unique letters.
2355
+ return [float(len(set(completion))) for completion in completions]
2356
+ trainer = RLOOTrainer(
2357
+ model="Qwen/Qwen2-0.5B-Instruct",
2358
+ reward_funcs=reward_func,
2359
+ train_dataset=dataset,
2360
+ )
2361
+
2362
+ trainer.train()
2363
+ ```
2364
+
2365
+ Args:
2366
+ model (`Union[str, PreTrainedModel]`):
2367
+ Model to be trained. Can be either:
2368
+
2369
+ - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
2370
+ path to a *directory* containing model weights saved using
2371
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
2372
+ using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in
2373
+ `args.model_init_kwargs`.
2374
+ - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
2375
+ reward_funcs (`Union[RewardFunc, list[RewardFunc]]`):
2376
+ Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
2377
+ functions with the prompts and completions and sum the rewards. Can be either:
2378
+
2379
+ - A single reward function, such as:
2380
+ - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a
2381
+ path to a *directory* containing model weights saved using
2382
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
2383
+ using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the
2384
+ keyword arguments in `args.model_init_kwargs`.
2385
+ - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported.
2386
+ - A custom reward function: The function is provided with the prompts and the generated completions,
2387
+ plus any additional columns in the dataset. It should return a list of rewards. Custom reward
2388
+ functions can also return `None` when the reward is not applicable to those samples. This is useful
2389
+ for multi-task training where different reward functions apply to different types of samples. When a
2390
+ reward function returns `None` for a sample, that reward function is excluded from the reward
2391
+ calculation for that sample. For more details, see [Using a custom reward
2392
+ function](#using-a-custom-reward-function).
2393
+
2394
+ The trainer's state is also passed to the reward function. The trainer's state is an instance of
2395
+ [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the
2396
+ reward function's signature.
2397
+ - A list of reward functions, where each item can independently be any of the above types. Mixing different
2398
+ types within the list (e.g., a string model ID and a custom reward function) is allowed.
2399
+ args ([`RLOOConfig`], *optional*):
2400
+ Configuration for this trainer. If `None`, a default configuration is used.
2401
+ train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
2402
+ Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is
2403
+ ignored. The format of the samples can be either:
2404
+
2405
+ - [Standard](dataset_formats#standard): Each sample contains plain text.
2406
+ - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
2407
+ and content).
2408
+ eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Union[Dataset, IterableDataset]]`):
2409
+ Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
2410
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*):
2411
+ Processing class used to process the data. The padding side must be set to "left". If `None`, the
2412
+ processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A
2413
+ padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
2414
+ `tokenizer.eos_token` will be used as the default.
2415
+ reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*):
2416
+ Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
2417
+
2418
+ - A single processing class: Used when `reward_funcs` contains only one reward function.
2419
+ - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
2420
+ If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is
2421
+ `None`, the tokenizer for the model is automatically loaded using
2422
+ [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward
2423
+ functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes`
2424
+ are ignored.
2425
+ callbacks (list of [`~transformers.TrainerCallback`], *optional*):
2426
+ List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
2427
+ in [here](https://huggingface.co/docs/transformers/main_classes/callback).
2428
+
2429
+ If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
2430
+ method.
2431
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`):
2432
+ A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your
2433
+ model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`.
2434
+ peft_config ([`~peft.PeftConfig`], *optional*):
2435
+ PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
2436
+
2437
+ config:
2438
+
2439
+ <Deprecated version="0.22.0">
2440
+
2441
+ This parameter is deprecated and will be removed in version 0.25.0. Use `args` instead.
2442
+
2443
+ </Deprecated>
2444
+
2445
+ reward_model:
2446
+ <Deprecated version="0.22.0">
2447
+
2448
+ This parameter is deprecated and will be removed in version 0.25.0. Use `reward_funcs` instead.
2449
+
2450
+ </Deprecated>
2451
+
2452
+ policy:
2453
+
2454
+ <Deprecated version="0.22.0">
2455
+
2456
+ This parameter is deprecated and will be removed in version 0.25.0. Use `model` instead.
2457
+
2458
+ </Deprecated>
2459
+
2460
+ ref_policy:
2461
+
2462
+ <Deprecated version="0.22.0">
2463
+
2464
+ This parameter is deprecated and will be removed in version 0.25.0. To use the initial model as the
2465
+ reference model, simply omit this parameter. The parameter is ignored.
2466
+
2467
+ </Deprecated>
2468
+
2469
+ data_collator:
2470
+
2471
+ <Deprecated version="0.22.0">
2472
+
2473
+ This parameter is deprecated and will be removed in version 0.25.0. The RLOOTrainer does not use a data
2474
+ collator, so this parameter is ignored.
2475
+
2476
+ </Deprecated>
2477
+
2478
+ """
2479
+ def __init__(
2480
+ self,
2481
+ model = None,
2482
+ reward_funcs = None,
2483
+ args = None,
2484
+ train_dataset = None,
2485
+ eval_dataset = None,
2486
+ processing_class = None,
2487
+ reward_processing_classes = None,
2488
+ callbacks = None,
2489
+ peft_config = None,
2490
+ config = None,
2491
+ reward_model = None,
2492
+ policy = None,
2493
+ ref_policy = None,
2494
+ data_collator = None,
2495
+ **kwargs
2496
+ ):
2497
+ if args is None: args = UnslothRLOOConfig()
2498
+ use_bf16 = getattr(args, 'bf16', False)
2499
+ if type(use_bf16) is not bool: use_bf16 = False
2500
+ use_fp16 = getattr(args, 'fp16', False)
2501
+ if type(use_fp16) is not bool: use_fp16 = False
2502
+ force_float32 = False
2503
+ full_finetuning = os.environ.get('UNSLOTH_ENABLE_FULL_FINETUNING', '0') == '1'
2504
+ if not full_finetuning and (os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '1'):
2505
+ print('Unsloth: Switching to float32 training since model cannot work with float16')
2506
+ force_float32 = True
2507
+ mixed_precision_dtype = os.environ.get('UNSLOTH_MIXED_PRECISION', 'float32')
2508
+ dtype = getattr(model.config, 'dtype', None) or getattr(model.config, 'torch_dtype', None)
2509
+ if dtype is None: dtype = model.get_input_embeddings().weight.dtype
2510
+ from unsloth_zoo.utils import _get_dtype
2511
+ dtype = _get_dtype(dtype)
2512
+ float16 = dtype == torch.float16
2513
+ if not force_float32 and (float16 and use_bf16): raise TypeError('Unsloth: Model is in float16 precision but you want to use bfloat16 precision. Set fp16 to `True` and bf16 to `False`')
2514
+ if not force_float32 and (not float16 and use_fp16): raise TypeError('Unsloth: Model is in bfloat16 precision but you want to use float16 precision. Set fp16 to `False` and bf16 to `True`')
2515
+ if force_float32:
2516
+ # Forced float32 training
2517
+ args.fp16 = False
2518
+ args.bf16 = False
2519
+ os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'
2520
+ if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'
2521
+ # args.mixed_precision is a new argument which needs to be set now
2522
+ elif (not use_bf16 and not use_fp16) and mixed_precision_dtype == 'float32':
2523
+ # Mixed precision training
2524
+ args.fp16 = float16
2525
+ args.bf16 = not float16
2526
+ os.environ['ACCELERATE_MIXED_PRECISION'] = 'fp16' if float16 else 'bf16'
2527
+ if hasattr(args, 'mixed_precision'): args.mixed_precision = 'fp16' if float16 else 'bf16'
2528
+ # args.mixed_precision is a new argument which needs to be set now
2529
+ elif mixed_precision_dtype == 'bfloat16':
2530
+ # Both False since bfloat16 full finetuning doesn't do any autocasting.
2531
+ args.fp16 = False
2532
+ args.bf16 = False
2533
+ os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'
2534
+ if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'
2535
+ # args.mixed_precision is a new argument which needs to be set now
2536
+
2537
+ if getattr(args, 'eval_dataset', None) is not None and getattr(args, 'eval_strategy', 'no') == 'no':
2538
+ args.eval_strategy = 'steps'
2539
+ if getattr(args, 'eval_steps', None) is None: args.eval_steps = 0.1
2540
+ ga_steps = getattr(args, 'gradient_accumulation_steps', None)
2541
+ if ga_steps is not None and ga_steps > 1:
2542
+ from transformers import __version__ as transformers_version
2543
+ if Version(transformers_version) <= Version('4.45.2'):
2544
+ print('**** Unsloth: Please use our fixed gradient_accumulation_steps by updating transformers, TRL and Unsloth!\n'
2545
+ '`pip install --upgrade --no-cache-dir --force-reinstall --no-deps unsloth transformers trl unsloth_zoo`')
2546
+ if getattr(args, 'eval_strategy', 'no') != 'no':
2547
+ eval_bsz = getattr(args, 'per_device_eval_batch_size', 8)
2548
+ if eval_bsz == 8 and args.per_device_train_batch_size < eval_bsz: args.per_device_eval_batch_size = args.per_device_train_batch_size
2549
+ if getattr(args, 'eval_accumulation_steps', None) is None and ga_steps is not None: args.eval_accumulation_steps = ga_steps
2550
+ fp16_full_eval = getattr(args, 'fp16_full_eval', False)
2551
+ if type(fp16_full_eval) is not bool: fp16_full_eval = False
2552
+ bf16_full_eval = getattr(args, 'bf16_full_eval', False)
2553
+ if type(bf16_full_eval) is not bool: bf16_full_eval = False
2554
+ if args.fp16 and bf16_full_eval: args.bf16_full_eval = False; args.fp16_full_eval = True
2555
+ if args.bf16 and fp16_full_eval: args.bf16_full_eval = True; args.fp16_full_eval = False
2556
+ if force_float32:
2557
+ args.bf16_full_eval = False
2558
+ args.fp16_full_eval = False
2559
+ elif os.environ.get('UNSLOTH_MIXED_PRECISION', 'float32') == 'bfloat16':
2560
+ args.bf16_full_eval = True
2561
+ args.fp16_full_eval = False
2562
+ elif not bf16_full_eval and not fp16_full_eval:
2563
+ args.bf16_full_eval = args.bf16
2564
+ args.fp16_full_eval = args.fp16
2565
+ _output_logits = False
2566
+ if locals().get('compute_metrics', None) is not None: _output_logits = True
2567
+ if locals().get('preprocess_logits_for_metrics', None) is not None: _output_logits = True
2568
+ if _output_logits:
2569
+ os.environ['UNSLOTH_RETURN_LOGITS'] = '1'
2570
+ if 'max_seq_length' not in locals() and not hasattr(args, 'max_seq_length'):
2571
+ pass
2572
+ else:
2573
+ model_max_seq_length = getattr(model, 'max_seq_length', None)
2574
+ args_max_seq_length = getattr(args, 'max_seq_length', None)
2575
+ if args_max_seq_length is None and model_max_seq_length is not None:
2576
+ max_seq_length = model.max_seq_length
2577
+ if hasattr(args, 'max_seq_length'): args.max_seq_length = max_seq_length
2578
+ if model is not None and hasattr(model, 'for_training'):
2579
+ model.for_training(use_gradient_checkpointing=getattr(args, 'gradient_checkpointing', True))
2580
+ if 'tokenizer' in locals() and hasattr(tokenizer, 'padding_side'): tokenizer.padding_side = 'right'
2581
+ if 'processing_class' in locals():
2582
+ if hasattr(processing_class, 'padding_side'): processing_class.padding_side = 'right'
2583
+ if hasattr(processing_class, 'tokenizer') and hasattr(processing_class.tokenizer, 'padding_side'): processing_class.tokenizer.padding_side = 'right'
2584
+ __tokenizer = processing_class if 'processing_class' in locals() else tokenizer
2585
+ from unsloth_zoo.vision_utils import UnslothVisionDataCollator
2586
+ if not isinstance(data_collator, UnslothVisionDataCollator):
2587
+ if isinstance(data_collator, DataCollatorForSeq2Seq) and 'labels' not in train_dataset.column_names:
2588
+ data_collator = TransformersDataCollatorForLanguageModeling(
2589
+ __tokenizer,
2590
+ mlm = False,
2591
+ mlm_probability = 0.0,
2592
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
2593
+ )
2594
+ elif isinstance(data_collator, TransformersDataCollatorForLanguageModeling) and 'labels' in train_dataset.column_names:
2595
+ data_collator = DataCollatorForSeq2Seq(
2596
+ __tokenizer,
2597
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
2598
+ )
2599
+ else:
2600
+ if hasattr(args, 'remove_unused_columns'): args.remove_unused_columns = False
2601
+ if hasattr(args, 'dataset_text_field'): args.dataset_text_field = ''
2602
+ if hasattr(args, 'dataset_kwargs'): args.dataset_kwargs = {'skip_prepare_dataset': True}
2603
+ if not isinstance(data_collator, UnslothVisionDataCollator):
2604
+ if not hasattr(__tokenizer, 'pad') and hasattr(__tokenizer, 'tokenizer'):
2605
+ if isinstance(data_collator, DataCollatorForSeq2Seq):
2606
+ data_collator = DataCollatorForSeq2Seq(
2607
+ __tokenizer.tokenizer,
2608
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
2609
+ )
2610
+ else:
2611
+ data_collator = TransformersDataCollatorForLanguageModeling(
2612
+ __tokenizer.tokenizer,
2613
+ mlm = False,
2614
+ mlm_probability = 0.0,
2615
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
2616
+ )
2617
+ other_metrics = []
2618
+
2619
+ from unsloth_zoo.logging_utils import PatchRLStatistics
2620
+ PatchRLStatistics('rloo_trainer', other_metrics)
2621
+
2622
+ # [TODO] Fix up DataParallel multiplying batch sizes
2623
+ # [TODO] DDP works, but DP seems to not work? [TODO]
2624
+ if getattr(args, "parallel_mode", None) == ParallelMode.NOT_DISTRIBUTED and args.n_gpu > 1:
2625
+ if getattr(args, "_n_gpu", 1) != 1:
2626
+ args._n_gpu = 1
2627
+ if "model" in locals() and hasattr(model, "for_training"):
2628
+ model.for_training(use_gradient_checkpointing=getattr(args, 'gradient_checkpointing', True))
2629
+ super().__init__(
2630
+ model = model,
2631
+ reward_funcs = reward_funcs,
2632
+ args = args,
2633
+ train_dataset = train_dataset,
2634
+ eval_dataset = eval_dataset,
2635
+ processing_class = processing_class,
2636
+ reward_processing_classes = reward_processing_classes,
2637
+ callbacks = callbacks,
2638
+ peft_config = peft_config,
2639
+ config = config,
2640
+ reward_model = reward_model,
2641
+ policy = policy,
2642
+ ref_policy = ref_policy,
2643
+ data_collator = data_collator,**kwargs)
2644
+ if "model" in locals() and hasattr(model, "for_inference"):
2645
+ model.for_inference()
2646
+ if hasattr(self, 'neftune_hook_handle'):
2647
+ self.neftune_hook_handle.remove()
2648
+ if hasattr(self, 'neftune_hook_handle'): del self.neftune_hook_handle
2649
+ if getattr(args, 'neftune_noise_alpha', None) is not None:
2650
+ model.get_input_embeddings().neftune_noise_alpha = self.neftune_noise_alpha
2651
+ pass
2652
+ if hasattr(self, 'accelerator'):
2653
+ scaler = self.accelerator.scaler
2654
+ current_model = model
2655
+ while hasattr(current_model, 'model'):
2656
+ current_model.accelerator_scaler = scaler
2657
+ current_model = current_model.model
2658
+ current_model.accelerator_scaler = scaler
2659
+ pass
2660
+ if hasattr(self, 'train'):
2661
+ self.train = MethodType(prepare_for_training_mode(self.__class__.train), self)
2662
+ pass
2663
+
2664
+ pass
2665
+
2666
+
2667
+ if hasattr(logger, "addFilter"):
2668
+ import logging
2669
+ class HideLoggingMessage(logging.Filter):
2670
+ def __init__(self, text): self.text = text
2671
+ def filter(self, x): return not (self.text in x.getMessage())
2672
+ pass
2673
+ logger.addFilter(HideLoggingMessage("`use_cache=True`"))
2674
+