AdithyaSK HF Staff commited on
Commit
6308978
·
verified ·
1 Parent(s): 6424201

Stage Harbor release files 1001-1500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/minillm/minillm_trainer.py +411 -0
  2. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/nash_md/__init__.py +19 -0
  3. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/nash_md/nash_md_config.py +46 -0
  4. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/nash_md/nash_md_trainer.py +509 -0
  5. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/online_dpo/__init__.py +19 -0
  6. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/online_dpo/online_dpo_config.py +390 -0
  7. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/online_dpo/online_dpo_trainer.py +1354 -0
  8. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/openenv/__init__.py +18 -0
  9. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/openenv/utils.py +214 -0
  10. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/openreward/__init__.py +18 -0
  11. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/openreward/_spec.py +359 -0
  12. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/openreward/environment.py +404 -0
  13. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/orpo/__init__.py +19 -0
  14. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/orpo/orpo_config.py +134 -0
  15. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/orpo/orpo_trainer.py +1042 -0
  16. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/papo/__init__.py +17 -0
  17. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/papo/papo_config.py +73 -0
  18. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/papo/papo_trainer.py +354 -0
  19. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ppo/__init__.py +30 -0
  20. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ppo/modeling_value_head.py +1020 -0
  21. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ppo/ppo_config.py +280 -0
  22. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ppo/ppo_trainer.py +1038 -0
  23. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/prm/__init__.py +19 -0
  24. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/prm/prm_config.py +88 -0
  25. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/prm/prm_trainer.py +371 -0
  26. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdft/__init__.py +19 -0
  27. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdft/loss_utils.py +135 -0
  28. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdft/sdft_config.py +472 -0
  29. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdft/sdft_trainer.py +1311 -0
  30. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdft/teacher_sync.py +184 -0
  31. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdpo/__init__.py +19 -0
  32. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdpo/loss_utils.py +135 -0
  33. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdpo/sdpo_config.py +644 -0
  34. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdpo/sdpo_trainer.py +1773 -0
  35. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdpo/teacher_sync.py +184 -0
  36. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ssd/__init__.py +19 -0
  37. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ssd/ssd_config.py +263 -0
  38. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ssd/ssd_trainer.py +532 -0
  39. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/tpo/__init__.py +19 -0
  40. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/tpo/tpo_config.py +174 -0
  41. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/tpo/tpo_trainer.py +790 -0
  42. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/utils.py +858 -0
  43. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/xpo/__init__.py +19 -0
  44. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/xpo/xpo_config.py +44 -0
  45. tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/xpo/xpo_trainer.py +506 -0
  46. tasks/tasksmith-03a6a091b12f/tests/source/trl/extras/__init__.py +13 -0
  47. tasks/tasksmith-03a6a091b12f/tests/source/trl/extras/dataset_formatting.py +32 -0
  48. tasks/tasksmith-03a6a091b12f/tests/source/trl/extras/profiling.py +224 -0
  49. tasks/tasksmith-03a6a091b12f/tests/source/trl/generation/__init__.py +25 -0
  50. tasks/tasksmith-03a6a091b12f/tests/source/trl/generation/vllm_client.py +764 -0
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/minillm/minillm_trainer.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import textwrap
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+ import transformers
21
+ from datasets import Dataset, IterableDataset
22
+ from packaging.version import Version
23
+ from transformers import (
24
+ AutoModelForCausalLM,
25
+ PreTrainedModel,
26
+ PreTrainedTokenizerBase,
27
+ ProcessorMixin,
28
+ TrainerCallback,
29
+ )
30
+ from transformers.utils import is_peft_available
31
+
32
+ from ...models import prepare_deepspeed
33
+ from ...trainer.grpo_trainer import GRPOTrainer, RewardFunc, RolloutFunc
34
+ from ...trainer.utils import disable_dropout_in_model, get_config_model_id
35
+ from ..utils import empty_cache
36
+ from .minillm_config import MiniLLMConfig
37
+
38
+
39
+ if is_peft_available():
40
+ from peft import PeftConfig
41
+
42
+
43
+ def dummy_reward_func(completions: list, **kwargs):
44
+ # placeholder reward function when no reward function is provided
45
+ return [1.0 for _ in completions]
46
+
47
+
48
+ class MiniLLMTrainer(GRPOTrainer):
49
+ """
50
+ Trainer for the Knowledge Distillation of Language Models (MiniLLM) method. This algorithm was initially proposed
51
+ in the paper [Knowledge Distillation of Large Language Models](https://huggingface.co/papers/2306.08543).
52
+
53
+ Example:
54
+
55
+ ```python
56
+ from datasets import load_dataset
57
+ from trl.experimental.minillm import MiniLLMTrainer
58
+
59
+ dataset = load_dataset("trl-lib/tldr", split="train")
60
+
61
+ trainer = MiniLLMTrainer(
62
+ model="Qwen/Qwen3-0.6B",
63
+ teacher_model="Qwen/Qwen3-1.7B",
64
+ train_dataset=dataset,
65
+ )
66
+ trainer.train()
67
+ ```
68
+
69
+ Args:
70
+ model (`str | PreTrainedModel`):
71
+ Model to be trained. Can be either:
72
+
73
+ - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
74
+ path to a *directory* containing model weights saved using
75
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
76
+ using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in
77
+ `args.model_init_kwargs`.
78
+ - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
79
+ teacher_model (`PreTrainedModel | nn.Module | str`):
80
+ Teacher model used for knowledge distillation. Instantiated similarly to `model`.
81
+ reward_funcs (`RewardFunc | list[RewardFunc]`, *optional*):
82
+ Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
83
+ functions with the prompts and completions and sum the rewards. Can be either:
84
+
85
+ - A single reward function, such as:
86
+ - A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a
87
+ path to a *directory* containing model weights saved using
88
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
89
+ using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the
90
+ keyword arguments in `args.model_init_kwargs`.
91
+ - A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported.
92
+ - A custom reward function: The function is provided with the prompts and the generated completions,
93
+ plus any additional columns in the dataset. It should return a list of rewards. Custom reward
94
+ functions can also return `None` when the reward is not applicable to those samples. This is useful
95
+ for multi-task training where different reward functions apply to different types of samples. When a
96
+ reward function returns `None` for a sample, that reward function is excluded from the reward
97
+ calculation for that sample. For more details, see [Using a custom reward
98
+ function](#using-a-custom-reward-function).
99
+
100
+ The trainer's state is also passed to the reward function. The trainer's state is an instance of
101
+ [`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the
102
+ reward function's signature.
103
+ - A list of reward functions, where each item can independently be any of the above types. Mixing different
104
+ types within the list (e.g., a string model ID and a custom reward function) is allowed.
105
+ args ([`experimental.minillm.MiniLLMConfig`], *optional*):
106
+ Configuration for this trainer. If `None`, a default configuration is used.
107
+ train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
108
+ Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is
109
+ ignored. The format of the samples can be either:
110
+
111
+ - [Standard](dataset_formats#standard): Each sample contains plain text.
112
+ - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
113
+ and content).
114
+ eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
115
+ Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
116
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*):
117
+ Processing class used to process the data. The padding side must be set to "left". If `None`, the
118
+ processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A
119
+ padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
120
+ `tokenizer.eos_token` will be used as the default.
121
+ reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*):
122
+ Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
123
+
124
+ - A single processing class: Used when `reward_funcs` contains only one reward function.
125
+ - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
126
+ If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is
127
+ `None`, the tokenizer for the model is automatically loaded using
128
+ [`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward
129
+ functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes`
130
+ are ignored.
131
+ callbacks (list of [`~transformers.TrainerCallback`], *optional*):
132
+ List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
133
+ in [here](https://huggingface.co/docs/transformers/main_classes/callback).
134
+
135
+ If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
136
+ method.
137
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`):
138
+ A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your
139
+ model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`.
140
+ peft_config ([`~peft.PeftConfig`], *optional*):
141
+ PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
142
+ rollout_func (`RolloutFunc`, *optional*):
143
+ Function to use for generating completions. It must take prompts, args, and processing_class as parameters
144
+ and return a dict with `"prompt_ids"`, `"completion_ids"`, and `"logprobs"` fields. Any other fields that
145
+ are forwarded to the reward functions. This feature is experimental and may change or be removed at any
146
+ time without prior notice.
147
+ """
148
+
149
+ _tag_names = ["trl", "minillm"]
150
+ _name = "MiniLLM"
151
+ _paper = {
152
+ "title": "MiniLLM: Knowledge Distillation of Large Language Models",
153
+ "id": "2306.08543",
154
+ # docstyle-ignore
155
+ "citation": textwrap.dedent("""\
156
+ @inproceedings{
157
+ gu2024minillm,
158
+ title={{MiniLLM: Knowledge Distillation of Large Language Models}},
159
+ author={Yuxian Gu and Li Dong and Furu Wei and Minlie Huang},
160
+ booktitle={The Twelfth International Conference on Learning Representations},
161
+ year={2024},
162
+ url={https://openreview.net/forum?id=5h0qf7IBZZ}
163
+ }"""),
164
+ }
165
+
166
+ def __init__(
167
+ self,
168
+ model: str | PreTrainedModel,
169
+ teacher_model: PreTrainedModel | nn.Module | str,
170
+ reward_funcs: RewardFunc | list[RewardFunc] | None = None,
171
+ args: MiniLLMConfig | None = None,
172
+ train_dataset: Dataset | IterableDataset | None = None,
173
+ eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
174
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
175
+ reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
176
+ callbacks: list[TrainerCallback] | None = None,
177
+ optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
178
+ peft_config: "PeftConfig | None" = None,
179
+ rollout_func: RolloutFunc | None = None,
180
+ ):
181
+ if reward_funcs is None:
182
+ reward_funcs = [dummy_reward_func]
183
+
184
+ # Args
185
+ if args is None:
186
+ model_name = model if isinstance(model, str) else get_config_model_id(model.config)
187
+ model_name = model_name.split("/")[-1]
188
+ args = MiniLLMConfig(f"{model_name}-MiniLLM")
189
+
190
+ # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
191
+ # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
192
+ # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
193
+ # default to the recommended non-reentrant behavior here, while preserving any user-provided value.
194
+ if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
195
+ args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
196
+ args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
197
+
198
+ super().__init__(
199
+ model,
200
+ reward_funcs,
201
+ args=args,
202
+ train_dataset=train_dataset,
203
+ eval_dataset=eval_dataset,
204
+ processing_class=processing_class,
205
+ reward_processing_classes=reward_processing_classes,
206
+ callbacks=callbacks,
207
+ optimizers=optimizers,
208
+ peft_config=peft_config,
209
+ rollout_func=rollout_func,
210
+ )
211
+
212
+ if args.teacher_model_init_kwargs is None:
213
+ teacher_model_init_kwargs = {}
214
+ elif not isinstance(teacher_model, str):
215
+ raise ValueError(
216
+ "You passed teacher_model_init_kwargs to the MiniLLMConfig, but your teacher_model is already instantiated."
217
+ )
218
+ else:
219
+ teacher_model_init_kwargs = args.teacher_model_init_kwargs
220
+ teacher_model_init_kwargs["dtype"] = (
221
+ teacher_model_init_kwargs["dtype"]
222
+ if teacher_model_init_kwargs["dtype"] in ["auto", None]
223
+ else getattr(torch, teacher_model_init_kwargs["dtype"])
224
+ )
225
+
226
+ if isinstance(teacher_model, str):
227
+ teacher_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
228
+ teacher_model = AutoModelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs)
229
+
230
+ # Disable dropout in the model
231
+ if args.disable_dropout:
232
+ disable_dropout_in_model(self.model)
233
+
234
+ if self.is_deepspeed_enabled:
235
+ self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator)
236
+ else:
237
+ self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True)
238
+
239
+ self.temperature = args.temperature
240
+ self.kd_temperature = args.kd_temperature
241
+ self.single_step_decomposition = args.single_step_decomposition
242
+ self.rkl_advantage = args.rkl_advantage
243
+ self.gamma = args.gamma
244
+ self.length_normalization = args.length_normalization
245
+
246
+ def _single_step_decomposition_loss(
247
+ self,
248
+ student_log_probs: torch.Tensor,
249
+ teacher_log_probs: torch.Tensor,
250
+ mask: torch.Tensor | None = None,
251
+ reduction: str = "batchmean",
252
+ ):
253
+ """
254
+ Compute the MiniLLM loss for knowledge distillation using F.kl_div. See Eq. (1) of
255
+ https://huggingface.co/papers/2306.08543 for the definition.
256
+
257
+ Args:
258
+ student_log_probs:
259
+ Per-token log-probabilities from the student, of shape (batch_size, sequence_length)
260
+ teacher_log_probs:
261
+ Per-token log-probabilities from the teacher, of shape (batch_size, sequence_length)
262
+ mask:
263
+ Optional boolean tensor of shape (batch_size, sequence_length) selecting the tokens to include in the
264
+ loss (e.g. excluding padding)
265
+ reduction:
266
+ Specifies the reduction to apply to the output: 'batchmean' (default), 'sum' or 'mean'; any other value
267
+ returns the unreduced per-token loss
268
+
269
+ Returns:
270
+ loss: Scalar tensor with the single-step KL regularization loss (unreduced if `reduction` is not one of the
271
+ above)
272
+ """
273
+ reg_loss = F.kl_div(
274
+ teacher_log_probs, student_log_probs, reduction="none", log_target=True
275
+ ) # (batch_size, sequence_length)
276
+
277
+ # Masking
278
+ if mask is not None:
279
+ reg_loss = reg_loss[mask]
280
+
281
+ # Apply reduction
282
+ if reduction == "batchmean":
283
+ return reg_loss.sum() / mask.sum() if mask is not None else reg_loss.sum() / reg_loss.size(0)
284
+ elif reduction == "sum":
285
+ return reg_loss.sum()
286
+ elif reduction == "mean":
287
+ return reg_loss.mean()
288
+ else:
289
+ return reg_loss
290
+
291
+ def _compute_advantage(
292
+ self,
293
+ student_log_probs_on_labels: torch.Tensor,
294
+ teacher_log_probs_on_labels: torch.Tensor,
295
+ mask: torch.Tensor | None = None,
296
+ ) -> torch.Tensor:
297
+ r"""Compute the advantage for Reverse KL Divergence.
298
+
299
+ Mostly following [this
300
+ implementation](https://github.com/microsoft/LMOps/blob/e210d2c026b9958617887762400778ace81172e6/minillm/minillm/losses.py#L37-L49).
301
+
302
+ $$ \text{rewards}_t = \text{teacher\_log\_probs\_on\_labels}_t - \text{student\_log\_probs\_on\_labels}_t $$
303
+
304
+ If length normalization is enabled:
305
+
306
+ $$ \text{lengths}_t = \sum_{i=t}^{T} \gamma^{i-t} $$
307
+
308
+ $$ \text{advantages}_t = \frac{\sum_{i=t}^{T} \gamma^{i-t} R_i}{\text{lengths}_t} $$
309
+
310
+ Otherwise:
311
+
312
+ $$ \text{advantages}_t = \sum_{i=t}^{T} \gamma^{i-t} R_i $$
313
+
314
+ Args:
315
+ student_log_probs_on_labels: Log probabilities of the student model on the labels.
316
+ Shape: (batch_size, sequence_length)
317
+ teacher_log_probs_on_labels: Log probabilities of the teacher model on the labels.
318
+ Shape: (batch_size, sequence_length)
319
+ mask: Optional mask to apply to the log probabilities. Shape: (batch_size, sequence_length)
320
+ Returns:
321
+ advantage: Computed advantage. Shape: (batch_size, sequence_length)
322
+ """
323
+ response_length = student_log_probs_on_labels.size(1)
324
+ if mask is None:
325
+ mask = torch.ones_like(student_log_probs_on_labels)
326
+ mask = mask.float()
327
+ student_log_probs_on_labels = student_log_probs_on_labels * mask
328
+ teacher_log_probs_on_labels = teacher_log_probs_on_labels * mask
329
+
330
+ rewards = teacher_log_probs_on_labels - student_log_probs_on_labels # (batch_size, sequence_length)
331
+
332
+ if self.gamma > 0.0:
333
+ gamma_pow = torch.pow(self.gamma, torch.arange(response_length, device=rewards.device))
334
+
335
+ advantages = rewards * gamma_pow
336
+ advantages = advantages.flip(1).cumsum(dim=1).flip(1)
337
+
338
+ if self.length_normalization:
339
+ mask = torch.where(mask < 0.5, 1e-4, mask)
340
+ lengths = mask * gamma_pow
341
+ lengths = lengths.flip(1).cumsum(dim=1).flip(1)
342
+ advantages = advantages / lengths
343
+ else:
344
+ advantages = rewards
345
+
346
+ return advantages
347
+
348
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
349
+ input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1)
350
+ attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1)
351
+ labels = input_ids.clone()
352
+ labels[attention_mask == 0] = -100
353
+
354
+ # Compute student output
355
+ student_outputs = model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False)
356
+
357
+ # Compute teacher output in eval mode
358
+ self.teacher_model.eval()
359
+ with torch.no_grad():
360
+ teacher_outputs = self.teacher_model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False)
361
+
362
+ # Slice the logits for the generated tokens using the inputs["prompts"] lengths
363
+ prompt_lengths = inputs["prompt_ids"].shape[1]
364
+ student_logits = student_outputs.logits[:, prompt_lengths - 1 : -1, :]
365
+ teacher_logits = teacher_outputs.logits[:, prompt_lengths - 1 : -1, :]
366
+ shifted_labels = input_ids[:, prompt_lengths:]
367
+
368
+ # Apply temperature scaling
369
+ student_logits = student_logits / self.kd_temperature
370
+ teacher_logits = teacher_logits / self.kd_temperature
371
+
372
+ # Compute log probabilities for student and probabilities for teacher
373
+ student_log_probs = F.log_softmax(student_logits, dim=-1)
374
+ teacher_log_probs = F.log_softmax(teacher_logits, dim=-1)
375
+
376
+ student_log_probs_on_labels = torch.gather(
377
+ student_log_probs, dim=-1, index=shifted_labels.unsqueeze(-1)
378
+ ).squeeze(-1)
379
+ teacher_log_probs_on_labels = torch.gather(
380
+ teacher_log_probs, dim=-1, index=shifted_labels.unsqueeze(-1)
381
+ ).squeeze(-1)
382
+
383
+ mask = shifted_labels != -100
384
+
385
+ if self.rkl_advantage:
386
+ reverse_kl_advantage = self._compute_advantage(
387
+ student_log_probs_on_labels=student_log_probs_on_labels,
388
+ teacher_log_probs_on_labels=teacher_log_probs_on_labels,
389
+ mask=mask,
390
+ )
391
+
392
+ inputs["advantages"] = inputs["advantages"].unsqueeze(1) + reverse_kl_advantage
393
+
394
+ # Compute GRPO loss on verifiable reward
395
+ loss = self._compute_loss(model, inputs)
396
+
397
+ # Compute loss
398
+ if self.single_step_decomposition:
399
+ single_step_decomposition_loss = self._single_step_decomposition_loss(
400
+ student_log_probs=student_log_probs,
401
+ teacher_log_probs=teacher_log_probs,
402
+ mask=mask,
403
+ )
404
+
405
+ loss += single_step_decomposition_loss
406
+
407
+ # Empty cache
408
+ empty_cache()
409
+
410
+ # Return loss
411
+ return (loss, student_outputs) if return_outputs else loss
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/nash_md/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .nash_md_config import NashMDConfig
16
+ from .nash_md_trainer import NashMDTrainer
17
+
18
+
19
+ __all__ = ["NashMDConfig", "NashMDTrainer"]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/nash_md/nash_md_config.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+ from ..online_dpo import OnlineDPOConfig
18
+
19
+
20
+ @dataclass
21
+ class NashMDConfig(OnlineDPOConfig):
22
+ r"""
23
+ Configuration class for the [`experimental.nash_md.NashMDTrainer`].
24
+
25
+ Subclass of [`experimental.online_dpo.OnlineDPOConfig`] we can use all its arguments and add the following:
26
+
27
+ Parameters:
28
+ mixture_coef (`float` or `list[float]`, *optional*, defaults to `0.5`):
29
+ Logit mixture coefficient for the model and reference model. If a list of floats is provided then the
30
+ mixture coefficient is selected for each new epoch and the last coefficient is used for the rest of the
31
+ epochs.
32
+ """
33
+
34
+ mixture_coef: list[float] = field(
35
+ default_factory=lambda: [0.5],
36
+ metadata={
37
+ "help": "Logit mixture coefficient for the model and reference model. If a list of floats is provided "
38
+ "then the mixture coefficient is selected for each new epoch and the last coefficient is used for the "
39
+ "rest of the epochs."
40
+ },
41
+ )
42
+
43
+ def __post_init__(self):
44
+ super().__post_init__()
45
+ if hasattr(self.mixture_coef, "__len__") and len(self.mixture_coef) == 1:
46
+ self.mixture_coef = self.mixture_coef[0]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/nash_md/nash_md_trainer.py ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import textwrap
16
+ from collections.abc import Callable
17
+ from typing import Any
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+ from datasets import Dataset, IterableDataset
23
+ from transformers import (
24
+ BaseImageProcessor,
25
+ FeatureExtractionMixin,
26
+ GenerationMixin,
27
+ PreTrainedModel,
28
+ PreTrainedTokenizerBase,
29
+ ProcessorMixin,
30
+ TrainerCallback,
31
+ )
32
+ from transformers.trainer_utils import EvalPrediction
33
+ from transformers.training_args import OptimizerNames
34
+ from transformers.utils import is_peft_available
35
+
36
+ from ...data_utils import maybe_apply_chat_template
37
+ from ...models.utils import unwrap_model_for_generation
38
+ from ...trainer.utils import selective_log_softmax
39
+ from ..online_dpo import OnlineDPOTrainer
40
+ from ..utils import empty_cache, get_reward, truncate_right
41
+ from .nash_md_config import NashMDConfig
42
+
43
+
44
+ if is_peft_available():
45
+ from peft import PeftConfig, PeftModel
46
+
47
+
48
+ class GeometricMixtureWrapper(GenerationMixin):
49
+ """
50
+ Geometric Mixture generation wrapper that samples from the logits of two model's geometric mixture.
51
+
52
+ Args:
53
+ model ([`~transformers.PreTrainedModel`]): The model to be wrapped.
54
+ ref_model ([`~transformers.PreTrainedModel`]): The reference model.
55
+ generation_config ([`~transformers.GenerationConfig`]): The generation config.
56
+ mixture_coef (`float`, *optional* - default: 0.5): The mixture coefficient.
57
+ """
58
+
59
+ main_input_name = "input_ids"
60
+ _supports_cache_class = False
61
+ _supports_static_cache = False
62
+ _is_stateful = False
63
+
64
+ def __init__(self, model, ref_model, generation_config, mixture_coef=0.5, device=None):
65
+ super().__init__()
66
+
67
+ self.model = model
68
+ self.config = model.config
69
+ self.ref_model = ref_model
70
+ self.generation_config = generation_config
71
+ self.mixture_coef = mixture_coef
72
+ self.device = device
73
+ if hasattr(self.model, "_is_stateful"):
74
+ self._is_stateful = self.model._is_stateful
75
+
76
+ def __call__(self, *args, **kwargs):
77
+ return self.forward(*args, **kwargs)
78
+
79
+ @torch.inference_mode()
80
+ def forward(self, *args, **kwargs):
81
+ model_outputs = self.model(*args, **kwargs)
82
+ model_logits = model_outputs.logits
83
+ ref_model_logits = self.ref_model(*args, **kwargs).logits
84
+
85
+ model_outputs.logits = torch.nn.functional.log_softmax(
86
+ self.mixture_coef * ref_model_logits + (1 - self.mixture_coef) * model_logits, dim=-1
87
+ )
88
+
89
+ return model_outputs
90
+
91
+ def prepare_inputs_for_generation(self, *args, **kwargs):
92
+ # turn off cache in the generation config
93
+ kwargs["use_cache"] = False
94
+ model_inputs = self.model.prepare_inputs_for_generation(*args, **kwargs)
95
+ _ = self.ref_model.prepare_inputs_for_generation(*args, **kwargs)
96
+
97
+ return model_inputs
98
+
99
+ def _validate_model_class(self):
100
+ self.model._validate_model_class()
101
+
102
+ def _validate_model_kwargs(self, model_kwargs):
103
+ return self.model._validate_model_kwargs(model_kwargs)
104
+
105
+
106
+ class NashMDTrainer(OnlineDPOTrainer):
107
+ """
108
+ Trainer for the Nash-MD method.
109
+
110
+ It is implemented as a subclass of [`experimental.online_dpo.OnlineDPOTrainer`].
111
+
112
+ Args:
113
+ model ([`~transformers.PreTrainedModel`]):
114
+ The model to train, preferably an `AutoModelForCausalLM`.
115
+ ref_model ([`~transformers.PreTrainedModel`]):
116
+ Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation
117
+ and loss. If no reference model is provided, the trainer will create a reference model with the same
118
+ architecture as the model to be optimized.
119
+ reward_funcs ([`~transformers.PreTrainedModel`]):
120
+ The reward model to score completions with, preferably an
121
+ [`~transformers.AutoModelForSequenceClassification`].
122
+ args ([`experimental.nash_md.NashMDConfig`]):
123
+ The NashMD config arguments to use for training.
124
+ data_collator ([`~transformers.DataCollator`]):
125
+ The data collator to use for training. If None is specified, the default data collator
126
+ ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the
127
+ maximum length of the sequences in the batch, given a dataset of paired sequences.
128
+ train_dataset ([`~datasets.Dataset`]):
129
+ The dataset to use for training.
130
+ eval_dataset ([`~datasets.Dataset`]):
131
+ The dataset to use for evaluation.
132
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
133
+ Processing class used to process the data. If provided, will be used to automatically process the inputs
134
+ for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
135
+ reuse the fine-tuned model.
136
+ peft_config ([`~peft.PeftConfig`], *optional*):
137
+ The peft config to use for training.
138
+ compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
139
+ The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
140
+ metric values.
141
+ callbacks (`list[transformers.TrainerCallback]`):
142
+ The callbacks to use for training.
143
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
144
+ The optimizer and scheduler to use for training.
145
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
146
+ The function to use to preprocess the logits before computing the metrics.
147
+ """
148
+
149
+ _tag_names = ["trl", "nash-md"]
150
+ _name = "Nash-MD"
151
+ _paper = {
152
+ "title": "Nash Learning from Human Feedback",
153
+ "id": "2312.00886",
154
+ # docstyle-ignore
155
+ "citation": textwrap.dedent("""\
156
+ @inproceedings{munos2024nash,
157
+ title = {{Nash Learning from Human Feedback}},
158
+ author = {R{\'{e}}mi Munos and Michal Valko and Daniele Calandriello and Mohammad Gheshlaghi Azar and Mark Rowland and Zhaohan Daniel Guo and Yunhao Tang and Matthieu Geist and Thomas Mesnard and C{\\^{o}}me Fiegel and Andrea Michi and Marco Selvi and Sertan Girgin and Nikola Momchev and Olivier Bachem and Daniel J. Mankowitz and Doina Precup and Bilal Piot},
159
+ year = 2024,
160
+ booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024},
161
+ publisher = {OpenReview.net},
162
+ url = {https://openreview.net/forum?id=Y5AmNYiyCQ}
163
+ }"""),
164
+ }
165
+
166
+ def __init__(
167
+ self,
168
+ model: PreTrainedModel | nn.Module = None,
169
+ ref_model: PreTrainedModel | nn.Module = None,
170
+ reward_funcs: PreTrainedModel | nn.Module | None = None,
171
+ args: NashMDConfig | None = None,
172
+ data_collator: Callable | None = None,
173
+ train_dataset: Dataset | IterableDataset | None = None,
174
+ eval_dataset: Dataset | dict[str, Dataset] | None = None,
175
+ processing_class: PreTrainedTokenizerBase
176
+ | BaseImageProcessor
177
+ | FeatureExtractionMixin
178
+ | ProcessorMixin
179
+ | None = None,
180
+ peft_config: "PeftConfig | None" = None,
181
+ compute_metrics: Callable[[EvalPrediction], dict] | None = None,
182
+ callbacks: list[TrainerCallback] | None = None,
183
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
184
+ preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
185
+ ) -> None:
186
+ super().__init__(
187
+ model=model,
188
+ ref_model=ref_model,
189
+ reward_funcs=reward_funcs,
190
+ args=args,
191
+ data_collator=data_collator,
192
+ train_dataset=train_dataset,
193
+ eval_dataset=eval_dataset,
194
+ processing_class=processing_class,
195
+ reward_processing_classes=processing_class,
196
+ peft_config=peft_config,
197
+ compute_metrics=compute_metrics,
198
+ callbacks=callbacks,
199
+ optimizers=optimizers,
200
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
201
+ )
202
+
203
+ self._mixture_coef = self.args.mixture_coef
204
+
205
+ # Overwrite the stats dictionary to include NashMD specific statistics
206
+ self.stats = {
207
+ # Remove "non_score_reward", "rlhf_reward", "scores_margin"
208
+ # Add "mixture_coef"
209
+ "loss/kl": [],
210
+ "objective/entropy": [],
211
+ "loss/score": [],
212
+ "rewards/probabilities": [],
213
+ "rewards/accuracies": [],
214
+ "rewards/margins": [],
215
+ "logps/chosen": [],
216
+ "logps/rejected": [],
217
+ "val/model_contain_eos_token": [],
218
+ "val/ref_contain_eos_token": [],
219
+ "rewards/chosen": [],
220
+ "rewards/rejected": [],
221
+ "beta": [],
222
+ "mixture_coef": [],
223
+ }
224
+ if len(self.reward_funcs) != 1:
225
+ raise ValueError("NashMDTrainer only supports one reward function/model.")
226
+ self.reward_funcs = self.reward_funcs[0]
227
+
228
+ @property
229
+ def mixture_coef(self):
230
+ if isinstance(self._mixture_coef, list):
231
+ epoch = self.state.epoch
232
+ return self._mixture_coef[epoch] if epoch < len(self._mixture_coef) else self._mixture_coef[-1]
233
+ else:
234
+ return self._mixture_coef
235
+
236
+ def _generate_completions(self, model, prompts):
237
+ # Generate completions from the policy model.
238
+ with (
239
+ unwrap_model_for_generation(
240
+ model,
241
+ self.accelerator,
242
+ generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
243
+ ) as unwrapped_policy_for_gen_ctx
244
+ ):
245
+ model_output = unwrapped_policy_for_gen_ctx.generate(
246
+ input_ids=prompts["input_ids"],
247
+ attention_mask=prompts["attention_mask"],
248
+ generation_config=self.generation_config,
249
+ )
250
+
251
+ # Get the DDP/FSDP unwrapped version of the main model.
252
+ # This will be the policy model for GeometricMixtureWrapper (PEFT adapters active if PEFT is used).
253
+ policy_model_for_gmw = self.accelerator.unwrap_model(model)
254
+
255
+ # Determine the correct reference model for GeometricMixtureWrapper.
256
+ # This also needs to be DDP/FSDP unwrapped.
257
+ ref_model_for_gmw: torch.nn.Module
258
+ if self.ref_model is None:
259
+ # No explicit ref_model is provided.
260
+ # Use the base of the main `model` if it's a PEFT model.
261
+ # policy_model_for_gmw is already DDP-unwrapped.
262
+ if is_peft_available() and isinstance(policy_model_for_gmw, PeftModel):
263
+ ref_model_for_gmw = policy_model_for_gmw.get_base_model()
264
+ else:
265
+ # Not a PEFT model (or PEFT not available), or already a base model.
266
+ # Use the DDP-unwrapped policy model itself as the reference.
267
+ ref_model_for_gmw = policy_model_for_gmw
268
+ else:
269
+ # An explicit ref_model is provided. Unwrap it for DDP/FSDP.
270
+ ref_model_for_gmw = self.accelerator.unwrap_model(self.ref_model)
271
+
272
+ # Both models given to GeometricMixtureWrapper (policy_model_for_gmw and ref_model_for_gmw) are DDP-unwrapped.
273
+ with torch.no_grad(): # Ensure no_grad context for mixture model generation
274
+ mixture_model = GeometricMixtureWrapper(
275
+ model=policy_model_for_gmw,
276
+ ref_model=ref_model_for_gmw,
277
+ generation_config=self.generation_config,
278
+ mixture_coef=self.mixture_coef,
279
+ device=self.accelerator.device,
280
+ )
281
+
282
+ # TODO: use self._override_model_generation_config for both models?
283
+ mixture_output = mixture_model.generate(
284
+ input_ids=prompts["input_ids"],
285
+ attention_mask=prompts["attention_mask"],
286
+ generation_config=self.generation_config,
287
+ )
288
+
289
+ return model_output, mixture_output
290
+
291
+ def _process_completions(self, model_output, mixture_output, prompts):
292
+ context_length = prompts["input_ids"].shape[1]
293
+
294
+ # Process model completions
295
+ model_completion_ids = model_output[:, context_length:]
296
+ model_completion_ids, model_completion_mask = truncate_right(
297
+ model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id
298
+ )
299
+ model_data = {
300
+ "input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1),
301
+ "attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1),
302
+ "raw": prompts["raw"],
303
+ }
304
+
305
+ # Process reference model completions
306
+ mixture_completion_ids = mixture_output[:, context_length:]
307
+ mixture_completion_ids, mixture_completion_mask = truncate_right(
308
+ mixture_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id
309
+ )
310
+ mixture_data = {
311
+ "input_ids": torch.cat((prompts["input_ids"], mixture_completion_ids), dim=1),
312
+ "attention_mask": torch.cat((prompts["attention_mask"], mixture_completion_mask), dim=1),
313
+ "raw": prompts["raw"],
314
+ }
315
+
316
+ return model_data, mixture_data
317
+
318
+ def _compute_rewards(self, model_data, mixture_data, context_length):
319
+ with torch.no_grad():
320
+ _, model_scores, _ = get_reward(
321
+ self.reward_funcs, model_data["input_ids"], self.processing_class.pad_token_id, context_length
322
+ )
323
+ _, mixture_scores, _ = get_reward(
324
+ self.reward_funcs, mixture_data["input_ids"], self.processing_class.pad_token_id, context_length
325
+ )
326
+
327
+ # Apply EOS penalty if needed
328
+ if self.args.missing_eos_penalty is not None:
329
+ model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1)
330
+ mixture_contain_eos = torch.any(mixture_data["input_ids"] == self.processing_class.eos_token_id, dim=-1)
331
+ model_scores[~model_contain_eos] -= self.args.missing_eos_penalty
332
+ mixture_scores[~mixture_contain_eos] -= self.args.missing_eos_penalty
333
+
334
+ return model_scores, mixture_scores
335
+
336
+ def _compute_logprobs(self, model, model_data, context_length):
337
+ def compute_logprobs_for_data(m, data):
338
+ output = m(data["input_ids"], attention_mask=data["attention_mask"])
339
+ logits = output.logits[:, context_length - 1 : -1]
340
+ token_logprobs = selective_log_softmax(logits, data["input_ids"][:, context_length:])
341
+ return token_logprobs
342
+
343
+ # Compute logprobs for model completions under the model
344
+ model_logprobs_model_data = compute_logprobs_for_data(model, model_data)
345
+
346
+ # Compute logprobs of model completions under the reference model
347
+ with torch.no_grad():
348
+ if self.ref_model is None:
349
+ with model.disable_adapter():
350
+ ref_logprobs_model_data = compute_logprobs_for_data(model, model_data)
351
+ else:
352
+ ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data)
353
+
354
+ # Mask padding tokens
355
+ model_padding_mask = model_data["attention_mask"][:, context_length:] == 0
356
+ model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0)
357
+ ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0)
358
+
359
+ return (model_logprobs_model_data, ref_logprobs_model_data)
360
+
361
+ def _compute_losses(
362
+ self,
363
+ model_logprobs_model_data,
364
+ ref_logprobs_model_data,
365
+ probability,
366
+ ):
367
+ # reinforce score where 0.5 is a control variate
368
+ score = (probability - 0.5) * model_logprobs_model_data.sum(1)
369
+
370
+ # kl divergence via reinforce
371
+ with torch.no_grad():
372
+ log_ratio = model_logprobs_model_data - ref_logprobs_model_data
373
+ kl_div_log = log_ratio.sum(1)
374
+ kl_div_loss = (log_ratio * model_logprobs_model_data).sum(1)
375
+
376
+ # final loss
377
+ loss = self.beta * kl_div_loss - score
378
+
379
+ return loss.mean(), score, kl_div_log
380
+
381
+ def _log_statistics(
382
+ self,
383
+ model_data,
384
+ mixture_data,
385
+ model_logprobs_model_data,
386
+ ref_logprobs_model_data,
387
+ probability,
388
+ score,
389
+ kl_div,
390
+ context_length,
391
+ model_scores,
392
+ mixture_scores,
393
+ ):
394
+ # Helper function to gather and compute mean
395
+ def gather_mean(tensor):
396
+ return self.accelerator.gather_for_metrics(tensor).mean().item()
397
+
398
+ # Log score
399
+ self.stats["loss/score"].append(gather_mean(score))
400
+ # Log KL divergence
401
+ self.stats["loss/kl"].append(gather_mean(kl_div))
402
+
403
+ # Log logprobs
404
+ model_logprobs_model_data_sum = model_logprobs_model_data.sum(1)
405
+ ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1)
406
+
407
+ self.stats["logps/chosen"].append(gather_mean(model_logprobs_model_data_sum))
408
+ self.stats["logps/rejected"].append(gather_mean(ref_logprobs_model_data_sum))
409
+
410
+ # Log rewards
411
+ self.stats["rewards/chosen"].append(gather_mean(model_scores))
412
+ self.stats["rewards/rejected"].append(gather_mean(mixture_scores))
413
+
414
+ # Log probabilities
415
+ self.stats["rewards/probabilities"].append(gather_mean(probability))
416
+
417
+ # Calculate entropy for model data
418
+ entropy_model_data = -model_logprobs_model_data.sum(1)
419
+ self.stats["objective/entropy"].append(gather_mean(entropy_model_data))
420
+
421
+ # Calculate margins
422
+ margin = model_logprobs_model_data_sum - ref_logprobs_model_data_sum
423
+ self.stats["rewards/margins"].append(gather_mean(margin))
424
+
425
+ # Calculate accuracy
426
+ accuracy = (margin > 0).float()
427
+ self.stats["rewards/accuracies"].append(gather_mean(accuracy))
428
+
429
+ # Log EOS token statistics
430
+ model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1)
431
+ mixture_eos = (mixture_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1)
432
+ self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float()))
433
+ self.stats["val/ref_contain_eos_token"].append(gather_mean(mixture_eos.float()))
434
+
435
+ # Log beta and mixture coef
436
+ self.stats["beta"].append(self.beta)
437
+ self.stats["mixture_coef"].append(self.mixture_coef)
438
+
439
+ def training_step(
440
+ self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None
441
+ ) -> torch.Tensor:
442
+ model.train()
443
+
444
+ # Apply chat template and tokenize the input
445
+ batch_size = len(next(iter(inputs.values())))
446
+ prompts = inputs["prompt"]
447
+ inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)]
448
+ inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs]
449
+ inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs]
450
+ inputs = self.data_collator(inputs)
451
+
452
+ # need the prompt_ only
453
+ inputs = self._prepare_inputs(inputs)
454
+ context_length = inputs["prompt_input_ids"].shape[1]
455
+ prompts = {
456
+ "input_ids": inputs["prompt_input_ids"],
457
+ "attention_mask": inputs["prompt_attention_mask"],
458
+ "raw": prompts,
459
+ }
460
+ del inputs
461
+
462
+ # Sample completions from both the model and the reference model
463
+ model_output, mixture_output = self._generate_completions(model, prompts)
464
+
465
+ # Process model completions
466
+ model_data, mixture_data = self._process_completions(model_output, mixture_output, prompts)
467
+
468
+ # Compute rewards
469
+ model_scores, mixture_scores = self._compute_rewards(model_data, mixture_data, context_length)
470
+ # probability of the model data vs the mixture data
471
+ probability = F.sigmoid(model_scores - mixture_scores)
472
+
473
+ # Compute logprobs
474
+ model_logprobs_model_data, ref_logprobs_model_data = self._compute_logprobs(model, model_data, context_length)
475
+
476
+ # Compute loss
477
+ loss, score, kl_div = self._compute_losses(model_logprobs_model_data, ref_logprobs_model_data, probability)
478
+
479
+ # Log everything
480
+ self._log_statistics(
481
+ model_data,
482
+ mixture_data,
483
+ model_logprobs_model_data.detach(),
484
+ ref_logprobs_model_data,
485
+ probability,
486
+ score.detach(),
487
+ kl_div.detach(),
488
+ context_length,
489
+ model_scores,
490
+ mixture_scores,
491
+ )
492
+
493
+ if (
494
+ self.args.torch_empty_cache_steps is not None
495
+ and self.state.global_step % self.args.torch_empty_cache_steps == 0
496
+ ):
497
+ empty_cache()
498
+
499
+ kwargs = {}
500
+ # For LOMO optimizers you need to explicitly use the learning rate
501
+ if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]:
502
+ kwargs["learning_rate"] = self._get_learning_rate()
503
+
504
+ if self.args.n_gpu > 1:
505
+ loss = loss.mean() # mean() to average on multi-gpu parallel training
506
+
507
+ self.accelerator.backward(loss, **kwargs)
508
+
509
+ return loss.detach() / self.args.gradient_accumulation_steps
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/online_dpo/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .online_dpo_config import OnlineDPOConfig
16
+ from .online_dpo_trainer import OnlineDPOTrainer
17
+
18
+
19
+ __all__ = ["OnlineDPOConfig", "OnlineDPOTrainer"]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/online_dpo/online_dpo_config.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import warnings
16
+ from dataclasses import dataclass, field
17
+ from typing import Any
18
+
19
+ from ...trainer.base_config import _BaseConfig
20
+
21
+
22
+ @dataclass
23
+ class OnlineDPOConfig(_BaseConfig):
24
+ # docstyle-ignore
25
+ r"""
26
+ Configuration class for the [`experimental.online_dpo.OnlineDPOTrainer`].
27
+
28
+ This class includes only the parameters that are specific to Online DPO training. For a full list of training
29
+ arguments, please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this
30
+ class may differ from those in [`~transformers.TrainingArguments`].
31
+
32
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
33
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
34
+ command line.
35
+
36
+ Parameters:
37
+ reward_model_path (`str`, *optional*):
38
+ Path to the reward model.
39
+ max_new_tokens (`int`, *optional*, defaults to `64`):
40
+ Maximum number of tokens to generate per completion.
41
+ max_length (`int`, *optional*, defaults to `512`):
42
+ Maximum total length of the sequence (prompt + completion) used to compute log probabilities. If the
43
+ sequence exceeds this limit, the leftmost tokens will be truncated to preserve as much of the completion as
44
+ possible.
45
+ temperature (`float`, *optional*, defaults to `0.9`):
46
+ Temperature for sampling. The higher the temperature, the more random the completions.
47
+ missing_eos_penalty (`float`, *optional*):
48
+ Penalty applied to the score when the model fails to generate an EOS token. This is useful to encourage to
49
+ generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be a positive
50
+ value.
51
+ beta (`float` or `list[float]`, *optional*, defaults to `0.1`):
52
+ Parameter controlling the deviation from the reference model. Higher β means less deviation from the
53
+ reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in
54
+ the [paper](https://huggingface.co/papers/2310.12036). If a list of floats is provided then the β is
55
+ selected for each new epoch and the last β is used for the rest of the epochs.
56
+ loss_type (`str`, *optional*, defaults to `"sigmoid"`):
57
+ Type of loss to use. Possible values are:
58
+
59
+ - `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper.
60
+ - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper.
61
+ disable_dropout (`bool`, *optional*, defaults to `True`):
62
+ Whether to disable dropout in the model and reference model.
63
+
64
+ > Parameters that control generation
65
+
66
+ top_p (`float`, *optional*, defaults to `1.0`):
67
+ Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to
68
+ `1.0` to consider all tokens.
69
+ top_k (`int`, *optional*, defaults to `0`):
70
+ Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is
71
+ disabled and all tokens are considered.
72
+ min_p (`float`, *optional*):
73
+ Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
74
+ value between `0.0` and `1.0`. Typical values are in the `0.01-0.2` range.
75
+ repetition_penalty (`float`, *optional*, defaults to `1.0`):
76
+ Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far.
77
+ Values > `1.0` encourage the model to use new tokens, while values < `1.0` encourage the model to repeat
78
+ tokens.
79
+ cache_implementation (`str`, *optional*):
80
+ Implementation of the cache method for faster generation when `use_vllm` is set to `False`.
81
+ generation_kwargs (`dict[str, Any]`, *optional*):
82
+ Additional keyword arguments to pass to [`~transformers.GenerationConfig`] (if using transformers) or
83
+ `SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the
84
+ generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict
85
+ with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them.
86
+
87
+ > Parameters that control generation acceleration powered by vLLM
88
+
89
+ use_vllm (`bool`, *optional*, defaults to `False`):
90
+ Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation
91
+ instead of the default model.generate(). Requires `vllm` to be installed.
92
+ vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
93
+ Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use
94
+ the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model
95
+ implementation.
96
+ vllm_mode (`str`, *optional*, defaults to `"colocate"`):
97
+ Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `"server"` or
98
+ `"colocate"`.
99
+
100
+ - `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM
101
+ server is running (start with `trl vllm-serve`).
102
+ - `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a
103
+ separate server but may cause resource contention with training.
104
+ vllm_structured_outputs_regex (`str`, *optional*):
105
+ Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled.
106
+
107
+ > Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`)
108
+
109
+ vllm_server_base_url (`str`, *optional*):
110
+ Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `vllm_server_host` and
111
+ `vllm_server_port` are ignored.
112
+ vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
113
+ Host of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
114
+ vllm_server_port (`int`, *optional*, defaults to `8000`):
115
+ Port of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
116
+ vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
117
+ Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the
118
+ timeout, a `ConnectionError` is raised.
119
+ vllm_group_port (`int`, *optional*, defaults to `51216`):
120
+ Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port
121
+ is occupied, there is no need to change it.
122
+
123
+ > Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`)
124
+
125
+ vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.55`):
126
+ Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to
127
+ `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
128
+ launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.
129
+ vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
130
+ Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to
131
+ `"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
132
+ launching the vLLM server via the `--vllm_tensor_parallel_size` flag.
133
+ vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
134
+ Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but
135
+ waking the engine adds host–device transfer latency.
136
+
137
+ > Other parameters
138
+
139
+ ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
140
+ This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
141
+ improving generation speed. However, disabling this option allows training models that exceed the VRAM
142
+ capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible
143
+ with vLLM generation.
144
+ model_init_kwargs (`dict[str, Any]`, *optional*):
145
+ Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a
146
+ string.
147
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
148
+ Whether to allow loading models that ship custom Python code from the Hub. Forwarded to
149
+ [`~transformers.AutoModelForCausalLM.from_pretrained`]. Also applied to reward-model and reward-tokenizer
150
+ loads.
151
+ reward_weights (`list[float]`, *optional*):
152
+ Weights for combining multiple reward functions. Must match the number of reward functions. If `None`, all
153
+ reward functions are equally weighted.
154
+
155
+ > [!NOTE]
156
+ > These parameters have default values different from [`~transformers.TrainingArguments`]:
157
+ > - `logging_steps`: Defaults to `10` instead of `500`.
158
+ > - `gradient_checkpointing`: Defaults to `True` instead of `False`.
159
+ > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
160
+ > - `learning_rate`: Defaults to `5e-7` instead of `5e-5`.
161
+ > - `remove_unused_columns`: Defaults to `False` instead of `True`.
162
+ """
163
+
164
+ _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
165
+
166
+ # Parameters whose default values are overridden from TrainingArguments
167
+ learning_rate: float = field(
168
+ default=5e-7,
169
+ metadata={"help": "The initial learning rate for AdamW."},
170
+ )
171
+ remove_unused_columns: bool = field(
172
+ default=False,
173
+ metadata={"help": "Whether or not to automatically remove the columns unused by the model forward method."},
174
+ )
175
+
176
+ reward_model_path: str | None = field(
177
+ default=None,
178
+ metadata={"help": "Path to the reward model."},
179
+ )
180
+ max_new_tokens: int = field(
181
+ default=64,
182
+ metadata={"help": "Maximum number of tokens to generate per completion."},
183
+ )
184
+ max_length: int = field(
185
+ default=512,
186
+ metadata={
187
+ "help": "Maximum total length of the sequence (prompt + completion) used to compute log probabilities. If "
188
+ "the sequence exceeds this limit, the leftmost tokens will be truncated to preserve as much of the "
189
+ "completion as possible."
190
+ },
191
+ )
192
+ temperature: float = field(
193
+ default=0.9,
194
+ metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."},
195
+ )
196
+ top_p: float = field(
197
+ default=1.0,
198
+ metadata={
199
+ "help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. "
200
+ "Set to 1.0 to consider all tokens."
201
+ },
202
+ )
203
+ top_k: int = field(
204
+ default=0,
205
+ metadata={
206
+ "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, "
207
+ "top-k-filtering is disabled and all tokens are considered."
208
+ },
209
+ )
210
+ min_p: float | None = field(
211
+ default=None,
212
+ metadata={
213
+ "help": "Minimum token probability, which will be scaled by the probability of the most likely token. It "
214
+ "must be a value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range."
215
+ },
216
+ )
217
+ repetition_penalty: float = field(
218
+ default=1.0,
219
+ metadata={
220
+ "help": "Float that penalizes new tokens based on whether they appear in the prompt and the generated "
221
+ "text so far. Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model "
222
+ "to repeat tokens."
223
+ },
224
+ )
225
+ generation_kwargs: dict | None = field(
226
+ default=None,
227
+ metadata={
228
+ "help": "Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or "
229
+ "`SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the "
230
+ "generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that "
231
+ "conflict with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them."
232
+ },
233
+ )
234
+ cache_implementation: str | None = field(
235
+ default=None,
236
+ metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."},
237
+ )
238
+ missing_eos_penalty: float | None = field(
239
+ default=None,
240
+ metadata={
241
+ "help": "Penalty applied to the score when the model fails to generate an EOS token. This is useful to "
242
+ "encourage to generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be "
243
+ "a positive value."
244
+ },
245
+ )
246
+ beta: list[float] = field(
247
+ default_factory=lambda: [0.1],
248
+ metadata={
249
+ "help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from "
250
+ "the reference model. For the IPO loss (`loss_type='ipo'`), β is the regularization parameter denoted by "
251
+ "τ in the [paper](https://huggingface.co/papers/2310.12036). If a list of floats is provided then the β "
252
+ "is selected for each new epoch and the last β is used for the rest of the epochs."
253
+ },
254
+ )
255
+ loss_type: str = field(
256
+ default="sigmoid",
257
+ metadata={
258
+ "help": "Type of loss to use.",
259
+ "choices": ["sigmoid", "ipo"],
260
+ },
261
+ )
262
+ disable_dropout: bool = field(
263
+ default=True,
264
+ metadata={"help": "Whether to disable dropout in the model."},
265
+ )
266
+ use_vllm: bool = field(
267
+ default=False,
268
+ metadata={
269
+ "help": "Whether to use vLLM for generating completions. Requires vLLM to be installed "
270
+ "(`pip install trl[vllm]`)."
271
+ },
272
+ )
273
+ vllm_model_impl: str = field(
274
+ default="vllm",
275
+ metadata={
276
+ "help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: "
277
+ "Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for "
278
+ "model implementation."
279
+ },
280
+ )
281
+ vllm_structured_outputs_regex: str | None = field(
282
+ default=None,
283
+ metadata={"help": "Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled."},
284
+ )
285
+ vllm_gpu_memory_utilization: float | None = field(
286
+ default=0.55,
287
+ metadata={
288
+ "help": "Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set "
289
+ "to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when "
290
+ "launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.",
291
+ },
292
+ )
293
+ vllm_mode: str = field(
294
+ default="colocate",
295
+ metadata={
296
+ "help": "Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or "
297
+ "`'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure "
298
+ "a TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same "
299
+ "process and share the training GPUs. This avoids the need for a separate server but may cause resource "
300
+ "contention with training.",
301
+ },
302
+ )
303
+ vllm_server_base_url: str | None = field(
304
+ default=None,
305
+ metadata={
306
+ "help": "Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` "
307
+ "and `vllm_server_port` are ignored.",
308
+ },
309
+ )
310
+ vllm_server_host: str = field(
311
+ default="0.0.0.0",
312
+ metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
313
+ )
314
+ vllm_server_port: int = field(
315
+ default=8000,
316
+ metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
317
+ )
318
+ vllm_server_timeout: float = field(
319
+ default=240.0,
320
+ metadata={
321
+ "help": "Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up "
322
+ "after the timeout, a `ConnectionError` is raised.",
323
+ },
324
+ )
325
+ vllm_group_port: int = field(
326
+ default=51216,
327
+ metadata={
328
+ "help": "Port number for the weight update group. This is used to communicate with the vLLM server. "
329
+ "Unless the port is occupied, there is no need to change it.",
330
+ },
331
+ )
332
+ vllm_tensor_parallel_size: int = field(
333
+ default=1,
334
+ metadata={
335
+ "help": "Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set "
336
+ "to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when "
337
+ "launching the vLLM server via the `--vllm_tensor_parallel_size` flag.",
338
+ },
339
+ )
340
+ vllm_enable_sleep_mode: bool = field(
341
+ default=False,
342
+ metadata={
343
+ "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory "
344
+ "usage low, but waking the engine adds host–device transfer latency."
345
+ },
346
+ )
347
+ ds3_gather_for_generation: bool = field(
348
+ default=True,
349
+ metadata={
350
+ "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for "
351
+ "generation, improving generation speed. However, disabling this option allows training models that "
352
+ "exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option "
353
+ "is not compatible with vLLM generation."
354
+ },
355
+ )
356
+ model_init_kwargs: dict[str, Any] | str | None = field(
357
+ default=None,
358
+ metadata={
359
+ "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model "
360
+ "from a string."
361
+ },
362
+ )
363
+ trust_remote_code: bool = field(
364
+ default=False,
365
+ metadata={
366
+ "help": "Whether to allow loading models that ship custom Python code from the Hub. Forwarded to "
367
+ "`AutoModelForCausalLM.from_pretrained`. Also applied to reward-model and reward-tokenizer loads."
368
+ },
369
+ )
370
+ reward_weights: list[float] | None = field(
371
+ default=None,
372
+ metadata={
373
+ "help": "Weights for combining multiple reward functions. Must match the number of reward functions. "
374
+ "If None, all reward functions are equally weighted."
375
+ },
376
+ )
377
+
378
+ def __post_init__(self):
379
+ super().__post_init__()
380
+
381
+ if hasattr(self.beta, "__len__") and len(self.beta) == 1:
382
+ self.beta = self.beta[0]
383
+
384
+ if self.max_new_tokens >= self.max_length:
385
+ warnings.warn(
386
+ f"The configuration has `max_new_tokens` ({self.max_new_tokens}) >= `max_length` ({self.max_length}). "
387
+ "This will cause prompts to be truncated or completely removed in the forward pass. "
388
+ "To preserve prompts, ensure e.g. `max_length > max_new_tokens + 512`. ",
389
+ stacklevel=3,
390
+ )
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/online_dpo/online_dpo_trainer.py ADDED
@@ -0,0 +1,1354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import re
17
+ import textwrap
18
+ from collections.abc import Callable
19
+ from contextlib import nullcontext
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ import torch
24
+ import torch.nn as nn
25
+ import torch.nn.functional as F
26
+ import torch.utils.data
27
+ import transformers
28
+ from accelerate.logging import get_logger
29
+ from accelerate.utils import broadcast_object_list, gather_object, is_peft_model
30
+ from datasets import Dataset
31
+ from packaging.version import Version
32
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
33
+ from torch.utils.data import IterableDataset
34
+ from transformers import (
35
+ AutoModelForCausalLM,
36
+ AutoModelForSequenceClassification,
37
+ AutoTokenizer,
38
+ DataCollator,
39
+ GenerationConfig,
40
+ PreTrainedModel,
41
+ PreTrainedTokenizerBase,
42
+ ProcessorMixin,
43
+ TrainerCallback,
44
+ is_bitsandbytes_available,
45
+ )
46
+ from transformers.models.auto.modeling_auto import MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES
47
+ from transformers.trainer_utils import EvalPrediction
48
+ from transformers.training_args import OptimizerNames
49
+ from transformers.utils import is_peft_available, is_sagemaker_mp_enabled
50
+
51
+ from ...data_utils import apply_chat_template, is_conversational, maybe_apply_chat_template
52
+ from ...extras.profiling import profiling_context
53
+ from ...generation.vllm_client import VLLMClient
54
+ from ...import_utils import is_vllm_available
55
+ from ...models.utils import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation
56
+ from ...trainer.base_trainer import _BaseTrainer
57
+ from ...trainer.utils import disable_dropout_in_model, ensure_master_addr_port, get_config_model_id
58
+ from ..utils import DPODataCollatorWithPadding, create_reference_model, empty_cache, prepare_peft_model, truncate_right
59
+ from .online_dpo_config import OnlineDPOConfig
60
+
61
+
62
+ if is_peft_available():
63
+ from peft import PeftConfig
64
+
65
+
66
+ if is_sagemaker_mp_enabled():
67
+ from smdistributed.modelparallel import __version__ as SMP_VERSION
68
+
69
+ IS_SAGEMAKER_MP_POST_1_10 = Version(SMP_VERSION) >= Version("1.10")
70
+
71
+ else:
72
+ IS_SAGEMAKER_MP_POST_1_10 = False
73
+
74
+
75
+ if Version(transformers.__version__) >= Version("5.2.0"):
76
+ from transformers.trainer_pt_utils import nested_gather
77
+
78
+
79
+ if is_vllm_available():
80
+ from vllm import LLM, SamplingParams
81
+ from vllm.sampling_params import StructuredOutputsParams
82
+
83
+ if is_bitsandbytes_available():
84
+ import bitsandbytes as bnb
85
+
86
+ logger = get_logger(__name__)
87
+
88
+ # A reward function can be a string, interpreted as a model ID and loaded as a pretrained model, a pretrained model, or
89
+ # a callable that returns a list of floats (the rewards). The callable receives prompts, completions, and additional
90
+ # arguments from the trainer (refer to the trainer's source for details). To ensure forward compatibility, it should
91
+ # accept **kwargs.
92
+ RewardFunc = str | PreTrainedModel | Callable[..., list[float | None]]
93
+
94
+
95
+ class OnlineDPOTrainer(_BaseTrainer):
96
+ r"""
97
+ Initialize OnlineDPOTrainer.
98
+
99
+ Args:
100
+ model (`str | nn.Module | PreTrainedModel`):
101
+ Model to be trained. Can be either:
102
+
103
+ - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
104
+ path to a *directory* containing model weights saved using
105
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
106
+ using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in
107
+ `args.model_init_kwargs`.
108
+ - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
109
+ ref_model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `None`):
110
+ The reference model to use for training. If None is specified, the reference model will be created from the
111
+ model.
112
+ reward_funcs (`RewardFunc | list[RewardFunc]`):
113
+ Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
114
+ functions with the prompts and completions and sum the rewards. Can be either:
115
+
116
+ - A single reward function: Can be a string (path to model), a [`~transformers.PreTrainedModel`], or a
117
+ custom callable function.
118
+ - A list of reward functions: Must all be of compatible types.
119
+ args ([`experimental.online_dpo.OnlineDPOConfig`]):
120
+ The online DPO config arguments to use for training.
121
+ data_collator ([`~transformers.DataCollator`]):
122
+ The data collator to use for training. If None is specified, the default data collator
123
+ ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the
124
+ maximum length of the sequences in the batch, given a dataset of paired sequences.
125
+ train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
126
+ The dataset to use for training.
127
+ eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
128
+ The dataset to use for evaluation.
129
+ processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`], *optional*):
130
+ Processing class used to process the data. If provided, will be used to automatically process the inputs
131
+ for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
132
+ reuse the fine-tuned model.
133
+ reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*):
134
+ Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
135
+
136
+ - A single processing class: Used when `reward_funcs` contains only one reward function.
137
+ - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
138
+
139
+ If set to `None`, the tokenizer for each model-based reward function is automatically loaded using
140
+ [`~transformers.AutoTokenizer.from_pretrained`].
141
+ peft_config ([`~peft.PeftConfig`], *optional*):
142
+ PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
143
+ compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
144
+ The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
145
+ metric values.
146
+ callbacks (`list[transformers.TrainerCallback]`):
147
+ The callbacks to use for training.
148
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
149
+ The optimizer and scheduler to use for training.
150
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
151
+ The function to use to preprocess the logits before computing the metrics.
152
+ """
153
+
154
+ _tag_names = ["trl", "online-dpo"]
155
+ _name = "Online DPO"
156
+ _paper = {
157
+ "title": "Direct Language Model Alignment from Online AI Feedback",
158
+ "id": "2402.04792",
159
+ # docstyle-ignore
160
+ "citation": textwrap.dedent("""\
161
+ @article{guo2024direct,
162
+ title = {{Direct Language Model Alignment from Online AI Feedback}},
163
+ author = {Shangmin Guo and Biao Zhang and Tianlin Liu and Tianqi Liu and Misha Khalman and Felipe Llinares and Alexandre Ram{\'{e}} and Thomas Mesnard and Yao Zhao and Bilal Piot and Johan Ferret and Mathieu Blondel},
164
+ year = 2024,
165
+ eprint = {arXiv:2402.04792}
166
+ }"""),
167
+ }
168
+
169
+ def __init__(
170
+ self,
171
+ model: PreTrainedModel | nn.Module | str,
172
+ ref_model: PreTrainedModel | nn.Module | None = None,
173
+ reward_funcs: RewardFunc | list[RewardFunc] | None = None,
174
+ args: OnlineDPOConfig | None = None,
175
+ data_collator: DataCollator | None = None,
176
+ train_dataset: Dataset | IterableDataset | None = None,
177
+ eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
178
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
179
+ reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
180
+ peft_config: "PeftConfig | None" = None,
181
+ compute_metrics: Callable[[EvalPrediction], dict] | None = None,
182
+ callbacks: list[TrainerCallback] | None = None,
183
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
184
+ preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
185
+ ) -> None:
186
+ if train_dataset is None:
187
+ raise ValueError("`train_dataset` is required")
188
+
189
+ if ref_model is model:
190
+ raise ValueError(
191
+ "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the "
192
+ "same as `model`, either omit the `ref_model` argument or pass `None`."
193
+ )
194
+
195
+ self.ref_model = ref_model
196
+
197
+ if reward_funcs is None:
198
+ raise ValueError("`reward_funcs` must be provided.")
199
+
200
+ # Handle reward_funcs
201
+ if not isinstance(reward_funcs, list):
202
+ reward_funcs = [reward_funcs]
203
+ self.reward_func_names = []
204
+
205
+ # Process reward functions (convert strings to models, collect names)
206
+ model_init_kwargs = args.model_init_kwargs or {}
207
+ model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
208
+ for i, reward_func in enumerate(reward_funcs):
209
+ if isinstance(reward_func, str):
210
+ # Load model from string path
211
+ reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained(
212
+ reward_func, num_labels=1, **model_init_kwargs
213
+ )
214
+ if isinstance(reward_funcs[i], nn.Module):
215
+ self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1])
216
+ else:
217
+ self.reward_func_names.append(reward_funcs[i].__name__)
218
+ self.reward_funcs = reward_funcs
219
+
220
+ # Handle reward processing classes for reward_funcs
221
+ if reward_processing_classes is None:
222
+ reward_processing_classes = [None] * len(reward_funcs)
223
+ elif not isinstance(reward_processing_classes, list):
224
+ reward_processing_classes = [reward_processing_classes]
225
+ else:
226
+ if len(reward_processing_classes) != len(reward_funcs):
227
+ raise ValueError("The number of reward processing classes must match the number of reward functions.")
228
+
229
+ self.reward_processing_classes = []
230
+ for reward_processing_class_i, reward_func in zip(reward_processing_classes, reward_funcs, strict=True):
231
+ if isinstance(reward_func, PreTrainedModel):
232
+ if reward_processing_class_i is None:
233
+ reward_processing_class_i = AutoTokenizer.from_pretrained(
234
+ reward_func.config._name_or_path, trust_remote_code=args.trust_remote_code
235
+ )
236
+ if reward_processing_class_i.pad_token_id is None:
237
+ reward_processing_class_i.pad_token = reward_processing_class_i.eos_token
238
+ # Set pad token ID on reward model config
239
+ reward_func.config.pad_token_id = reward_processing_class_i.pad_token_id
240
+ self.reward_processing_classes.append(reward_processing_class_i)
241
+
242
+ # Handle reward_weights
243
+ if args.reward_weights is not None:
244
+ if len(args.reward_weights) != len(self.reward_funcs):
245
+ raise ValueError(
246
+ f"Number of reward weights ({len(args.reward_weights)}) must match number of reward "
247
+ f"functions ({len(self.reward_funcs)})"
248
+ )
249
+ self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32)
250
+ else:
251
+ self.reward_weights = torch.ones(len(self.reward_funcs), dtype=torch.float32)
252
+
253
+ if args is None:
254
+ raise ValueError("`args` must be provided.")
255
+
256
+ # Check that the processing_class is provided
257
+ if processing_class is None:
258
+ raise ValueError("`processing_class` must be provided.")
259
+
260
+ model_init_kwargs = args.model_init_kwargs or {}
261
+ if isinstance(model, str):
262
+ model_id = model
263
+
264
+ # Handle dtype in model_init_kwargs
265
+ dtype = model_init_kwargs.get("dtype", "auto")
266
+ if isinstance(dtype, torch.dtype) or dtype == "auto" or dtype is None:
267
+ pass
268
+ elif isinstance(dtype, str):
269
+ dtype = getattr(torch, dtype)
270
+ model_init_kwargs["dtype"] = dtype
271
+ else:
272
+ raise ValueError(
273
+ "Invalid `dtype` passed to `OnlineDPOConfig`. Expected either 'auto' or a string "
274
+ f"representing a `torch.dtype` (e.g., 'float32'), but got {dtype}."
275
+ )
276
+ model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto")
277
+ model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
278
+
279
+ model = AutoModelForCausalLM.from_pretrained(model_id, **model_init_kwargs)
280
+ else:
281
+ if args.model_init_kwargs is not None:
282
+ raise ValueError(
283
+ "You passed `model_init_kwargs` to the `OnlineDPOConfig`, but your model is already instantiated. "
284
+ "This argument can only be used when the `model` argument is a string."
285
+ )
286
+ self.is_encoder_decoder = model.config.is_encoder_decoder
287
+ self.is_vision_model = model.config.model_type in MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES.keys()
288
+
289
+ # PEFT
290
+ if peft_config is not None:
291
+ if not is_peft_available():
292
+ raise ImportError(
293
+ "You passed `peft_config` but the `peft` library is not installed. "
294
+ "Install it with `pip install trl[peft]`."
295
+ )
296
+ if not isinstance(peft_config, PeftConfig):
297
+ raise TypeError(
298
+ f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
299
+ f"got {type(peft_config).__name__}."
300
+ )
301
+ if peft_config is not None or is_peft_model(model):
302
+ model = prepare_peft_model(model, peft_config, args)
303
+
304
+ # Enable gradient checkpointing if requested
305
+ if args.gradient_checkpointing:
306
+ model = self._enable_gradient_checkpointing(model, args)
307
+
308
+ # Disable dropout in the model and reference model
309
+ if args.disable_dropout:
310
+ disable_dropout_in_model(model)
311
+ if self.ref_model is not None:
312
+ disable_dropout_in_model(self.ref_model)
313
+
314
+ # Handle the ref_model
315
+ # Usually, the user wants the ref model to be the initial version of the model. When using PEFT, it's easy to
316
+ # get the ref model, as it's just the model with a disabled adapter. When not using PEFT, we need to create
317
+ # the ref model from the model by copying it and disable the gradients and set it in evaluation mode.
318
+ if ref_model is None: # No ref model provided, the most common case
319
+ if peft_config is None:
320
+ self.ref_model = create_reference_model(model) # copy, disable gradients, set eval mode
321
+ else:
322
+ self.ref_model = None # we don't need a ref model here, we can just disable the adapter.
323
+ else: # rare case, the user provided a ref model
324
+ self.ref_model = ref_model
325
+ self.ref_model.eval()
326
+
327
+ # Disable the gradient and set the reward model in eval mode
328
+ if reward_funcs is not None:
329
+ for reward_func in reward_funcs:
330
+ if isinstance(reward_func, PreTrainedModel):
331
+ reward_func.eval()
332
+
333
+ self.max_length = args.max_length
334
+
335
+ self.stats = {
336
+ "objective/kl": [],
337
+ "objective/entropy": [],
338
+ "objective/non_score_reward": [],
339
+ "rewards/chosen": [],
340
+ "rewards/rejected": [],
341
+ "rewards/accuracies": [],
342
+ "rewards/margins": [],
343
+ "logps/chosen": [],
344
+ "logps/rejected": [],
345
+ "val/contain_eos_token": [],
346
+ "beta": [],
347
+ }
348
+ if self.reward_funcs is not None:
349
+ self.stats["objective/rlhf_reward"] = []
350
+ self.stats["objective/scores_margin"] = []
351
+ self.stats["objective/scores"] = []
352
+
353
+ # Store generation parameters for later use
354
+ self.use_vllm = args.use_vllm
355
+ self.num_generations = 2 # Generate 2 completions per prompt for Online DPO
356
+ self.temperature = args.temperature
357
+ self.top_p = args.top_p
358
+ self.top_k = args.top_k
359
+ self.min_p = args.min_p
360
+ self.repetition_penalty = args.repetition_penalty
361
+ self.vllm_mode = args.vllm_mode if args.use_vllm else None
362
+ self.vllm_gpu_memory_utilization = args.vllm_gpu_memory_utilization
363
+ self.vllm_tensor_parallel_size = args.vllm_tensor_parallel_size
364
+ self.vllm_model_impl = args.vllm_model_impl
365
+
366
+ # Handle pad token for processors or tokenizers
367
+ if isinstance(processing_class, ProcessorMixin):
368
+ self._tokenizer = processing_class.tokenizer
369
+ elif isinstance(processing_class, PreTrainedTokenizerBase):
370
+ self._tokenizer = processing_class
371
+ else:
372
+ raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
373
+
374
+ if self._tokenizer.pad_token is None:
375
+ self._tokenizer.pad_token = self._tokenizer.eos_token
376
+
377
+ # Vision tokens for VLM support
378
+ self.image_token_id = getattr(processing_class, "image_token_id", None)
379
+ self.vision_start_token_id = getattr(processing_class, "vision_start_token_id", None)
380
+ self.vision_end_token_id = getattr(processing_class, "vision_end_token_id", None)
381
+ # Get the image token string for token collapsing
382
+ self.image_token = None
383
+ if self.image_token_id is not None:
384
+ self.image_token = self._tokenizer.decode([self.image_token_id])
385
+
386
+ # Define the collator if not provided
387
+ if data_collator is None:
388
+ data_collator = DPODataCollatorWithPadding(pad_token_id=self._tokenizer.pad_token_id)
389
+
390
+ # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
391
+ # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
392
+ # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
393
+ # default to the recommended non-reentrant behavior here, while preserving any user-provided value.
394
+ if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
395
+ args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
396
+ args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
397
+
398
+ super().__init__(
399
+ model=model,
400
+ args=args,
401
+ data_collator=data_collator,
402
+ train_dataset=train_dataset,
403
+ eval_dataset=eval_dataset,
404
+ processing_class=processing_class,
405
+ compute_metrics=compute_metrics,
406
+ callbacks=callbacks,
407
+ optimizers=optimizers,
408
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
409
+ )
410
+
411
+ # Add tags for models that have been loaded with the correct transformers version
412
+ if hasattr(self.model, "add_model_tags"):
413
+ self.model.add_model_tags(self._tag_names)
414
+
415
+ self._beta = args.beta
416
+
417
+ # Set up generation configuration and vLLM after super().__init__
418
+ if self.use_vllm:
419
+ if not is_vllm_available():
420
+ raise ImportError(
421
+ "vLLM is not available and `use_vllm` is set to True. Please install vLLM with "
422
+ "`pip install trl[vllm]` to use it."
423
+ )
424
+
425
+ if self.vllm_mode == "server":
426
+ if self.accelerator.is_main_process:
427
+ if args.vllm_server_base_url is not None:
428
+ base_url = args.vllm_server_base_url
429
+ else:
430
+ base_url = f"http://{args.vllm_server_host}:{args.vllm_server_port}"
431
+ self.vllm_client = VLLMClient(
432
+ base_url=base_url, group_port=args.vllm_group_port, connection_timeout=args.vllm_server_timeout
433
+ )
434
+
435
+ # Determine device type (supports cuda, xpu, etc.)
436
+ accelerator_type = torch.accelerator.current_accelerator().type
437
+ current_device = getattr(torch, accelerator_type).current_device()
438
+ self.vllm_client.init_communicator(device=current_device)
439
+ else:
440
+ self.vllm_client = None
441
+ elif self.vllm_mode == "colocate":
442
+ # vLLM dynamically adjusts the size of the key-value cache based on available GPU memory at instantiation.
443
+ # A larger cache size improves speed, so we would expect gpu_memory_utilization=1.
444
+ # However, at this stage, the optimizer's weights are not yet loaded onto the GPU; they will be loaded
445
+ # after the first optimizer step and remain in GPU memory throughout training. So we must reserve enough
446
+ # space for them.
447
+ # Configure vLLM parameters
448
+ vllm_quantization = None
449
+ if is_bitsandbytes_available():
450
+ for _, module in model.named_modules():
451
+ if isinstance(module, bnb.nn.Linear4bit):
452
+ vllm_quantization = "bitsandbytes"
453
+ break
454
+ elif isinstance(module, bnb.nn.Linear8bitLt):
455
+ raise ValueError("vLLM does not support in-flight 8-bit quantization.")
456
+ vllm_kwargs = {
457
+ "model": model.name_or_path,
458
+ "tensor_parallel_size": self.vllm_tensor_parallel_size,
459
+ "gpu_memory_utilization": self.vllm_gpu_memory_utilization,
460
+ "model_impl": self.vllm_model_impl,
461
+ "max_num_seqs": self.args.per_device_train_batch_size * self.vllm_tensor_parallel_size,
462
+ "max_model_len": args.max_length + args.max_new_tokens, # max_length includes prompt + completion
463
+ "distributed_executor_backend": "external_launcher",
464
+ # Feed identical seed for tp groups to ensure sampling results are the same across workers
465
+ "seed": self.accelerator.process_index // self.vllm_tensor_parallel_size,
466
+ # Latest vLLM v1 memory profiler is misled by the high default value (i.e., 32768)
467
+ "max_num_batched_tokens": 4096,
468
+ "enable_sleep_mode": self.args.vllm_enable_sleep_mode,
469
+ "quantization": vllm_quantization,
470
+ }
471
+
472
+ # vLLM requires the environment variables to be set for distributed training.
473
+ os.environ["RANK"] = str(self.accelerator.process_index)
474
+ os.environ["LOCAL_RANK"] = str(self.accelerator.local_process_index)
475
+ os.environ["WORLD_SIZE"] = str(self.accelerator.num_processes)
476
+ # Ensure distributed rendezvous variables are set without colliding across concurrent runs
477
+ ensure_master_addr_port()
478
+
479
+ self.llm = LLM(**vllm_kwargs)
480
+ if self.args.vllm_enable_sleep_mode:
481
+ self.llm.sleep(level=2)
482
+ else:
483
+ raise ValueError(f"vllm_mode must be either 'server' or 'colocate', got '{self.vllm_mode}'.")
484
+ # vLLM specific sampling arguments
485
+ self.structured_outputs_regex = args.vllm_structured_outputs_regex
486
+ self._last_loaded_step = -1 # tag to avoid useless loading during grad accumulation
487
+
488
+ # Set up vLLM generation config
489
+ generation_kwargs = {
490
+ "n": 2, # 2 generations per prompt for Online DPO
491
+ "repetition_penalty": self.repetition_penalty,
492
+ "temperature": self.temperature,
493
+ "top_p": self.top_p,
494
+ "top_k": self.top_k,
495
+ "min_p": 0.0 if self.min_p is None else self.min_p,
496
+ "max_tokens": args.max_new_tokens,
497
+ "detokenize": False, # to avoid vllm to decode (we don't need it)
498
+ }
499
+ if args.generation_kwargs is not None:
500
+ generation_kwargs.update(args.generation_kwargs)
501
+ if self.structured_outputs_regex is not None:
502
+ if generation_kwargs.get("structured_outputs") is not None:
503
+ logger.warning(
504
+ "Both `vllm_structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; "
505
+ "`vllm_structured_outputs_regex` takes precedence."
506
+ )
507
+ generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=self.structured_outputs_regex)
508
+ elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict):
509
+ generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs)
510
+ self.generation_config = SamplingParams(**generation_kwargs)
511
+
512
+ # When using vLLM, the main process is responsible for loading the model weights. This can cause process
513
+ # desynchronization and seems to lead to DeepSpeed hanging during initialization. To prevent this, we
514
+ # synchronize all processes after vLLM has been fully initialized.
515
+ self.accelerator.wait_for_everyone()
516
+ else:
517
+ # Set up transformers generation config
518
+ generation_kwargs = {
519
+ "max_new_tokens": args.max_new_tokens,
520
+ "do_sample": True,
521
+ "pad_token_id": self._tokenizer.pad_token_id,
522
+ "bos_token_id": self._tokenizer.bos_token_id,
523
+ "eos_token_id": self._tokenizer.eos_token_id,
524
+ "temperature": self.temperature,
525
+ "top_k": self.top_k,
526
+ "top_p": self.top_p,
527
+ "repetition_penalty": self.repetition_penalty,
528
+ "use_cache": True if not self.args.gradient_checkpointing else False,
529
+ }
530
+ # Add min_p if supported
531
+ if self.min_p is not None:
532
+ generation_kwargs["min_p"] = self.min_p
533
+ if args.generation_kwargs is not None:
534
+ generation_kwargs.update(args.generation_kwargs)
535
+ # Remove None values
536
+ generation_kwargs = {k: v for k, v in generation_kwargs.items() if v is not None}
537
+ self.generation_config = GenerationConfig(**generation_kwargs)
538
+ # Keep training-specific generation kwargs to overwrite model's original generation config
539
+ self.generation_kwargs = generation_kwargs
540
+
541
+ if self.ref_model is not None:
542
+ if self.is_deepspeed_enabled:
543
+ self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
544
+ elif self.is_fsdp_enabled:
545
+ self.ref_model = prepare_fsdp(self.ref_model, self.accelerator)
546
+ else:
547
+ self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
548
+ if self.reward_funcs is not None:
549
+ for i, reward_func in enumerate(self.reward_funcs):
550
+ if isinstance(reward_func, PreTrainedModel):
551
+ if self.is_deepspeed_enabled:
552
+ self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator)
553
+ else:
554
+ # set device placement to True to make `prepare_model` move `reward_func` to device when using fsdp
555
+ self.reward_funcs[i] = self.accelerator.prepare_model(
556
+ reward_func, evaluation_mode=True, device_placement=True
557
+ )
558
+
559
+ @property
560
+ def beta(self):
561
+ if isinstance(self._beta, list):
562
+ epoch = self.state.epoch
563
+ return self._beta[epoch] if epoch < len(self._beta) else self._beta[-1]
564
+ else:
565
+ return self._beta
566
+
567
+ @staticmethod
568
+ def tokenize_row(feature, is_encoder_decoder: bool, tokenizer: PreTrainedTokenizerBase) -> dict[str, Any]:
569
+ """Tokenize a single row from a DPO specific dataset."""
570
+ if not is_encoder_decoder:
571
+ batch = tokenizer(feature["prompt"], add_special_tokens=False)
572
+ # Add BOS token to head of prompt. Avoid adding if it's already there
573
+ if tokenizer.bos_token_id is not None:
574
+ prompt_len_input_ids = len(batch["input_ids"])
575
+ if prompt_len_input_ids == 0 or tokenizer.bos_token_id != batch["input_ids"][0]:
576
+ batch["input_ids"] = [tokenizer.bos_token_id] + batch["input_ids"]
577
+ batch["attention_mask"] = [1] + batch["attention_mask"]
578
+ else:
579
+ batch = tokenizer(feature["prompt"], add_special_tokens=True)
580
+ batch = {f"prompt_{key}": value for key, value in batch.items()}
581
+ return batch
582
+
583
+ def _enable_gradient_checkpointing(self, model: PreTrainedModel, args: OnlineDPOConfig) -> PreTrainedModel:
584
+ """Enables gradient checkpointing for the model."""
585
+ # Ensure use_cache is disabled
586
+ model.config.use_cache = False
587
+
588
+ # Enable gradient checkpointing on the base model for PEFT
589
+ if is_peft_model(model):
590
+ model.base_model.gradient_checkpointing_enable()
591
+ # Enable gradient checkpointing for non-PEFT models
592
+ else:
593
+ model.gradient_checkpointing_enable()
594
+
595
+ model.enable_input_require_grads()
596
+ return model
597
+
598
+ def _generate_vllm(self, prompts, images=None):
599
+ eos_token_id = self._tokenizer.eos_token_id
600
+ pad_token_id = self._tokenizer.pad_token_id
601
+
602
+ # Generate completion_ids and prompt_ids based on mode
603
+ if self.vllm_mode == "server":
604
+ completion_ids, prompt_ids = self._generate_vllm_server(prompts, images)
605
+ elif self.vllm_mode == "colocate":
606
+ completion_ids, prompt_ids = self._generate_vllm_colocate(prompts, images)
607
+
608
+ # Shared padding, masking, and tensor conversion logic
609
+ max_prompt_length = max(len(ids) for ids in prompt_ids)
610
+ prompt_mask = [[0] * (max_prompt_length - len(ids)) + [1] * len(ids) for ids in prompt_ids]
611
+ prompt_ids = [[pad_token_id] * (max_prompt_length - len(ids)) + ids for ids in prompt_ids]
612
+ max_tokens = self.generation_config.max_tokens
613
+ completion_mask = [[1] * len(ids) + [0] * (max_tokens - len(ids)) for ids in completion_ids]
614
+ completion_ids = [
615
+ ids + [eos_token_id] if ids[-1] != eos_token_id and len(ids) < max_tokens else ids
616
+ for ids in completion_ids
617
+ ]
618
+ completion_ids = [ids + [pad_token_id] * (max_tokens - len(ids)) for ids in completion_ids]
619
+
620
+ # Convert to tensors
621
+ prompt_ids = torch.tensor(prompt_ids, device=self.accelerator.device)
622
+ prompt_mask = torch.tensor(prompt_mask, device=self.accelerator.device)
623
+ completion_ids = torch.tensor(completion_ids, device=self.accelerator.device)
624
+ completion_mask = torch.tensor(completion_mask, device=self.accelerator.device)
625
+
626
+ return prompt_ids, prompt_mask, completion_ids, completion_mask
627
+
628
+ def _generate_vllm_server(self, prompts, images=None):
629
+ """Generate completions using vLLM server mode"""
630
+ has_images = images is not None
631
+
632
+ # Update vLLM server weights if needed
633
+ if hasattr(self, "_last_loaded_step") and self.state.global_step != self._last_loaded_step:
634
+ self._move_model_to_vllm()
635
+ self._last_loaded_step = self.state.global_step
636
+ elif not hasattr(self, "_last_loaded_step"):
637
+ self._move_model_to_vllm()
638
+ self._last_loaded_step = self.state.global_step
639
+
640
+ # Apply chat template if conversational
641
+ if is_conversational({"prompt": prompts[0]}):
642
+ prompts_text = [apply_chat_template({"prompt": p}, self.processing_class)["prompt"] for p in prompts]
643
+ else:
644
+ prompts_text = prompts
645
+ # Gather all prompts to main process
646
+ all_prompts = gather_object(prompts_text)
647
+ if has_images:
648
+ all_images = gather_object(images)
649
+
650
+ if self.accelerator.is_main_process:
651
+ # Since 'prompts' contains 'num_generations' duplicates, we first take unique prompts, and generate
652
+ # num_generations outputs for each one. This is faster than generating outputs for each duplicate
653
+ # prompt individually.
654
+ ordered_set_of_prompts = all_prompts[:: self.num_generations]
655
+ if has_images:
656
+ ordered_set_of_images = [
657
+ [img] if img is not None else None for img in all_images[:: self.num_generations]
658
+ ]
659
+ else:
660
+ ordered_set_of_images = None
661
+ completion_ids = self.vllm_client.generate(
662
+ prompts=ordered_set_of_prompts,
663
+ images=ordered_set_of_images,
664
+ n=self.num_generations,
665
+ repetition_penalty=self.repetition_penalty,
666
+ temperature=self.temperature,
667
+ top_p=self.top_p,
668
+ top_k=-1 if self.top_k is None else self.top_k,
669
+ min_p=0.0 if self.min_p is None else self.min_p,
670
+ max_tokens=self.generation_config.max_tokens,
671
+ structured_outputs_regex=self.structured_outputs_regex
672
+ if hasattr(self, "structured_outputs_regex")
673
+ else None,
674
+ generation_kwargs=self.args.generation_kwargs,
675
+ )["completion_ids"]
676
+ # Flatten: each prompt generates 2 completions
677
+ completion_ids = [[comp_id] for prompt_completions in completion_ids for comp_id in prompt_completions]
678
+ else:
679
+ completion_ids = [None] * (len(all_prompts) * 2)
680
+
681
+ # Broadcast completions to all processes
682
+ completion_ids = broadcast_object_list(completion_ids, from_process=0)
683
+
684
+ # Each process takes its slice
685
+ process_slice = slice(
686
+ self.accelerator.process_index * len(prompts) * 2,
687
+ (self.accelerator.process_index + 1) * len(prompts) * 2,
688
+ )
689
+ completion_ids = completion_ids[process_slice]
690
+
691
+ # Create prompt_ids by tokenizing locally
692
+ prompt_inputs = self.processing_class(
693
+ text=prompts_text,
694
+ return_tensors="pt",
695
+ padding=True,
696
+ padding_side="left",
697
+ add_special_tokens=False,
698
+ )
699
+ prompt_ids = []
700
+ for prompt_tokens in prompt_inputs["input_ids"]:
701
+ prompt_ids.extend([prompt_tokens.tolist(), prompt_tokens.tolist()]) # 2 copies for 2 completions
702
+ return completion_ids, prompt_ids
703
+
704
+ def _generate_vllm_colocate(self, prompts, images=None):
705
+ """Generate completions using vLLM colocate mode"""
706
+ if self.args.vllm_enable_sleep_mode:
707
+ # wake up colocated vLLM instances if needed
708
+ torch.cuda.empty_cache() # required to avoid OOM in some cases
709
+ self.llm.wake_up(tags=["weights"])
710
+
711
+ # Update model weights if needed - only after gradient accumulation completes
712
+ if self.state.global_step != self._last_loaded_step:
713
+ self._move_model_to_vllm()
714
+ self._last_loaded_step = self.state.global_step
715
+
716
+ # Apply chat template if conversational
717
+ if is_conversational({"prompt": prompts[0]}):
718
+ prompts_text = [apply_chat_template({"prompt": p}, self.processing_class)["prompt"] for p in prompts]
719
+ else:
720
+ prompts_text = prompts
721
+
722
+ # Prepare vLLM inputs with images if available
723
+ if images is not None:
724
+ vllm_inputs = []
725
+ for prompt, image in zip(prompts_text, images, strict=True):
726
+ if image is not None:
727
+ vllm_inputs.append({"prompt": prompt, "multi_modal_data": {"image": image}})
728
+ else:
729
+ vllm_inputs.append(prompt)
730
+ else:
731
+ vllm_inputs = prompts_text
732
+
733
+ if self.args.vllm_enable_sleep_mode:
734
+ self.llm.wake_up(tags=["kv_cache"])
735
+
736
+ outputs = self.llm.generate(vllm_inputs, self.generation_config, use_tqdm=False)
737
+
738
+ completion_ids = [list(output.outputs[i].token_ids) for i in range(2) for output in outputs]
739
+ prompt_ids = [list(output.prompt_token_ids) for _ in range(2) for output in outputs]
740
+ if self.args.vllm_enable_sleep_mode:
741
+ self.llm.sleep(level=2)
742
+
743
+ return completion_ids, prompt_ids
744
+
745
+ def _sync_fsdp2_params_to_vllm(self, module: nn.Module):
746
+ # For FSDP2, module.state_dict() already covers all parameters, so no need for recursion
747
+ for name, param in module.state_dict().items():
748
+ # When using PEFT, we need to recover the original parameter name
749
+ name = name.removeprefix("base_model.model.").replace(".base_layer", "")
750
+ # Skip PEFT layers: they don’t exist in vLLM, and they are merged already.
751
+ if is_peft_model(module) and module.prefix in name:
752
+ continue
753
+ # When module to save, remove its prefix and discard the original module
754
+ if "original_module" in name:
755
+ continue
756
+ name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."])
757
+
758
+ if param.is_cpu:
759
+ param = param.to(torch.device("cuda"))
760
+ param = param.full_tensor()
761
+
762
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
763
+ self.vllm_client.update_named_param(name, param)
764
+ elif self.vllm_mode == "colocate":
765
+ llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
766
+ llm_model.load_weights([(name, param)])
767
+
768
+ def _move_model_to_vllm(self):
769
+ # For DeepSpeed ZeRO-3 and FSDP, we need to gather all parameters before operations
770
+ deepspeed_plugin = self.accelerator.state.deepspeed_plugin
771
+ zero_stage_3 = deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3
772
+ if zero_stage_3:
773
+ import deepspeed
774
+
775
+ gather_if_zero3 = deepspeed.zero.GatheredParameters
776
+ else:
777
+ gather_if_zero3 = nullcontext
778
+
779
+ if is_peft_model(self.model):
780
+ # With PEFT and FSDP/DeepSpeed ZeRO Stage 3, we must gather the full model at once before merging, as
781
+ # merging adapters in a sharded manner is not supported.
782
+ # TODO: does this work with FSDP?
783
+ with gather_if_zero3(list(self.model.parameters())):
784
+ self.model.merge_adapter()
785
+
786
+ # Update vLLM weights while parameters are gathered
787
+ if self.is_fsdp_enabled: # note if using FSDP, gather_if_zero3 is nullcontext
788
+ # Update vLLM weights while parameters are gathered
789
+ # For PEFT with FSDP we need to use the memory efficient post-order traversal
790
+ fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None)
791
+ fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1
792
+ if fsdp_version == 1:
793
+ self._sync_fsdp1_params_to_vllm(
794
+ self.model
795
+ ) # use memory-efficient post-order traversal for FSDP
796
+ elif fsdp_version == 2:
797
+ self._sync_fsdp2_params_to_vllm(self.model)
798
+ else:
799
+ # DeepSpeed ZeRO-3 with PEFT
800
+ for name, param in self.model.named_parameters():
801
+ # When using PEFT, we need to recover the original parameter name
802
+ name = name.removeprefix("base_model.model.").replace(".base_layer", "")
803
+ # Skip PEFT layers: they don’t exist in vLLM, and they are merged already.
804
+ if self.model.prefix in name:
805
+ continue
806
+ # When module to save, remove its prefix and discard the original module
807
+ if "original_module" in name:
808
+ continue
809
+ name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."])
810
+
811
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
812
+ self.vllm_client.update_named_param(name, param.data)
813
+ elif self.vllm_mode == "colocate":
814
+ llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
815
+ llm_model.load_weights([(name, param.data)])
816
+ # Unmerge adapters while parameters are still gathered
817
+ self.model.unmerge_adapter()
818
+ # Parameters will automatically be repartitioned when exiting the context
819
+ else:
820
+ # For non-PEFT models, simply gather (if needed) and update each parameter individually.
821
+ if self.is_fsdp_enabled:
822
+ fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None)
823
+ fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1
824
+ if fsdp_version == 1:
825
+ self._sync_fsdp1_params_to_vllm(self.model) # use memory-efficient post-order traversal for FSDP
826
+ elif fsdp_version == 2:
827
+ self._sync_fsdp2_params_to_vllm(self.model)
828
+ else:
829
+ for name, param in self.model.named_parameters():
830
+ name = self._fix_param_name_to_vllm(name)
831
+ with gather_if_zero3([param]):
832
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
833
+ self.vllm_client.update_named_param(name, param.data)
834
+ elif self.vllm_mode == "colocate":
835
+ llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
836
+ llm_model.load_weights([(name, param.data)])
837
+
838
+ # Reset cache on vLLM
839
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
840
+ self.vllm_client.reset_prefix_cache()
841
+ elif self.vllm_mode == "colocate":
842
+ self.llm.reset_prefix_cache()
843
+
844
+ def _sync_fsdp1_params_to_vllm(self, module: nn.Module, prefix: str = "", visited=None):
845
+ """Memory-efficient post-order traversal of FSDP modules to extract full parameters and sync with vLLM."""
846
+ # For FSDP1, we need to recurse into children and also use summon_full_params
847
+ if visited is None:
848
+ visited = set()
849
+ for child_name, child_module in module.named_children():
850
+ child_prefix = f"{prefix}.{child_name}" if prefix else child_name
851
+ self._sync_fsdp1_params_to_vllm(
852
+ child_module, prefix=child_prefix, visited=visited
853
+ ) # recurse into the child
854
+
855
+ if isinstance(module, FSDP):
856
+ with FSDP.summon_full_params(module, recurse=False, writeback=False):
857
+ for param_name, param in module.named_parameters():
858
+ full_name = f"{prefix}.{param_name}" if prefix else param_name
859
+ full_name = self._fix_param_name_to_vllm(full_name, extra_prefixes=["_fsdp_wrapped_module."])
860
+
861
+ if full_name in visited:
862
+ continue # skip FSDP subtrees already traversed
863
+ visited.add(full_name)
864
+
865
+ if self.vllm_mode == "server" and self.accelerator.is_main_process:
866
+ self.vllm_client.update_named_param(full_name, param.data)
867
+ elif self.vllm_mode == "colocate":
868
+ llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
869
+ llm_model.load_weights([(full_name, param.data)])
870
+
871
+ def _fix_param_name_to_vllm(self, name, extra_prefixes: list[str] | None = None):
872
+ """Clean parameter names for vLLM compatibility"""
873
+ extra_prefixes = extra_prefixes or []
874
+ prefixes = ["_checkpoint_wrapped_module."] + extra_prefixes
875
+ for prefix in prefixes:
876
+ name = name.replace(prefix, "")
877
+ return name
878
+
879
+ def process_vision_row(
880
+ self, features: dict[str, list | torch.Tensor], processing_class=None
881
+ ) -> dict[str, list[int]]:
882
+ """
883
+ Process a vision row for VLM models (adapted from DPO trainer)
884
+ """
885
+ processor = processing_class or self.processing_class
886
+ processed_features = processor(images=[features["image"]], text=features["prompt"], add_special_tokens=False)
887
+
888
+ prompt_input_ids = processed_features["input_ids"][0]
889
+
890
+ # Create the output dict with required fields
891
+ output = {
892
+ "prompt_input_ids": prompt_input_ids,
893
+ "prompt_attention_mask": processed_features["attention_mask"][0],
894
+ }
895
+
896
+ # Add vision-specific fields
897
+ if "pixel_values" in processed_features:
898
+ output["pixel_values"] = processed_features["pixel_values"][0]
899
+ if "pixel_attention_mask" in processed_features:
900
+ output["pixel_attention_mask"] = processed_features["pixel_attention_mask"][0]
901
+ if "image_sizes" in processed_features:
902
+ output["image_sizes"] = processed_features["image_sizes"][0]
903
+
904
+ return output
905
+
906
+ def _generate(self, model, prompts, images=None):
907
+ """Generate completions using the model"""
908
+ device = next(model.parameters()).device
909
+ eos_token_id = self._tokenizer.eos_token_id
910
+ pad_token_id = self._tokenizer.pad_token_id
911
+
912
+ # Apply chat template and tokenize the input
913
+ inputs = [{"prompt": prompt} for prompt in prompts]
914
+
915
+ # Add images if provided (VLM support)
916
+ if images is not None:
917
+ for i, image in enumerate(images):
918
+ inputs[i]["image"] = image
919
+
920
+ # Apply chat template to get text prompts
921
+ prompts_text = [maybe_apply_chat_template(x, self.processing_class)["prompt"] for x in inputs]
922
+
923
+ # Handle image token collapsing/removal
924
+ # The chat template sometimes inserts a single image token into the prompt text. However, when this text is
925
+ # later tokenized, the single image token string is expanded into multiple image token IDs, depending on the
926
+ # image size. We need to handle this properly.
927
+ if self.image_token is not None and images is not None:
928
+ escaped_img_token = re.escape(self.image_token)
929
+ # Search for the image token in the chat template
930
+ if hasattr(self.processing_class, "chat_template") and self.processing_class.chat_template:
931
+ if re.search(escaped_img_token, self.processing_class.chat_template):
932
+ # Collapse repeated image tokens back into a single token
933
+ prompts_text = [
934
+ re.sub(rf"({escaped_img_token})+", self.image_token, text) for text in prompts_text
935
+ ]
936
+ else:
937
+ # If the chat template doesn't use the image token, remove all instances
938
+ if self.vision_end_token_id is not None:
939
+ escaped_eoi_token = re.escape(self._tokenizer.decode([self.vision_end_token_id]))
940
+ prompts_text = [
941
+ re.sub(rf"({escaped_img_token})+{escaped_eoi_token}", "", text) for text in prompts_text
942
+ ]
943
+ else:
944
+ # If vision_end_token_id is None, just remove the image tokens
945
+ prompts_text = [re.sub(rf"({escaped_img_token})+", "", text) for text in prompts_text]
946
+
947
+ # Prepare kwargs for processing class
948
+ kwargs = {}
949
+ if images is not None:
950
+ kwargs = {"images": [[img] for img in images]}
951
+
952
+ # Process inputs using the processing class (handles both VLM and LLM)
953
+ prompt_inputs = self.processing_class(
954
+ text=prompts_text,
955
+ return_tensors="pt",
956
+ padding=True,
957
+ padding_side="left",
958
+ add_special_tokens=False,
959
+ **kwargs,
960
+ )
961
+
962
+ prompt_inputs = {k: v.to(device) for k, v in prompt_inputs.items()}
963
+ # Convert vision inputs to model's dtype for proper computation
964
+ if "pixel_values" in prompt_inputs:
965
+ # Handle DataParallel wrapped models
966
+ model_dtype = getattr(model, "dtype", None)
967
+ if model_dtype is None and hasattr(model, "module"):
968
+ model_dtype = model.module.dtype
969
+ if model_dtype is not None:
970
+ prompt_inputs["pixel_values"] = prompt_inputs["pixel_values"].to(model_dtype)
971
+
972
+ # Sample 2 completions per prompt of size `max_new_tokens` from the model
973
+ prompt_ids = prompt_inputs["input_ids"].repeat(2, 1)
974
+ prompt_mask = prompt_inputs["attention_mask"].repeat(2, 1)
975
+
976
+ # Prepare vision inputs if available
977
+ vision_generation_kwargs = {}
978
+ if self.is_vision_model and images is not None:
979
+ if "pixel_values" in prompt_inputs:
980
+ vision_generation_kwargs["pixel_values"] = prompt_inputs["pixel_values"].repeat(2, 1, 1, 1)
981
+ if "pixel_attention_mask" in prompt_inputs:
982
+ vision_generation_kwargs["pixel_attention_mask"] = prompt_inputs["pixel_attention_mask"].repeat(2, 1)
983
+ if "image_sizes" in prompt_inputs:
984
+ vision_generation_kwargs["image_sizes"] = prompt_inputs["image_sizes"].repeat(2, 1)
985
+ if "image_grid_thw" in prompt_inputs:
986
+ vision_generation_kwargs["image_grid_thw"] = prompt_inputs["image_grid_thw"].repeat(2, 1)
987
+
988
+ with (
989
+ profiling_context(self, "transformers.generate"),
990
+ unwrap_model_for_generation(
991
+ model,
992
+ self.accelerator,
993
+ gather_deepspeed3_params=self.args.ds3_gather_for_generation,
994
+ generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
995
+ ) as unwrapped_model,
996
+ torch.no_grad(),
997
+ FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(),
998
+ ):
999
+ # Setup cache implementation if specified
1000
+ if self.args.cache_implementation is not None:
1001
+ unwrapped_model.generation_config.cache_implementation = self.args.cache_implementation
1002
+
1003
+ # Standard generation
1004
+ output = unwrapped_model.generate(
1005
+ input_ids=prompt_ids,
1006
+ attention_mask=prompt_mask,
1007
+ generation_config=self.generation_config,
1008
+ **vision_generation_kwargs,
1009
+ )
1010
+
1011
+ completion_ids = output[:, prompt_ids.size(1) :]
1012
+ completion_ids, completion_mask = truncate_right(completion_ids, eos_token_id, pad_token_id)
1013
+
1014
+ return prompt_ids, prompt_mask, completion_ids, completion_mask
1015
+
1016
+ def _calculate_rewards_from_functions(self, prompts, completions, completion_ids_list, **reward_kwargs):
1017
+ """
1018
+ Calculate rewards using reward functions
1019
+ """
1020
+ device = self.accelerator.device
1021
+ rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device)
1022
+
1023
+ # Add trainer state to reward kwargs for dynamic reward shaping
1024
+ reward_kwargs["trainer_state"] = self.state
1025
+
1026
+ for i, (reward_func, reward_processing_class) in enumerate(
1027
+ zip(self.reward_funcs, self.reward_processing_classes, strict=True)
1028
+ ):
1029
+ if isinstance(reward_func, nn.Module): # Model-based reward function
1030
+ # Handle conversational vs text input
1031
+ if is_conversational({"prompt": prompts[0]}):
1032
+ messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)]
1033
+ texts = [apply_chat_template(x, reward_processing_class)["text"] for x in messages]
1034
+ else:
1035
+ texts = [p + c for p, c in zip(prompts, completions, strict=True)]
1036
+
1037
+ # Tokenize and get reward scores
1038
+ reward_inputs = reward_processing_class(
1039
+ text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False
1040
+ )
1041
+ reward_inputs = {k: v.to(device) for k, v in reward_inputs.items()}
1042
+
1043
+ with torch.inference_mode():
1044
+ rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,)
1045
+ else:
1046
+ # Custom reward function
1047
+ output_reward_func = reward_func(
1048
+ prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs
1049
+ )
1050
+ # Convert None values to NaN
1051
+ output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func]
1052
+ rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device)
1053
+
1054
+ # Weight and sum across all reward functions
1055
+ if self.reward_weights is not None:
1056
+ total_rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
1057
+ else:
1058
+ total_rewards = rewards_per_func.nansum(dim=1)
1059
+
1060
+ return total_rewards
1061
+
1062
+ def _forward(self, model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs=None):
1063
+ # Get the number of tokens to truncate from prompt
1064
+ num_tokens_to_truncate = max(prompt_ids.size(1) + completion_ids.size(1) - self.max_length, 0)
1065
+
1066
+ # Truncate left to avoid oom
1067
+ prompt_ids = prompt_ids[:, num_tokens_to_truncate:]
1068
+ prompt_mask = prompt_mask[:, num_tokens_to_truncate:]
1069
+
1070
+ # Concat the prompt and completion
1071
+ prompt_completion_ids = torch.cat((prompt_ids, completion_ids), dim=1)
1072
+ prompt_completion_mask = torch.cat((prompt_mask, completion_mask), dim=1)
1073
+
1074
+ # Prepare model kwargs with vision inputs if available
1075
+ model_kwargs = {"attention_mask": prompt_completion_mask}
1076
+ if vision_inputs is not None:
1077
+ if "pixel_values" in vision_inputs:
1078
+ model_kwargs["pixel_values"] = vision_inputs["pixel_values"]
1079
+ if "pixel_attention_mask" in vision_inputs:
1080
+ model_kwargs["pixel_attention_mask"] = vision_inputs["pixel_attention_mask"]
1081
+ if "image_sizes" in vision_inputs:
1082
+ model_kwargs["image_sizes"] = vision_inputs["image_sizes"]
1083
+ if "image_grid_thw" in vision_inputs:
1084
+ model_kwargs["image_grid_thw"] = vision_inputs["image_grid_thw"]
1085
+
1086
+ # Get the logprobs of the completions from the model
1087
+ output = model(prompt_completion_ids, **model_kwargs)
1088
+
1089
+ # There is 1 offset, because the model predicts the next token
1090
+ prompt_len = prompt_ids.size(1)
1091
+ start_idx = prompt_len - 1 if prompt_len > 0 else 0
1092
+ # Only slice off the last logit when we have a prompt, otherwise we need all logits
1093
+ end_idx = -1 if prompt_len > 0 else None
1094
+ logits = output.logits[:, start_idx:end_idx]
1095
+
1096
+ # Take the completion tokens logprob
1097
+ logprobs = torch.take_along_dim(logits.log_softmax(dim=-1), completion_ids.unsqueeze(-1), dim=2).squeeze(-1)
1098
+ return logprobs
1099
+
1100
+ def training_step(
1101
+ self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None
1102
+ ) -> torch.Tensor:
1103
+ model.train()
1104
+
1105
+ prompts = inputs["prompt"]
1106
+ batch_size = len(prompts)
1107
+
1108
+ # Handle images for VLM support
1109
+ has_images = "image" in inputs
1110
+ images = None
1111
+ if has_images:
1112
+ images = inputs["image"]
1113
+ # Convert conversational prompts to include image tokens
1114
+ for prompt in prompts:
1115
+ if isinstance(prompt, list):
1116
+ for message in prompt:
1117
+ if not isinstance(message, dict):
1118
+ continue
1119
+ content = message.get("content")
1120
+ role = message.get("role")
1121
+ if isinstance(content, str):
1122
+ if role == "user":
1123
+ message["content"] = [{"type": "image"}, {"type": "text", "text": content}]
1124
+ elif role == "system":
1125
+ message["content"] = [{"type": "text", "text": content}]
1126
+
1127
+ if self.args.use_vllm:
1128
+ prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate_vllm(prompts, images)
1129
+ else:
1130
+ prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate(model, prompts, images)
1131
+
1132
+ contain_eos_token = torch.any(completion_ids == self._tokenizer.eos_token_id, dim=-1)
1133
+
1134
+ # Extract vision inputs if available for VLM support
1135
+ vision_inputs = None
1136
+ if has_images and self.is_vision_model and not self.args.use_vllm:
1137
+ # For vision models with transformers generation, we need to prepare vision inputs
1138
+ # Process the images to get vision inputs that can be passed through the forward pass
1139
+ vision_inputs = {}
1140
+ kwargs = {"images": [[img] for img in images]}
1141
+ processed = self.processing_class(
1142
+ text=[""] * len(images), # Dummy text for vision processing
1143
+ return_tensors="pt",
1144
+ **kwargs,
1145
+ )
1146
+ # Handle DataParallel wrapped models
1147
+ model_device = getattr(model, "device", None)
1148
+ model_dtype = getattr(model, "dtype", None)
1149
+ if model_device is None and hasattr(model, "module"):
1150
+ model_device = model.module.device
1151
+ model_dtype = model.module.dtype
1152
+ # Move vision tensors to device and convert to model dtype
1153
+ # Need to duplicate for 2 completions per prompt
1154
+ if "pixel_values" in processed:
1155
+ vision_inputs["pixel_values"] = (
1156
+ processed["pixel_values"].to(model_device, dtype=model_dtype).repeat(2, 1, 1, 1)
1157
+ )
1158
+ if "pixel_attention_mask" in processed:
1159
+ vision_inputs["pixel_attention_mask"] = processed["pixel_attention_mask"].to(model_device).repeat(2, 1)
1160
+ if "image_sizes" in processed:
1161
+ vision_inputs["image_sizes"] = processed["image_sizes"].to(model_device).repeat(2, 1)
1162
+ if "image_grid_thw" in processed:
1163
+ vision_inputs["image_grid_thw"] = processed["image_grid_thw"].to(model_device).repeat(2, 1)
1164
+
1165
+ logprobs = self._forward(model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs)
1166
+ with torch.no_grad():
1167
+ if self.ref_model is not None:
1168
+ ref_logprobs = self._forward(
1169
+ self.ref_model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs
1170
+ )
1171
+ else: # peft case: we just need to disable the adapter
1172
+ with self.model.disable_adapter():
1173
+ ref_logprobs = self._forward(
1174
+ self.model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs
1175
+ )
1176
+
1177
+ # Decode the completions, and format them if the input is conversational
1178
+ device = logprobs.device
1179
+ completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
1180
+ if is_conversational({"prompt": prompts[0]}):
1181
+ completions = [[{"role": "assistant", "content": completion}] for completion in completions]
1182
+
1183
+ # Get the reward from reward functions
1184
+ # First create completion_ids_list for custom reward functions
1185
+ completion_ids_list = [completion_ids[i].tolist() for i in range(completion_ids.shape[0])]
1186
+
1187
+ # Extract additional fields from inputs for reward functions
1188
+ reward_kwargs = {}
1189
+ keys = [key for key in inputs if key not in ["prompt"]]
1190
+ for key in keys:
1191
+ if isinstance(inputs[key], (list, tuple)):
1192
+ # Repeat input fields to match number of completions (2 per prompt)
1193
+ reward_kwargs[key] = inputs[key] * 2
1194
+ else:
1195
+ reward_kwargs[key] = inputs[key]
1196
+
1197
+ # Calculate rewards using reward functions
1198
+ rewards = self._calculate_rewards_from_functions(
1199
+ prompts=2 * prompts, completions=completions, completion_ids_list=completion_ids_list, **reward_kwargs
1200
+ )
1201
+
1202
+ # Apply missing EOS penalty if configured
1203
+ if self.args.missing_eos_penalty is not None:
1204
+ rewards[~contain_eos_token] -= self.args.missing_eos_penalty
1205
+
1206
+ # Split rewards into chosen/rejected pairs
1207
+ first_half, second_half = rewards.split(batch_size)
1208
+ mask = first_half >= second_half
1209
+
1210
+ batch_range = torch.arange(batch_size, device=device)
1211
+ chosen_indices = batch_range + (~mask * batch_size)
1212
+ rejected_indices = batch_range + (mask * batch_size)
1213
+
1214
+ # Build tensor so that the first half is the chosen examples and the second half the rejected examples
1215
+ cr_indices = torch.cat((chosen_indices, rejected_indices), dim=0) # cr = chosen and rejected
1216
+ cr_logprobs = logprobs[cr_indices]
1217
+ cr_ref_logprobs = ref_logprobs[cr_indices]
1218
+
1219
+ # mask out the padding tokens
1220
+ padding_mask = ~completion_mask.bool()
1221
+ cr_padding_mask = padding_mask[cr_indices]
1222
+
1223
+ cr_logprobs_sum = (cr_logprobs * ~cr_padding_mask).sum(1)
1224
+ cr_ref_logprobs_sum = (cr_ref_logprobs * ~cr_padding_mask).sum(1)
1225
+
1226
+ # Split the chosen and rejected examples
1227
+ chosen_logprobs_sum, rejected_logprobs_sum = torch.split(cr_logprobs_sum, batch_size)
1228
+ chosen_ref_logprobs_sum, rejected_ref_logprobs_sum = torch.split(cr_ref_logprobs_sum, batch_size)
1229
+ pi_logratios = chosen_logprobs_sum - rejected_logprobs_sum
1230
+ ref_logratios = chosen_ref_logprobs_sum - rejected_ref_logprobs_sum
1231
+
1232
+ logits = pi_logratios - ref_logratios
1233
+
1234
+ if self.args.loss_type == "sigmoid":
1235
+ losses = -F.logsigmoid(self.beta * logits)
1236
+ elif self.args.loss_type == "ipo":
1237
+ losses = (logits - 1 / (2 * self.beta)) ** 2
1238
+ else:
1239
+ raise NotImplementedError(f"invalid loss type {self.args.loss_type}")
1240
+
1241
+ loss = losses.mean()
1242
+
1243
+ # Log everything
1244
+ if self.reward_funcs is not None:
1245
+ # When using reward_funcs, we have rewards instead of scores
1246
+ scores_margin = rewards[chosen_indices] - rewards[rejected_indices]
1247
+ self.stats["objective/scores_margin"].append(
1248
+ self.accelerator.gather_for_metrics(scores_margin.mean()).mean().item()
1249
+ )
1250
+ self.stats["objective/scores"].append(self.accelerator.gather_for_metrics(rewards.mean()).mean().item())
1251
+ self.stats["val/contain_eos_token"].append(contain_eos_token.float().mean().item())
1252
+ self.stats["logps/chosen"].append(self.accelerator.gather_for_metrics(chosen_logprobs_sum).mean().item())
1253
+ self.stats["logps/rejected"].append(self.accelerator.gather_for_metrics(rejected_logprobs_sum).mean().item())
1254
+
1255
+ kl = logprobs - ref_logprobs
1256
+ mean_kl = kl.sum(1).mean()
1257
+ self.stats["objective/kl"].append(self.accelerator.gather_for_metrics(mean_kl).mean().item())
1258
+ non_score_reward = (-self.beta * kl).sum(1)
1259
+ mean_non_score_reward = non_score_reward.mean()
1260
+ self.stats["objective/non_score_reward"].append(
1261
+ self.accelerator.gather_for_metrics(mean_non_score_reward).mean().item()
1262
+ )
1263
+ if self.reward_funcs is not None:
1264
+ # Calculate RLHF reward by combining rewards with non_score_reward
1265
+ rlhf_reward = rewards + non_score_reward
1266
+ self.stats["objective/rlhf_reward"].append(self.accelerator.gather_for_metrics(rlhf_reward).mean().item())
1267
+
1268
+ mean_entropy = -logprobs.sum(1).mean()
1269
+ self.stats["objective/entropy"].append(self.accelerator.gather_for_metrics(mean_entropy).mean().item())
1270
+ chosen_rewards = self.beta * (chosen_logprobs_sum - chosen_ref_logprobs_sum)
1271
+ gathered_chosen_rewards = self.accelerator.gather_for_metrics(chosen_rewards)
1272
+ self.stats["rewards/chosen"].append(gathered_chosen_rewards.mean().item())
1273
+ rejected_rewards = self.beta * (rejected_logprobs_sum - rejected_ref_logprobs_sum)
1274
+ gathered_rejected_rewards = self.accelerator.gather_for_metrics(rejected_rewards)
1275
+ self.stats["rewards/rejected"].append(gathered_rejected_rewards.mean().item())
1276
+ margin = gathered_chosen_rewards - gathered_rejected_rewards
1277
+ self.stats["rewards/margins"].append(margin.mean().item())
1278
+ accuracy = margin > 0
1279
+ self.stats["rewards/accuracies"].append(accuracy.float().mean().item())
1280
+ self.stats["beta"].append(self.beta)
1281
+
1282
+ if (
1283
+ self.args.torch_empty_cache_steps is not None
1284
+ and self.state.global_step % self.args.torch_empty_cache_steps == 0
1285
+ ):
1286
+ empty_cache()
1287
+
1288
+ kwargs = {}
1289
+
1290
+ # For LOMO optimizers you need to explicitly use the learning rate
1291
+ if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]:
1292
+ kwargs["learning_rate"] = self._get_learning_rate()
1293
+
1294
+ if self.args.n_gpu > 1:
1295
+ loss = loss.mean() # mean() to average on multi-gpu parallel training
1296
+
1297
+ self.accelerator.backward(loss, **kwargs)
1298
+
1299
+ return loss.detach() / self.args.gradient_accumulation_steps
1300
+
1301
+ # Same as Trainer._maybe_log_save_evaluate but log our metrics
1302
+ def _maybe_log_save_evaluate(
1303
+ self, tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval, start_time, learning_rate=None
1304
+ ):
1305
+ if self.control.should_log and self.state.global_step > self._globalstep_last_logged:
1306
+ logs: dict[str, float] = {}
1307
+
1308
+ # all_gather + mean() to get average loss over all processes
1309
+ if Version(transformers.__version__) >= Version("5.2.0"):
1310
+ tr_loss_scalar = nested_gather(tr_loss, self.args.parallel_mode).mean().item()
1311
+ else:
1312
+ tr_loss_scalar = self._nested_gather(tr_loss).mean().item()
1313
+
1314
+ # reset tr_loss to zero
1315
+ tr_loss -= tr_loss
1316
+
1317
+ logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)
1318
+ if grad_norm is not None:
1319
+ logs["grad_norm"] = grad_norm.detach().item() if isinstance(grad_norm, torch.Tensor) else grad_norm
1320
+ if learning_rate is not None:
1321
+ logs["learning_rate"] = learning_rate
1322
+ else:
1323
+ logs["learning_rate"] = self._get_learning_rate()
1324
+
1325
+ # Add our metrics
1326
+ for key, val in self.stats.items():
1327
+ logs[key] = sum(val) / len(val)
1328
+ self.stats = {key: [] for key in self.stats} # reset stats
1329
+
1330
+ self._total_loss_scalar += tr_loss_scalar
1331
+ self._globalstep_last_logged = self.state.global_step
1332
+ self.store_flos()
1333
+ self.log(logs, start_time)
1334
+
1335
+ metrics = None
1336
+ if self.control.should_evaluate:
1337
+ metrics = self._evaluate(trial, ignore_keys_for_eval)
1338
+ is_new_best_metric = self._determine_best_metric(metrics=metrics, trial=trial)
1339
+
1340
+ if self.args.save_strategy == "best":
1341
+ self.control.should_save = is_new_best_metric
1342
+
1343
+ if self.control.should_save:
1344
+ self._save_checkpoint(model, trial)
1345
+ self.control = self.callback_handler.on_save(self.args, self.state, self.control)
1346
+
1347
+ # Ensure the model card is saved along with the checkpoint
1348
+ def _save_checkpoint(self, model, trial):
1349
+ if self.args.hub_model_id is None:
1350
+ model_name = Path(self.args.output_dir).name
1351
+ else:
1352
+ model_name = self.args.hub_model_id.split("/")[-1]
1353
+ self.create_model_card(model_name=model_name)
1354
+ super()._save_checkpoint(model, trial)
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/openenv/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .utils import generate_rollout_completions
16
+
17
+
18
+ __all__ = ["generate_rollout_completions"]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/openenv/utils.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Any
16
+
17
+ import torch
18
+
19
+ from ...data_utils import is_conversational
20
+ from ...extras.profiling import profiling_context
21
+ from ...import_utils import is_vllm_available
22
+
23
+
24
+ if is_vllm_available():
25
+ from vllm import SamplingParams
26
+ from vllm.sampling_params import StructuredOutputsParams
27
+
28
+
29
+ def _build_base_generation_kwargs(
30
+ trainer,
31
+ overrides: dict[str, Any] | None = None,
32
+ ) -> dict[str, Any]:
33
+ """Build base generation kwargs common to both colocate and server modes."""
34
+ generation_kwargs: dict[str, Any] = {
35
+ "n": 1,
36
+ "temperature": trainer.temperature,
37
+ "top_k": trainer.top_k,
38
+ "min_p": 0.0 if trainer.min_p is None else trainer.min_p,
39
+ "max_tokens": trainer.max_completion_length,
40
+ }
41
+ if trainer.repetition_penalty is not None:
42
+ generation_kwargs["repetition_penalty"] = trainer.repetition_penalty
43
+ if trainer.top_p is not None:
44
+ generation_kwargs["top_p"] = trainer.top_p
45
+
46
+ if trainer.args.generation_kwargs is not None:
47
+ generation_kwargs.update(trainer.args.generation_kwargs)
48
+
49
+ if overrides is not None:
50
+ generation_kwargs.update(overrides)
51
+
52
+ generation_kwargs = {key: value for key, value in generation_kwargs.items() if value is not None}
53
+
54
+ if generation_kwargs.get("n", 1) != 1:
55
+ raise ValueError("generate_rollout_completions expects n=1.")
56
+
57
+ return generation_kwargs
58
+
59
+
60
+ def _build_colocate_sampling_params(
61
+ trainer,
62
+ overrides: dict[str, Any] | None = None,
63
+ *,
64
+ logprobs: bool = True,
65
+ ) -> "SamplingParams":
66
+ """Build SamplingParams for colocate mode."""
67
+ generation_kwargs = _build_base_generation_kwargs(trainer, overrides)
68
+
69
+ # Add colocate-specific parameters
70
+ if trainer.vllm_generation.structured_outputs_regex:
71
+ generation_kwargs["structured_outputs"] = StructuredOutputsParams(
72
+ regex=trainer.vllm_generation.structured_outputs_regex
73
+ )
74
+ if logprobs:
75
+ generation_kwargs["logprobs"] = 0
76
+
77
+ return SamplingParams(**generation_kwargs)
78
+
79
+
80
+ def _build_server_generation_kwargs(
81
+ trainer,
82
+ overrides: dict[str, Any] | None = None,
83
+ ) -> dict[str, Any]:
84
+ """Build generation kwargs for server mode."""
85
+ return _build_base_generation_kwargs(trainer, overrides)
86
+
87
+
88
+ def generate_rollout_completions(
89
+ trainer,
90
+ prompts: list[str],
91
+ *,
92
+ generation_overrides: dict[str, Any] | None = None,
93
+ as_chat: bool | None = None,
94
+ ) -> list[dict[str, Any]]:
95
+ """
96
+ Generate completions for custom rollouts when vLLM is running in colocate or server mode.
97
+
98
+ Returns one result per prompt, containing prompt and completion token ids along with per-token log probabilities
99
+ and the generated text.
100
+ """
101
+
102
+ if not prompts:
103
+ return []
104
+
105
+ if not trainer.use_vllm:
106
+ raise RuntimeError("Custom rollouts require vLLM to call generate_rollout_completions.")
107
+
108
+ if trainer.vllm_mode == "server":
109
+ return _generate_rollout_completions_server(trainer, prompts, generation_overrides, as_chat)
110
+ elif trainer.vllm_mode == "colocate":
111
+ return _generate_rollout_completions_colocate(trainer, prompts, generation_overrides, as_chat)
112
+ else:
113
+ raise ValueError(f"vllm_mode must be 'server' or 'colocate', got '{trainer.vllm_mode}'")
114
+
115
+
116
+ def _generate_rollout_completions_server(
117
+ trainer,
118
+ prompts: list[str],
119
+ generation_overrides: dict[str, Any] | None = None,
120
+ as_chat: bool | None = None,
121
+ ) -> list[dict[str, Any]]:
122
+ """Generate completions using vLLM server mode."""
123
+ generation_kwargs = _build_server_generation_kwargs(trainer, generation_overrides)
124
+
125
+ if as_chat is None:
126
+ as_chat = prompts and is_conversational({"prompt": prompts[0]})
127
+
128
+ with profiling_context(trainer, "vLLM.generate_rollout_server"):
129
+ if as_chat:
130
+ # Prompts are raw message dicts; use .chat() so the vLLM server applies the chat template
131
+ output = trainer.vllm_generation.vllm_client.chat(
132
+ messages=prompts,
133
+ **generation_kwargs,
134
+ chat_template_kwargs=trainer.chat_template_kwargs,
135
+ tools=trainer.tools or None,
136
+ chat_template=trainer.chat_template,
137
+ )
138
+ else:
139
+ output = trainer.vllm_generation.vllm_client.generate(prompts=prompts, **generation_kwargs)
140
+
141
+ # Format results to match colocate output format
142
+ results: list[dict[str, Any]] = []
143
+ for i in range(len(prompts)):
144
+ results.append(
145
+ {
146
+ "prompt_ids": output["prompt_ids"][i],
147
+ "completion_ids": list(output["completion_ids"][i]),
148
+ "logprobs": list(output["logprobs"][i]),
149
+ "text": trainer.processing_class.decode(output["completion_ids"][i], skip_special_tokens=True),
150
+ }
151
+ )
152
+
153
+ return results
154
+
155
+
156
+ def _generate_rollout_completions_colocate(
157
+ trainer,
158
+ prompts: list[str],
159
+ generation_overrides: dict[str, Any] | None = None,
160
+ as_chat: bool | None = None,
161
+ ) -> list[dict[str, Any]]:
162
+ """Generate completions using vLLM colocate mode."""
163
+ sampling_params = _build_colocate_sampling_params(trainer, generation_overrides)
164
+ prompts_for_generation = prompts
165
+ original_size = len(prompts)
166
+
167
+ if trainer.vllm_tensor_parallel_size > 1:
168
+ gathered_prompts = [None for _ in range(trainer.vllm_tensor_parallel_size)]
169
+ torch.distributed.all_gather_object(gathered_prompts, prompts, group=trainer.vllm_generation.tp_group)
170
+ prompts_for_generation = [prompt for group_prompts in gathered_prompts for prompt in group_prompts]
171
+
172
+ if as_chat is None:
173
+ as_chat = prompts_for_generation and is_conversational({"prompt": prompts_for_generation[0]})
174
+
175
+ if trainer.args.vllm_enable_sleep_mode:
176
+ trainer.vllm_generation.llm.wake_up(tags=["kv_cache"])
177
+ # Work around for https://github.com/vllm-project/vllm/issues/29341
178
+ trainer.vllm_generation.llm.collective_rpc("reload_weights")
179
+
180
+ with profiling_context(trainer, "vLLM.generate_rollout"):
181
+ if as_chat:
182
+ vllm_outputs = trainer.vllm_generation.llm.chat(
183
+ prompts_for_generation, sampling_params=sampling_params, use_tqdm=False
184
+ )
185
+ else:
186
+ vllm_outputs = trainer.vllm_generation.llm.generate(
187
+ prompts_for_generation, sampling_params=sampling_params, use_tqdm=False
188
+ )
189
+
190
+ results: list[dict[str, Any]] = []
191
+ for request in vllm_outputs:
192
+ if not request.outputs:
193
+ results.append({"prompt_ids": request.prompt_token_ids, "completion_ids": [], "logprobs": [], "text": ""})
194
+ continue
195
+ sequence = request.outputs[0]
196
+ logprobs = [next(iter(token_logprob.values())).logprob for token_logprob in sequence.logprobs]
197
+ results.append(
198
+ {
199
+ "prompt_ids": request.prompt_token_ids,
200
+ "completion_ids": sequence.token_ids,
201
+ "logprobs": logprobs,
202
+ "text": sequence.text,
203
+ }
204
+ )
205
+
206
+ if trainer.vllm_tensor_parallel_size > 1:
207
+ local_rank_in_group = torch.distributed.get_rank(group=trainer.vllm_generation.tp_group)
208
+ tp_slice = slice(local_rank_in_group * original_size, (local_rank_in_group + 1) * original_size)
209
+ results = results[tp_slice]
210
+
211
+ if trainer.args.vllm_enable_sleep_mode:
212
+ trainer.vllm_generation.llm.sleep(level=2)
213
+
214
+ return results
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/openreward/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from ._spec import OpenRewardSpec
16
+
17
+
18
+ __all__ = ["OpenRewardSpec"]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/openreward/_spec.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """User-facing spec object for the OpenReward × TRL integration.
16
+
17
+ The user constructs **one** ``OpenRewardSpec`` (a thin specification holding the env target + a few options) and reads
18
+ three properties off of it — ``.train_dataset``, ``.environment_factory``, ``.reward_funcs`` — each of which plugs
19
+ directly into the matching ``GRPOTrainer`` kwarg:
20
+
21
+ ```python
22
+ from trl import GRPOConfig, GRPOTrainer
23
+ from trl.experimental.openreward import OpenRewardSpec
24
+
25
+ spec = OpenRewardSpec("Eigent/SETA", num_tasks=64)
26
+
27
+ trainer = GRPOTrainer(
28
+ model="Qwen/Qwen3-4B",
29
+ args=GRPOConfig(num_generations=2, max_steps=5, max_tool_calling_iterations=20),
30
+ train_dataset=spec.train_dataset,
31
+ environment_factory=spec.environment_factory,
32
+ reward_funcs=spec.reward_funcs,
33
+ )
34
+ trainer.train()
35
+ ```
36
+
37
+ Backed by the official ``openreward`` SDK (lazy-imported); install with ``pip install trl[openreward]``.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import logging
43
+ import os
44
+ from collections.abc import Callable
45
+ from functools import cached_property
46
+ from typing import Any
47
+
48
+ from .environment import _import_openreward, _RolloutEnvironment, _spec_to_dict
49
+
50
+
51
+ logger = logging.getLogger(__name__)
52
+
53
+
54
+ def _tool_specs_from_session_list_tools(out: Any) -> list[Any]:
55
+ """Normalise ``session.list_tools()`` / ``environment.list_tools()`` to a flat list.
56
+
57
+ The client SDK (``openreward.api``) returns ``list[ToolSpec]`` directly.
58
+ """
59
+ return list(out)
60
+
61
+
62
+ def _to_spec(task) -> dict[str, Any]:
63
+ """Normalise an SDK ``Task`` (or already-a-dict) to its task_spec dict."""
64
+ if isinstance(task, dict):
65
+ return task
66
+ return task.task_spec
67
+
68
+
69
+ def _outcome_only_reward_func(environments, **_):
70
+ """Default reward function: last non-null reward in each rollout's trajectory.
71
+
72
+ Suitable for sparse-outcome envs (e.g. SETA, where only `submit_solution` returns a non-null reward). Override by
73
+ passing a different callable to ``reward_funcs=``.
74
+ """
75
+ return [env.reward for env in environments]
76
+
77
+
78
+ class OpenRewardSpec:
79
+ """Single spec object that wires an ORS environment into a TRL trainer.
80
+
81
+ Args:
82
+ target (`str`):
83
+ Either an openreward.ai catalog name (`"Eigent/SETA"`) or a URL pointing at any ORS server
84
+ (`"https://you-seta.hf.space"`, `"http://localhost:8080"`). Auto-detected by the presence of `://` in the
85
+ string.
86
+ num_tasks (`int`, *optional*):
87
+ Cap on the number of tasks pulled into the dataset. ``None`` uses every task the env exposes.
88
+ split (`str`, *optional*, defaults to `"train"`):
89
+ Which split's task list to draw from.
90
+ indices (`list[int]`, *optional*):
91
+ Specific task indices to train on. Mutually exclusive with ``num_tasks``. Useful for debugging or
92
+ curriculum subsets.
93
+ api_key (`str`, *optional*):
94
+ ``OPENREWARD_API_KEY`` override. Only used when ``target`` is a catalog name.
95
+ secrets (`dict[str, str]`, *optional*):
96
+ Per-session secrets forwarded to ``env.session(secrets=)``.
97
+ env_name (`str`, *optional*):
98
+ Override for the env name to look up on the server. Rarely needed.
99
+ include_metadata (`bool`, *optional*, defaults to `True`):
100
+ Fold per-task metadata (`difficulty`, `category`, `tags`, ...) into the dataset rows so reward funcs can
101
+ read them via TRL's ``inputs`` argument.
102
+ discover_task_tools (`bool`, *optional*, defaults to `True`):
103
+ If ``True``, opens a short-lived ORS session and uses ``session.list_tools()`` so task-specific tools
104
+ (``GET …/task_tools`` per ORS — e.g. ``@tool(shared=False)`` and ``list_task_tools()``) are bound for GRPO.
105
+ If probe fails, falls back to ``environment.list_tools()`` only. Set ``False`` to skip the extra session
106
+ (shared tools only / offline quirks).
107
+ task_tools_discovery_index (`int`, *optional*):
108
+ Task index used only for the discovery session when set; **overrides** multi-index probing below. When
109
+ omitted and ``indices=`` is set, discovery opens one probe session per **distinct** entry in ``indices``
110
+ (sorted) and **merges** tool specs by name so task-specific tools from every listed task are bound. When
111
+ omitted and ``num_tasks`` / full-list mode is used, probes task ``0`` only. Ignored when
112
+ ``discover_task_tools=False``.
113
+ """
114
+
115
+ def __init__(
116
+ self,
117
+ target: str,
118
+ *,
119
+ num_tasks: int | None = None,
120
+ split: str = "train",
121
+ indices: list[int] | None = None,
122
+ api_key: str | None = None,
123
+ secrets: dict[str, str] | None = None,
124
+ env_name: str | None = None,
125
+ include_metadata: bool = True,
126
+ discover_task_tools: bool = True,
127
+ task_tools_discovery_index: int | None = None,
128
+ ) -> None:
129
+ if num_tasks is not None and indices is not None:
130
+ raise ValueError("Provide num_tasks or indices, not both.")
131
+
132
+ self._target = target
133
+ self._is_url = "://" in target
134
+ self._num_tasks = num_tasks
135
+ self._split = split
136
+ self._indices = indices
137
+ self._api_key = api_key
138
+ self._secrets = secrets
139
+ self._env_name = env_name
140
+ self._include_metadata = include_metadata
141
+ self._discover_task_tools = discover_task_tools
142
+ self._task_tools_discovery_index = task_tools_discovery_index
143
+
144
+ # ── public surface ──────────────────────────────────────────────
145
+
146
+ @cached_property
147
+ def train_dataset(self):
148
+ """A `datasets.Dataset` derived from the env's task list.
149
+
150
+ Plugs directly into TRL's ``train_dataset=`` slot. Built lazily on first access. Has at minimum:
151
+ - `prompt`: empty user message (TRL appends the env's prompt).
152
+ - `task_index`: int passed to the adapter's `reset()`.
153
+ - per-task metadata columns (when `include_metadata=True`).
154
+ """
155
+ from datasets import Dataset
156
+
157
+ env = self._sdk_env
158
+
159
+ # When the user asked for a specific subset (`num_tasks` cap or
160
+ # explicit `indices`), fetch only those — `list_tasks` returns
161
+ # the whole split (1376 entries for SETA, etc.) and is slow on
162
+ # the platform. Per-index `get_task` is fast and cheap.
163
+ if self._indices is not None:
164
+ indexes = list(self._indices)
165
+ task_specs = [_to_spec(env.get_task(self._split, i)) for i in indexes]
166
+ elif self._num_tasks is not None:
167
+ n_total = env.num_tasks(self._split)
168
+ n = min(self._num_tasks, n_total)
169
+ indexes = list(range(n))
170
+ task_specs = [_to_spec(env.get_task(self._split, i)) for i in indexes]
171
+ else:
172
+ # No cap — fetch everything in one shot.
173
+ try:
174
+ tasks = env.list_tasks(self._split)
175
+ except Exception: # noqa: BLE001
176
+ n = env.num_tasks(self._split)
177
+ tasks = [env.get_task(self._split, i) for i in range(n)]
178
+ task_specs = [_to_spec(t) for t in tasks]
179
+ indexes = list(range(len(task_specs)))
180
+
181
+ rows: dict[str, list[Any]] = {
182
+ "prompt": [[{"role": "user", "content": ""}] for _ in indexes],
183
+ "task_index": indexes,
184
+ }
185
+
186
+ if self._include_metadata and task_specs:
187
+ metadata_keys: set[str] = set()
188
+ for spec in task_specs:
189
+ if isinstance(spec, dict):
190
+ metadata_keys.update(spec.keys())
191
+ # Never let a task-spec key overwrite our reserved row columns
192
+ # (e.g. an env that exposes a `prompt` task-spec field would
193
+ # otherwise replace our chat-format prompt with a raw string).
194
+ metadata_keys -= rows.keys()
195
+ for key in sorted(metadata_keys):
196
+ rows[key] = [s.get(key) if isinstance(s, dict) else None for s in task_specs]
197
+
198
+ return Dataset.from_dict(rows)
199
+
200
+ @cached_property
201
+ def environment_factory(self) -> Callable[[], _RolloutEnvironment]:
202
+ """Zero-arg callable that returns a fresh ``_RolloutEnvironment``.
203
+
204
+ Plugs directly into TRL's ``environment_factory=`` slot. TRL calls this once per rollout at trainer
205
+ construction time, so each rollout has an isolated ORS session. Reuses the spec's already-discovered SDK env +
206
+ tool specs to skip per-env HTTP at trainer init.
207
+ """
208
+ # Pre-fetch tool specs once at the spec level. ORS exposes shared tools on GET /tools and the full
209
+ # shared+task-specific set on GET /task_tools (session-scoped). GRPO inspects methods before reset(), so we
210
+ # must bind every tool the episode will see — use session.list_tools() when discover_task_tools=True.
211
+ env = self._sdk_env
212
+ tool_specs = self._discovered_tool_specs(env)
213
+ client = self._sdk_client
214
+
215
+ # Each spec gets its own `_RolloutEnvironment` subclass so two specs
216
+ # for different envs (different tool sets) never clobber each other's
217
+ # bound methods on the shared parent class.
218
+ rollout_cls = type(f"_RolloutEnvironment_{id(self):x}", (_RolloutEnvironment,), {})
219
+
220
+ kwargs = {
221
+ "split": self._split,
222
+ "secrets": self._effective_secrets(),
223
+ "env_name": self._env_name,
224
+ "_client": client,
225
+ "_env": env,
226
+ "_tool_specs": tool_specs,
227
+ }
228
+ if self._is_url:
229
+ kwargs["base_url"] = self._target
230
+ else:
231
+ kwargs["name"] = self._target
232
+ if self._api_key:
233
+ kwargs["api_key"] = self._api_key
234
+
235
+ kwargs = {k: v for k, v in kwargs.items() if v is not None}
236
+
237
+ def _make() -> _RolloutEnvironment:
238
+ return rollout_cls(**kwargs)
239
+
240
+ return _make
241
+
242
+ @property
243
+ def reward_funcs(self) -> Callable[..., list[float]]:
244
+ """Default outcome-only reward function (last non-null reward per rollout).
245
+
246
+ Plugs directly into TRL's ``reward_funcs=`` slot. Stable identity — module-level function, picklable for
247
+ multi-process workers.
248
+ """
249
+ return _outcome_only_reward_func
250
+
251
+ # ── internals ───────────────────────────────────────────────────
252
+
253
+ def _effective_secrets(self) -> dict[str, str] | None:
254
+ """Auto-forward ``OPENREWARD_API_KEY`` as the conventional ``api_key``
255
+ per-session secret on platform mode (most envs need it)."""
256
+ if self._secrets is not None or self._is_url:
257
+ return self._secrets
258
+ key = self._api_key or os.environ.get("OPENREWARD_API_KEY")
259
+ return {"api_key": key} if key else None
260
+
261
+ def _task_tools_probe_indices(self) -> list[int]:
262
+ """Pick task indices for ``session.list_tools()`` discovery (ORS ``/task_tools``)."""
263
+ if self._task_tools_discovery_index is not None:
264
+ return [self._task_tools_discovery_index]
265
+ if self._indices is not None:
266
+ return sorted(set(self._indices))
267
+ return [0]
268
+
269
+ def _discovered_tool_specs(self, env):
270
+ """Return ToolSpec list for binding on `_RolloutEnvironment`.
271
+
272
+ Prefer ``session.list_tools()`` (ORS ``/task_tools``) so task-specific tools match what the OpenReward SDK
273
+ exposes during rollouts. Fall back to ``environment.list_tools()`` on failure or when disabled.
274
+ """
275
+ shared = env.list_tools()
276
+ shared = _tool_specs_from_session_list_tools(shared)
277
+ if not self._discover_task_tools:
278
+ return shared
279
+
280
+ try:
281
+ n = env.num_tasks(self._split)
282
+ except Exception as e: # noqa: BLE001
283
+ logger.warning("OpenRewardSpec: num_tasks failed (%s); using shared tools only.", e)
284
+ return shared
285
+
286
+ if n <= 0:
287
+ return shared
288
+
289
+ probe_indices = self._task_tools_probe_indices()
290
+ bad = [idx for idx in probe_indices if idx < 0 or idx >= n]
291
+ if bad:
292
+ logger.warning(
293
+ "OpenRewardSpec: task tool probe index(es) %s out of range for split=%r (num_tasks=%s); ignoring them.",
294
+ bad,
295
+ self._split,
296
+ n,
297
+ )
298
+ probe_indices = [idx for idx in probe_indices if 0 <= idx < n]
299
+ if not probe_indices:
300
+ logger.warning("OpenRewardSpec: no valid task indices for tool discovery; using shared tools only.")
301
+ return shared
302
+
303
+ secrets = self._effective_secrets()
304
+ merged: list[Any] = []
305
+ seen: dict[str, Any] = {}
306
+ any_probe_ok = False
307
+
308
+ for idx in probe_indices:
309
+ try:
310
+ with env.session(split=self._split, index=idx, secrets=secrets) as sess:
311
+ specs = _tool_specs_from_session_list_tools(sess.list_tools())
312
+ except Exception as e: # noqa: BLE001
313
+ logger.warning(
314
+ "OpenRewardSpec: session tool discovery failed for task_index=%s (%s); skipping.",
315
+ idx,
316
+ e,
317
+ )
318
+ continue
319
+ any_probe_ok = True
320
+ for spec in specs:
321
+ d = _spec_to_dict(spec)
322
+ name = d["name"]
323
+ if name not in seen:
324
+ seen[name] = spec
325
+ merged.append(spec)
326
+ elif _spec_to_dict(seen[name]) != d:
327
+ logger.warning(
328
+ "OpenRewardSpec: tool %r has differing schemas across probe tasks; keeping first.",
329
+ name,
330
+ )
331
+
332
+ if not any_probe_ok:
333
+ logger.warning("OpenRewardSpec: all task tool probes failed; using shared tools only.")
334
+ return shared
335
+ return merged
336
+
337
+ @cached_property
338
+ def _sdk_client(self):
339
+ """The shared ``openreward.OpenReward`` client used by `dataset` and `factory`."""
340
+ openreward = _import_openreward()
341
+ kwargs: dict[str, Any] = {}
342
+ if self._api_key:
343
+ kwargs["api_key"] = self._api_key
344
+ elif not self._is_url and "OPENREWARD_API_KEY" in os.environ:
345
+ kwargs["api_key"] = os.environ["OPENREWARD_API_KEY"]
346
+ if self._is_url:
347
+ kwargs["base_url"] = self._target
348
+ return openreward.OpenReward(**kwargs)
349
+
350
+ @cached_property
351
+ def _sdk_env(self):
352
+ """The shared SDK ``Environment`` handle."""
353
+ if self._is_url:
354
+ # Self-hosted single-env URL — pass any name; the SDK redirects.
355
+ # Fallback to "env" matches `_RolloutEnvironment.__init__`.
356
+ target = self._env_name or "env"
357
+ else:
358
+ target = self._target
359
+ return self._sdk_client.environments.get(target)
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/openreward/environment.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """TRL `environment_factory` adapter for any ORS-compliant server.
16
+
17
+ Wraps the official ``openreward`` SDK so platform quirks (X-Secrets encoding, ephemeral session for discovery,
18
+ sticky-routing subdomain, SSE chunk reassembly, ping keepalive, …) are handled by code that ships with the spec. Our
19
+ job is only to expose the SDK's per-rollout session as a TRL-compatible class with dynamically-bound tool methods.
20
+
21
+ Install: ``pip install trl[openreward]``.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import logging
27
+ import os
28
+ import re
29
+ from typing import Any
30
+
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+
35
+ def _import_openreward():
36
+ """Lazy-import the openreward package with a friendly error message."""
37
+ try:
38
+ import openreward
39
+
40
+ return openreward
41
+ except ImportError as e:
42
+ raise ImportError(
43
+ "trl.experimental.openreward requires the `openreward` package. "
44
+ "Install with `pip install trl[openreward]`."
45
+ ) from e
46
+
47
+
48
+ # ── JSON Schema → Python type mapping (used by dynamic tool binding) ──
49
+
50
+ _JSON_TYPE_TO_PY: dict[str, str] = {
51
+ "string": "str",
52
+ "integer": "int",
53
+ "number": "float",
54
+ "boolean": "bool",
55
+ "array": "list",
56
+ "object": "dict",
57
+ }
58
+
59
+ _PY_TYPE_OBJECTS: dict[str, type] = {
60
+ "str": str,
61
+ "int": int,
62
+ "float": float,
63
+ "bool": bool,
64
+ "list": list,
65
+ "dict": dict,
66
+ }
67
+
68
+ _PY_TYPE_FROM_VALUE: dict[type, str] = {
69
+ bool: "bool",
70
+ int: "int",
71
+ float: "float",
72
+ str: "str",
73
+ list: "list",
74
+ dict: "dict",
75
+ }
76
+
77
+
78
+ def _resolve_param_type(pdef: dict[str, Any]) -> str:
79
+ """Pick the best Python type name for one JSON-Schema property.
80
+
81
+ Handles primitive ``"type"``, Pydantic's ``anyOf``/``oneOf`` form for ``Optional[T]``, and falls back to the type
82
+ of ``default``. Critical because transformers' tool-schema generator uses our Python annotations to build the
83
+ schema the model sees.
84
+ """
85
+ t = pdef.get("type")
86
+ if isinstance(t, str) and t in _JSON_TYPE_TO_PY:
87
+ return _JSON_TYPE_TO_PY[t]
88
+ for key in ("anyOf", "oneOf"):
89
+ for opt in pdef.get(key) or []:
90
+ if isinstance(opt, dict):
91
+ inner = opt.get("type")
92
+ if isinstance(inner, str) and inner in _JSON_TYPE_TO_PY and inner != "null":
93
+ return _JSON_TYPE_TO_PY[inner]
94
+ if "default" in pdef and pdef["default"] is not None:
95
+ for value_type, name in _PY_TYPE_FROM_VALUE.items():
96
+ if isinstance(pdef["default"], value_type):
97
+ return name
98
+ return "str"
99
+
100
+
101
+ # ────────────────────────────────────────────────────────────────────
102
+
103
+
104
+ class _RolloutEnvironment:
105
+ """Per-rollout TRL adapter backed by the ``openreward`` SDK.
106
+
107
+ **Internal class.** Users don't construct this directly; they create an :class:`OpenRewardSpec` and pass
108
+ ``spec.environment_factory`` to ``GRPOTrainer``. TRL's trainer then constructs one instance of this per rollout
109
+ slot.
110
+
111
+ The tool surface is built once at construction by reading the env's tools and binding one Python method per ORS
112
+ tool — so swapping the URL or env name is the only thing needed to train against a different environment.
113
+
114
+ Args:
115
+ name (`str`, *optional*):
116
+ openreward.ai catalog name (e.g. ``"Eigent/SETA"``). Mutually exclusive with `base_url`. Requires
117
+ ``OPENREWARD_API_KEY`` (env var or `api_key=`).
118
+ base_url (`str`, *optional*):
119
+ Direct URL of an ORS server (HF Space, local Docker, etc.). Mutually exclusive with `name`.
120
+ env_name (`str`, *optional*):
121
+ Name to look up on the server. Defaults to the canonical name parsed from `name`/`base_url`.
122
+ split (`str`, *optional*, defaults to `"train"`):
123
+ Split passed to ``env.session(split=, index=)``.
124
+ api_key (`str`, *optional*):
125
+ Override for ``OPENREWARD_API_KEY``. Only used with `name=`.
126
+ secrets (`dict[str, str]`, *optional*):
127
+ Per-session secrets. Forwarded to ``env.session(secrets=)``; the SDK encodes them and adds platform-domain
128
+ entries.
129
+ timeout (`float`, *optional*):
130
+ Reserved for future use. The SDK manages its own timeouts.
131
+
132
+ Attributes:
133
+ reward (`float`):
134
+ Last non-null reward in the trajectory (outcome-only convention).
135
+ rewards (`list[float | None]`):
136
+ Per-step reward sequence in tool-call order.
137
+ metadata (`list[dict | None]`):
138
+ Per-step ``ToolOutput.metadata`` dicts.
139
+ finished (`bool`):
140
+ True after a tool returned ``finished: true``.
141
+ last_output (`str`):
142
+ Joined text of the most recent tool result.
143
+ """
144
+
145
+ def __init__(
146
+ self,
147
+ *,
148
+ name: str | None = None,
149
+ base_url: str | None = None,
150
+ env_name: str | None = None,
151
+ split: str = "train",
152
+ api_key: str | None = None,
153
+ secrets: dict[str, str] | None = None,
154
+ timeout: float | None = None,
155
+ _client: Any = None,
156
+ _env: Any = None,
157
+ _tool_specs: list[Any] | None = None,
158
+ ) -> None:
159
+ if (name is None) == (base_url is None):
160
+ raise ValueError("Provide exactly one of: name, base_url.")
161
+
162
+ # Reuse a pre-built client/env when the spec has already discovered
163
+ # them (saves N HTTP calls at trainer init); otherwise build fresh.
164
+ if _client is None:
165
+ openreward = _import_openreward()
166
+ client_kwargs: dict[str, Any] = {}
167
+ if api_key:
168
+ client_kwargs["api_key"] = api_key
169
+ elif name and "OPENREWARD_API_KEY" in os.environ:
170
+ client_kwargs["api_key"] = os.environ["OPENREWARD_API_KEY"]
171
+ if base_url:
172
+ client_kwargs["base_url"] = base_url
173
+ self._client = openreward.OpenReward(**client_kwargs)
174
+ else:
175
+ self._client = _client
176
+
177
+ if _env is None:
178
+ target = name if name is not None else env_name or ""
179
+ if base_url and not target:
180
+ # Self-hosted single-env URL — pass any name; SDK redirects.
181
+ target = "env"
182
+ self._env = self._client.environments.get(target)
183
+ else:
184
+ self._env = _env
185
+
186
+ self._split = split
187
+ self._secrets = secrets
188
+ self._session_cm = None # the SDK context manager itself, retained for clean teardown
189
+ self._session = None # the entered Session object
190
+
191
+ # Episode state — read by the trainer's reward_func.
192
+ self.reward: float = 0.0
193
+ self.rewards: list[float | None] = []
194
+ self.metadata: list[dict[str, Any] | None] = []
195
+ self.finished: bool = False
196
+ self.last_output: str = ""
197
+
198
+ # Bind one Python method per server-side tool. Pre-fetched specs
199
+ # come from the spec object; otherwise we ask the SDK ourselves.
200
+ specs = _tool_specs if _tool_specs is not None else self._env.list_tools()
201
+ for spec in specs:
202
+ _bind_tool_method(self.__class__, _spec_to_dict(spec))
203
+
204
+ # ── TRL contract ─────────────────────────────────────────────────
205
+
206
+ def reset(
207
+ self,
208
+ *,
209
+ task_index: int = 0,
210
+ task_spec: dict[str, Any] | None = None,
211
+ **_: Any,
212
+ ) -> str:
213
+ """Open a fresh ORS session for this rollout.
214
+
215
+ Closes any prior session, starts a new one via the SDK's ``env.session(...)`` context manager, fetches the
216
+ prompt, and returns its text (which TRL appends to the user message).
217
+ """
218
+ self._teardown_session()
219
+ self.reward = 0.0
220
+ self.rewards = []
221
+ self.metadata = []
222
+ self.finished = False
223
+ self.last_output = ""
224
+
225
+ if task_spec is not None:
226
+ from openreward.api.environments.client import Task
227
+
228
+ task = Task(
229
+ server_name=self._env.server,
230
+ environment_name=self._env.name,
231
+ task_spec=task_spec,
232
+ namespace=self._env.namespace,
233
+ )
234
+ cm = self._env.session(task=task, secrets=self._secrets)
235
+ else:
236
+ cm = self._env.session(split=self._split, index=int(task_index), secrets=self._secrets)
237
+
238
+ # Retain the context manager itself so `_teardown_session` can call
239
+ # its __exit__; calling __exit__ on the entered Session alone leaves
240
+ # the CM's exit logic (which deletes the env state + sid) unrun.
241
+ self._session_cm = cm
242
+ self._session = cm.__enter__()
243
+ prompt = self._session.get_prompt()
244
+ return _join_text_blocks(prompt)
245
+
246
+ # Leading underscore so TRL's tool collector at grpo_trainer.py:502-506
247
+ # excludes this from the model's tool surface.
248
+ def _close(self) -> None:
249
+ """Tear down the active session (best-effort)."""
250
+ self._teardown_session()
251
+
252
+ # ── helpers ──────────────────────────────────────────────────────
253
+
254
+ def _teardown_session(self) -> None:
255
+ if self._session_cm is None:
256
+ return
257
+ try:
258
+ # Exit the SDK's Session context manager — this deletes both
259
+ # the per-rollout env state and the sid on the server.
260
+ self._session_cm.__exit__(None, None, None)
261
+ except Exception as e: # noqa: BLE001
262
+ logger.debug("session teardown failed: %s", e)
263
+ self._session_cm = None
264
+ self._session = None
265
+
266
+ def _call_ors_tool(self, tool_name: str, tool_input: dict[str, Any]) -> str:
267
+ """Invoke a server-side tool and update episode state."""
268
+ if self._session is None:
269
+ raise RuntimeError("Cannot call a tool before reset() opens a session.")
270
+
271
+ try:
272
+ out = self._session.call_tool(tool_name, tool_input)
273
+ except Exception as e: # noqa: BLE001
274
+ self.rewards.append(None)
275
+ self.metadata.append(None)
276
+ self.last_output = f"Error: {e}"
277
+ return self.last_output
278
+
279
+ # `out` is `openreward.api.environments.types.ToolOutput` — a stable dataclass
280
+ # with `blocks: list`, `reward: Optional[float]`, `metadata: Optional[dict]`, `finished: bool`.
281
+ text = _join_text_blocks(out.blocks or []) or "(no output)"
282
+
283
+ step_reward: float | None = None
284
+ if out.reward is not None:
285
+ try:
286
+ step_reward = float(out.reward)
287
+ except (TypeError, ValueError):
288
+ step_reward = None
289
+ self.rewards.append(step_reward)
290
+ if step_reward is not None:
291
+ self.reward = step_reward # last-non-null wins (outcome-only convention)
292
+
293
+ self.metadata.append(out.metadata if isinstance(out.metadata, dict) else None)
294
+ self.finished = bool(out.finished)
295
+ self.last_output = text
296
+ return text
297
+
298
+
299
+ # ── dynamic tool binding ─────────────────────────────────────────────
300
+
301
+
302
+ _VALID_TOOL_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
303
+
304
+
305
+ def _bind_tool_method(cls: type, spec: dict[str, Any]) -> None:
306
+ """Generate a typed Python method for one ORS tool spec.
307
+
308
+ Signature comes from the JSON Schema; docstring is Google-style so ``transformers.utils.get_json_schema`` (used by
309
+ vLLM) can produce a correct tool schema for the model.
310
+
311
+ Untrusted text from the server (tool name, descriptions) is never spliced raw into the generated source — the name
312
+ is validated against a Python-identifier regex and the description / per-param descriptions are passed through
313
+ ``repr()`` before being interpolated, so a tool description containing triple quotes can't break binding.
314
+ """
315
+ tool_name = spec["name"]
316
+ if not _VALID_TOOL_NAME.match(tool_name):
317
+ logger.warning("skipping tool with non-identifier name: %r", tool_name)
318
+ return
319
+ if tool_name in cls.__dict__:
320
+ # Already bound by an earlier instance — idempotent skip.
321
+ return
322
+
323
+ description = spec.get("description") or f"Call the {tool_name} tool."
324
+ schema = spec.get("input_schema") or {}
325
+ properties: dict[str, dict[str, Any]] = schema.get("properties") or {}
326
+ required: set[str] = set(schema.get("required") or [])
327
+
328
+ # Required params must come before optional ones in Python — sort.
329
+ required_props = [(n, p) for n, p in properties.items() if n in required]
330
+ optional_props = [(n, p) for n, p in properties.items() if n not in required]
331
+
332
+ params_src: list[str] = []
333
+ annotations: dict[str, type] = {}
334
+ args_doc_lines: list[str] = []
335
+ for pname, pdef in required_props + optional_props:
336
+ if not _VALID_TOOL_NAME.match(pname):
337
+ logger.warning("skipping tool %r — non-identifier param name: %r", tool_name, pname)
338
+ return
339
+ py_type = _resolve_param_type(pdef)
340
+ annotations[pname] = _PY_TYPE_OBJECTS[py_type]
341
+ if pname in required:
342
+ params_src.append(f"{pname}: {py_type}")
343
+ else:
344
+ default = pdef.get("default", None)
345
+ params_src.append(f"{pname}: {py_type} = {default!r}")
346
+ pdesc = pdef.get("description") or pdef.get("title") or pname
347
+ args_doc_lines.append(f" {pname}: {pdesc}")
348
+
349
+ # Build the docstring as a single repr-quoted string so triple-quotes / quotes / newlines in the description or
350
+ # arg text can never close out the generated docstring early.
351
+ docstring = description + (("\n\n Args:\n" + "\n".join(args_doc_lines)) if args_doc_lines else "")
352
+ src = (
353
+ f"def {tool_name}(self, {', '.join(params_src)}) -> str:\n"
354
+ f" {docstring!r}\n"
355
+ f" _kwargs = dict(locals()); _kwargs.pop('self', None)\n"
356
+ f" return self._call_ors_tool({tool_name!r}, _kwargs)\n"
357
+ )
358
+ ns: dict[str, Any] = {}
359
+ exec(src, ns)
360
+ fn = ns[tool_name]
361
+ fn.__qualname__ = f"{cls.__name__}.{tool_name}"
362
+ fn.__annotations__ = {**annotations, "return": str}
363
+ setattr(cls, tool_name, fn)
364
+
365
+
366
+ # ── small utilities ──────────────────────────────────────────────────
367
+
368
+
369
+ def _spec_to_dict(spec: Any) -> dict[str, Any]:
370
+ """Normalise SDK ``ToolSpec`` and dict shapes to the same dict form.
371
+
372
+ ``openreward.api.environments.types.ToolSpec`` is a stable dataclass with ``name``, ``description``,
373
+ ``input_schema`` fields, so direct attribute access is safe.
374
+ """
375
+ if isinstance(spec, dict):
376
+ return spec
377
+ return {
378
+ "name": spec.name,
379
+ "description": spec.description,
380
+ "input_schema": spec.input_schema or {},
381
+ }
382
+
383
+
384
+ def _join_text_blocks(blocks: list[Any]) -> str:
385
+ """Concatenate the ``text`` field of every text block in order.
386
+
387
+ Accepts both SDK ``TextBlock`` dataclasses and plain dicts. Both shapes expose a ``type`` discriminator (`"text"`
388
+ vs `"image"`); non-text blocks are skipped so e.g. ``ImageBlock`` doesn't trip up the join.
389
+ """
390
+ if not blocks:
391
+ return ""
392
+ parts: list[str] = []
393
+ for b in blocks:
394
+ if isinstance(b, dict):
395
+ if b.get("type") != "text":
396
+ continue
397
+ text = b.get("text")
398
+ else:
399
+ if b.type != "text":
400
+ continue
401
+ text = b.text
402
+ if text:
403
+ parts.append(str(text))
404
+ return "\n".join(parts)
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/orpo/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .orpo_config import ORPOConfig
16
+ from .orpo_trainer import ORPOTrainer
17
+
18
+
19
+ __all__ = ["ORPOConfig", "ORPOTrainer"]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/orpo/orpo_config.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ from ...trainer.base_config import _BaseConfig
19
+
20
+
21
+ @dataclass
22
+ class ORPOConfig(_BaseConfig):
23
+ # docstyle-ignore
24
+ r"""
25
+ Configuration class for the [`experimental.orpo.ORPOTrainer`].
26
+
27
+ This class includes only the parameters that are specific to ORPO training. For a full list of training arguments,
28
+ please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
29
+ differ from those in [`~transformers.TrainingArguments`].
30
+
31
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
32
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
33
+ command line.
34
+
35
+ Parameters:
36
+ max_length (`int` or `None`, *optional*, defaults to `1024`):
37
+ Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want
38
+ to use the default data collator.
39
+ max_completion_length (`int`, *optional*):
40
+ Maximum length of the completion. This argument is required if you want to use the default data collator
41
+ and your model is an encoder-decoder.
42
+ beta (`float`, *optional*, defaults to `0.1`):
43
+ Parameter controlling the relative ratio loss weight in the ORPO loss. In the
44
+ [paper](https://huggingface.co/papers/2403.07691), it is denoted by λ. In the
45
+ [code](https://github.com/xfactlab/orpo), it is denoted by `alpha`.
46
+ disable_dropout (`bool`, *optional*, defaults to `True`):
47
+ Whether to disable dropout in the model.
48
+ padding_value (`int`, *optional*):
49
+ Padding value to use. If `None`, the padding value of the tokenizer is used.
50
+ generate_during_eval (`bool`, *optional*, defaults to `False`):
51
+ If `True`, generates and logs completions from the model to W&B or Comet during evaluation.
52
+ is_encoder_decoder (`bool`, *optional*):
53
+ When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument,
54
+ you need to specify if the model returned by the callable is an encoder-decoder model.
55
+ model_init_kwargs (`dict[str, Any]`, *optional*):
56
+ Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a
57
+ string.
58
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
59
+ Whether to allow loading models that ship custom Python code from the Hub. Forwarded to
60
+ [`~transformers.AutoModelForCausalLM.from_pretrained`].
61
+ dataset_num_proc (`int`, *optional*):
62
+ Number of processes to use for processing the dataset.
63
+
64
+ > [!NOTE]
65
+ > These parameters have default values different from [`~transformers.TrainingArguments`]:
66
+ > - `logging_steps`: Defaults to `10` instead of `500`.
67
+ > - `gradient_checkpointing`: Defaults to `True` instead of `False`.
68
+ > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
69
+ > - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.
70
+ """
71
+
72
+ _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
73
+
74
+ # Parameters whose default values are overridden from TrainingArguments
75
+ learning_rate: float = field(
76
+ default=1e-6,
77
+ metadata={"help": "The initial learning rate for AdamW."},
78
+ )
79
+
80
+ max_length: int | None = field(
81
+ default=1024,
82
+ metadata={"help": "Maximum length of the sequences (prompt + completion) in the batch."},
83
+ )
84
+ max_completion_length: int | None = field(
85
+ default=None,
86
+ metadata={
87
+ "help": "Maximum length of the completion. This argument is required if you want to use the default data "
88
+ "collator and your model is an encoder-decoder."
89
+ },
90
+ )
91
+ beta: float = field(
92
+ default=0.1,
93
+ metadata={
94
+ "help": "Parameter controlling the relative ratio loss weight in the ORPO loss. In the paper, it is "
95
+ "denoted by λ."
96
+ },
97
+ )
98
+ disable_dropout: bool = field(
99
+ default=True,
100
+ metadata={"help": "Whether to disable dropout in the model."},
101
+ )
102
+ padding_value: int | None = field(
103
+ default=None,
104
+ metadata={"help": "Padding value to use. If `None`, the padding value of the tokenizer is used."},
105
+ )
106
+ generate_during_eval: bool = field(
107
+ default=False,
108
+ metadata={"help": "If `True`, generates and logs completions from the model to W&B during evaluation."},
109
+ )
110
+ is_encoder_decoder: bool | None = field(
111
+ default=None,
112
+ metadata={
113
+ "help": "When using the `model_init` argument (callable) to instantiate the model instead of the `model` "
114
+ "argument, you need to specify if the model returned by the callable is an encoder-decoder model."
115
+ },
116
+ )
117
+ model_init_kwargs: dict[str, Any] | str | None = field(
118
+ default=None,
119
+ metadata={
120
+ "help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model "
121
+ "from a string."
122
+ },
123
+ )
124
+ trust_remote_code: bool = field(
125
+ default=False,
126
+ metadata={
127
+ "help": "Whether to allow loading models that ship custom Python code from the Hub. Forwarded to "
128
+ "`AutoModelForCausalLM.from_pretrained`."
129
+ },
130
+ )
131
+ dataset_num_proc: int | None = field(
132
+ default=None,
133
+ metadata={"help": "Number of processes to use for processing the dataset."},
134
+ )
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/orpo/orpo_trainer.py ADDED
@@ -0,0 +1,1042 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import random
17
+ import textwrap
18
+ from collections import defaultdict
19
+ from collections.abc import Callable
20
+ from contextlib import nullcontext
21
+ from pathlib import Path
22
+ from typing import Any, Literal
23
+
24
+ import numpy as np
25
+ import pandas as pd
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+ import transformers
30
+ from accelerate import PartialState
31
+ from accelerate.logging import get_logger
32
+ from accelerate.utils import is_peft_model
33
+ from datasets import Dataset
34
+ from packaging.version import Version
35
+ from torch import autocast
36
+ from torch.utils.data import DataLoader
37
+ from transformers import (
38
+ AutoModelForCausalLM,
39
+ BaseImageProcessor,
40
+ DataCollator,
41
+ FeatureExtractionMixin,
42
+ PreTrainedModel,
43
+ PreTrainedTokenizerBase,
44
+ ProcessorMixin,
45
+ TrainerCallback,
46
+ is_comet_available,
47
+ is_torch_xla_available,
48
+ is_wandb_available,
49
+ )
50
+ from transformers.trainer_utils import EvalLoopOutput
51
+ from transformers.utils import is_peft_available, is_torch_fx_proxy
52
+
53
+ from ...data_utils import maybe_apply_chat_template, maybe_extract_prompt
54
+ from ...trainer.base_trainer import _BaseTrainer
55
+ from ...trainer.utils import disable_dropout_in_model, log_table_to_comet_experiment, selective_log_softmax
56
+ from ..utils import (
57
+ DPODataCollatorWithPadding,
58
+ add_bos_token_if_needed,
59
+ add_eos_token_if_needed,
60
+ pad_to_length,
61
+ peft_module_casting_to_bf16,
62
+ )
63
+ from .orpo_config import ORPOConfig
64
+
65
+
66
+ if is_peft_available():
67
+ from peft import PeftConfig, get_peft_model, prepare_model_for_kbit_training
68
+
69
+
70
+ if is_wandb_available():
71
+ import wandb
72
+
73
+ if is_torch_xla_available():
74
+ import torch_xla.core.xla_model as xm
75
+
76
+
77
+ logger = get_logger(__name__)
78
+
79
+
80
+ def log1mexp(x: torch.FloatTensor) -> torch.FloatTensor:
81
+ """Numerically stable computation of log(1-exp(x))."""
82
+ # branch at -ln 2 ~ -0.693 to avoid cancellation
83
+ t = -0.6931471805599453
84
+ return torch.where(x < t, torch.log1p(-torch.exp(x)), torch.log(-torch.expm1(x)))
85
+
86
+
87
+ class ORPOTrainer(_BaseTrainer):
88
+ r"""
89
+ Initialize ORPOTrainer.
90
+
91
+ Args:
92
+ model ([`~transformers.PreTrainedModel`]):
93
+ The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`].
94
+ args ([`experimental.orpo.ORPOConfig`]):
95
+ The ORPO config arguments to use for training.
96
+ data_collator ([`~transformers.DataCollator`]):
97
+ The data collator to use for training. If None is specified, the default data collator
98
+ ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the
99
+ maximum length of the sequences in the batch, given a dataset of paired sequences.
100
+ train_dataset ([`~datasets.Dataset`]):
101
+ The dataset to use for training.
102
+ eval_dataset ([`~datasets.Dataset`]):
103
+ The dataset to use for evaluation.
104
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
105
+ Processing class used to process the data. If provided, will be used to automatically process the inputs
106
+ for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
107
+ reuse the fine-tuned model.
108
+ model_init (`Callable[[], transformers.PreTrainedModel]`):
109
+ The model initializer to use for training. If None is specified, the default model initializer will be
110
+ used.
111
+ callbacks (`list[transformers.TrainerCallback]`):
112
+ The callbacks to use for training.
113
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
114
+ The optimizer and scheduler to use for training.
115
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
116
+ The function to use to preprocess the logits before computing the metrics.
117
+ peft_config ([`~peft.PeftConfig`], *optional*):
118
+ The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in
119
+ a PEFT model.
120
+ compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
121
+ The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
122
+ metric values.
123
+ """
124
+
125
+ _tag_names = ["trl", "orpo"]
126
+ _name = "ORPO"
127
+ _paper = {
128
+ "title": "ORPO: Monolithic Preference Optimization without Reference Model",
129
+ "id": "2403.07691",
130
+ # docstyle-ignore
131
+ "citation": textwrap.dedent("""\
132
+ @article{hong2024orpo,
133
+ title = {{ORPO: Monolithic Preference Optimization without Reference Model}},
134
+ author = {Jiwoo Hong and Noah Lee and James Thorne},
135
+ year = 2024,
136
+ eprint = {arXiv:2403.07691}
137
+ }"""),
138
+ }
139
+
140
+ def __init__(
141
+ self,
142
+ model: PreTrainedModel | nn.Module | str | None = None,
143
+ args: ORPOConfig | None = None,
144
+ data_collator: DataCollator | None = None,
145
+ train_dataset: Dataset | None = None,
146
+ eval_dataset: Dataset | dict[str, Dataset] | None = None,
147
+ processing_class: PreTrainedTokenizerBase
148
+ | BaseImageProcessor
149
+ | FeatureExtractionMixin
150
+ | ProcessorMixin
151
+ | None = None,
152
+ model_init: Callable[[], PreTrainedModel] | None = None,
153
+ callbacks: list[TrainerCallback] | None = None,
154
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
155
+ preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
156
+ peft_config: "PeftConfig | None" = None,
157
+ compute_metrics: Callable[[EvalLoopOutput], dict] | None = None,
158
+ ):
159
+ if train_dataset is None:
160
+ raise ValueError("`train_dataset` is required")
161
+
162
+ if args.model_init_kwargs is None:
163
+ model_init_kwargs = {}
164
+ elif not isinstance(model, str):
165
+ raise ValueError("You passed model_kwargs to the ORPOTrainer. But your model is already instantiated.")
166
+ else:
167
+ model_init_kwargs = args.model_init_kwargs
168
+ dtype = model_init_kwargs.get("dtype", "auto")
169
+ if dtype is not None:
170
+ # Convert to `torch.dtype` if an str is passed
171
+ if isinstance(dtype, str) and dtype != "auto":
172
+ dtype = getattr(torch, dtype)
173
+ if dtype != "auto" and not isinstance(dtype, torch.dtype):
174
+ raise ValueError(
175
+ f"Invalid `dtype` passed to the ORPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {dtype}."
176
+ )
177
+ model_init_kwargs["dtype"] = dtype
178
+ model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto")
179
+
180
+ model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
181
+
182
+ if isinstance(model, str):
183
+ model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
184
+
185
+ # PEFT
186
+ # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16`
187
+ # has been called in order to properly call autocast if needed.
188
+ self._peft_has_been_casted_to_bf16 = False
189
+ if peft_config is not None:
190
+ if not is_peft_available():
191
+ raise ImportError(
192
+ "You passed `peft_config` but the `peft` library is not installed. "
193
+ "Install it with `pip install trl[peft]`."
194
+ )
195
+ if not isinstance(peft_config, PeftConfig):
196
+ raise TypeError(
197
+ f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
198
+ f"got {type(peft_config).__name__}."
199
+ )
200
+ if is_peft_model(model):
201
+ raise ValueError(
202
+ "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first "
203
+ "merge and unload the existing adapter, save the resulting base model, and then pass that base "
204
+ "model along with the new `peft_config` to the trainer."
205
+ )
206
+
207
+ if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False):
208
+ _support_gc_kwargs = hasattr(
209
+ args, "gradient_checkpointing_kwargs"
210
+ ) and "gradient_checkpointing_kwargs" in list(
211
+ inspect.signature(prepare_model_for_kbit_training).parameters
212
+ )
213
+
214
+ prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing}
215
+
216
+ if _support_gc_kwargs:
217
+ prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs
218
+
219
+ model = prepare_model_for_kbit_training(model, **prepare_model_kwargs)
220
+ elif args.gradient_checkpointing:
221
+ # For backward compatibility with older versions of transformers
222
+ if hasattr(model, "enable_input_require_grads"):
223
+ model.enable_input_require_grads()
224
+ else:
225
+
226
+ def make_inputs_require_grad(module, input, output):
227
+ output.requires_grad_(True)
228
+
229
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
230
+
231
+ # get peft model with the given config
232
+ model = get_peft_model(model, peft_config)
233
+ if args.bf16 and getattr(model, "is_loaded_in_4bit", False):
234
+ peft_module_casting_to_bf16(model)
235
+ # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager
236
+ self._peft_has_been_casted_to_bf16 = True
237
+
238
+ # For models that use gradient_checkpointing, we need to attach a hook that enables input
239
+ # to explicitly have `requires_grad=True`, otherwise training will either silently
240
+ # fail or completely fail.
241
+ elif args.gradient_checkpointing:
242
+ # For backward compatibility with older versions of transformers
243
+ if hasattr(model, "enable_input_require_grads"):
244
+ model.enable_input_require_grads()
245
+ else:
246
+
247
+ def make_inputs_require_grad(module, input, output):
248
+ output.requires_grad_(True)
249
+
250
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
251
+
252
+ if args.generate_during_eval and not (is_wandb_available() or is_comet_available()):
253
+ raise ValueError(
254
+ "`generate_during_eval=True` requires Weights and Biases or Comet to be installed."
255
+ " Please install `wandb` or `comet-ml` to resolve."
256
+ )
257
+
258
+ if model is not None:
259
+ self.is_encoder_decoder = model.config.is_encoder_decoder
260
+ elif args.is_encoder_decoder is None:
261
+ raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.")
262
+ else:
263
+ self.is_encoder_decoder = args.is_encoder_decoder
264
+
265
+ if self.is_encoder_decoder:
266
+ self.decoder_start_token_id = model.config.decoder_start_token_id
267
+ self.pad_token_id = model.config.pad_token_id
268
+
269
+ if processing_class is None:
270
+ raise ValueError("processing_class must be specified to tokenize a ORPO dataset.")
271
+ if args.max_length is None:
272
+ logger.warning(
273
+ "`max_length` is not set in the ORPOConfig's init"
274
+ " it will default to `512` by default, but you should do it yourself in the future.",
275
+ )
276
+ max_length = 512
277
+ else:
278
+ max_length = args.max_length
279
+
280
+ if args.max_completion_length is None and self.is_encoder_decoder:
281
+ logger.warning(
282
+ "When using an encoder decoder architecture, you should set `max_completion_length` in the ORPOConfig's init"
283
+ " it will default to `128` by default, but you should do it yourself in the future.",
284
+ )
285
+ self.max_completion_length = 128
286
+ else:
287
+ self.max_completion_length = args.max_completion_length
288
+
289
+ if data_collator is None:
290
+ data_collator = DPODataCollatorWithPadding(
291
+ pad_token_id=processing_class.pad_token_id,
292
+ is_encoder_decoder=self.is_encoder_decoder,
293
+ )
294
+
295
+ if args.remove_unused_columns:
296
+ args.remove_unused_columns = False
297
+ # warn users
298
+ logger.warning(
299
+ "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments"
300
+ " we have set it for you, but you should do it yourself in the future.",
301
+ )
302
+
303
+ self.use_dpo_data_collator = True
304
+ else:
305
+ self.use_dpo_data_collator = False
306
+
307
+ # Disable dropout in the model and reference model
308
+ if args.disable_dropout:
309
+ disable_dropout_in_model(model)
310
+
311
+ self.max_length = max_length
312
+ self.generate_during_eval = args.generate_during_eval
313
+ self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id
314
+ self.processing_class = processing_class
315
+
316
+ self.beta = args.beta
317
+ self.aux_loss_enabled = getattr(model.config, "output_router_logits", False)
318
+ self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0)
319
+ if self.aux_loss_enabled and self.aux_loss_coef == 0.0:
320
+ logger.warning(
321
+ "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to "
322
+ "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value "
323
+ "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary "
324
+ "loss.",
325
+ )
326
+
327
+ self._stored_metrics = defaultdict(lambda: defaultdict(list))
328
+
329
+ # Compute that only on the main process for faster data processing.
330
+ # see: https://github.com/huggingface/trl/pull/1255
331
+ with PartialState().main_process_first():
332
+ # Extract the prompt if needed, and apply the chat template if needed
333
+ train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc)
334
+ train_dataset = train_dataset.map(
335
+ maybe_apply_chat_template,
336
+ fn_kwargs={"processing_class": processing_class},
337
+ num_proc=args.dataset_num_proc,
338
+ )
339
+ train_dataset = train_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc)
340
+ if eval_dataset is not None:
341
+ eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc)
342
+ eval_dataset = eval_dataset.map(
343
+ maybe_apply_chat_template,
344
+ fn_kwargs={"processing_class": processing_class},
345
+ num_proc=args.dataset_num_proc,
346
+ )
347
+ eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc)
348
+
349
+ # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
350
+ # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
351
+ # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
352
+ # default to the recommended non-reentrant behavior here, while preserving any user-provided value.
353
+ if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
354
+ args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
355
+ args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
356
+
357
+ super().__init__(
358
+ model=model,
359
+ args=args,
360
+ data_collator=data_collator,
361
+ train_dataset=train_dataset,
362
+ eval_dataset=eval_dataset,
363
+ processing_class=processing_class,
364
+ model_init=model_init,
365
+ compute_metrics=compute_metrics,
366
+ callbacks=callbacks,
367
+ optimizers=optimizers,
368
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
369
+ )
370
+
371
+ # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
372
+ # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
373
+ # self.model_accepts_loss_kwargs to False to enable scaling.
374
+ self.model_accepts_loss_kwargs = False
375
+
376
+ # Add tags for models that have been loaded with the correct transformers version
377
+ if hasattr(self.model, "add_model_tags"):
378
+ self.model.add_model_tags(self._tag_names)
379
+
380
+ if not hasattr(self, "accelerator"):
381
+ raise AttributeError(
382
+ "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`."
383
+ )
384
+
385
+ def build_tokenized_answer(self, prompt, answer):
386
+ """
387
+ Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. It does ensure `enc(a + b) = enc(a) + enc(a +
388
+ b)[len(enc(a)):]`. Reference:
389
+ https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
390
+ """
391
+
392
+ full_tokenized = self.processing_class(prompt + answer, add_special_tokens=False)
393
+ prompt_input_ids = self.processing_class(prompt, add_special_tokens=False)["input_ids"]
394
+
395
+ answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :]
396
+ answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :]
397
+
398
+ # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]`
399
+ full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids])
400
+
401
+ # Prepare input tokens for token by token comparison
402
+ full_input_ids = np.array(full_tokenized["input_ids"])
403
+
404
+ if len(full_input_ids) != len(full_concat_input_ids):
405
+ raise ValueError("Prompt input ids and answer input ids should have the same length.")
406
+
407
+ # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens
408
+ # can be merged together when tokenizing prompt+answer. This could result
409
+ # on the last token from the prompt being different when tokenized on its own
410
+ # vs when done as prompt+answer.
411
+ response_token_ids_start_idx = len(prompt_input_ids)
412
+
413
+ # If tokenized prompt is different than both prompt+answer, then it means the
414
+ # last token has changed due to merging.
415
+ if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]:
416
+ response_token_ids_start_idx -= 1
417
+
418
+ prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx]
419
+ prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx]
420
+
421
+ if len(prompt_input_ids) != len(prompt_attention_mask):
422
+ raise ValueError("Prompt input ids and attention mask should have the same length.")
423
+
424
+ answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:]
425
+ answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:]
426
+
427
+ return dict(
428
+ prompt_input_ids=prompt_input_ids,
429
+ prompt_attention_mask=prompt_attention_mask,
430
+ input_ids=answer_input_ids,
431
+ attention_mask=answer_attention_mask,
432
+ )
433
+
434
+ def tokenize_row(self, feature, model: PreTrainedModel | nn.Module | None = None) -> dict:
435
+ """Tokenize a single row from a ORPO specific dataset.
436
+
437
+ At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt +
438
+ chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long,
439
+ we truncate the chosen/rejected.
440
+
441
+ We also create the labels for the chosen/rejected responses, which are of length equal to the sum of the length
442
+ of the prompt and the chosen/rejected response, with `-100` for the prompt tokens.
443
+ """
444
+ batch = {}
445
+ prompt = feature["prompt"]
446
+ chosen = feature["chosen"]
447
+ rejected = feature["rejected"]
448
+
449
+ if not self.is_encoder_decoder:
450
+ # Check issues below for more details
451
+ # 1. https://github.com/huggingface/trl/issues/907
452
+ # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
453
+ # 3. https://github.com/LianjiaTech/BELLE/issues/337
454
+
455
+ if not isinstance(prompt, str):
456
+ raise ValueError(f"prompt should be an str but got {type(prompt)}")
457
+ prompt_tokens = self.processing_class(prompt, add_special_tokens=False)
458
+ prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()}
459
+
460
+ if not isinstance(chosen, str):
461
+ raise ValueError(f"chosen should be an str but got {type(chosen)}")
462
+ chosen_tokens = self.build_tokenized_answer(prompt, chosen)
463
+
464
+ if not isinstance(rejected, str):
465
+ raise ValueError(f"rejected should be an str but got {type(rejected)}")
466
+ rejected_tokens = self.build_tokenized_answer(prompt, rejected)
467
+
468
+ # Last prompt token might get merged by tokenizer and
469
+ # it should not be included for generation if that happens
470
+ prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"])
471
+
472
+ chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"])
473
+ rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"])
474
+ prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids)
475
+
476
+ for k, v in prompt_tokens.items():
477
+ prompt_tokens[k] = v[:prompt_len_input_ids]
478
+
479
+ # Make sure prompts only have one different token at most an
480
+ # and length only differs by 1 at most
481
+ num_diff_tokens = sum(
482
+ a != b
483
+ for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"], strict=False)
484
+ )
485
+ num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids)
486
+ if num_diff_tokens > 1 or num_diff_len > 1:
487
+ raise ValueError(
488
+ "Chosen and rejected prompt_input_ids might only differ on the "
489
+ "last token due to tokenizer merge ops."
490
+ )
491
+
492
+ # add BOS token to head of prompt. Avoid adding if it's already there
493
+ prompt_tokens, chosen_tokens, rejected_tokens = add_bos_token_if_needed(
494
+ self.processing_class.bos_token_id,
495
+ prompt_len_input_ids,
496
+ prompt_tokens,
497
+ chosen_prompt_len_input_ids,
498
+ chosen_tokens,
499
+ rejected_prompt_len_input_ids,
500
+ rejected_tokens,
501
+ )
502
+
503
+ # add EOS token to end of answer. Avoid adding if it's already there
504
+ chosen_tokens, rejected_tokens = add_eos_token_if_needed(
505
+ self.processing_class.eos_token_id, chosen_tokens, rejected_tokens
506
+ )
507
+
508
+ longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"]))
509
+
510
+ # if combined sequence is too long, truncate the response
511
+ for answer_tokens in [chosen_tokens, rejected_tokens]:
512
+ if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
513
+ for k in ["input_ids", "attention_mask"]:
514
+ answer_tokens[k] = answer_tokens[k][: self.max_length - longer_response_length]
515
+
516
+ # Create labels
517
+ chosen_sequence_tokens = {
518
+ k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"]
519
+ }
520
+ rejected_sequence_tokens = {
521
+ k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"]
522
+ }
523
+ chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:]
524
+ chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [-100] * len(
525
+ chosen_tokens["prompt_input_ids"]
526
+ )
527
+ rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:]
528
+ rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [-100] * len(
529
+ rejected_tokens["prompt_input_ids"]
530
+ )
531
+
532
+ for k, toks in {
533
+ "chosen_": chosen_sequence_tokens,
534
+ "rejected_": rejected_sequence_tokens,
535
+ "": prompt_tokens,
536
+ }.items():
537
+ for type_key, tokens in toks.items():
538
+ if type_key == "token_type_ids":
539
+ continue
540
+ batch[f"{k}{type_key}"] = tokens
541
+
542
+ else:
543
+ chosen_tokens = self.processing_class(
544
+ chosen, truncation=True, max_length=self.max_completion_length, add_special_tokens=True
545
+ )
546
+ rejected_tokens = self.processing_class(
547
+ rejected, truncation=True, max_length=self.max_completion_length, add_special_tokens=True
548
+ )
549
+ prompt_tokens = self.processing_class(prompt, add_special_tokens=True)
550
+
551
+ batch["chosen_labels"] = chosen_tokens["input_ids"]
552
+ batch["rejected_labels"] = rejected_tokens["input_ids"]
553
+ batch["prompt_input_ids"] = prompt_tokens["input_ids"]
554
+ batch["prompt_attention_mask"] = prompt_tokens["attention_mask"]
555
+
556
+ if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"):
557
+ batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(
558
+ labels=torch.tensor(batch["rejected_labels"])
559
+ )
560
+ batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(
561
+ labels=torch.tensor(batch["chosen_labels"])
562
+ )
563
+
564
+ if is_torch_xla_available():
565
+ # Pad the sequences to global max_length to avoid TorchXLA recompilation
566
+ for k in batch:
567
+ if "labels" in k or self.is_encoder_decoder:
568
+ pad_value = -100
569
+ elif k.endswith("_input_ids"):
570
+ pad_value = self.padding_value
571
+ elif k.endswith("_attention_mask"):
572
+ pad_value = 0
573
+ batch[k] = batch[k] + [pad_value] * (self.max_length - len(batch[k]))
574
+ return batch
575
+
576
+ @staticmethod
577
+ def concatenated_inputs(
578
+ batch: dict[str, list | torch.LongTensor],
579
+ is_encoder_decoder: bool = False,
580
+ padding_value: int = 0,
581
+ device: torch.device | None = None,
582
+ ) -> dict[str, torch.LongTensor]:
583
+ """Concatenate the chosen and rejected inputs into a single tensor.
584
+
585
+ Args:
586
+ batch:
587
+ A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors
588
+ of shape (batch_size, sequence_length).
589
+ is_encoder_decoder:
590
+ Whether the model is an encoder-decoder model.
591
+ padding_value:
592
+ The padding value to use for the concatenated inputs_ids.
593
+ device:
594
+ The device for the concatenated inputs.
595
+
596
+ Returns:
597
+ A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'.
598
+ """
599
+ concatenated_batch = {}
600
+
601
+ if is_encoder_decoder:
602
+ max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1])
603
+ else:
604
+ max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1])
605
+
606
+ for k in batch:
607
+ if k.startswith("chosen") and isinstance(batch[k], torch.Tensor):
608
+ if "labels" in k or is_encoder_decoder:
609
+ pad_value = -100
610
+ elif k.endswith("_input_ids"):
611
+ pad_value = padding_value
612
+ elif k.endswith("_attention_mask"):
613
+ pad_value = 0
614
+ concatenated_key = k.replace("chosen", "concatenated")
615
+ concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value)
616
+ for k in batch:
617
+ if k.startswith("rejected") and isinstance(batch[k], torch.Tensor):
618
+ if "labels" in k or is_encoder_decoder:
619
+ pad_value = -100
620
+ elif k.endswith("_input_ids"):
621
+ pad_value = padding_value
622
+ elif k.endswith("_attention_mask"):
623
+ pad_value = 0
624
+ concatenated_key = k.replace("rejected", "concatenated")
625
+ concatenated_batch[concatenated_key] = torch.cat(
626
+ (
627
+ concatenated_batch[concatenated_key],
628
+ pad_to_length(batch[k], max_length, pad_value=pad_value),
629
+ ),
630
+ dim=0,
631
+ ).to(device=device)
632
+
633
+ if is_encoder_decoder:
634
+ concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device)
635
+ concatenated_batch["concatenated_attention_mask"] = (
636
+ batch["prompt_attention_mask"].repeat(2, 1).to(device=device)
637
+ )
638
+
639
+ return concatenated_batch
640
+
641
+ def odds_ratio_loss(
642
+ self,
643
+ policy_chosen_logps: torch.FloatTensor,
644
+ policy_rejected_logps: torch.FloatTensor,
645
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
646
+ """Compute ORPO's odds ratio (OR) loss for a batch of policy and reference model log probabilities.
647
+
648
+ Args:
649
+ policy_chosen_logps:
650
+ Log probabilities of the policy model for the chosen responses. Shape: (batch_size,)
651
+ policy_rejected_logps:
652
+ Log probabilities of the policy model for the rejected responses. Shape: (batch_size,)
653
+
654
+ Returns:
655
+ A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). The losses tensor contains the ORPO
656
+ loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for
657
+ the chosen and rejected responses, respectively. The log odds ratio of the chosen responses over the
658
+ rejected responses ratio for logging purposes. The `log(sigmoid(log_odds_chosen))` for logging purposes.
659
+ """
660
+
661
+ # Derived from Eqs. (4) and (7) from https://huggingface.co/papers/2403.07691 by using log identities and exp(log(P(y|x)) = P(y|x)
662
+ policy_chosen_logps = policy_chosen_logps.float()
663
+ policy_rejected_logps = policy_rejected_logps.float()
664
+ log_odds = (policy_chosen_logps - policy_rejected_logps) - (
665
+ log1mexp(policy_chosen_logps) - log1mexp(policy_rejected_logps)
666
+ )
667
+ ratio = F.logsigmoid(log_odds)
668
+ losses = self.beta * ratio
669
+
670
+ chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach()
671
+ rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach()
672
+
673
+ return losses, chosen_rewards, rejected_rewards, torch.mean(ratio), torch.mean(log_odds)
674
+
675
+ @staticmethod
676
+ def get_batch_logps(
677
+ logits: torch.FloatTensor,
678
+ labels: torch.LongTensor,
679
+ average_log_prob: bool = False,
680
+ is_encoder_decoder: bool = False,
681
+ ) -> torch.FloatTensor:
682
+ """Compute the log probabilities of the given labels under the given logits.
683
+
684
+ Args:
685
+ logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size)
686
+ labels:
687
+ Labels for which to compute the log probabilities. Label tokens with a value of `-100` are ignored.
688
+ Shape: (batch_size, sequence_length)
689
+ average_log_prob:
690
+ If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the
691
+ log probabilities of the (non-masked) tokens.
692
+ is_encoder_decoder: Whether the model is an encoder-decoder model.
693
+
694
+ Returns:
695
+ A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the
696
+ given logits.
697
+ """
698
+ if logits.shape[:-1] != labels.shape:
699
+ raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.")
700
+
701
+ if not is_encoder_decoder:
702
+ labels = labels[:, 1:].clone()
703
+ logits = logits[:, :-1, :]
704
+ loss_mask = labels != -100
705
+
706
+ # dummy token; we'll ignore the losses on these tokens later
707
+ labels = torch.where(labels == -100, 0, labels)
708
+
709
+ per_token_logps = selective_log_softmax(logits, labels)
710
+
711
+ if average_log_prob:
712
+ return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1)
713
+ else:
714
+ return (per_token_logps * loss_mask).sum(-1)
715
+
716
+ def concatenated_forward(
717
+ self, model: nn.Module, batch: dict[str, list | torch.LongTensor]
718
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
719
+ """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together.
720
+
721
+ We do this to avoid doing two forward passes, because it's faster for FSDP.
722
+ """
723
+ concatenated_batch = self.concatenated_inputs(
724
+ batch,
725
+ is_encoder_decoder=self.is_encoder_decoder,
726
+ padding_value=self.padding_value,
727
+ device=self.accelerator.device,
728
+ )
729
+ len_chosen = batch["chosen_labels"].shape[0]
730
+
731
+ model_kwargs = (
732
+ {
733
+ "decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]),
734
+ }
735
+ if self.is_encoder_decoder
736
+ else {}
737
+ )
738
+
739
+ if self.aux_loss_enabled:
740
+ model_kwargs["output_router_logits"] = True
741
+
742
+ outputs = model(
743
+ concatenated_batch["concatenated_input_ids"],
744
+ attention_mask=concatenated_batch["concatenated_attention_mask"],
745
+ use_cache=False,
746
+ **model_kwargs,
747
+ )
748
+ all_logits = outputs.logits
749
+
750
+ def cross_entropy_loss(logits, labels):
751
+ if not self.is_encoder_decoder:
752
+ # Shift so that tokens < n predict n
753
+ logits = logits[..., :-1, :].contiguous()
754
+ labels = labels[..., 1:].contiguous()
755
+ # Flatten the tokens
756
+ loss_fct = nn.CrossEntropyLoss()
757
+ logits = logits.view(-1, logits.shape[-1])
758
+ labels = labels.view(-1)
759
+ # Enable model parallelism
760
+ labels = labels.to(logits.device)
761
+ loss = loss_fct(logits, labels)
762
+ return loss
763
+
764
+ if self.is_encoder_decoder:
765
+ labels = concatenated_batch["concatenated_labels"].clone()
766
+ else:
767
+ labels = concatenated_batch["concatenated_input_ids"].clone()
768
+ attention_mask = concatenated_batch["concatenated_attention_mask"]
769
+ labels = torch.where(attention_mask == 1, labels, -100)
770
+ # orpo chosen nll loss is computed over the full prompt and response
771
+ chosen_nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen])
772
+
773
+ all_logps = self.get_batch_logps(
774
+ all_logits,
775
+ concatenated_batch["concatenated_labels"],
776
+ average_log_prob=True,
777
+ is_encoder_decoder=self.is_encoder_decoder,
778
+ )
779
+
780
+ chosen_logps = all_logps[:len_chosen]
781
+ rejected_logps = all_logps[len_chosen:]
782
+
783
+ if not self.is_encoder_decoder:
784
+ chosen_logits = all_logits[:len_chosen, :-1, :]
785
+ rejected_logits = all_logits[len_chosen:, :-1, :]
786
+ else:
787
+ chosen_logits = all_logits[:len_chosen]
788
+ rejected_logits = all_logits[len_chosen:]
789
+
790
+ if self.aux_loss_enabled:
791
+ return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss, outputs.aux_loss)
792
+
793
+ return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss)
794
+
795
+ def get_batch_loss_metrics(
796
+ self,
797
+ model,
798
+ batch: dict[str, list | torch.LongTensor],
799
+ train_eval: Literal["train", "eval"] = "train",
800
+ ):
801
+ """Compute the ORPO loss and other metrics for the given batch of inputs for train or test."""
802
+ metrics = {}
803
+
804
+ forward_output = self.concatenated_forward(model, batch)
805
+ (
806
+ policy_chosen_logps,
807
+ policy_rejected_logps,
808
+ policy_chosen_logits,
809
+ policy_rejected_logits,
810
+ policy_nll_loss,
811
+ ) = forward_output[:5]
812
+ if self.aux_loss_enabled:
813
+ aux_loss = forward_output[5]
814
+
815
+ losses, chosen_rewards, rejected_rewards, log_odds_ratio, log_odds_chosen = self.odds_ratio_loss(
816
+ policy_chosen_logps, policy_rejected_logps
817
+ )
818
+ # full ORPO loss
819
+ loss = policy_nll_loss - losses.mean()
820
+
821
+ reward_accuracies = (chosen_rewards > rejected_rewards).float()
822
+
823
+ prefix = "eval_" if train_eval == "eval" else ""
824
+ metrics[f"{prefix}rewards/chosen"] = self.accelerator.gather_for_metrics(chosen_rewards).mean()
825
+ metrics[f"{prefix}rewards/rejected"] = self.accelerator.gather_for_metrics(rejected_rewards).mean()
826
+ metrics[f"{prefix}rewards/accuracies"] = self.accelerator.gather_for_metrics(reward_accuracies).mean()
827
+ metrics[f"{prefix}rewards/margins"] = self.accelerator.gather_for_metrics(
828
+ chosen_rewards - rejected_rewards
829
+ ).mean()
830
+ metrics[f"{prefix}logps/rejected"] = self.accelerator.gather_for_metrics(policy_rejected_logps).detach().mean()
831
+ metrics[f"{prefix}logps/chosen"] = self.accelerator.gather_for_metrics(policy_chosen_logps).detach().mean()
832
+ metrics[f"{prefix}logits/rejected"] = self.accelerator.gather_for_metrics(
833
+ policy_rejected_logits.detach().mean()
834
+ ).mean()
835
+ metrics[f"{prefix}logits/chosen"] = self.accelerator.gather_for_metrics(
836
+ policy_chosen_logits.detach().mean()
837
+ ).mean()
838
+ metrics[f"{prefix}nll_loss"] = self.accelerator.gather_for_metrics(policy_nll_loss).detach().mean()
839
+ metrics[f"{prefix}log_odds_ratio"] = self.accelerator.gather_for_metrics(log_odds_ratio).detach().mean()
840
+ metrics[f"{prefix}log_odds_chosen"] = self.accelerator.gather_for_metrics(log_odds_chosen).detach().mean()
841
+ if is_torch_xla_available():
842
+ xm.mark_step() # needed because .item() calls
843
+ for k, v in metrics.items():
844
+ metrics[k] = v.item()
845
+ if self.aux_loss_enabled:
846
+ loss += self.aux_loss_coef * aux_loss
847
+
848
+ return loss, metrics
849
+
850
+ def compute_loss(
851
+ self,
852
+ model: PreTrainedModel | nn.Module,
853
+ inputs: dict[str, torch.Tensor | Any],
854
+ return_outputs=False,
855
+ num_items_in_batch=None,
856
+ ) -> torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]:
857
+ compute_loss_context_manager = (
858
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
859
+ )
860
+
861
+ with compute_loss_context_manager:
862
+ loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train")
863
+
864
+ # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class:
865
+ loss = loss.to(self.args.device)
866
+
867
+ # force log the metrics
868
+ self.store_metrics(metrics, train_eval="train")
869
+
870
+ if return_outputs:
871
+ return (loss, metrics)
872
+ return loss
873
+
874
+ def generate_from_model(self, model, batch: dict[str, torch.LongTensor]) -> str:
875
+ """Generate samples from the model and reference model for the given batch of inputs."""
876
+
877
+ # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with
878
+ # the torch amp context manager as some hidden states are silently casted to full precision.
879
+ generate_context_manager = (
880
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
881
+ )
882
+
883
+ with generate_context_manager:
884
+ policy_output = model.generate(
885
+ input_ids=batch["prompt_input_ids"],
886
+ attention_mask=batch["prompt_attention_mask"],
887
+ max_length=self.max_length,
888
+ do_sample=True,
889
+ pad_token_id=self.processing_class.pad_token_id,
890
+ )
891
+
892
+ policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id)
893
+ policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True)
894
+
895
+ return policy_output_decoded
896
+
897
+ def prediction_step(
898
+ self,
899
+ model: PreTrainedModel | nn.Module,
900
+ inputs: dict[str, torch.Tensor | Any],
901
+ prediction_loss_only: bool,
902
+ ignore_keys: list[str] | None = None,
903
+ ):
904
+ if not self.use_dpo_data_collator:
905
+ logger.warning(
906
+ "prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than "
907
+ "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator"
908
+ )
909
+ if ignore_keys is None:
910
+ if hasattr(model, "config"):
911
+ ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", [])
912
+ else:
913
+ ignore_keys = []
914
+
915
+ prediction_context_manager = (
916
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
917
+ )
918
+
919
+ with torch.no_grad(), prediction_context_manager:
920
+ loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval")
921
+
922
+ # force log the metrics
923
+ self.store_metrics(metrics, train_eval="eval")
924
+
925
+ if prediction_loss_only:
926
+ return (loss.detach(), None, None)
927
+
928
+ # logits for the chosen and rejected samples from model
929
+ logits_dict = {
930
+ "eval_logits/chosen": metrics["eval_logits/chosen"],
931
+ "eval_logits/rejected": metrics["eval_logits/rejected"],
932
+ }
933
+ logits = [v for k, v in logits_dict.items() if k not in ignore_keys]
934
+ logits = torch.tensor(logits, device=self.accelerator.device)
935
+ labels = torch.zeros(logits.shape[0], device=self.accelerator.device)
936
+
937
+ return (loss.detach(), logits, labels)
938
+
939
+ def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None:
940
+ for key, value in metrics.items():
941
+ self._stored_metrics[train_eval][key].append(value)
942
+
943
+ def evaluation_loop(
944
+ self,
945
+ dataloader: DataLoader,
946
+ description: str,
947
+ prediction_loss_only: bool | None = None,
948
+ ignore_keys: list[str] | None = None,
949
+ metric_key_prefix: str = "eval",
950
+ ) -> EvalLoopOutput:
951
+ """
952
+ Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by
953
+ `Trainer.evaluate()` and `Trainer.predict()`.
954
+
955
+ Works both with or without labels.
956
+ """
957
+
958
+ # Sample and save to game log if requested (for one batch to save time)
959
+ if self.generate_during_eval:
960
+ # Generate random indices within the range of the total number of samples
961
+ num_samples = len(dataloader.dataset)
962
+ random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size)
963
+
964
+ # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader
965
+ random_batch_dataset = dataloader.dataset.select(random_indices)
966
+ random_batch = self.data_collator(random_batch_dataset)
967
+ random_batch = self._prepare_inputs(random_batch)
968
+
969
+ policy_output_decoded = self.generate_from_model(self.model, random_batch)
970
+
971
+ table = pd.DataFrame(
972
+ columns=["Prompt", "Policy"],
973
+ data=[
974
+ [prompt, pol[len(prompt) :]]
975
+ for prompt, pol in zip(random_batch["prompt"], policy_output_decoded, strict=True)
976
+ ],
977
+ )
978
+ if "wandb" in self.args.report_to:
979
+ wandb.log({"game_log": wandb.Table(data=table)})
980
+
981
+ if "comet_ml" in self.args.report_to:
982
+ log_table_to_comet_experiment(
983
+ name="game_log.csv",
984
+ table=table,
985
+ )
986
+
987
+ # Base evaluation
988
+ initial_output = super().evaluation_loop(
989
+ dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix
990
+ )
991
+
992
+ return initial_output
993
+
994
+ def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
995
+ """
996
+ Log `logs` on the various objects watching training, including stored metrics.
997
+
998
+ Args:
999
+ logs (`dict[str, float]`):
1000
+ The values to log.
1001
+ start_time (`float`, *optional*):
1002
+ Start time of the training.
1003
+ """
1004
+ # logs either has 'loss' or 'eval_loss'
1005
+ train_eval = "train" if "loss" in logs else "eval"
1006
+ # Add averaged stored metrics to logs
1007
+ for key, metrics in self._stored_metrics[train_eval].items():
1008
+ logs[key] = torch.tensor(metrics).mean().item()
1009
+ del self._stored_metrics[train_eval]
1010
+ return super().log(logs, start_time)
1011
+
1012
+ def _shift_right(self, input_ids):
1013
+ if self.decoder_start_token_id is None:
1014
+ raise ValueError(
1015
+ "model.config.decoder_start_token_id has to be defined. It is usually set to the pad_token_id."
1016
+ )
1017
+
1018
+ # shift inputs to the right
1019
+ if is_torch_fx_proxy(input_ids):
1020
+ # Item assignment is not supported natively for proxies.
1021
+ shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), self.decoder_start_token_id)
1022
+ shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1)
1023
+ else:
1024
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
1025
+ shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
1026
+ shifted_input_ids[..., 0] = self.decoder_start_token_id
1027
+
1028
+ if self.pad_token_id is None:
1029
+ raise ValueError("model.config.pad_token_id has to be defined.")
1030
+ # replace possible -100 values in labels by `pad_token_id`
1031
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, self.pad_token_id)
1032
+
1033
+ return shifted_input_ids
1034
+
1035
+ # Ensure the model card is saved along with the checkpoint
1036
+ def _save_checkpoint(self, model, trial):
1037
+ if self.args.hub_model_id is None:
1038
+ model_name = Path(self.args.output_dir).name
1039
+ else:
1040
+ model_name = self.args.hub_model_id.split("/")[-1]
1041
+ self.create_model_card(model_name=model_name)
1042
+ super()._save_checkpoint(model, trial)
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/papo/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from .papo_config import PAPOConfig
17
+ from .papo_trainer import PAPOTrainer
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/papo/papo_config.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass
16
+ from typing import Literal
17
+
18
+ from ...trainer.grpo_config import GRPOConfig
19
+
20
+
21
+ @dataclass
22
+ class PAPOConfig(GRPOConfig):
23
+ """
24
+ Configuration class for PAPOTrainer.
25
+
26
+ PAPO (Perception-Aware Policy Optimization) extends GRPO/DAPO for multimodal reasoning by adding an implicit
27
+ perception loss and double entropy regularization.
28
+
29
+ Args:
30
+ perception_loss_weight (`float`, *optional*, defaults to `0.1`):
31
+ gamma Weight coefficient for the perception loss term. This encourages the model to be sensitive to visual
32
+ changes.
33
+
34
+ mask_ratio (`float`, *optional*, defaults to `0.3`):
35
+ Ratio of the image to mask when computing perception loss.
36
+
37
+ mask_type (`Literal["random", "patch", "grid"]`, *optional*, defaults to `"random"`):
38
+ Type of masking strategy to use.
39
+
40
+ der_loss_weight1 (`float`, *optional*, defaults to `0.03`):
41
+ eta1 Weight coefficient for the Double Entropy Regularization (DER) term. This term encourages confident
42
+ predictions with original images (low entropy) and uncertain predictions with masked images (high entropy).
43
+
44
+ der_loss_weight2 (`float`, *optional*, defaults to `0.03`):
45
+ eta2 Weight coefficient for the Double Entropy Regularization (DER) term. This term encourages confident
46
+ predictions with original images (low entropy) and uncertain predictions with masked images (high entropy).
47
+
48
+ loss_type (`Literal["grpo", "dapo"]`, inherited from GRPOConfig):
49
+ Base loss type to use. Set to "grpo" for PAPO-G or "dapo" for PAPO-D.
50
+ """
51
+
52
+ perception_loss_weight: float = 0.1
53
+ mask_ratio: float = 0.3
54
+ mask_type: Literal["random", "patch", "grid"] = "random"
55
+
56
+ # Added for Double Entropy Regularization
57
+ der_loss_weight1: float = 0.03
58
+ der_loss_weight2: float = 0.03
59
+
60
+ def __post_init__(self):
61
+ super().__post_init__()
62
+
63
+ # Validation
64
+ if not 0.0 <= self.mask_ratio <= 1.0:
65
+ raise ValueError(f"mask_ratio must be between 0 and 1, got {self.mask_ratio}")
66
+
67
+ if self.der_loss_weight1 < 0 or self.der_loss_weight2 < 0:
68
+ raise ValueError(
69
+ f"der_loss_weight1 and der_loss_weight2 must be non-negative, got {self.der_loss_weight1} and {self.der_loss_weight2}"
70
+ )
71
+
72
+ if self.mask_type not in ["random", "patch", "grid"]:
73
+ raise ValueError(f"mask_type must be one of ['random', 'patch', 'grid'], got {self.mask_type}")
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/papo/papo_trainer.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import random
16
+ import textwrap
17
+
18
+ import torch
19
+ from datasets import Dataset, IterableDataset
20
+ from transformers import PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin
21
+
22
+ from ...trainer.grpo_trainer import GRPOTrainer, RewardFunc
23
+ from ...trainer.utils import nanmax, nanmin
24
+ from .papo_config import PAPOConfig
25
+
26
+
27
+ class PAPOTrainer(GRPOTrainer):
28
+ """
29
+ Trainer for Perception-Aware Policy Optimization (PAPO).
30
+
31
+ PAPO extends GRPO/DAPO for multimodal reasoning by adding an implicit perception loss that encourages the model to
32
+ better utilize visual information. The key innovation is computing KL divergence between model outputs on original
33
+ vs. corrupted (masked) images.
34
+
35
+ Two variants are supported:
36
+ - PAPO-G: PAPO + GRPO (use loss_type="grpo")
37
+ - PAPO-D: PAPO + DAPO (use loss_type="dapo")
38
+
39
+ Example:
40
+
41
+ ```python
42
+ from datasets import load_dataset
43
+ from trl.experimental.papo import PAPOTrainer, PAPOConfig
44
+
45
+ dataset = load_dataset("your-vlm-dataset", split="train")
46
+
47
+
48
+ def reward_func(completions, **kwargs):
49
+ # Your reward function for multimodal reasoning
50
+ return [compute_reward(c) for c in completions]
51
+
52
+
53
+ # PAPO-G
54
+ config = PAPOConfig(
55
+ loss_type="grpo", # Use GRPO as base
56
+ perception_loss_weight=0.1,
57
+ mask_ratio=0.3,
58
+ )
59
+
60
+ # PAPO-G
61
+ config = PAPOConfig(
62
+ loss_type="dapo", # Use DAPO as base
63
+ perception_loss_weight=0.1,
64
+ mask_ratio=0.3,
65
+ )
66
+
67
+ trainer = PAPOTrainer(
68
+ model="Qwen/Qwen2-VL-2B-Instruct",
69
+ reward_funcs=reward_func,
70
+ args=config,
71
+ train_dataset=dataset,
72
+ )
73
+
74
+ trainer.train()
75
+ ```
76
+
77
+ Args:
78
+ model (`Union[str, PreTrainedModel]`):
79
+ Model to be trained (must be a vision-language model).
80
+ reward_funcs (`Union[RewardFunc, list[RewardFunc]]`):
81
+ Reward functions for computing rewards (same as GRPO).
82
+ args ([`PAPOConfig`], *optional*, defaults to `None`):
83
+ Configuration for this trainer. If `None`, a default configuration is used.
84
+ train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
85
+ Dataset to use for training. Must include "prompt" and "image" columns.
86
+ eval_dataset: Same requirements as train_dataset.
87
+ processing_class: Processing class (tokenizer/processor) for the model.
88
+ reward_processing_classes: Processing classes for reward models.
89
+ callbacks: Training callbacks.
90
+ optimizers: Optimizer and scheduler tuple.
91
+ peft_config: PEFT configuration if using parameter-efficient fine-tuning.
92
+ """
93
+
94
+ _tag_names = ["trl", "papo"]
95
+ _name = "PAPO"
96
+ _paper = {
97
+ "title": "Perception-Aware Policy Optimization for Multimodal Reasoning",
98
+ "id": "2507.06448",
99
+ # docstyle-ignore
100
+ "citation": textwrap.dedent(
101
+ """\
102
+ @misc{wang2025perceptionawarepolicyoptimizationmultimodal,
103
+ title = {{Perception-Aware Policy Optimization for Multimodal Reasoning}},
104
+ author = {Zhenhailong Wang and Xuehang Guo and Sofia Stoica and Haiyang Xu and Hongru Wang and Hyeonjeong Ha and Xiusi Chen and Yangyi Chen and Ming Yan and Fei Huang and Heng Ji},
105
+ year = 2025,
106
+ url = {https://arxiv.org/abs/2507.06448},
107
+ archivePrefix= {arXiv},
108
+ eprint = {2507.06448},
109
+ primaryClass = {cs.CL}
110
+ }"""
111
+ ),
112
+ }
113
+
114
+ def __init__(
115
+ self,
116
+ model: str | PreTrainedModel,
117
+ reward_funcs: RewardFunc | list[RewardFunc],
118
+ args: PAPOConfig | None = None,
119
+ train_dataset: Dataset | IterableDataset | None = None,
120
+ eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
121
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
122
+ reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
123
+ callbacks=None,
124
+ optimizers=(None, None),
125
+ peft_config=None,
126
+ ):
127
+ # Initialize with default PAPO config if not provided
128
+ if args is None:
129
+ model_name = model if isinstance(model, str) else model.config._name_or_path
130
+ model_name = model_name.split("/")[-1]
131
+ args = PAPOConfig(f"{model_name}-PAPO")
132
+
133
+ # Store PAPO-specific parameters
134
+ self.perception_loss_weight = args.perception_loss_weight
135
+ self.mask_ratio = args.mask_ratio
136
+ self.mask_type = args.mask_type
137
+ self.der_loss_weight1 = args.der_loss_weight1
138
+ self.der_loss_weight2 = args.der_loss_weight2
139
+
140
+ # Initialize parent GRPO trainer
141
+ super().__init__(
142
+ model=model,
143
+ reward_funcs=reward_funcs,
144
+ args=args,
145
+ train_dataset=train_dataset,
146
+ eval_dataset=eval_dataset,
147
+ processing_class=processing_class,
148
+ reward_processing_classes=reward_processing_classes,
149
+ callbacks=callbacks,
150
+ optimizers=optimizers,
151
+ peft_config=peft_config,
152
+ )
153
+
154
+ def _mask_image(self, pixel_values: torch.Tensor, mask_ratio: float = None) -> torch.Tensor:
155
+ """
156
+ Apply masking to image pixel values.
157
+
158
+ Args:
159
+ pixel_values: Image tensor of shape (B, C, H, W) or (B, N, C, H, W) for multi-image
160
+ mask_ratio: Ratio of image to mask (defaults to self.mask_ratio)
161
+
162
+ Returns:
163
+ Masked pixel values tensor
164
+ """
165
+ if mask_ratio is None:
166
+ mask_ratio = self.mask_ratio
167
+
168
+ masked_pixel_values = pixel_values.clone()
169
+
170
+ if self.mask_type == "random":
171
+ # Random pixel masking
172
+ mask = torch.rand_like(pixel_values) > mask_ratio
173
+ masked_pixel_values = masked_pixel_values * mask
174
+
175
+ elif self.mask_type == "patch":
176
+ # Patch-based masking (mask contiguous regions)
177
+ B = pixel_values.shape[0]
178
+ if pixel_values.ndim == 4: # (B, C, H, W)
179
+ C, H, W = pixel_values.shape[1:]
180
+ for i in range(B):
181
+ # Calculate patch size to mask
182
+ patch_h = int(H * mask_ratio**0.5)
183
+ patch_w = int(W * mask_ratio**0.5)
184
+ # Random starting position
185
+ start_h = random.randint(0, max(0, H - patch_h))
186
+ start_w = random.randint(0, max(0, W - patch_w))
187
+ # Apply mask
188
+ masked_pixel_values[i, :, start_h : start_h + patch_h, start_w : start_w + patch_w] = 0
189
+
190
+ elif pixel_values.ndim == 5: # (B, N, C, H, W) for multi-image
191
+ N, C, H, W = pixel_values.shape[1:]
192
+ for i in range(B):
193
+ for n in range(N):
194
+ patch_h = int(H * mask_ratio**0.5)
195
+ patch_w = int(W * mask_ratio**0.5)
196
+ start_h = random.randint(0, max(0, H - patch_h))
197
+ start_w = random.randint(0, max(0, W - patch_w))
198
+ masked_pixel_values[i, n, :, start_h : start_h + patch_h, start_w : start_w + patch_w] = 0
199
+
200
+ elif self.mask_type == "grid":
201
+ # Grid-based masking (mask regular grid cells)
202
+ if pixel_values.ndim == 4:
203
+ C, H, W = pixel_values.shape[1:]
204
+ grid_size = int((1 / mask_ratio) ** 0.5)
205
+ cell_h, cell_w = H // grid_size, W // grid_size
206
+
207
+ for i in range(grid_size):
208
+ for j in range(grid_size):
209
+ if random.random() < mask_ratio:
210
+ masked_pixel_values[:, :, i * cell_h : (i + 1) * cell_h, j * cell_w : (j + 1) * cell_w] = 0
211
+
212
+ return masked_pixel_values
213
+
214
+ def _compute_loss(self, model, inputs):
215
+ # >>> 1. GRPO loss
216
+ # Compute the per-token log probabilities for the model
217
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
218
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
219
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
220
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
221
+ logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
222
+
223
+ # Compute the per_token_logps and the entropy at each position in the completion
224
+ per_token_logps, entropies, _ = self._get_per_token_logps_and_entropies(
225
+ model,
226
+ input_ids,
227
+ attention_mask,
228
+ logits_to_keep,
229
+ compute_entropy=True,
230
+ pixel_values=inputs.get("pixel_values"),
231
+ image_grid_thw=inputs.get("image_grid_thw"),
232
+ num_images=inputs.get("num_images"),
233
+ pixel_attention_mask=inputs.get("pixel_attention_mask"),
234
+ image_sizes=inputs.get("image_sizes"),
235
+ )
236
+
237
+ if self.top_entropy_quantile < 1.0:
238
+ entropy_mask = self.get_high_entropy_mask(entropies, completion_mask, 1 - self.top_entropy_quantile)
239
+ else:
240
+ entropy_mask = None
241
+
242
+ # Compute the KL divergence between the model and the reference model
243
+ if self.beta != 0.0:
244
+ ref_per_token_logps = inputs["ref_per_token_logps"]
245
+ per_token_kl = (
246
+ torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
247
+ )
248
+
249
+ # Compute the loss
250
+ advantages = inputs["advantages"]
251
+ # When using num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps
252
+ # old_per_token_logps == per_token_logps, so we can skip it's computation
253
+ # (see _generate_and_score_completions) and use per_token_logps.detach() instead.
254
+ old_per_token_logps = inputs.get("old_per_token_logps")
255
+ old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps
256
+
257
+ log_ratio = per_token_logps - old_per_token_logps
258
+ if self.importance_sampling_level == "token":
259
+ log_importance_weights = log_ratio
260
+ elif self.importance_sampling_level == "sequence":
261
+ log_importance_weights = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)
262
+ log_importance_weights = log_importance_weights.unsqueeze(-1)
263
+ else:
264
+ raise ValueError(
265
+ f"Unknown importance sampling level: {self.importance_sampling_level}. Possible values are 'token' "
266
+ "and 'sequence'."
267
+ )
268
+ # From here, log_importance_weights (and all subsequent tensors, coef_1, coef_2, etc.) shape depends on
269
+ # importance_sampling_level: "token" level: (B, T); "sequence" level: (B, 1)
270
+
271
+ coef_1 = torch.exp(log_importance_weights)
272
+ coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
273
+
274
+ # Two-sided clipping
275
+ if self.args.delta is not None:
276
+ coef_1 = torch.clamp(coef_1, max=self.args.delta)
277
+
278
+ per_token_loss1 = coef_1 * advantages.unsqueeze(1)
279
+ per_token_loss2 = coef_2 * advantages.unsqueeze(1)
280
+ per_token_loss = -torch.min(per_token_loss1, per_token_loss2)
281
+ if entropy_mask is not None:
282
+ per_token_loss = per_token_loss * entropy_mask
283
+ if self.beta != 0.0:
284
+ per_token_loss = per_token_loss + self.beta * per_token_kl
285
+
286
+ if self.loss_type == "grpo":
287
+ loss = ((per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)).mean()
288
+ loss = loss / self.current_gradient_accumulation_steps
289
+ elif self.loss_type == "dapo":
290
+ normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes
291
+ loss = (per_token_loss * completion_mask).sum() / normalizer
292
+ else:
293
+ raise ValueError(f"Unknown loss type: {self.loss_type}")
294
+ # >>> 2. Implicit Perception Loss
295
+ inputs["pixel_values"] = self._mask_image(inputs["pixel_values"], self.mask_ratio)
296
+ mask_img_per_token_logps, mask_img_entropies, _ = self._get_per_token_logps_and_entropies(
297
+ model,
298
+ input_ids,
299
+ attention_mask,
300
+ logits_to_keep,
301
+ compute_entropy=True,
302
+ pixel_values=inputs.get("pixel_values"),
303
+ image_grid_thw=inputs.get("image_grid_thw"),
304
+ num_images=inputs.get("num_images"),
305
+ pixel_attention_mask=inputs.get("pixel_attention_mask"),
306
+ image_sizes=inputs.get("image_sizes"),
307
+ )
308
+ perception_kl = (
309
+ torch.exp(mask_img_per_token_logps - per_token_logps) - (mask_img_per_token_logps - per_token_logps) - 1
310
+ )
311
+ perception_kl = torch.clamp(perception_kl, min=0.0, max=0.2)
312
+ perception_loss = self.perception_loss_weight * perception_kl
313
+
314
+ # >>> 3. Double Entropy Loss
315
+ der_loss = self.der_loss_weight1 * entropies + self.der_loss_weight2 * mask_img_entropies
316
+
317
+ # PAPO Loss
318
+ loss = (loss - perception_loss + der_loss).mean()
319
+ # Log the metrics
320
+ mode = "train" if self.model.training else "eval"
321
+
322
+ completion_token_count = completion_mask.sum().clamp(min=1.0)
323
+
324
+ def masked_batch_mean(x):
325
+ if x.shape[1] == 1: # when importance_sampling_level == "sequence"
326
+ return x.mean()
327
+ else:
328
+ return (x * completion_mask).sum() / completion_token_count
329
+
330
+ if self.beta != 0.0:
331
+ mean_kl = masked_batch_mean(per_token_kl)
332
+ self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
333
+
334
+ mean_entropy = masked_batch_mean(entropies)
335
+ self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item())
336
+
337
+ # Compute the clipped probability ratios
338
+ is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages.unsqueeze(1) < 0)
339
+ is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages.unsqueeze(1) > 0)
340
+ is_region_clipped = is_low_clipped | is_high_clipped
341
+
342
+ low_clip = masked_batch_mean(is_low_clipped.float())
343
+ high_clip = masked_batch_mean(is_high_clipped.float())
344
+ clip_ratio = masked_batch_mean(is_region_clipped.float())
345
+
346
+ gathered_low_clip = self.accelerator.gather(low_clip)
347
+ self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item())
348
+ self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item())
349
+ gathered_high_clip = self.accelerator.gather(high_clip)
350
+ self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item())
351
+ self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item())
352
+ gathered_clip_ratio = self.accelerator.gather(clip_ratio)
353
+ self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item())
354
+ return loss
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ppo/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .modeling_value_head import (
16
+ AutoModelForCausalLMWithValueHead,
17
+ AutoModelForSeq2SeqLMWithValueHead,
18
+ PreTrainedModelWrapper,
19
+ )
20
+ from .ppo_config import PPOConfig
21
+ from .ppo_trainer import PPOTrainer
22
+
23
+
24
+ __all__ = [
25
+ "AutoModelForCausalLMWithValueHead",
26
+ "AutoModelForSeq2SeqLMWithValueHead",
27
+ "PreTrainedModelWrapper",
28
+ "PPOConfig",
29
+ "PPOTrainer",
30
+ ]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ppo/modeling_value_head.py ADDED
@@ -0,0 +1,1020 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import json
16
+ import logging
17
+ import os
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ from accelerate import PartialState
22
+ from huggingface_hub import hf_hub_download
23
+ from huggingface_hub.utils import (
24
+ EntryNotFoundError,
25
+ HFValidationError,
26
+ LocalEntryNotFoundError,
27
+ RepositoryNotFoundError,
28
+ )
29
+ from safetensors.torch import load_file as safe_load_file
30
+ from transformers import (
31
+ AutoModelForCausalLM,
32
+ AutoModelForSeq2SeqLM,
33
+ PreTrainedModel,
34
+ is_torch_npu_available,
35
+ is_torch_xpu_available,
36
+ )
37
+ from transformers.utils import is_peft_available
38
+
39
+
40
+ if is_peft_available():
41
+ from peft import (
42
+ PeftConfig,
43
+ PeftModel,
44
+ PeftModelForCausalLM,
45
+ PeftModelForSeq2SeqLM,
46
+ PromptLearningConfig,
47
+ get_peft_model,
48
+ prepare_model_for_kbit_training,
49
+ )
50
+
51
+
52
+ class PreTrainedModelWrapper(nn.Module):
53
+ """
54
+ Wrapper for a [`~transformers.PreTrainedModel`] implemented as a standard PyTorch [`torch.nn.Module`].
55
+
56
+ This class provides a compatibility layer that preserves the key attributes and methods of the original
57
+ [`~transformers.PreTrainedModel`], while exposing a uniform interface consistent with PyTorch modules. It enables
58
+ seamless integration of pretrained Transformer models into custom training, evaluation, or inference workflows.
59
+
60
+ Attributes:
61
+ pretrained_model ([`~transformers.PreTrainedModel`]):
62
+ The model to be wrapped.
63
+ parent_class ([`~transformers.PreTrainedModel`]):
64
+ The parent class of the model to be wrapped.
65
+ supported_args (`list`):
66
+ The list of arguments that are supported by the wrapper class.
67
+ """
68
+
69
+ transformers_parent_class = None
70
+ supported_args = None
71
+ supported_modules = ("v_head",)
72
+ supported_rm_modules = ("score",)
73
+ supported_pretrained_model_architectures = (
74
+ (PreTrainedModel)
75
+ if not is_peft_available()
76
+ else (PreTrainedModel, PeftModelForCausalLM, PeftModelForSeq2SeqLM)
77
+ )
78
+
79
+ def __init__(
80
+ self, pretrained_model=None, score_module=None, supports_rm_adapter=False, rm_adapter_name=None, **kwargs
81
+ ):
82
+ super().__init__()
83
+ self.pretrained_model = pretrained_model
84
+
85
+ self.config = pretrained_model.config
86
+ self.prepare_inputs_for_generation = pretrained_model.prepare_inputs_for_generation
87
+ self.is_loaded_in_8bit = getattr(pretrained_model, "is_loaded_in_8bit", False)
88
+ self.is_loaded_in_4bit = getattr(pretrained_model, "is_loaded_in_4bit", False)
89
+ self.is_sequential_parallel = False
90
+
91
+ if hasattr(pretrained_model, "gradient_checkpointing_disable"):
92
+ self.gradient_checkpointing_disable = pretrained_model.gradient_checkpointing_disable
93
+
94
+ if hasattr(pretrained_model, "gradient_checkpointing_enable"):
95
+ self.gradient_checkpointing_enable = pretrained_model.gradient_checkpointing_enable
96
+
97
+ if hasattr(pretrained_model, "enable_input_require_grads"):
98
+ self.enable_input_require_grads = pretrained_model.enable_input_require_grads
99
+
100
+ self.supports_rm_adapter = supports_rm_adapter
101
+ self.rm_adapter_name = rm_adapter_name
102
+ self.policy_adapter_name = "default"
103
+ if score_module is not None:
104
+ self.score = score_module
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
108
+ r"""
109
+ Instantiates a new model from a pretrained model from `transformers`. The pretrained model is loaded using the
110
+ `from_pretrained` method of the [`~transformers.PreTrainedModel`] class. The arguments that are specific to the
111
+ [`~transformers.PreTrainedModel`] class are passed along this method and filtered out from the `kwargs`
112
+ argument.
113
+
114
+ Args:
115
+ pretrained_model_name_or_path (`str` or [`~transformers.PreTrainedModel`]):
116
+ The path to the pretrained model or its name.
117
+ *model_args (`list`, *optional*):
118
+ Additional positional arguments passed along to the underlying model's `from_pretrained` method.
119
+ **kwargs (`dict`, *optional*):
120
+ Additional keyword arguments passed along to the underlying model's `from_pretrained` method. We also
121
+ pre-process the kwargs to extract the arguments that are specific to the
122
+ [`~transformers.PreTrainedModel`] class and the arguments that are specific to trl models. The kwargs
123
+ also support `prepare_model_for_kbit_training` arguments from `peft` library.
124
+ """
125
+ if kwargs is not None:
126
+ peft_config = kwargs.pop("peft_config", None)
127
+ reward_adapter = kwargs.pop("reward_adapter", None)
128
+ reward_adapter_name = kwargs.pop("reward_adapter_name", "reward_adapter")
129
+ is_trainable = kwargs.pop("is_trainable", False)
130
+ trl_model_args, pretrained_kwargs, peft_quantization_kwargs = cls._split_kwargs(kwargs)
131
+ token = pretrained_kwargs.get("token", None)
132
+ else:
133
+ peft_config = None
134
+ is_trainable = False
135
+ trl_model_args = {}
136
+ pretrained_kwargs = {}
137
+ peft_quantization_kwargs = {}
138
+ token = None
139
+
140
+ if reward_adapter is not None and not isinstance(reward_adapter, str):
141
+ raise ValueError(
142
+ "The `reward_adapter` argument should be a string representing the name of local path or the Hub id to the Reward Modeling adapter."
143
+ )
144
+
145
+ is_peft_model = False
146
+
147
+ current_device = cls._get_current_device()
148
+ if isinstance(pretrained_model_name_or_path, str):
149
+ quantization_config = pretrained_kwargs.get("quantization_config", None)
150
+ if quantization_config is not None:
151
+ is_loaded_in_8bit = getattr(quantization_config, "load_in_8bit", False)
152
+ is_loaded_in_4bit = getattr(quantization_config, "load_in_4bit", False)
153
+ else:
154
+ is_loaded_in_8bit = pretrained_kwargs["load_in_8bit"] if "load_in_8bit" in pretrained_kwargs else False
155
+ is_loaded_in_4bit = pretrained_kwargs["load_in_4bit"] if "load_in_4bit" in pretrained_kwargs else False
156
+ else:
157
+ is_loaded_in_8bit = getattr(pretrained_model_name_or_path, "is_loaded_in_8bit", False)
158
+ is_loaded_in_4bit = getattr(pretrained_model_name_or_path, "is_loaded_in_4bit", False)
159
+
160
+ if (is_loaded_in_8bit or is_loaded_in_4bit) and "device_map" not in pretrained_kwargs:
161
+ # warn users
162
+ logging.warning(
163
+ "The `device_map` argument is not provided. We will override the device_map argument."
164
+ " to set the entire"
165
+ " model on the current device. If you want to set the model on multiple devices, please provide"
166
+ " a custom `device_map` argument."
167
+ )
168
+ pretrained_kwargs["device_map"] = {"": current_device}
169
+
170
+ if is_peft_available() and peft_config is not None and not isinstance(peft_config, PeftConfig):
171
+ raise ValueError("The `peft_config` argument should be an instance of `peft.PeftConfig` class.")
172
+
173
+ # First, load the pre-trained model using the parent-class
174
+ # either `AutoModelForCausalLM` or `AutoModelForSeq2SeqLM`
175
+ if isinstance(pretrained_model_name_or_path, str):
176
+ if is_peft_available():
177
+ try:
178
+ # If there is a trained peft adapter in the hub, load its config.
179
+ remote_adapter_config = hf_hub_download(
180
+ pretrained_model_name_or_path,
181
+ "adapter_config.json",
182
+ token=token,
183
+ )
184
+ except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
185
+ remote_adapter_config = None
186
+ else:
187
+ remote_adapter_config = None
188
+
189
+ local_adapter_present = os.path.exists(os.path.join(pretrained_model_name_or_path, "adapter_config.json"))
190
+
191
+ if (local_adapter_present or remote_adapter_config is not None) and is_peft_available():
192
+ if peft_config is not None:
193
+ logging.warning(
194
+ "`peft_config` argument ignored since a peft config file was found in "
195
+ f"{pretrained_model_name_or_path}"
196
+ )
197
+
198
+ # Load the trained peft adapter config
199
+ if local_adapter_present:
200
+ trained_adapter_config = PeftConfig.from_pretrained(pretrained_model_name_or_path)
201
+ else:
202
+ remote_adapter_dir = os.path.dirname(remote_adapter_config)
203
+ trained_adapter_config = PeftConfig.from_pretrained(remote_adapter_dir)
204
+
205
+ # Load the pretrained base model
206
+ pretrained_model = cls.transformers_parent_class.from_pretrained(
207
+ trained_adapter_config.base_model_name_or_path, *model_args, **pretrained_kwargs
208
+ )
209
+
210
+ # Wrap the pretrained model with the trained peft adapter
211
+ pretrained_model = PeftModel.from_pretrained(
212
+ pretrained_model, pretrained_model_name_or_path, is_trainable=is_trainable, token=token
213
+ )
214
+ logging.info("Trained peft adapter loaded")
215
+ else:
216
+ pretrained_model = cls.transformers_parent_class.from_pretrained(
217
+ pretrained_model_name_or_path, *model_args, **pretrained_kwargs
218
+ )
219
+
220
+ if peft_config is not None:
221
+ # Initialize a new peft adapter with the given config
222
+ if is_loaded_in_8bit or is_loaded_in_4bit:
223
+ pretrained_model = prepare_model_for_kbit_training(
224
+ pretrained_model,
225
+ **peft_quantization_kwargs,
226
+ )
227
+ pretrained_model = get_peft_model(pretrained_model, peft_config)
228
+ logging.info("peft adapter initialised")
229
+
230
+ elif isinstance(pretrained_model_name_or_path, cls.supported_pretrained_model_architectures):
231
+ pretrained_model = pretrained_model_name_or_path
232
+
233
+ if peft_config is not None and isinstance(pretrained_model, PreTrainedModel):
234
+ # Initialize a new peft adapter with the given config
235
+ if is_loaded_in_8bit or is_loaded_in_4bit:
236
+ pretrained_model = prepare_model_for_kbit_training(
237
+ pretrained_model,
238
+ **peft_quantization_kwargs,
239
+ )
240
+ pretrained_model = get_peft_model(pretrained_model, peft_config)
241
+ logging.info("peft adapter initialised")
242
+ else:
243
+ raise ValueError(
244
+ "pretrained_model_name_or_path should be a string or a PreTrainedModel, "
245
+ f"but is {type(pretrained_model_name_or_path)}"
246
+ )
247
+
248
+ if is_peft_available():
249
+ if isinstance(pretrained_model, PeftModel):
250
+ is_peft_model = True
251
+ # for backward compatibility
252
+ if hasattr(pretrained_model, "active_peft_config") and isinstance(
253
+ pretrained_model.active_peft_config, PromptLearningConfig
254
+ ):
255
+ raise ValueError("PromptLearningConfig is not supported for PPO training.")
256
+
257
+ # Add reward modeling adapter if specified
258
+ if not is_peft_model and reward_adapter is not None:
259
+ raise ValueError("reward_adapter can only be used with a PeftModel. ")
260
+ elif is_peft_model and reward_adapter is not None:
261
+ score_module = cls.add_and_load_reward_modeling_adapter(
262
+ pretrained_model, reward_adapter, reward_adapter_name, token=token
263
+ )
264
+ multi_adapter_args = {
265
+ "score_module": score_module,
266
+ "supports_rm_adapter": True,
267
+ "rm_adapter_name": reward_adapter_name,
268
+ }
269
+ else:
270
+ multi_adapter_args = {"supports_rm_adapter": False}
271
+
272
+ # Then, create the full model by instantiating the wrapper class
273
+ model = cls(pretrained_model, **multi_adapter_args, **trl_model_args)
274
+
275
+ # if resume_training, load the state_dict again - this is ok since the
276
+ # state_dict is removed from the model after loading it.
277
+ is_resuming_training = True
278
+ if isinstance(pretrained_model_name_or_path, str):
279
+ safe_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors")
280
+ filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin")
281
+
282
+ sharded_index_filename = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin.index.json")
283
+ safe_sharded_index_filename = os.path.join(pretrained_model_name_or_path, "model.safetensors.index.json")
284
+ is_sharded = False
285
+ use_safe = os.path.exists(safe_filename)
286
+
287
+ if not (os.path.exists(filename) or os.path.exists(safe_filename)):
288
+ # Try with `pytorch_model.bin`
289
+ filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub(
290
+ pretrained_model,
291
+ pretrained_model_name_or_path,
292
+ sharded_index_filename,
293
+ token=token,
294
+ )
295
+ # Try with safetensors
296
+ if filename is None and files_to_download is None:
297
+ safe_filename, files_to_download, is_sharded, is_resuming_training = cls._get_checkpoint_from_hub(
298
+ pretrained_model,
299
+ pretrained_model_name_or_path,
300
+ safe_sharded_index_filename,
301
+ token=token,
302
+ model_name="model.safetensors",
303
+ model_index_name="model.safetensors.index.json",
304
+ )
305
+ use_safe = True
306
+ else:
307
+ use_safe = False
308
+
309
+ loading_func = safe_load_file if use_safe else torch.load
310
+ load_kwargs = {} if use_safe else {"map_location": "cpu", "weights_only": True}
311
+
312
+ if is_resuming_training:
313
+ if is_sharded:
314
+ # download each file and add it to the state_dict
315
+ state_dict = {}
316
+
317
+ for shard_file in files_to_download:
318
+ filename = hf_hub_download(
319
+ pretrained_model_name_or_path,
320
+ shard_file,
321
+ token=token,
322
+ )
323
+ state_dict.update(loading_func(filename, **load_kwargs))
324
+ else:
325
+ state_dict = loading_func(filename if not use_safe else safe_filename, **load_kwargs)
326
+
327
+ else:
328
+ state_dict = pretrained_model_name_or_path.state_dict()
329
+
330
+ model.is_peft_model = is_peft_model
331
+ model.current_device = current_device
332
+
333
+ if is_resuming_training:
334
+ model.post_init(state_dict=state_dict)
335
+
336
+ return model
337
+
338
+ @classmethod
339
+ def _get_checkpoint_from_hub(
340
+ cls,
341
+ pretrained_model,
342
+ pretrained_model_name_or_path,
343
+ index_filename,
344
+ token=None,
345
+ model_name="pytorch_model.bin",
346
+ model_index_name="pytorch_model.bin.index.json",
347
+ ):
348
+ files_to_download = None
349
+ filename = None
350
+ is_resuming_training = True
351
+ is_sharded = False
352
+
353
+ try:
354
+ filename = hf_hub_download(
355
+ pretrained_model_name_or_path,
356
+ model_name,
357
+ token=token,
358
+ )
359
+ # sharded
360
+ except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
361
+ if os.path.exists(index_filename):
362
+ index_file_name = index_filename
363
+ else:
364
+ try:
365
+ index_file_name = hf_hub_download(
366
+ pretrained_model_name_or_path,
367
+ model_index_name,
368
+ token=token,
369
+ )
370
+ except (EntryNotFoundError, LocalEntryNotFoundError, HFValidationError, RepositoryNotFoundError):
371
+ # not continue training, do not have v_head weight
372
+ is_resuming_training = False
373
+ logging.warning(
374
+ f"A {type(pretrained_model)} model is loaded from '{pretrained_model_name_or_path}', "
375
+ f"and no v_head weight is found. This IS expected if you are not resuming PPO training."
376
+ )
377
+ # load json
378
+ if is_resuming_training:
379
+ with open(index_file_name) as f:
380
+ index = json.load(f)
381
+ # check filename with `v_head` or any known extra module:
382
+ files_to_download = set()
383
+ for k, v in index["weight_map"].items():
384
+ if any(module in k for module in cls.supported_modules):
385
+ files_to_download.add(v)
386
+ is_sharded = True
387
+
388
+ return filename, files_to_download, is_sharded, is_resuming_training
389
+
390
+ @classmethod
391
+ def _get_current_device(cls):
392
+ r"""
393
+ Get the current device. For GPU & XPU, we return the local process index using the `accelerate.PartialState`
394
+ object to handle corner cases when running scripts in distributed environments.
395
+
396
+ Returns:
397
+ current_device (`int | str`):
398
+ The current device.
399
+ """
400
+ state = PartialState()
401
+ if torch.cuda.is_available() or is_torch_xpu_available():
402
+ return state.local_process_index
403
+ elif is_torch_npu_available():
404
+ return f"npu:{state.local_process_index}"
405
+ else:
406
+ return "cpu"
407
+
408
+ @classmethod
409
+ def _split_kwargs(cls, kwargs):
410
+ """
411
+ Separate the kwargs from the arguments that we support inside `supported_args` and the ones that we don't.
412
+ """
413
+ check_peft_kwargs = False
414
+
415
+ if is_peft_available():
416
+ from peft import prepare_model_for_kbit_training
417
+
418
+ check_peft_kwargs = True
419
+
420
+ supported_kwargs = {}
421
+ unsupported_kwargs = {}
422
+ peft_kwargs = {}
423
+
424
+ for key, value in kwargs.items():
425
+ if key in cls.supported_args:
426
+ supported_kwargs[key] = value
427
+ else:
428
+ unsupported_kwargs[key] = value
429
+
430
+ if check_peft_kwargs:
431
+ if key in prepare_model_for_kbit_training.__code__.co_varnames:
432
+ peft_kwargs[key] = value
433
+ if key in unsupported_kwargs:
434
+ unsupported_kwargs.pop(key)
435
+
436
+ return supported_kwargs, unsupported_kwargs, peft_kwargs
437
+
438
+ @classmethod
439
+ def add_and_load_reward_modeling_adapter(
440
+ cls, pretrained_model, adapter_model_id, adapter_name="reward_model_adapter", token=None
441
+ ):
442
+ r"""
443
+ Add and load a reward modeling adapter. This method can only be used if the model is a `PeftModel` and if you
444
+ have initialized the model with the `reward_modeling_adapter_id` argument, pointing to the id of the reward
445
+ modeling adapter. The latest needs also to contain the score head in order to produce the reward.
446
+ """
447
+ pretrained_model.load_adapter(adapter_model_id, adapter_name, is_trainable=False)
448
+ pretrained_model.train()
449
+
450
+ filename = os.path.join(adapter_model_id, "adapter_model.bin")
451
+ safe_loading = False
452
+ if not os.path.exists(filename):
453
+ try:
454
+ local_filename = hf_hub_download(
455
+ adapter_model_id,
456
+ "adapter_model.bin",
457
+ token=token,
458
+ )
459
+ except Exception:
460
+ filename = os.path.join(adapter_model_id, "adapter_model.safetensors")
461
+ safe_loading = True
462
+ if not os.path.exists(filename):
463
+ try:
464
+ local_filename = hf_hub_download(
465
+ adapter_model_id,
466
+ "adapter_model.safetensors",
467
+ token=token,
468
+ )
469
+ except Exception as exc:
470
+ raise ValueError(
471
+ "Could not find adapter model in the Hub, make sure you have the correct adapter model id."
472
+ ) from exc
473
+ else:
474
+ local_filename = filename
475
+ else:
476
+ local_filename = filename
477
+
478
+ loading_func = safe_load_file if safe_loading else torch.load
479
+ load_kwargs = {} if safe_loading else {"map_location": "cpu", "weights_only": True}
480
+
481
+ adapter_state_dict = loading_func(local_filename, **load_kwargs)
482
+
483
+ for score_name_candidate in cls.supported_rm_modules:
484
+ if any(score_name_candidate in name for name in adapter_state_dict.keys()):
485
+ score_name = score_name_candidate
486
+ # we have found the correct head name and can break
487
+ break
488
+
489
+ score_dict = {}
490
+
491
+ for name, param in adapter_state_dict.items():
492
+ if score_name in name:
493
+ key_name = ".".join(name.split(".")[-1:])
494
+ score_dict[key_name] = param.to(cls._get_current_device())
495
+
496
+ num_labels, hidden_dim = score_dict["weight"].shape
497
+ has_bias = any("bias" in name for name in adapter_state_dict.keys())
498
+
499
+ score = nn.Linear(hidden_dim, num_labels, bias=has_bias).to(
500
+ device=cls._get_current_device(),
501
+ dtype=pretrained_model.dtype,
502
+ )
503
+ score.load_state_dict(score_dict)
504
+ for param in score.parameters():
505
+ param.requires_grad = False
506
+
507
+ return score
508
+
509
+ def push_to_hub(self, *args, **kwargs):
510
+ r"""
511
+ Push the pretrained model to the hub. This method is a wrapper around
512
+ [`~transformers.PreTrainedModel.push_to_hub`]. Please refer to the documentation of
513
+ [`~transformers.PreTrainedModel.push_to_hub`] for more information.
514
+
515
+ Args:
516
+ *args (`list`, *optional*):
517
+ Positional arguments passed along to the underlying model's `push_to_hub` method.
518
+ **kwargs (`dict`, *optional*):
519
+ Keyword arguments passed along to the underlying model's `push_to_hub` method.
520
+ """
521
+ raise NotImplementedError
522
+
523
+ def save_pretrained(self, *args, **kwargs):
524
+ r"""
525
+ Save the pretrained model to a directory. This method is a wrapper around
526
+ [`~transformers.PreTrainedModel.save_pretrained`]. Please refer to the documentation of
527
+ [`~transformers.PreTrainedModel.save_pretrained`] for more information.
528
+
529
+ Args:
530
+ *args (`list`, *optional*):
531
+ Positional arguments passed along to the underlying model's `save_pretrained` method.
532
+ **kwargs (`dict`, *optional*):
533
+ Keyword arguments passed along to the underlying model's `save_pretrained` method.
534
+ """
535
+ state_dict = kwargs.get("state_dict")
536
+ if state_dict is None:
537
+ state_dict = self.state_dict()
538
+ kwargs["state_dict"] = state_dict
539
+
540
+ # if it is a peft model only save the `v_head` state_dict and
541
+ # pop the `state_dict` from the kwargs to avoid silent bugs with `peft`
542
+ if self.is_peft_model:
543
+ save_path = args[0]
544
+ save_path = os.path.join(save_path, "pytorch_model.bin")
545
+ torch.save(state_dict, save_path)
546
+ _ = kwargs.pop("state_dict", None)
547
+
548
+ return self.pretrained_model.save_pretrained(*args, **kwargs)
549
+
550
+ def state_dict(self, *args, **kwargs):
551
+ r"""
552
+ Return the state_dict of the pretrained model.
553
+ """
554
+ raise NotImplementedError
555
+
556
+ def post_init(self, *args, **kwargs):
557
+ r"""
558
+ Post initialization method. This method is called after the model is instantiated and loaded from a checkpoint.
559
+ It can be used to perform additional operations such as loading the state_dict.
560
+ """
561
+ raise NotImplementedError
562
+
563
+ def compute_reward_score(self, input_ids, attention_mask=None, **kwargs):
564
+ r"""
565
+ Computes the reward score for a given input. The method has first to enable the adapter and then compute the
566
+ reward score. After that the model disables the reward modeling adapter and enables the default ppo adapter
567
+ again.
568
+ """
569
+ if not self.supports_rm_adapter:
570
+ raise ValueError("This model does not support reward modeling adapter.")
571
+
572
+ # enable rm adapter
573
+ self.pretrained_model.set_adapter(self.rm_adapter_name)
574
+ self.pretrained_model.eval()
575
+
576
+ with torch.no_grad():
577
+ base_model_output = self.pretrained_model(
578
+ input_ids=input_ids,
579
+ attention_mask=attention_mask,
580
+ output_hidden_states=True,
581
+ return_dict=True,
582
+ **kwargs,
583
+ )
584
+
585
+ last_hidden_states = base_model_output.hidden_states[-1]
586
+ scores = self.score(last_hidden_states)
587
+
588
+ self.pretrained_model.set_adapter(self.policy_adapter_name)
589
+ self.pretrained_model.eval()
590
+
591
+ return scores
592
+
593
+
594
+ class ValueHead(nn.Module):
595
+ r"""
596
+ The ValueHead class implements a head for GPT2 that returns a scalar for each output token.
597
+ """
598
+
599
+ def __init__(self, config, **kwargs):
600
+ super().__init__()
601
+ if not hasattr(config, "summary_dropout_prob"):
602
+ summary_dropout_prob = kwargs.pop("summary_dropout_prob", 0.1)
603
+ else:
604
+ summary_dropout_prob = config.summary_dropout_prob
605
+
606
+ self.dropout = nn.Dropout(summary_dropout_prob) if summary_dropout_prob else nn.Identity()
607
+
608
+ # Determine hidden_size in priority order:
609
+ # 1. word_embed_proj_dim (OPT-350m): output projection dim, != internal hidden_size
610
+ # 2. hidden_size: standard attribute for most decoder-only and seq2seq models
611
+ # 3. text_config.hidden_size: multimodal configs (Gemma3, LLaVA,...) with no top-level hidden_size
612
+ # 4. decoder.hidden_size: EncoderDecoder compositions (e.g. BERT encoder + BERT decoder)
613
+ if hasattr(config, "word_embed_proj_dim"):
614
+ hidden_size = config.word_embed_proj_dim
615
+ elif hasattr(config, "hidden_size"):
616
+ hidden_size = config.hidden_size
617
+ elif hasattr(config, "text_config") and hasattr(config.text_config, "hidden_size"):
618
+ hidden_size = config.text_config.hidden_size
619
+ elif (
620
+ getattr(config, "is_encoder_decoder", False)
621
+ and hasattr(config, "decoder")
622
+ and hasattr(config.decoder, "hidden_size")
623
+ ):
624
+ hidden_size = config.decoder.hidden_size
625
+ else:
626
+ raise ValueError(
627
+ "Cannot determine `hidden_size` from model config. "
628
+ "Please open an issue or pass a model whose config exposes one of: "
629
+ "`hidden_size`, `word_embed_proj_dim`, `text_config.hidden_size`, or `decoder.hidden_size`."
630
+ )
631
+ self.summary = nn.Linear(hidden_size, 1)
632
+
633
+ self.flatten = nn.Flatten()
634
+
635
+ def forward(self, hidden_states):
636
+ output = self.dropout(hidden_states)
637
+
638
+ # For now force upcast in fp32 if needed. Let's keep the
639
+ # output in fp32 for numerical stability.
640
+ if output.dtype != self.summary.weight.dtype:
641
+ output = output.to(self.summary.weight.dtype)
642
+
643
+ output = self.summary(output)
644
+ return output
645
+
646
+
647
+ class AutoModelForCausalLMWithValueHead(PreTrainedModelWrapper):
648
+ """
649
+ An autoregressive model with a value head in addition to the language model head. This class inherits from
650
+ [`experimental.ppo.PreTrainedModelWrapper`] and wraps a [`~transformers.PreTrainedModel`] class. The wrapper class
651
+ supports classic functions such as `from_pretrained`, `push_to_hub` and `generate`. To call a method of the wrapped
652
+ model, simply manipulate the `pretrained_model` attribute of this class.
653
+
654
+ Class attributes:
655
+ - **transformers_parent_class** ([`~transformers.PreTrainedModel`]) -- The parent class of the wrapped model.
656
+ This
657
+ should be set to `transformers.AutoModelForCausalLM` for this class.
658
+ - **supported_args** (`tuple`) -- A tuple of strings that are used to identify the arguments that are supported
659
+ by the [`ValueHead`] class. Currently, the supported args are:
660
+ - **summary_dropout_prob** (`float`, `optional`, defaults to `None`) -- The dropout probability for the
661
+ [`ValueHead`] class.
662
+ - **v_head_initializer_range** (`float`, `optional`, defaults to `0.2`) -- The initializer range for the
663
+ [`ValueHead`] if a specific initialization strategy is selected.
664
+ - **v_head_init_strategy** (`str`, `optional`, defaults to `None`) -- The initialization strategy for the
665
+ [`ValueHead`]. Currently, the supported strategies are:
666
+ - **`None`** -- Initializes the weights of the [`ValueHead`] with a random distribution. This is the
667
+ default strategy.
668
+ - **"normal"** -- Initializes the weights of the [`ValueHead`] with a normal distribution.
669
+ """
670
+
671
+ transformers_parent_class = AutoModelForCausalLM
672
+ supported_args = (
673
+ "summary_dropout_prob",
674
+ "v_head_initializer_range",
675
+ "v_head_init_strategy",
676
+ )
677
+
678
+ def __init__(self, pretrained_model, **kwargs):
679
+ """
680
+ Initializes the model.
681
+
682
+ Args:
683
+ pretrained_model ([`~transformers.PreTrainedModel`]):
684
+ The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the
685
+ `AutoModelForCausalLM` class.
686
+ kwargs (`dict`, `optional`):
687
+ Additional keyword arguments, that are passed to the [`ValueHead`] class.
688
+ """
689
+ super().__init__(pretrained_model, **kwargs)
690
+ v_head_kwargs, _, _ = self._split_kwargs(kwargs)
691
+ self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs)
692
+ self._init_weights(**v_head_kwargs)
693
+
694
+ def _init_weights(self, **kwargs):
695
+ r"""
696
+ Initializes the weights of the value head. The default initialization strategy is random. Users can pass a
697
+ different initialization strategy by passing the `v_head_init_strategy` argument when calling
698
+ `.from_pretrained`. Supported strategies are:
699
+ - `normal`: initializes the weights with a normal distribution.
700
+
701
+ Args:
702
+ **kwargs (`dict`, `optional`):
703
+ Additional keyword arguments, that are passed to the [`ValueHead`] class. These arguments can contain
704
+ the `v_head_init_strategy` argument as well as the `v_head_initializer_range` argument.
705
+ """
706
+ initializer_range = kwargs.pop("v_head_initializer_range", 0.2)
707
+ # random init by default
708
+ init_strategy = kwargs.pop("v_head_init_strategy", None)
709
+ if init_strategy is None:
710
+ # do nothing
711
+ pass
712
+ elif init_strategy == "normal":
713
+ self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range)
714
+ self.v_head.summary.bias.data.zero_()
715
+
716
+ def forward(
717
+ self,
718
+ input_ids=None,
719
+ past_key_values=None,
720
+ attention_mask=None,
721
+ return_past_key_values=False,
722
+ **kwargs,
723
+ ):
724
+ r"""
725
+ Applies a forward pass to the wrapped model and returns the logits of the value head.
726
+
727
+ Args:
728
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
729
+ Indices of input sequence tokens in the vocabulary.
730
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, `optional`):
731
+ Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model
732
+ (see `past_key_values` input) to speed up sequential decoding.
733
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, `optional`):
734
+ Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
735
+ - 1 for tokens that are **not masked**,
736
+ - 0 for tokens that are **masked**.
737
+ return_past_key_values (bool): A flag indicating if the computed hidden-states should be returned.
738
+ kwargs (`dict`, `optional`):
739
+ Additional keyword arguments, that are passed to the wrapped model.
740
+ """
741
+ kwargs["output_hidden_states"] = True # this had already been set in the LORA / PEFT examples
742
+ kwargs["past_key_values"] = past_key_values
743
+
744
+ if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING":
745
+ kwargs.pop("past_key_values")
746
+
747
+ base_model_output = self.pretrained_model(
748
+ input_ids=input_ids,
749
+ attention_mask=attention_mask,
750
+ **kwargs,
751
+ )
752
+
753
+ last_hidden_state = base_model_output.hidden_states[-1]
754
+ lm_logits = base_model_output.logits
755
+ loss = base_model_output.loss
756
+
757
+ if last_hidden_state.device != self.v_head.summary.weight.device:
758
+ last_hidden_state = last_hidden_state.to(self.v_head.summary.weight.device)
759
+
760
+ value = self.v_head(last_hidden_state).squeeze(-1)
761
+
762
+ # force upcast in fp32 if logits are in half-precision
763
+ if lm_logits.dtype != torch.float32:
764
+ lm_logits = lm_logits.float()
765
+
766
+ if return_past_key_values:
767
+ return (lm_logits, loss, value, base_model_output.past_key_values)
768
+ else:
769
+ return (lm_logits, loss, value)
770
+
771
+ def generate(self, *args, **kwargs):
772
+ r"""
773
+ A simple wrapper around the `generate` method of the wrapped model. Please refer to the
774
+ [`generate`](https://huggingface.co/docs/transformers/internal/generation_utils) method of the wrapped model
775
+ for more information about the supported arguments.
776
+
777
+ Args:
778
+ *args (`list`, *optional*):
779
+ Positional arguments passed to the `generate` method of the wrapped model.
780
+ **kwargs (`dict`, *optional*):
781
+ Keyword arguments passed to the `generate` method of the wrapped model.
782
+ """
783
+ return self.pretrained_model.generate(*args, **kwargs)
784
+
785
+ def state_dict(self, *args, **kwargs):
786
+ r"""
787
+ Returns the state dictionary of the model. We add the state dictionary of the value head to the state
788
+ dictionary of the wrapped model by prepending the key with `v_head.`.
789
+ """
790
+ if not self.is_peft_model:
791
+ pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs)
792
+ else:
793
+ # if it is a peft model, only save the v_head
794
+ pretrained_model_state_dict = {}
795
+
796
+ v_head_state_dict = self.v_head.state_dict(*args, **kwargs)
797
+ for k, v in v_head_state_dict.items():
798
+ pretrained_model_state_dict[f"v_head.{k}"] = v
799
+ return pretrained_model_state_dict
800
+
801
+ def push_to_hub(self, *args, **kwargs):
802
+ self.pretrained_model.v_head = self.v_head
803
+
804
+ return self.pretrained_model.push_to_hub(*args, **kwargs)
805
+
806
+ def post_init(self, state_dict):
807
+ r"""
808
+ We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the
809
+ key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state
810
+ dictionary.
811
+ """
812
+ for k in list(state_dict.keys()):
813
+ if "v_head." in k:
814
+ state_dict[k.replace("v_head.", "")] = state_dict.pop(k)
815
+ self.v_head.load_state_dict(state_dict, strict=False)
816
+ del state_dict
817
+
818
+ if hasattr(self.pretrained_model, "hf_device_map"):
819
+ if (
820
+ "cpu" in self.pretrained_model.hf_device_map.values()
821
+ or "disk" in self.pretrained_model.hf_device_map.values()
822
+ ):
823
+ raise ValueError(
824
+ "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models."
825
+ )
826
+
827
+ first_device = list(set(self.pretrained_model.hf_device_map.values()))[0]
828
+ if isinstance(first_device, int):
829
+ if is_torch_npu_available():
830
+ first_device = f"npu:{first_device}"
831
+ elif is_torch_xpu_available():
832
+ first_device = f"xpu:{first_device}"
833
+ else:
834
+ first_device = f"cuda:{first_device}"
835
+ self.v_head = self.v_head.to(first_device)
836
+
837
+ def set_device_hook(module, input, outputs):
838
+ new_output = ()
839
+ for output in outputs:
840
+ if isinstance(output, torch.Tensor):
841
+ new_output += (output.to(first_device),)
842
+ else:
843
+ new_output += (output,)
844
+ return new_output
845
+
846
+ self.register_forward_hook(set_device_hook)
847
+
848
+ self.is_sequential_parallel = True
849
+
850
+
851
+ class AutoModelForSeq2SeqLMWithValueHead(PreTrainedModelWrapper):
852
+ """
853
+ A seq2seq model with a value head in addition to the language model head. This class inherits from
854
+ [`experimental.ppo.PreTrainedModelWrapper`] and wraps a [`~transformers.PreTrainedModel`] class. The wrapper class
855
+ supports classic functions such as `from_pretrained` and `push_to_hub` and also provides some additional
856
+ functionalities such as `generate`.
857
+
858
+ Args:
859
+ pretrained_model ([`~transformers.PreTrainedModel`]):
860
+ The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the
861
+ [`~transformers.AutoModelForSeq2SeqLM`] class.
862
+ kwargs:
863
+ Additional keyword arguments passed along to the [`ValueHead`] class.
864
+ """
865
+
866
+ transformers_parent_class = AutoModelForSeq2SeqLM
867
+ lm_head_namings = ["lm_head", "embed_out", "output_projection"]
868
+ supported_args = (
869
+ "summary_dropout_prob",
870
+ "v_head_initializer_range",
871
+ "v_head_init_strategy",
872
+ )
873
+
874
+ def __init__(self, pretrained_model, **kwargs):
875
+ super().__init__(pretrained_model, **kwargs)
876
+ v_head_kwargs, _, _ = self._split_kwargs(kwargs)
877
+ self.is_encoder_decoder = True
878
+
879
+ if not self._has_lm_head():
880
+ raise ValueError("The model does not have a language model head, please use a model that has one.")
881
+
882
+ self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs)
883
+
884
+ self._init_weights(**v_head_kwargs)
885
+
886
+ def _has_lm_head(self):
887
+ # check module names of all modules inside `pretrained_model` to find the language model head
888
+ for name, _module in self.pretrained_model.named_modules():
889
+ if any(attribute in name for attribute in self.lm_head_namings):
890
+ return True
891
+ return False
892
+
893
+ def post_init(self, state_dict):
894
+ r"""
895
+ We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the
896
+ key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state
897
+ dictionary.
898
+ """
899
+ for k in list(state_dict.keys()):
900
+ if "v_head." in k:
901
+ state_dict[k.replace("v_head.", "")] = state_dict.pop(k)
902
+ self.v_head.load_state_dict(state_dict, strict=False)
903
+ del state_dict
904
+
905
+ if hasattr(self.pretrained_model, "hf_device_map"):
906
+ if (
907
+ "cpu" in self.pretrained_model.hf_device_map.values()
908
+ or "disk" in self.pretrained_model.hf_device_map.values()
909
+ ):
910
+ raise ValueError(
911
+ "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models."
912
+ )
913
+
914
+ # get the lm_head device
915
+ for name, module in self.pretrained_model.named_modules():
916
+ if any(attribute in name for attribute in self.lm_head_namings):
917
+ lm_head_device = module.weight.device
918
+ break
919
+
920
+ # put v_head on the same device as the lm_head to avoid issues
921
+ self.v_head = self.v_head.to(lm_head_device)
922
+
923
+ def set_device_hook(module, input, outputs):
924
+ r"""
925
+ A hook that sets the device of the output of the model to the device of the first parameter of the
926
+ model.
927
+
928
+ Args:
929
+ module (`nn.Module`):
930
+ The module to which the hook is attached.
931
+ input (`tuple`):
932
+ The input to the module.
933
+ outputs (`tuple`):
934
+ The output of the module.
935
+ """
936
+ new_output = ()
937
+ for output in outputs:
938
+ if isinstance(output, torch.Tensor):
939
+ new_output += (output.to(lm_head_device),)
940
+ else:
941
+ new_output += (output,)
942
+ return new_output
943
+
944
+ self.register_forward_hook(set_device_hook)
945
+ self.is_sequential_parallel = True
946
+
947
+ def state_dict(self, *args, **kwargs):
948
+ r"""
949
+ Returns the state dictionary of the model. We add the state dictionary of the value head to the state
950
+ dictionary of the wrapped model by prepending the key with `v_head.`.
951
+ """
952
+ if not self.is_peft_model:
953
+ pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs)
954
+ else:
955
+ # if it is a peft model, only save the v_head
956
+ pretrained_model_state_dict = {}
957
+
958
+ v_head_state_dict = self.v_head.state_dict(*args, **kwargs)
959
+ for k, v in v_head_state_dict.items():
960
+ pretrained_model_state_dict[f"v_head.{k}"] = v
961
+ return pretrained_model_state_dict
962
+
963
+ def push_to_hub(self, *args, **kwargs):
964
+ self.pretrained_model.v_head = self.v_head
965
+
966
+ return self.pretrained_model.push_to_hub(*args, **kwargs)
967
+
968
+ def _init_weights(self, **kwargs):
969
+ r"""
970
+ We initialize the weights of the value head.
971
+ """
972
+ initializer_range = kwargs.pop("v_head_initializer_range", 0.2)
973
+ # random init by default
974
+ init_strategy = kwargs.pop("v_head_init_strategy", None)
975
+ if init_strategy is None:
976
+ # do nothing
977
+ pass
978
+ elif init_strategy == "normal":
979
+ self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range)
980
+ self.v_head.summary.bias.data.zero_()
981
+
982
+ def forward(
983
+ self,
984
+ input_ids=None,
985
+ past_key_values=None,
986
+ attention_mask=None,
987
+ return_past_key_values=False,
988
+ **kwargs,
989
+ ):
990
+ kwargs["past_key_values"] = past_key_values
991
+ if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING":
992
+ kwargs.pop("past_key_values")
993
+
994
+ base_model_output = self.pretrained_model(
995
+ input_ids=input_ids,
996
+ attention_mask=attention_mask,
997
+ output_hidden_states=True, # We force the model to output hidden states
998
+ **kwargs,
999
+ )
1000
+
1001
+ last_hidden_state = base_model_output.decoder_hidden_states[-1]
1002
+ lm_logits = base_model_output.logits
1003
+ loss = base_model_output.loss
1004
+
1005
+ value = self.v_head(last_hidden_state).squeeze(-1)
1006
+
1007
+ # force upcast in fp32 if logits are in half-precision
1008
+ if lm_logits.dtype != torch.float32:
1009
+ lm_logits = lm_logits.float()
1010
+
1011
+ if return_past_key_values:
1012
+ return (lm_logits, loss, value, base_model_output.past_key_values)
1013
+ else:
1014
+ return (lm_logits, loss, value)
1015
+
1016
+ def generate(self, *args, **kwargs):
1017
+ r"""
1018
+ We call `generate` on the wrapped model.
1019
+ """
1020
+ return self.pretrained_model.generate(*args, **kwargs)
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ppo/ppo_config.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+ from typing import Literal
17
+
18
+ from ...trainer.base_config import _BaseConfig
19
+
20
+
21
+ @dataclass
22
+ class PPOConfig(_BaseConfig):
23
+ # docstyle-ignore
24
+ r"""
25
+ Configuration class for the [`experimental.ppo.PPOTrainer`].
26
+
27
+ This class includes only the parameters that are specific to PPO training. For a full list of training arguments,
28
+ please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
29
+ differ from those in [`~transformers.TrainingArguments`].
30
+
31
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
32
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
33
+ command line.
34
+
35
+ Parameters:
36
+ dataset_num_proc (`int`, *optional*):
37
+ Number of processes to use for processing the dataset.
38
+ num_mini_batches (`int`, *optional*, defaults to `1`):
39
+ Number of minibatches to split a batch into.
40
+ total_episodes (`int`, *optional*):
41
+ Total number of episodes in the dataset.
42
+ local_rollout_forward_batch_size (`int`, *optional*, defaults to `64`):
43
+ Per rank no grad forward pass in the rollout phase.
44
+ num_sample_generations (`int`, *optional*, defaults to `10`):
45
+ Number of debugging samples generations (i.e., `generate_completions` calls) throughout training.
46
+ response_length (`int`, *optional*, defaults to `53`):
47
+ Length of the response.
48
+ stop_token (`str`, *optional*):
49
+ Specifies the stop token to use for text generation. This parameter is mutually exclusive with
50
+ `stop_token_id`.
51
+
52
+ - `None`: No stop token is applied, unless `stop_token_id` is specified.
53
+ - `'eos'`: Uses the tokenizer's `eos_token`.
54
+
55
+ stop_token_id (`int`, *optional*):
56
+ Specifies the ID of the stop token to use for text generation. If `None`, no stop token ID is applied,
57
+ unless `stop_token` is specified. This parameter is mutually exclusive with `stop_token`.
58
+ temperature (`float`, *optional*, defaults to `0.7`):
59
+ Sampling temperature.
60
+ missing_eos_penalty (`float`, *optional*):
61
+ Penalty applied to the score when the model fails to generate an EOS token. This is useful to encourage to
62
+ generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be a positive
63
+ value.
64
+ sft_model_path (`str`, *optional*, defaults to `"EleutherAI/pythia-160m"`):
65
+ Path to the SFT model.
66
+ world_size (`int`, *optional*):
67
+ Number of processes (GPUs) to use for the training.
68
+ num_total_batches (`int`, *optional*):
69
+ Number of total batches to train.
70
+ micro_batch_size (`int`, *optional*):
71
+ Micro batch size across devices (HF's `per_device_train_batch_size` * `world_size`).
72
+ local_batch_size (`int`, *optional*):
73
+ Batch size per GPU (HF's `per_device_train_batch_size` * `gradient_accumulation_steps`).
74
+ batch_size (`int`, *optional*):
75
+ Batch size across devices (HF's `per_device_train_batch_size` * `world_size` *
76
+ `gradient_accumulation_steps`).
77
+ local_mini_batch_size (`int`, *optional*):
78
+ Mini batch size per GPU.
79
+ mini_batch_size (`int`, *optional*):
80
+ Mini batch size across GPUs.
81
+ push_to_hub (`bool`, *optional*, defaults to `False`):
82
+ Whether to push the model to the Hub after training.
83
+ reward_model_path (`str`, *optional*, defaults to `"EleutherAI/pythia-160m"`):
84
+ Path to the reward model.
85
+ model_adapter_name (`str`, *optional*):
86
+ Name of the train target PEFT adapter, when using LoRA with multiple adapters.
87
+ ref_adapter_name (`str`, *optional*):
88
+ Name of the reference PEFT adapter, when using LoRA with multiple adapters.
89
+ num_ppo_epochs (`int`, *optional*, defaults to `4`):
90
+ Number of epochs to train.
91
+ whiten_rewards (`bool`, *optional*, defaults to `False`):
92
+ Whether to whiten the rewards.
93
+ kl_coef (`float`, *optional*, defaults to `0.05`):
94
+ KL coefficient.
95
+ kl_estimator (`Literal["k1", "k3"]`, *optional*, defaults to `"k1"`):
96
+ Which estimator for KL-Divergence to use from [Approximating KL
97
+ Divergence](http://joschu.net/blog/kl-approx.html). Defaults to "k1", a straightforward, unbiased
98
+ estimator. Can be set to "k3", an unbiased estimator with lower variance which "appears to be a strictly
99
+ better estimator". Cannot be set to "k2", as it is used for logging purposes.
100
+ cliprange (`float`, *optional*, defaults to `0.2`):
101
+ Clip range.
102
+ vf_coef (`float`, *optional*, defaults to `0.1`):
103
+ Value function coefficient.
104
+ cliprange_value (`float`, *optional*, defaults to `0.2`):
105
+ Clip range for the value function.
106
+ gamma (`float`, *optional*, defaults to `1.0`):
107
+ Discount factor.
108
+ lam (`float`, *optional*, defaults to `0.95`):
109
+ Lambda value for GAE.
110
+ ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
111
+ This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
112
+ improving generation speed. However, disabling this option allows training models that exceed the VRAM
113
+ capacity of a single GPU, albeit at the cost of slower generation.
114
+
115
+ > [!NOTE]
116
+ > These parameters have default values different from [`~transformers.TrainingArguments`]:
117
+ > - `logging_steps`: Defaults to `10` instead of `500`.
118
+ > - `gradient_checkpointing`: Defaults to `True` instead of `False`.
119
+ > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
120
+ > - `learning_rate`: Defaults to `3e-6` instead of `5e-5`.
121
+ """
122
+
123
+ # Parameters whose default values are overridden from TrainingArguments
124
+ learning_rate: float = field(
125
+ default=3e-6,
126
+ metadata={"help": "The initial learning rate for AdamW."},
127
+ )
128
+
129
+ dataset_num_proc: int | None = field(
130
+ default=None,
131
+ metadata={"help": "Number of processes to use for processing the dataset."},
132
+ )
133
+ num_mini_batches: int = field(
134
+ default=1,
135
+ metadata={"help": "Number of minibatches to split a batch into."},
136
+ )
137
+ total_episodes: int | None = field(
138
+ default=None,
139
+ metadata={"help": "Total number of episodes in the dataset."},
140
+ )
141
+ local_rollout_forward_batch_size: int = field(
142
+ default=64,
143
+ metadata={"help": "Per rank no grad forward pass in the rollout phase."},
144
+ )
145
+ num_sample_generations: int = field(
146
+ default=10,
147
+ metadata={
148
+ "help": "Number of debugging samples generations (i.e., `generate_completions` calls) throughout training."
149
+ },
150
+ )
151
+ response_length: int = field(
152
+ default=53,
153
+ metadata={"help": "Length of the response."},
154
+ )
155
+ stop_token: Literal["eos"] | None = field(
156
+ default=None,
157
+ metadata={
158
+ "help": "Specifies the stop token to use for text generation. This parameter is mutually exclusive with "
159
+ "`stop_token_id`."
160
+ },
161
+ )
162
+ stop_token_id: int | None = field(
163
+ default=None,
164
+ metadata={
165
+ "help": "Specifies the ID of the stop token to use for text generation. If `None`, no stop token ID is "
166
+ "applied, unless `stop_token` is specified. This parameter is mutually exclusive with `stop_token`."
167
+ },
168
+ )
169
+ temperature: float = field(
170
+ default=0.7,
171
+ metadata={"help": "Sampling temperature."},
172
+ )
173
+ missing_eos_penalty: float | None = field(
174
+ default=None,
175
+ metadata={
176
+ "help": "Penalty applied to the score when the model fails to generate an EOS token. This is useful to "
177
+ "encourage to generate completions shorter than the maximum length (`max_new_tokens`). The penalty must be "
178
+ "a positive value."
179
+ },
180
+ )
181
+ sft_model_path: str = field(
182
+ default="EleutherAI/pythia-160m",
183
+ metadata={"help": "Path to the SFT model."},
184
+ )
185
+ world_size: int | None = field(
186
+ default=None,
187
+ metadata={"help": "Number of processes (GPUs) to use for the training."},
188
+ )
189
+ num_total_batches: int | None = field(
190
+ default=None,
191
+ metadata={"help": "Number of total batches to train."},
192
+ )
193
+ micro_batch_size: int | None = field(
194
+ default=None,
195
+ metadata={"help": "Micro batch size across devices (HF's `per_device_train_batch_size` * `world_size`)."},
196
+ )
197
+ local_batch_size: int | None = field(
198
+ default=None,
199
+ metadata={"help": "Batch size per GPU (HF's `per_device_train_batch_size` * `gradient_accumulation_steps`)."},
200
+ )
201
+ batch_size: int | None = field(
202
+ default=None,
203
+ metadata={
204
+ "help": "Batch size across devices (HF's `per_device_train_batch_size` * `world_size` * "
205
+ "`gradient_accumulation_steps`)."
206
+ },
207
+ )
208
+ local_mini_batch_size: int | None = field(
209
+ default=None,
210
+ metadata={"help": "Mini batch size per GPU."},
211
+ )
212
+ mini_batch_size: int | None = field(
213
+ default=None,
214
+ metadata={"help": "Mini batch size across GPUs."},
215
+ )
216
+ push_to_hub: bool = field(
217
+ default=False,
218
+ metadata={"help": "Whether to push the model to the Hub after training."},
219
+ )
220
+ reward_model_path: str = field(
221
+ default="EleutherAI/pythia-160m",
222
+ metadata={"help": "Path to the reward model."},
223
+ )
224
+ model_adapter_name: str | None = field(
225
+ default=None,
226
+ metadata={"help": "Name of the train target PEFT adapter, when using LoRA with multiple adapters."},
227
+ )
228
+ ref_adapter_name: str | None = field(
229
+ default=None,
230
+ metadata={"help": "Name of the reference PEFT adapter, when using LoRA with multiple adapters."},
231
+ )
232
+ num_ppo_epochs: int = field(
233
+ default=4,
234
+ metadata={"help": "Number of epochs to train."},
235
+ )
236
+ whiten_rewards: bool = field(
237
+ default=False,
238
+ metadata={"help": "Whether to whiten the rewards."},
239
+ )
240
+ kl_coef: float = field(
241
+ default=0.05,
242
+ metadata={"help": "KL coefficient."},
243
+ )
244
+ kl_estimator: Literal["k1", "k3"] = field(
245
+ default="k1",
246
+ metadata={
247
+ "help": "Which estimator for KL-Divergence to use from Approximating KL Divergence "
248
+ "(http://joschu.net/blog/kl-approx.html). Defaults to 'k1', a straightforward, unbiased estimator. Can be "
249
+ "set to 'k3', an unbiased estimator with lower variance which 'appears to be a strictly better "
250
+ "estimator'. Cannot be set to 'k2', as it is used for logging purposes."
251
+ },
252
+ )
253
+ cliprange: float = field(
254
+ default=0.2,
255
+ metadata={"help": "Clip range."},
256
+ )
257
+ vf_coef: float = field(
258
+ default=0.1,
259
+ metadata={"help": "Value function coefficient."},
260
+ )
261
+ cliprange_value: float = field(
262
+ default=0.2,
263
+ metadata={"help": "Clip range for the value function."},
264
+ )
265
+ gamma: float = field(
266
+ default=1.0,
267
+ metadata={"help": "Discount factor."},
268
+ )
269
+ lam: float = field(
270
+ default=0.95,
271
+ metadata={"help": "Lambda value for GAE."},
272
+ )
273
+ ds3_gather_for_generation: bool = field(
274
+ default=True,
275
+ metadata={
276
+ "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for "
277
+ "generation, improving generation speed. However, disabling this option allows training models that "
278
+ "exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation."
279
+ },
280
+ )
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ppo/ppo_trainer.py ADDED
@@ -0,0 +1,1038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import gc
16
+ import math
17
+ import os
18
+ import textwrap
19
+ import time
20
+ from collections import defaultdict
21
+ from contextlib import contextmanager, nullcontext
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+ import pandas as pd
27
+ import torch
28
+ import torch.nn as nn
29
+ import transformers
30
+ from accelerate import Accelerator
31
+ from accelerate.logging import get_logger
32
+ from accelerate.utils import gather_object
33
+ from datasets import Dataset
34
+ from packaging.version import Version
35
+ from torch.utils.data import DataLoader
36
+ from transformers import (
37
+ BaseImageProcessor,
38
+ DataCollatorWithPadding,
39
+ FeatureExtractionMixin,
40
+ GenerationConfig,
41
+ PreTrainedTokenizerBase,
42
+ ProcessorMixin,
43
+ TrainerCallback,
44
+ TrainerControl,
45
+ TrainerState,
46
+ )
47
+ from transformers.integrations import get_reporting_integration_callbacks
48
+ from transformers.trainer import DEFAULT_CALLBACKS, DEFAULT_PROGRESS_CALLBACK
49
+ from transformers.trainer_callback import CallbackHandler, ExportableState, PrinterCallback
50
+ from transformers.utils import ModelOutput, is_peft_available, is_rich_available
51
+
52
+ from ...models.utils import prepare_deepspeed, unwrap_model_for_generation
53
+ from ...trainer.base_trainer import _BaseTrainer
54
+ from ...trainer.utils import (
55
+ disable_dropout_in_model,
56
+ log_table_to_comet_experiment,
57
+ pad,
58
+ selective_log_softmax,
59
+ )
60
+ from ..utils import (
61
+ create_reference_model,
62
+ empty_cache,
63
+ first_true_indices,
64
+ get_reward,
65
+ peft_module_casting_to_bf16,
66
+ )
67
+ from .ppo_config import PPOConfig
68
+
69
+
70
+ if is_rich_available():
71
+ from rich.console import Console
72
+ from rich.table import Table
73
+
74
+
75
+ logger = get_logger(__name__)
76
+
77
+ if is_peft_available():
78
+ from peft import PeftConfig, PeftModel, get_peft_model
79
+
80
+
81
+ INVALID_LOGPROB = 1.0
82
+
83
+
84
+ def generate(
85
+ lm_backbone: torch.nn.Module, queries: torch.Tensor, pad_token_id: int, generation_config: GenerationConfig
86
+ ) -> tuple[torch.Tensor, torch.Tensor]:
87
+ """
88
+ Generates sequences from the language model backbone in a way that does not affect padding tokens.
89
+
90
+ Args:
91
+ lm_backbone (`torch.nn.Module`):
92
+ The language model backbone used for generation.
93
+ queries (`torch.Tensor`):
94
+ The tensor containing the input queries.
95
+ pad_token_id (`int`):
96
+ The token ID representing the pad token.
97
+ generation_config ([`~transformers.GenerationConfig`]):
98
+ The configuration for the generation process.
99
+
100
+ Returns:
101
+ tuple:
102
+ - `generated_sequences` (`torch.Tensor`):
103
+ The concatenated tensor of input queries and generated sequences.
104
+ - `logits` (`torch.Tensor`):
105
+ The logits output from the generation process.
106
+ """
107
+ context_length = queries.shape[1]
108
+ attention_mask = queries != pad_token_id
109
+ input_ids = torch.masked_fill(queries, ~attention_mask, 0)
110
+ output = lm_backbone.generate(
111
+ input_ids=input_ids,
112
+ attention_mask=attention_mask,
113
+ # position_ids=attention_mask.cumsum(1) - attention_mask.long(), # not needed: already adjusted in generations
114
+ # https://github.com/huggingface/transformers/blob/ac33aeeeee2a7a89b89c93c2962e6feb90daef0a/src/transformers/models/gpt2/modeling_gpt2.py#L1227-L1250
115
+ generation_config=generation_config,
116
+ return_dict_in_generate=True,
117
+ output_scores=True,
118
+ )
119
+ logits = torch.stack(output.scores, 1)
120
+ return torch.cat((queries, output.sequences[:, context_length:]), dim=1), logits
121
+
122
+
123
+ @torch.no_grad()
124
+ def batch_generation(
125
+ model: torch.nn.Module,
126
+ queries: torch.Tensor,
127
+ local_rollout_forward_batch_size: int,
128
+ pad_token_id: int,
129
+ generation_config: GenerationConfig,
130
+ ):
131
+ query_responses = []
132
+ logitss = []
133
+ batch_size = queries.shape[0]
134
+ for i in range(0, batch_size, local_rollout_forward_batch_size):
135
+ query = queries[i : i + local_rollout_forward_batch_size]
136
+ query_response, logits = generate(
137
+ model,
138
+ query,
139
+ pad_token_id,
140
+ generation_config,
141
+ )
142
+ query_responses.append(query_response)
143
+ logitss.append(logits)
144
+
145
+ # padding tensors
146
+ padded_query_responses = pad(query_responses, padding_value=pad_token_id, padding_side="right")
147
+ padded_logitss = pad(logitss, padding_value=0, padding_side="right")
148
+
149
+ # reshaping
150
+ padded_query_responses = padded_query_responses.view(-1, padded_query_responses.shape[-1])[:batch_size]
151
+ padded_logitss = padded_logitss.view(-1, *padded_logitss.shape[2:])[:batch_size]
152
+
153
+ return padded_query_responses, padded_logitss
154
+
155
+
156
+ def exact_div(a, b, custom_error_message=""):
157
+ q = a // b
158
+ if a != q * b:
159
+ raise ValueError(f"{custom_error_message}, inexact division: {a} / {b} = {a / b}")
160
+ return q
161
+
162
+
163
+ def print_rich_table(df: pd.DataFrame) -> None:
164
+ if not is_rich_available():
165
+ raise ImportError(
166
+ "The function `print_rich_table` requires the `rich` library. Please install it with `pip install rich`."
167
+ )
168
+ console = Console()
169
+ table = Table(show_lines=True)
170
+ for column in df.columns:
171
+ table.add_column(column)
172
+ for _, row in df.iterrows():
173
+ table.add_row(*row.astype(str).tolist())
174
+ console.print(table)
175
+
176
+
177
+ def truncate_response(stop_token_id: int, pad_token_id: int, responses: torch.Tensor) -> torch.Tensor:
178
+ """
179
+ Truncates the responses at the first occurrence of the stop token, filling the rest with pad tokens.
180
+
181
+ Args:
182
+ stop_token_id (`int`):
183
+ The token ID representing the stop token where truncation occurs.
184
+ pad_token_id (`int`):
185
+ The token ID representing the pad token used to fill the truncated responses.
186
+ responses (`torch.Tensor`):
187
+ The tensor containing the responses to be truncated.
188
+
189
+ Returns:
190
+ `torch.Tensor`:
191
+ The truncated responses tensor with pad tokens filled after the stop token.
192
+ """
193
+ trunc_idxs = first_true_indices(responses == stop_token_id).unsqueeze(-1)
194
+ new_size = [1] * (len(responses.size()) - 1) + [responses.shape[1]]
195
+ idxs = torch.arange(responses.shape[1], device=responses.device).view(*new_size)
196
+ postprocessed_responses = torch.masked_fill(responses, idxs > trunc_idxs, pad_token_id)
197
+ return postprocessed_responses
198
+
199
+
200
+ def forward(
201
+ model: torch.nn.Module,
202
+ query_responses: torch.Tensor,
203
+ pad_token_id: int,
204
+ ) -> ModelOutput:
205
+ """
206
+ Performs a forward pass through the model with the given query responses and pad token ID.
207
+
208
+ Args:
209
+ model (`torch.nn.Module`):
210
+ The model to perform the forward pass.
211
+ query_responses (`torch.Tensor`):
212
+ The tensor containing the query responses.
213
+ pad_token_id (`int`):
214
+ The token ID representing the pad token.
215
+
216
+ Returns:
217
+ `ModelOutput`:
218
+ The output of the model, including hidden states.
219
+ """
220
+ attention_mask = query_responses != pad_token_id
221
+ position_ids = attention_mask.cumsum(1) - attention_mask.long()
222
+ input_ids = torch.masked_fill(query_responses, ~attention_mask, 0)
223
+ return model(
224
+ input_ids=input_ids,
225
+ attention_mask=attention_mask,
226
+ position_ids=position_ids,
227
+ return_dict=True,
228
+ output_hidden_states=True,
229
+ )
230
+
231
+
232
+ @dataclass
233
+ class OnlineTrainerState(TrainerState):
234
+ """
235
+ Training state for online/on-policy trainers.
236
+
237
+ Extends [`~transformers.TrainerState`] with an `episode` counter to track the current rollout/episode.
238
+
239
+ Args:
240
+ episode (`int`, defaults to 0): Zero-based episode index.
241
+ """
242
+
243
+ episode: int = 0
244
+
245
+
246
+ def masked_mean(values: torch.Tensor, mask: torch.Tensor, axis: bool | None = None) -> torch.Tensor:
247
+ """Compute mean of tensor with a masked values."""
248
+ if axis is not None:
249
+ return (values * mask).sum(axis=axis) / mask.sum(axis=axis)
250
+ else:
251
+ return (values * mask).sum() / mask.sum()
252
+
253
+
254
+ def masked_var(values: torch.Tensor, mask: torch.Tensor, unbiased: bool = True) -> torch.Tensor:
255
+ """Compute variance of tensor with masked values."""
256
+ mean = masked_mean(values, mask)
257
+ centered_values = values - mean
258
+ variance = masked_mean(centered_values**2, mask)
259
+ if unbiased:
260
+ mask_sum = mask.sum()
261
+ if mask_sum == 0:
262
+ raise ValueError(
263
+ "The sum of the mask is zero, which can happen when `mini_batch_size=1`;"
264
+ "try increase the `mini_batch_size` or `gradient_accumulation_steps`"
265
+ )
266
+ # note that if mask_sum == 1, then there is a division by zero issue
267
+ # to avoid it you just need to use a larger minibatch_size
268
+ bessel_correction = mask_sum / (mask_sum - 1)
269
+ variance = variance * bessel_correction
270
+ return variance
271
+
272
+
273
+ def masked_whiten(values: torch.Tensor, mask: torch.Tensor, shift_mean: bool = True) -> torch.Tensor:
274
+ """Whiten values with masked values."""
275
+ mean, var = masked_mean(values, mask), masked_var(values, mask)
276
+ whitened = (values - mean) * torch.rsqrt(var + 1e-8)
277
+ if not shift_mean:
278
+ whitened += mean
279
+ return whitened
280
+
281
+
282
+ # taken from https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b16919addede0341d2bef70825d/ppo/ppo_trainer.py#L29
283
+ # we did this we can do a single `model = accelerator.prepare(model)`
284
+ class PolicyAndValueWrapper(nn.Module):
285
+ def __init__(self, policy, value_model) -> None:
286
+ super().__init__()
287
+ self.policy = policy
288
+ self.value_model = value_model
289
+ self.critic_backbone = getattr(value_model, value_model.base_model_prefix)
290
+ self.is_gradient_checkpointing = policy.is_gradient_checkpointing
291
+
292
+ def gradient_checkpointing_enable(self, **kwargs):
293
+ self.policy.gradient_checkpointing_enable(**kwargs)
294
+ self.is_gradient_checkpointing = True
295
+
296
+ def gradient_checkpointing_disable(self):
297
+ self.policy.gradient_checkpointing_disable()
298
+ self.is_gradient_checkpointing = False
299
+
300
+ def forward(self, **kwargs):
301
+ output = self.critic_backbone(**kwargs)
302
+ logits = self.value_model.score(output.hidden_states[-1])
303
+ return self.policy(**kwargs), logits
304
+
305
+
306
+ class PPOTrainer(_BaseTrainer):
307
+ """Trainer for Proximal Policy Optimization (PPO).
308
+
309
+ For details on PPO, see the paper: [Proximal Policy Optimization
310
+ Algorithms](https://huggingface.co/papers/1707.06347).
311
+
312
+ Args:
313
+ args ([`experimental.ppo.PPOConfig`]):
314
+ Training arguments.
315
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`]):
316
+ Class to process the data.
317
+ model (`torch.nn.Module`):
318
+ Model to be trained. This is the policy model.
319
+ ref_model (`torch.nn.Module`, *optional*):
320
+ Reference model used to compute the KL divergence. If `None`, a copy of the policy model is created.
321
+ reward_model (`torch.nn.Module`):
322
+ Reward model used to compute the rewards.
323
+ train_dataset ([`~datasets.Dataset`]):
324
+ Dataset for training.
325
+ value_model (`torch.nn.Module`):
326
+ Value model used to predict the value of a state.
327
+ data_collator ([`~transformers.DataCollatorWithPadding`], *optional*):
328
+ Data collator to batch and pad samples from the dataset. If `None`, a default data collator is created
329
+ using the `processing_class`.
330
+ eval_dataset ([`~datasets.Dataset`] or `dict` of [`~datasets.Dataset`], *optional*):
331
+ Dataset for evaluation.
332
+ optimizers (`tuple` of `torch.optim.Optimizer` and `torch.optim.lr_scheduler.LambdaLR`, *optional*, defaults to `(None, None)`):
333
+ Tuple containing the optimizer and the learning rate scheduler to use for training. If `None`, the
334
+ optimizer and the learning rate scheduler are created using the
335
+ [`~transformers.Trainer.create_optimizer_and_scheduler`] method.
336
+ callbacks (`list` of [`~transformers.TrainerCallback`], *optional*):
337
+ Callbacks to use during training.
338
+ peft_config ([`~peft.PeftConfig`], *optional*):
339
+ PEFT configuration to use PEFT for training. If `None`, PEFT is not used. If provided, the policy `model`
340
+ will be wrapped with the specified PEFT adapter.
341
+ """
342
+
343
+ _tag_names = ["trl", "ppo"]
344
+ _name = "PPO"
345
+ _paper = {
346
+ "title": "Fine-Tuning Language Models from Human Preferences",
347
+ "id": "1909.08593",
348
+ # docstyle-ignore
349
+ "citation": textwrap.dedent("""\
350
+ @article{mziegler2019fine-tuning,
351
+ title = {{Fine-Tuning Language Models from Human Preferences}},
352
+ author = {Daniel M. Ziegler and Nisan Stiennon and Jeffrey Wu and Tom B. Brown and Alec Radford and Dario Amodei and Paul F. Christiano and Geoffrey Irving},
353
+ year = 2019,
354
+ eprint = {arXiv:1909.08593}
355
+ }"""),
356
+ }
357
+
358
+ def __init__(
359
+ self,
360
+ args: PPOConfig,
361
+ processing_class: PreTrainedTokenizerBase | BaseImageProcessor | FeatureExtractionMixin | ProcessorMixin,
362
+ model: nn.Module,
363
+ ref_model: nn.Module | None,
364
+ reward_model: nn.Module,
365
+ train_dataset: Dataset,
366
+ value_model: nn.Module,
367
+ data_collator: DataCollatorWithPadding | None = None,
368
+ eval_dataset: Dataset | dict[str, Dataset] | None = None,
369
+ # less commonly used
370
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
371
+ callbacks: list[TrainerCallback] | None = None,
372
+ peft_config: "PeftConfig | None" = None,
373
+ ) -> None:
374
+ if train_dataset is None:
375
+ raise ValueError("`train_dataset` is required")
376
+
377
+ if ref_model is model:
378
+ raise ValueError(
379
+ "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the "
380
+ "same as `model`, you must make a copy of it, or `None` if you use peft."
381
+ )
382
+
383
+ self.args = args
384
+ self.processing_class = processing_class
385
+ self.policy_model = model
386
+
387
+ # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
388
+ # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
389
+ # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
390
+ # default to the recommended non-reentrant behavior here, while preserving any user-provided value.
391
+ if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
392
+ args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
393
+ args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
394
+
395
+ # Define the collator if not provided
396
+ if data_collator is None:
397
+ data_collator = DataCollatorWithPadding(self.processing_class)
398
+
399
+ # Handle stop token settings: update policy model's generation_config to use provided stop token
400
+ if args.stop_token and args.stop_token_id:
401
+ raise ValueError("You cannot set both `stop_token` and `stop_token_id`.")
402
+ elif args.stop_token:
403
+ if args.stop_token == "eos":
404
+ self.policy_model.generation_config.eos_token_id = self.stop_token_id = processing_class.eos_token_id
405
+ else:
406
+ raise ValueError(
407
+ f"Unknown `stop_token` {args.stop_token}. Allowed values are: `'eos'` and `None` (no stop token)."
408
+ )
409
+ else:
410
+ self.policy_model.generation_config.eos_token_id = self.stop_token_id = args.stop_token_id # None or int
411
+
412
+ # Check that the kl estimator is valid
413
+ if self.args.kl_estimator not in {"k1", "k3"}:
414
+ raise ValueError(
415
+ "kl_estimator must be either 'k1' (straightforward, unbiased) or 'k3' (lower variance, unbiased, "
416
+ "appears to be a strictly better estimator). See "
417
+ "[Approximating KL Divergence](http://joschu.net/blog/kl-approx.html) for details."
418
+ )
419
+
420
+ # PEFT
421
+ if peft_config is not None:
422
+ if not is_peft_available():
423
+ raise ImportError(
424
+ "You passed `peft_config` but the `peft` library is not installed. "
425
+ "Install it with `pip install trl[peft]`."
426
+ )
427
+ if not isinstance(peft_config, PeftConfig):
428
+ raise TypeError(
429
+ f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
430
+ f"got {type(peft_config).__name__}."
431
+ )
432
+ if isinstance(self.policy_model, PeftModel):
433
+ raise ValueError(
434
+ "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first "
435
+ "merge and unload the existing adapter, save the resulting base model, and then pass that base "
436
+ "model along with the new `peft_config` to the trainer."
437
+ )
438
+
439
+ # get peft model with the given config
440
+ self.policy_model = get_peft_model(self.policy_model, peft_config)
441
+ if args.bf16 and getattr(self.policy_model, "is_loaded_in_4bit", False):
442
+ peft_module_casting_to_bf16(self.policy_model)
443
+
444
+ self.is_peft_model = is_peft_available() and isinstance(self.policy_model, PeftModel)
445
+ self.model_adapter_name = args.model_adapter_name
446
+ self.ref_adapter_name = args.ref_adapter_name
447
+
448
+ if ref_model:
449
+ self.ref_model = ref_model
450
+ elif self.is_peft_model:
451
+ self.ref_model = None
452
+ else:
453
+ self.ref_model = create_reference_model(self.policy_model)
454
+
455
+ self.reward_model = reward_model
456
+ self.train_dataset = train_dataset
457
+ self.train_dataset_len = len(train_dataset)
458
+ self.value_model = value_model
459
+ self.data_collator = data_collator
460
+ self.eval_dataset = eval_dataset
461
+ self.optimizer, self.lr_scheduler = optimizers
462
+ self.optimizer_cls_and_kwargs = None # needed for transformers >= 4.47
463
+
464
+ #########
465
+ # calculate various batch sizes
466
+ #########
467
+ if args.total_episodes is None: # allow the users to define episodes in terms of epochs.
468
+ args.total_episodes = int(args.num_train_epochs * self.train_dataset_len)
469
+ accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps)
470
+ self.accelerator = accelerator
471
+ args.world_size = accelerator.num_processes
472
+ args.local_batch_size = args.per_device_train_batch_size * args.gradient_accumulation_steps
473
+ args.micro_batch_size = int(args.per_device_train_batch_size * args.world_size)
474
+ args.batch_size = int(args.local_batch_size * args.world_size)
475
+ args.mini_batch_size = exact_div(
476
+ args.batch_size, args.num_mini_batches, "`batch_size` must be a multiple of `num_mini_batches`"
477
+ )
478
+ args.local_mini_batch_size = exact_div(
479
+ args.local_batch_size, args.num_mini_batches, "`local_batch_size` must be a multiple of `num_mini_batches`"
480
+ )
481
+ if args.whiten_rewards:
482
+ assert args.local_mini_batch_size >= 8, (
483
+ f"Per-rank minibatch size {args.local_mini_batch_size} is insufficient for whitening"
484
+ )
485
+ # `per_rank_rollout_batch_size` is our `args.local_batch_size`
486
+ # `per_rank_minibatch_size` is our `args.local_mini_batch_size`
487
+ args.num_total_batches = math.ceil(
488
+ args.total_episodes / args.batch_size
489
+ ) # we may train for more than `total_episodes`
490
+ self.local_seed = args.seed + accelerator.process_index * 100003 # Prime
491
+ if args.num_sample_generations > 0:
492
+ self.sample_generations_freq = max(1, args.num_total_batches // args.num_sample_generations)
493
+ self.local_dataloader_batch_size = args.local_batch_size
494
+
495
+ #########
496
+ # setup model, optimizer, and others
497
+ #########
498
+ for module in [self.policy_model, self.ref_model, self.value_model, self.reward_model]:
499
+ if module is not None:
500
+ disable_dropout_in_model(module)
501
+ self.model = PolicyAndValueWrapper(self.policy_model, self.value_model)
502
+ self.model.config = self.policy_model.config # needed for pushing to hub
503
+ self.create_optimizer_and_scheduler(
504
+ num_training_steps=args.num_total_batches
505
+ ) # note that we are calling `self.lr_scheduler.step()` manually only at the batch level
506
+
507
+ #########
508
+ # trainer specifics
509
+ #########
510
+ default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to)
511
+ self.callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks
512
+ self.callback_handler = CallbackHandler(
513
+ self.callbacks, self.model, self.processing_class, self.optimizer, self.lr_scheduler
514
+ )
515
+ self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK)
516
+ self.control = TrainerControl()
517
+ self.state = OnlineTrainerState(
518
+ is_local_process_zero=self.is_local_process_zero(),
519
+ is_world_process_zero=self.is_world_process_zero(),
520
+ stateful_callbacks=[
521
+ cb for cb in self.callback_handler.callbacks + [self.control] if isinstance(cb, ExportableState)
522
+ ],
523
+ )
524
+ self.current_flos = 0
525
+ self.hp_search_backend = None
526
+ self.is_deepspeed_enabled = getattr(self.accelerator.state, "deepspeed_plugin", None) is not None
527
+ self.is_fsdp_enabled = getattr(self.accelerator.state, "fsdp_plugin", None) is not None
528
+ # Create distant repo and output directory if needed
529
+ self.hub_model_id = None
530
+ if self.args.push_to_hub:
531
+ self.init_hf_repo()
532
+ if self.args.should_save:
533
+ os.makedirs(self.args.output_dir, exist_ok=True)
534
+
535
+ # Add tags for models that have been loaded with the correct transformers version
536
+ if hasattr(self.model, "add_model_tags"):
537
+ self.model.add_model_tags(self._tag_names)
538
+
539
+ #########
540
+ # setup dataloader
541
+ #########
542
+ self.dataloader = DataLoader(
543
+ self.train_dataset,
544
+ batch_size=self.local_dataloader_batch_size,
545
+ shuffle=True,
546
+ collate_fn=self.data_collator,
547
+ drop_last=True, # needed; otherwise the last batch will be of ragged shape
548
+ )
549
+ # sync random states for DataLoader(shuffle=True) before `accelerator.prepare`
550
+ # see https://gist.github.com/vwxyzjn/2581bff1e48e185e0b85b6dfe1def79c
551
+ torch.manual_seed(args.seed)
552
+ self.model, self.optimizer, self.dataloader = accelerator.prepare(self.model, self.optimizer, self.dataloader)
553
+ torch.manual_seed(self.local_seed) # reset the local seed again
554
+
555
+ self.eval_dataloader = DataLoader(
556
+ self.eval_dataset,
557
+ batch_size=args.per_device_eval_batch_size,
558
+ collate_fn=self.data_collator,
559
+ drop_last=True,
560
+ ) # no need to shuffle eval dataset
561
+ self.eval_dataloader = accelerator.prepare(self.eval_dataloader)
562
+
563
+ if self.is_deepspeed_enabled:
564
+ self.reward_model = prepare_deepspeed(self.reward_model, accelerator)
565
+
566
+ if self.ref_model is None:
567
+ if not self.is_peft_model:
568
+ raise ValueError("No reference model and model is not a Peft model.")
569
+ else:
570
+ self.ref_model = prepare_deepspeed(self.ref_model, accelerator)
571
+ else:
572
+ if self.ref_model is None:
573
+ if not self.is_peft_model:
574
+ raise ValueError("No reference model and model is not a Peft model.")
575
+ else:
576
+ self.ref_model = self.ref_model.to(self.accelerator.device)
577
+ self.reward_model = self.reward_model.to(self.accelerator.device)
578
+
579
+ def get_train_dataloader(self) -> DataLoader:
580
+ return self.dataloader
581
+
582
+ def get_eval_dataloader(self) -> DataLoader:
583
+ return self.eval_dataloader
584
+
585
+ @contextmanager
586
+ def null_ref_context(self):
587
+ """Context manager for handling null reference model (that is, peft adapter manipulation)."""
588
+ with (
589
+ self.accelerator.unwrap_model(self.model.policy).disable_adapter()
590
+ if self.is_peft_model and not self.ref_adapter_name
591
+ else nullcontext()
592
+ ):
593
+ if self.ref_adapter_name:
594
+ self.model.policy.set_adapter(self.ref_adapter_name)
595
+ yield
596
+ if self.ref_adapter_name:
597
+ self.model.policy.set_adapter(self.model_adapter_name or "default")
598
+
599
+ def save_model(self, output_dir: str | None = None, _internal_call: bool = False):
600
+ backup_model = self.model
601
+ if hasattr(self.model, "policy"):
602
+ self.model = self.model.policy # save only the policy for inference
603
+ if self.is_deepspeed_enabled:
604
+ backup_deepspeed = self.deepspeed
605
+ self.deepspeed = self.model
606
+
607
+ super().save_model(output_dir, _internal_call)
608
+
609
+ self.model = backup_model
610
+ if self.is_deepspeed_enabled:
611
+ self.deepspeed = backup_deepspeed
612
+
613
+ def train(self):
614
+ args = self.args
615
+ accelerator = self.accelerator
616
+ optimizer = self.optimizer
617
+ model = self.model
618
+ ref_policy = self.ref_model
619
+ reward_model = self.reward_model
620
+ processing_class = self.processing_class
621
+ dataloader = self.dataloader
622
+ device = accelerator.device
623
+
624
+ def repeat_generator():
625
+ while True:
626
+ yield from dataloader
627
+
628
+ iter_dataloader = iter(repeat_generator())
629
+ generation_kwargs = {
630
+ "max_new_tokens": args.response_length,
631
+ "temperature": (args.temperature + 1e-7),
632
+ "top_k": 0.0,
633
+ "top_p": 1.0,
634
+ "do_sample": True,
635
+ }
636
+ generation_config = GenerationConfig(**generation_kwargs)
637
+
638
+ accelerator.print("===training policy===")
639
+ start_time = time.time()
640
+ stats_shape = (args.num_ppo_epochs, args.num_mini_batches, args.gradient_accumulation_steps)
641
+ approxkl_stats = torch.zeros(stats_shape, device=device)
642
+ pg_clipfrac_stats = torch.zeros(stats_shape, device=device)
643
+ pg_loss_stats = torch.zeros(stats_shape, device=device)
644
+ vf_loss_stats = torch.zeros(stats_shape, device=device)
645
+ vf_clipfrac_stats = torch.zeros(stats_shape, device=device)
646
+ entropy_stats = torch.zeros(stats_shape, device=device)
647
+ ratio_stats = torch.zeros(stats_shape, device=device)
648
+ model.train()
649
+
650
+ # trainer state initialization
651
+ self.state.global_step = 0
652
+ self.state.episode = 0
653
+ self.state.max_steps = args.num_total_batches
654
+ self.state.num_train_epochs = args.total_episodes / self.train_dataset_len
655
+ # Compute absolute values for logging, eval, and save if given as ratio
656
+ if args.logging_steps is not None:
657
+ if args.logging_steps < 1:
658
+ self.state.logging_steps = math.ceil(self.state.max_steps * args.logging_steps)
659
+ else:
660
+ self.state.logging_steps = args.logging_steps
661
+ if args.eval_steps is not None:
662
+ if args.eval_steps < 1:
663
+ self.state.eval_steps = math.ceil(self.state.max_steps * args.eval_steps)
664
+ else:
665
+ self.state.eval_steps = args.eval_steps
666
+ if args.save_steps is not None:
667
+ if args.save_steps < 1:
668
+ self.state.save_steps = math.ceil(self.state.max_steps * args.save_steps)
669
+ else:
670
+ self.state.save_steps = args.save_steps
671
+ self.control = self.callback_handler.on_train_begin(args, self.state, self.control)
672
+
673
+ # backward compatibility
674
+ if self.is_deepspeed_enabled:
675
+ self.deepspeed = self.model
676
+ self.model_wrapped = self.model
677
+
678
+ for update in range(1, args.num_total_batches + 1):
679
+ self.state.episode += 1 * args.batch_size
680
+ data = next(iter_dataloader)
681
+ with torch.no_grad():
682
+ queries = data["input_ids"].to(device)
683
+ context_length = queries.shape[1]
684
+ responses = []
685
+ postprocessed_responses = []
686
+ logprobs = []
687
+ ref_logprobs = []
688
+ scores = []
689
+ sequence_lengths = []
690
+ values = []
691
+ with (
692
+ unwrap_model_for_generation(
693
+ self.model,
694
+ self.accelerator,
695
+ gather_deepspeed3_params=self.args.ds3_gather_for_generation,
696
+ generation_kwargs=generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
697
+ ) as unwrapped_model
698
+ ):
699
+ query_responses, logitss = batch_generation(
700
+ unwrapped_model.policy,
701
+ queries,
702
+ args.local_rollout_forward_batch_size,
703
+ processing_class.pad_token_id,
704
+ generation_config,
705
+ )
706
+
707
+ for i in range(0, queries.shape[0], args.local_rollout_forward_batch_size):
708
+ query = queries[i : i + args.local_rollout_forward_batch_size]
709
+ query_response = query_responses[i : i + args.local_rollout_forward_batch_size]
710
+ response = query_response[:, context_length:]
711
+ logits = logitss[i : i + args.local_rollout_forward_batch_size]
712
+ logprob = selective_log_softmax(logits, response)
713
+ del logits
714
+ empty_cache()
715
+
716
+ if ref_policy is None:
717
+ with self.null_ref_context():
718
+ ref_output = forward(model.policy, query_response, processing_class.pad_token_id)
719
+ else:
720
+ ref_output = forward(ref_policy, query_response, processing_class.pad_token_id)
721
+ ref_logits = ref_output.logits[:, context_length - 1 : -1]
722
+ ref_logits /= args.temperature + 1e-7
723
+ ref_logprob = selective_log_softmax(ref_logits, response)
724
+ del ref_output, ref_logits
725
+ empty_cache()
726
+
727
+ # Response Processing 1. truncate response after the first occurrence of `stop_token_id`
728
+ postprocessed_response = response
729
+ if self.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0
730
+ postprocessed_response = truncate_response(
731
+ self.stop_token_id, processing_class.pad_token_id, response
732
+ )
733
+
734
+ # Response Processing 2. run reward model on the truncated responses
735
+ postprocessed_query_response = torch.cat((query, postprocessed_response), 1)
736
+ sequence_length = first_true_indices(postprocessed_response == processing_class.pad_token_id) - 1
737
+ unwrapped_value_model = accelerator.unwrap_model(model).value_model
738
+ full_value, _, _ = get_reward(
739
+ unwrapped_value_model, query_response, processing_class.pad_token_id, context_length
740
+ )
741
+ value = full_value[:, context_length - 1 : -1].squeeze(-1)
742
+ _, score, _ = get_reward(
743
+ reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length
744
+ )
745
+
746
+ responses.append(response)
747
+ postprocessed_responses.append(postprocessed_response)
748
+ logprobs.append(logprob)
749
+ ref_logprobs.append(ref_logprob)
750
+ sequence_lengths.append(sequence_length)
751
+ scores.append(score)
752
+ values.append(value)
753
+ responses = torch.cat(responses, 0)
754
+ postprocessed_responses = torch.cat(postprocessed_responses, 0)
755
+ logprobs = torch.cat(logprobs, 0)
756
+ ref_logprobs = torch.cat(ref_logprobs, 0)
757
+ sequence_lengths = torch.cat(sequence_lengths, 0)
758
+ scores = torch.cat(scores, 0)
759
+ values = torch.cat(values, 0)
760
+ del (logprob, ref_logprob, full_value, value, score, unwrapped_model)
761
+ empty_cache()
762
+ gc.collect()
763
+
764
+ # Response Processing 3. Filter completion. Ensure that the sample contains stop_token_id
765
+ # Completions not passing that filter will receive a lower score.
766
+ contain_eos_token = torch.any(postprocessed_responses == self.processing_class.eos_token_id, dim=-1)
767
+ if self.args.missing_eos_penalty is not None:
768
+ scores[~contain_eos_token] -= self.args.missing_eos_penalty
769
+ # accelerator.print(f"{scores=}, {(contain_eos_token.sum() / len(contain_eos_token))=}")
770
+
771
+ # be very careful with `padding_mask_p1`; see https://excalidraw.com/#json=LWnzG4w2k5DjF_EOL_xPt,e2w3a-hFJ_gX5vOfeyXGTw
772
+ response_idxs = torch.arange(responses.shape[1], device=responses.device).repeat(responses.shape[0], 1)
773
+ padding_mask = response_idxs > sequence_lengths.unsqueeze(1)
774
+ logprobs = torch.masked_fill(logprobs, padding_mask, INVALID_LOGPROB)
775
+ ref_logprobs = torch.masked_fill(ref_logprobs, padding_mask, INVALID_LOGPROB)
776
+ sequence_lengths_p1 = sequence_lengths + 1
777
+ padding_mask_p1 = response_idxs > (sequence_lengths_p1.unsqueeze(1))
778
+ values = torch.masked_fill(values, padding_mask_p1, 0)
779
+
780
+ # 4. compute rewards
781
+ # Formula used by http://joschu.net/blog/kl-approx.html for the k1 and k3 estimators
782
+ logr = ref_logprobs - logprobs
783
+ kl = -logr if args.kl_estimator == "k1" else (logr.exp() - 1) - logr # Else statement is k3
784
+ non_score_reward = -args.kl_coef * kl
785
+ rewards = non_score_reward.clone()
786
+ actual_start = torch.arange(rewards.size(0), device=rewards.device)
787
+ actual_end = torch.where(sequence_lengths_p1 < rewards.size(1), sequence_lengths_p1, sequence_lengths)
788
+ rewards[actual_start, actual_end] += scores
789
+
790
+ # 5. whiten rewards
791
+ if args.whiten_rewards:
792
+ rewards = masked_whiten(rewards, mask=~padding_mask_p1, shift_mean=False)
793
+ rewards = torch.masked_fill(rewards, padding_mask_p1, 0)
794
+
795
+ # 6. compute advantages and returns
796
+ lastgaelam = 0
797
+ advantages_reversed = []
798
+ gen_length = responses.shape[1]
799
+ for t in reversed(range(gen_length)):
800
+ nextvalues = values[:, t + 1] if t < gen_length - 1 else 0.0
801
+ delta = rewards[:, t] + args.gamma * nextvalues - values[:, t]
802
+ lastgaelam = delta + args.gamma * args.lam * lastgaelam
803
+ advantages_reversed.append(lastgaelam)
804
+ advantages = torch.stack(advantages_reversed[::-1], axis=1)
805
+ returns = advantages + values
806
+ advantages = masked_whiten(advantages, ~padding_mask)
807
+ advantages = torch.masked_fill(advantages, padding_mask, 0)
808
+ empty_cache()
809
+
810
+ # Do multiple epochs of PPO training, with a fresh random shuffle in each epoch
811
+ for ppo_epoch_idx in range(args.num_ppo_epochs):
812
+ b_inds = np.random.permutation(args.local_batch_size)
813
+ minibatch_idx = 0
814
+ for mini_batch_start in range(0, args.local_batch_size, args.local_mini_batch_size):
815
+ mini_batch_end = mini_batch_start + args.local_mini_batch_size
816
+ mini_batch_inds = b_inds[mini_batch_start:mini_batch_end]
817
+ gradient_accumulation_idx = 0
818
+ for micro_batch_start in range(0, args.local_mini_batch_size, args.per_device_train_batch_size):
819
+ with accelerator.accumulate(model):
820
+ micro_batch_end = micro_batch_start + args.per_device_train_batch_size
821
+ micro_batch_inds = mini_batch_inds[micro_batch_start:micro_batch_end]
822
+ mb_advantage = advantages[micro_batch_inds]
823
+ mb_responses = responses[micro_batch_inds]
824
+ mb_query_responses = query_responses[micro_batch_inds]
825
+ mb_logprobs = logprobs[micro_batch_inds]
826
+ mb_return = returns[micro_batch_inds]
827
+ mb_values = values[micro_batch_inds]
828
+
829
+ output, vpred_temp = forward(model, mb_query_responses, processing_class.pad_token_id)
830
+ logits = output.logits[:, context_length - 1 : -1]
831
+ logits /= args.temperature + 1e-7
832
+ new_logprobs = selective_log_softmax(logits, mb_responses)
833
+ new_logprobs = torch.masked_fill(
834
+ new_logprobs, padding_mask[micro_batch_inds], INVALID_LOGPROB
835
+ )
836
+ vpred = vpred_temp[:, context_length - 1 : -1].squeeze(-1)
837
+ vpred = torch.masked_fill(vpred, padding_mask_p1[micro_batch_inds], 0)
838
+ vpredclipped = torch.clamp(
839
+ vpred,
840
+ mb_values - args.cliprange_value,
841
+ mb_values + args.cliprange_value,
842
+ )
843
+ vf_losses1 = torch.square(vpred - mb_return)
844
+ vf_losses2 = torch.square(vpredclipped - mb_return)
845
+ vf_loss_max = torch.max(vf_losses1, vf_losses2)
846
+ vf_loss = 0.5 * masked_mean(vf_loss_max, ~padding_mask_p1[micro_batch_inds])
847
+ vf_clipfrac = masked_mean(
848
+ (vf_losses2 > vf_losses1).float(), ~padding_mask_p1[micro_batch_inds]
849
+ )
850
+ logprobs_diff = new_logprobs - mb_logprobs
851
+ ratio = torch.exp(logprobs_diff)
852
+ pg_losses = -mb_advantage * ratio
853
+ pg_losses2 = -mb_advantage * torch.clamp(ratio, 1.0 - args.cliprange, 1.0 + args.cliprange)
854
+ pg_loss_max = torch.max(pg_losses, pg_losses2)
855
+ pg_loss = masked_mean(pg_loss_max, ~padding_mask[micro_batch_inds])
856
+ loss = pg_loss + args.vf_coef * vf_loss
857
+ accelerator.backward(loss)
858
+ optimizer.step()
859
+ optimizer.zero_grad()
860
+ with torch.no_grad():
861
+ pg_clipfrac = masked_mean(
862
+ (pg_losses2 > pg_losses).float(), ~padding_mask[micro_batch_inds]
863
+ )
864
+ prob_dist = torch.nn.functional.softmax(logits, dim=-1)
865
+ entropy = torch.logsumexp(logits, dim=-1) - torch.sum(prob_dist * logits, dim=-1)
866
+ approxkl = 0.5 * (logprobs_diff**2).mean()
867
+ approxkl_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = approxkl
868
+ pg_clipfrac_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = (
869
+ pg_clipfrac
870
+ )
871
+ pg_loss_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = pg_loss
872
+ vf_loss_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = vf_loss
873
+ vf_clipfrac_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = (
874
+ vf_clipfrac
875
+ )
876
+ entropy_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = entropy.mean()
877
+ ratio_stats[ppo_epoch_idx, minibatch_idx, gradient_accumulation_idx] = ratio.mean()
878
+ gradient_accumulation_idx += 1
879
+ minibatch_idx += 1
880
+ # del everything and empty cache
881
+ # fmt: off
882
+ del (
883
+ output, vpred_temp, logits, new_logprobs, vpred, vpredclipped,
884
+ vf_losses1, vf_losses2, vf_loss, vf_clipfrac, logprobs_diff, ratio, pg_losses, pg_losses2, pg_loss_max,
885
+ pg_loss, loss, pg_clipfrac, prob_dist, entropy, approxkl, mb_return,
886
+ mb_advantage, mb_values, mb_responses, mb_query_responses, mb_logprobs,
887
+ )
888
+ # fmt: on
889
+ empty_cache()
890
+ with torch.no_grad():
891
+ mean_kl = kl.sum(1).mean()
892
+ mean_entropy = (-logprobs).sum(1).mean()
893
+ mean_non_score_reward = non_score_reward.sum(1).mean()
894
+ rlhf_reward = mean_non_score_reward + scores.mean()
895
+ eps = int(self.state.episode / (time.time() - start_time))
896
+ metrics = {}
897
+ metrics["eps"] = eps
898
+ metrics["objective/kl"] = self.accelerator.gather_for_metrics(mean_kl).mean().item()
899
+ metrics["objective/entropy"] = self.accelerator.gather_for_metrics(mean_entropy).mean().item()
900
+ metrics["objective/non_score_reward"] = (
901
+ self.accelerator.gather_for_metrics(mean_non_score_reward).mean().item()
902
+ )
903
+ metrics["objective/rlhf_reward"] = self.accelerator.gather_for_metrics(rlhf_reward).mean().item()
904
+ metrics["objective/scores"] = self.accelerator.gather_for_metrics(scores.mean()).mean().item()
905
+ metrics["policy/approxkl_avg"] = self.accelerator.gather_for_metrics(approxkl_stats).mean().item()
906
+ metrics["policy/clipfrac_avg"] = self.accelerator.gather_for_metrics(pg_clipfrac_stats).mean().item()
907
+ metrics["loss/policy_avg"] = self.accelerator.gather_for_metrics(pg_loss_stats).mean().item()
908
+ metrics["loss/value_avg"] = self.accelerator.gather_for_metrics(vf_loss_stats).mean().item()
909
+ metrics["val/clipfrac_avg"] = self.accelerator.gather_for_metrics(vf_clipfrac_stats).mean().item()
910
+ metrics["policy/entropy_avg"] = self.accelerator.gather_for_metrics(entropy_stats).mean().item()
911
+ metrics["val/ratio"] = self.accelerator.gather_for_metrics(ratio_stats).mean().item()
912
+ metrics["val/ratio_var"] = self.accelerator.gather_for_metrics(ratio_stats).var().item()
913
+ metrics["val/num_eos_tokens"] = (responses == processing_class.eos_token_id).sum().item()
914
+ metrics["lr"] = self.lr_scheduler.get_last_lr()[0]
915
+ metrics["episode"] = self.state.episode
916
+ self.state.epoch = self.state.episode / self.train_dataset_len # used by self.log
917
+ self.state.global_step += 1
918
+ self.log(metrics)
919
+
920
+ self.lr_scheduler.step()
921
+ self.control = self.callback_handler.on_step_end(args, self.state, self.control)
922
+ if self.control.should_save:
923
+ self._save_checkpoint(model, trial=None)
924
+ self.control = self.callback_handler.on_save(self.args, self.state, self.control)
925
+ del kl, mean_kl, mean_entropy, mean_non_score_reward, scores, metrics, non_score_reward
926
+ empty_cache()
927
+ gc.collect()
928
+
929
+ if args.num_sample_generations > 0 and (update - 1) % self.sample_generations_freq == 0:
930
+ self.generate_completions(sampling=True)
931
+ empty_cache()
932
+ del (
933
+ query_responses,
934
+ responses,
935
+ postprocessed_responses,
936
+ logprobs,
937
+ ref_logprobs,
938
+ values,
939
+ sequence_lengths,
940
+ contain_eos_token,
941
+ sequence_lengths_p1,
942
+ response_idxs,
943
+ padding_mask,
944
+ padding_mask_p1,
945
+ rewards,
946
+ actual_start,
947
+ actual_end,
948
+ advantages,
949
+ returns,
950
+ )
951
+ empty_cache()
952
+
953
+ # HF trainer specifics
954
+ self.control = self.callback_handler.on_train_end(args, self.state, self.control)
955
+ if self.control.should_save:
956
+ self._save_checkpoint(model, trial=None)
957
+ self.control = self.callback_handler.on_save(self.args, self.state, self.control)
958
+
959
+ def generate_completions(self, sampling: bool = False):
960
+ if self.eval_dataset is None:
961
+ return # no eval set to sample from (pass eval_dataset and eval_strategy != "no" for sample generations)
962
+ args = self.args
963
+ processing_class = self.processing_class
964
+ generation_kwargs = {
965
+ "max_new_tokens": args.response_length,
966
+ "temperature": (0.01 + 1e-7),
967
+ "top_k": 0.0,
968
+ "top_p": 1.0,
969
+ "do_sample": True,
970
+ }
971
+ generation_config = GenerationConfig(**generation_kwargs)
972
+
973
+ table = defaultdict(list)
974
+ with (
975
+ unwrap_model_for_generation(
976
+ self.model,
977
+ self.accelerator,
978
+ gather_deepspeed3_params=self.args.ds3_gather_for_generation,
979
+ generation_kwargs=generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
980
+ ) as unwrapped_model
981
+ ):
982
+ for batch in self.eval_dataloader:
983
+ query = batch["input_ids"]
984
+ with torch.no_grad():
985
+ context_length = query.shape[1]
986
+ query_response, _ = batch_generation(
987
+ unwrapped_model.policy,
988
+ query,
989
+ query.shape[0],
990
+ processing_class.pad_token_id,
991
+ generation_config,
992
+ )
993
+ response = query_response[:, context_length:]
994
+ postprocessed_response = response
995
+ if self.stop_token_id is not None: # handle the edge case when stop_token_id exists but is 0
996
+ postprocessed_response = truncate_response(
997
+ self.stop_token_id, processing_class.pad_token_id, response
998
+ )
999
+ table["query"].extend(
1000
+ gather_object(processing_class.batch_decode(query, skip_special_tokens=True))
1001
+ )
1002
+ table["model response"].extend(
1003
+ gather_object(processing_class.batch_decode(postprocessed_response))
1004
+ )
1005
+
1006
+ postprocessed_query_response = torch.cat((query, postprocessed_response), 1)
1007
+ _, score, _ = get_reward(
1008
+ self.reward_model, postprocessed_query_response, processing_class.pad_token_id, context_length
1009
+ )
1010
+ table["score"].extend(self.accelerator.gather_for_metrics(score).float().cpu().numpy())
1011
+
1012
+ if sampling:
1013
+ break
1014
+ df = pd.DataFrame(table)
1015
+
1016
+ if self.accelerator.is_main_process:
1017
+ if is_rich_available():
1018
+ print_rich_table(df.iloc[0 : 0 + 5])
1019
+ if "wandb" in args.report_to:
1020
+ import wandb
1021
+
1022
+ if wandb.run is not None:
1023
+ wandb.log({"completions": wandb.Table(dataframe=df)})
1024
+
1025
+ if "comet_ml" in args.report_to:
1026
+ log_table_to_comet_experiment(
1027
+ name="completions.csv",
1028
+ table=df,
1029
+ )
1030
+
1031
+ # Ensure the model card is saved along with the checkpoint
1032
+ def _save_checkpoint(self, model, trial):
1033
+ if self.args.hub_model_id is None:
1034
+ model_name = Path(self.args.output_dir).name
1035
+ else:
1036
+ model_name = self.args.hub_model_id.split("/")[-1]
1037
+ self.create_model_card(model_name=model_name)
1038
+ super()._save_checkpoint(model, trial)
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/prm/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .prm_config import PRMConfig
16
+ from .prm_trainer import PRMTrainer
17
+
18
+
19
+ __all__ = ["PRMConfig", "PRMTrainer"]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/prm/prm_config.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+ from ...trainer.base_config import _BaseConfig
18
+
19
+
20
+ @dataclass
21
+ class PRMConfig(_BaseConfig):
22
+ # docstyle-ignore
23
+ r"""
24
+ Configuration class for the [`experimental.prm.PRMTrainer`].
25
+
26
+ This class includes only the parameters that are specific to PRM training. For a full list of training arguments,
27
+ please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
28
+ differ from those in [`~transformers.TrainingArguments`].
29
+
30
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
31
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
32
+ command line.
33
+
34
+ Parameters:
35
+ max_length (`int` or `None`, *optional*, defaults to `1024`):
36
+ Maximum length of the sequences (prompt + completion) used for truncation.
37
+ max_completion_length (`int`, *optional*):
38
+ Maximum length of the completion used for truncation. The completion is the concatenation of the steps.
39
+ disable_dropout (`bool`, *optional*, defaults to `True`):
40
+ Whether to disable dropout in the model.
41
+ step_separator (`str`, *optional*, defaults to `"\n"`):
42
+ Separator used to separate each step of the reasoning process.
43
+ train_on_last_step_only (`bool`, *optional*, defaults to `False`):
44
+ Whether to train only on the last step.
45
+ dataset_num_proc (`int`, *optional*):
46
+ Number of processes to use for processing the dataset.
47
+
48
+ > [!NOTE]
49
+ > These parameters have default values different from [`~transformers.TrainingArguments`]:
50
+ > - `logging_steps`: Defaults to `10` instead of `500`.
51
+ > - `gradient_checkpointing`: Defaults to `True` instead of `False`.
52
+ > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
53
+ > - `learning_rate`: Defaults to `1e-5` instead of `5e-5`.
54
+ """
55
+
56
+ # Parameters whose default values are overridden from TrainingArguments
57
+ learning_rate: float = field(
58
+ default=1e-5,
59
+ metadata={"help": "The initial learning rate for AdamW."},
60
+ )
61
+
62
+ max_length: int | None = field(
63
+ default=1024,
64
+ metadata={"help": "Maximum length of the sequences (prompt + completion) used for truncation."},
65
+ )
66
+ max_completion_length: int | None = field(
67
+ default=None,
68
+ metadata={
69
+ "help": "Maximum length of the completion used for truncation. The completion is the concatenation of the "
70
+ "steps."
71
+ },
72
+ )
73
+ disable_dropout: bool = field(
74
+ default=True,
75
+ metadata={"help": "Whether to disable dropout in the model and reference model."},
76
+ )
77
+ step_separator: str = field(
78
+ default="\n",
79
+ metadata={"help": "Separator used to separate each step of the reasoning process."},
80
+ )
81
+ train_on_last_step_only: bool = field(
82
+ default=False,
83
+ metadata={"help": "Whether to train only on the last step."},
84
+ )
85
+ dataset_num_proc: int | None = field(
86
+ default=None,
87
+ metadata={"help": "Number of processes to use for processing the dataset."},
88
+ )
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/prm/prm_trainer.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import textwrap
16
+ from collections.abc import Callable
17
+ from itertools import chain
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn as nn
23
+ import transformers
24
+ from accelerate import PartialState
25
+ from accelerate.logging import get_logger
26
+ from accelerate.utils import is_peft_model
27
+ from datasets import Dataset, features
28
+ from packaging.version import Version
29
+ from transformers import (
30
+ BaseImageProcessor,
31
+ DataCollator,
32
+ DataCollatorForTokenClassification,
33
+ FeatureExtractionMixin,
34
+ PreTrainedModel,
35
+ PreTrainedTokenizerBase,
36
+ ProcessorMixin,
37
+ TrainerCallback,
38
+ )
39
+ from transformers.trainer_utils import EvalPrediction
40
+ from transformers.utils import is_peft_available
41
+
42
+ from ...trainer.base_trainer import _BaseTrainer
43
+ from ...trainer.utils import disable_dropout_in_model
44
+ from ..utils import prepare_peft_model
45
+ from .prm_config import PRMConfig
46
+
47
+
48
+ if is_peft_available():
49
+ from peft import PeftConfig
50
+
51
+ logger = get_logger(__name__)
52
+
53
+
54
+ def compute_accuracy(eval_pred: EvalPrediction) -> dict[str, float]:
55
+ predictions, labels = eval_pred
56
+ if predictions.ndim == 3:
57
+ # Token classification task. Shapes are (batch_size, seq_len, num_labels) and (batch_size, seq_len)
58
+ # Used to compute the accuracy in the prm_trainer.
59
+ predictions = np.argmax(predictions, axis=2)
60
+
61
+ # Flatten the predictions and labels to remove the ignored tokens.
62
+ predictions = np.array(
63
+ [
64
+ p
65
+ for prediction, label in zip(predictions, labels, strict=True)
66
+ for (p, lbl) in zip(prediction, label, strict=True)
67
+ if lbl != -100
68
+ ]
69
+ )
70
+ labels = np.array([lbl for label in labels for lbl in label if lbl != -100])
71
+
72
+ else:
73
+ # Here, predictions is rewards_chosen and rewards_rejected. Shapes are (batch_size, 2) and (batch_size,)
74
+ # We want to see how much of the time rewards_chosen > rewards_rejected.
75
+ equal_mask = predictions[:, 0] == predictions[:, 1]
76
+ equal_predictions_count = int(equal_mask.sum())
77
+
78
+ if equal_predictions_count > 0:
79
+ # Before using the logger, the accelerate state must be initialized. It'susually the case when using this
80
+ # function inside a Trainer, but it may not be the case otherwise, in particular when unit testing.
81
+ PartialState()
82
+
83
+ logger.warning(
84
+ f"There are {equal_predictions_count} out of {len(predictions[:, 0])} instances where the predictions "
85
+ "for both options are equal. These instances are ignored in the accuracy computation.",
86
+ )
87
+
88
+ # Filter out equal predictions
89
+ predictions = predictions[~equal_mask]
90
+ labels = labels[~equal_mask]
91
+
92
+ # Use the remaining predictions for accuracy calculation
93
+ predictions = np.argmax(predictions, axis=1)
94
+
95
+ accuracy = np.array(predictions == labels, dtype=float).mean().item()
96
+ return {"accuracy": accuracy}
97
+
98
+
99
+ class PRMTrainer(_BaseTrainer):
100
+ """
101
+ Initialize PRMTrainer.
102
+
103
+ Args:
104
+ model ([`~transformers.PreTrainedModel`]):
105
+ The model to train, preferably an `AutoModelForTokenClassification`.
106
+ args ([`experimental.prm.PRMConfig`]):
107
+ The arguments to use for training.
108
+ data_collator ([`~transformers.DataCollator`]):
109
+ The data collator to use for training. If None is specified, the default data collator
110
+ ([`~transformers.DataCollatorForTokenClassification`]) will be used which will pad the sequences to the
111
+ maximum length of the sequences in the batch, given a dataset of paired sequences.
112
+ train_dataset ([`~datasets.Dataset`]):
113
+ The dataset to use for training.
114
+ eval_dataset ([`~datasets.Dataset`]):
115
+ The dataset to use for evaluation.
116
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
117
+ Processing class used to process the data. If provided, will be used to automatically process the inputs
118
+ for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
119
+ reuse the fine-tuned model.
120
+ model_init (`Callable[[], transformers.PreTrainedModel]`):
121
+ The model initializer to use for training. If None is specified, the default model initializer will be
122
+ used.
123
+ compute_metrics (`Callable[[transformers.EvalPrediction], dict]`, *optional* defaults to `compute_accuracy`):
124
+ The metrics to use for evaluation. If no metrics are specified, the default metric (`compute_accuracy`)
125
+ will be used.
126
+ callbacks (`list[transformers.TrainerCallback]`):
127
+ The callbacks to use for training.
128
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
129
+ The optimizer and scheduler to use for training.
130
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
131
+ The function to use to preprocess the logits before computing the metrics.
132
+ peft_config ([`~peft.PeftConfig`], *optional*):
133
+ The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in
134
+ a PEFT model.
135
+ """
136
+
137
+ _tag_names = ["trl", "prm"]
138
+ _name = "PRM"
139
+ _paper = {
140
+ "title": "Solving math word problems with process-and outcome-based feedback",
141
+ "id": "2211.14275",
142
+ # docstyle-ignore
143
+ "citation": textwrap.dedent("""\
144
+ @article{uesato2022solving,
145
+ title = {{Solving Math Word Problems With Process- and Outcome-Based Feedback}},
146
+ author = {Uesato, Jonathan and Kushman, Nate and Kumar, Ramana and Song, Francis and Siegel, Noah and Wang, Lisa and Creswell, Antonia and Irving, Geoffrey and Higgins, Irina},
147
+ year = 2022,
148
+ journal = {arXiv preprint arXiv:2211.14275}
149
+ }"""),
150
+ }
151
+
152
+ def __init__(
153
+ self,
154
+ model: PreTrainedModel | nn.Module | None = None,
155
+ args: PRMConfig | None = None,
156
+ data_collator: DataCollator | None = None,
157
+ train_dataset: Dataset | None = None,
158
+ eval_dataset: Dataset | dict[str, Dataset] | None = None,
159
+ processing_class: PreTrainedTokenizerBase
160
+ | BaseImageProcessor
161
+ | FeatureExtractionMixin
162
+ | ProcessorMixin
163
+ | None = None,
164
+ model_init: Callable[[], PreTrainedModel] | None = None,
165
+ compute_metrics: Callable[[EvalPrediction], dict] | None = None,
166
+ callbacks: list[TrainerCallback] | None = None,
167
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (
168
+ None,
169
+ None,
170
+ ),
171
+ preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
172
+ peft_config: "PeftConfig | None" = None,
173
+ ):
174
+ if train_dataset is None:
175
+ raise ValueError("`train_dataset` is required")
176
+
177
+ # PEFT
178
+ if peft_config is not None:
179
+ if not is_peft_available():
180
+ raise ImportError(
181
+ "You passed `peft_config` but the `peft` library is not installed. "
182
+ "Install it with `pip install trl[peft]`."
183
+ )
184
+ if not isinstance(peft_config, PeftConfig):
185
+ raise TypeError(
186
+ f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
187
+ f"got {type(peft_config).__name__}."
188
+ )
189
+ if peft_config is not None or is_peft_model(model):
190
+ model = prepare_peft_model(model, peft_config, args)
191
+
192
+ # Disable dropout in the model
193
+ if args.disable_dropout:
194
+ disable_dropout_in_model(model)
195
+
196
+ if compute_metrics is None:
197
+ compute_metrics = compute_accuracy
198
+
199
+ if data_collator is None:
200
+ if processing_class is None:
201
+ raise ValueError(
202
+ "A processing_class must be specified when using the default DataCollatorForTokenClassification"
203
+ )
204
+ data_collator = DataCollatorForTokenClassification(processing_class)
205
+
206
+ if "input_ids" not in train_dataset.column_names:
207
+ with PartialState().main_process_first():
208
+ fn_kwargs = {
209
+ "tokenizer": processing_class,
210
+ "step_separator": args.step_separator,
211
+ "max_length": args.max_length,
212
+ "max_completion_length": args.max_completion_length,
213
+ "train_on_last_step_only": args.train_on_last_step_only,
214
+ }
215
+ train_fn_kwargs = {**fn_kwargs, "is_eval": False}
216
+ train_dataset = train_dataset.map(
217
+ self.tokenize_row,
218
+ fn_kwargs=train_fn_kwargs,
219
+ num_proc=args.dataset_num_proc,
220
+ remove_columns=train_dataset.features,
221
+ desc="Tokenizing train dataset",
222
+ features=features.Features( # needed to avoid map to cast labels to bool
223
+ {
224
+ "labels": features.Sequence(features.Value("int64")),
225
+ "input_ids": features.Sequence(features.Value("int64")),
226
+ }
227
+ ),
228
+ )
229
+
230
+ eval_fn_kwargs = {**fn_kwargs, "is_eval": True}
231
+ if eval_dataset is not None:
232
+ eval_dataset = eval_dataset.map(
233
+ self.tokenize_row,
234
+ fn_kwargs=eval_fn_kwargs,
235
+ num_proc=args.dataset_num_proc,
236
+ remove_columns=eval_dataset.features,
237
+ desc="Tokenizing eval dataset",
238
+ features=features.Features( # needed to avoid map to cast labels to bool
239
+ {
240
+ "labels": features.Sequence(features.Value("int64")),
241
+ "input_ids": features.Sequence(features.Value("int64")),
242
+ }
243
+ ),
244
+ )
245
+
246
+ # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
247
+ # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
248
+ # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
249
+ # default to the recommended non-reentrant behavior here, while preserving any user-provided value.
250
+ if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
251
+ args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
252
+ args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
253
+
254
+ super().__init__(
255
+ model=model,
256
+ args=args,
257
+ data_collator=data_collator,
258
+ train_dataset=train_dataset,
259
+ eval_dataset=eval_dataset,
260
+ processing_class=processing_class,
261
+ model_init=model_init,
262
+ compute_metrics=compute_metrics,
263
+ callbacks=callbacks,
264
+ optimizers=optimizers,
265
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
266
+ )
267
+
268
+ # Add tags for models that have been loaded with the correct transformers version
269
+ if hasattr(self.model, "add_model_tags"):
270
+ self.model.add_model_tags(self._tag_names)
271
+
272
+ @staticmethod
273
+ def tokenize_row(
274
+ features,
275
+ tokenizer,
276
+ step_separator,
277
+ max_length,
278
+ max_completion_length,
279
+ train_on_last_step_only,
280
+ is_eval,
281
+ ):
282
+ r"""
283
+ Tokenize a row of the dataset.
284
+
285
+ Args:
286
+ features (`dict[str, str]`):
287
+ Row of the dataset, should contain the keys `"prompt"`, `"completions"`, and `"labels"`.
288
+ tokenizer ([`~transformers.PreTrainedTokenizerBase`]):
289
+ Tokenizer used to process the data.
290
+ step_separator (`str`):
291
+ Separator between steps in the completion.
292
+ max_length (`int` or `None`):
293
+ Maximum length of the sequences (prompt + completion). If `None`, the sequences are not truncated.
294
+ max_completion_length (`int` or `None`):
295
+ Maximum length of the completion sequences. If `None`, the completion sequences are not truncated.
296
+ train_on_last_step_only (`bool`):
297
+ Whether to train only on the last step. If `True`, the labels are `-100` for all tokens except the last
298
+ token of the completion.
299
+ is_eval (`bool`):
300
+ Whether the function is used to tokenize samples from a training or an evaluation dataset. Used only if
301
+ `train_on_last_step_only` is set to `True`.
302
+
303
+ Returns:
304
+ `dict[str, list[int]]`:
305
+ Tokenized sequences with the keys `"input_ids"`, and `"labels".
306
+
307
+ Example:
308
+ ```python
309
+ >>> from transformers import AutoTokenizer
310
+
311
+ >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
312
+ >>> features = {
313
+ ... "prompt": "Which number is larger, 9.8 or 9.11?",
314
+ ... "completions": ["11 is greater than 8.", "Hence, 9.11 > 9.8."],
315
+ ... "labels": [True, False],
316
+ ... }
317
+ >>> PRMTrainer.tokenize_row(
318
+ ... features, tokenizer, "\n", max_completion_length=None, train_on_last_step_only=False, is_eval=False
319
+ ... )
320
+ {'input_ids': [23085, 1372, 374, 8131, 11, 220, 24, 13, 23, 476, 220, 24, 13, 16, 16, 30, 16, 16, 374, 7046, 1091, 220, 23, 13, 198, 39, 763, 11, 220, 24, 13, 16, 16, 861, 220, 24, 13, 23, 13, 198],
321
+ 'labels': [-100, -100, -100, -100, -100, -100, -100, -100, 1, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, 0]}
322
+ ```
323
+ """
324
+ # Tokenize the prompt and completions
325
+ prompt_ids = tokenizer(features["prompt"], add_special_tokens=False)["input_ids"]
326
+ completions_ids = [
327
+ tokenizer(completion, add_special_tokens=False)["input_ids"] for completion in features["completions"]
328
+ ]
329
+ if train_on_last_step_only and not is_eval:
330
+ labels = [-100] * (len(features["labels"]) - 1) + [int(features["labels"][-1])]
331
+ else:
332
+ labels = [int(label) for label in features["labels"]]
333
+
334
+ # Get the ID of the separator token and add it to the completions
335
+ separator_ids = tokenizer.encode(step_separator, add_special_tokens=False)
336
+ completions_ids = [completion + separator_ids for completion in completions_ids]
337
+
338
+ # Create the label
339
+ labels = [
340
+ [-100] * (len(completion) - 1) + [label] for completion, label in zip(completions_ids, labels, strict=True)
341
+ ]
342
+
343
+ # Join the completions and labels steps
344
+ completion_ids = list(chain(*completions_ids))
345
+ labels = list(chain(*labels))
346
+
347
+ if tokenizer.bos_token_id is not None:
348
+ prompt_ids = [tokenizer.bos_token_id] + prompt_ids
349
+
350
+ # Truncate completion sequences
351
+ if max_completion_length is not None:
352
+ completion_ids = completion_ids[:max_completion_length]
353
+ labels = labels[:max_completion_length]
354
+
355
+ input_ids = prompt_ids + completion_ids
356
+ labels = [-100] * len(prompt_ids) + labels
357
+
358
+ if max_length is not None:
359
+ input_ids = input_ids[:max_length]
360
+ labels = labels[:max_length]
361
+
362
+ return {"input_ids": input_ids, "labels": labels}
363
+
364
+ # Ensure the model card is saved along with the checkpoint
365
+ def _save_checkpoint(self, model, trial):
366
+ if self.args.hub_model_id is None:
367
+ model_name = Path(self.args.output_dir).name
368
+ else:
369
+ model_name = self.args.hub_model_id.split("/")[-1]
370
+ self.create_model_card(model_name=model_name)
371
+ super()._save_checkpoint(model, trial)
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdft/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .sdft_config import SDFTConfig
16
+ from .sdft_trainer import SDFTTrainer
17
+
18
+
19
+ __all__ = ["SDFTConfig", "SDFTTrainer"]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdft/loss_utils.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Pure helper functions for self-distillation loss computation."""
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+
20
+ from ...trainer.utils import selective_log_softmax
21
+
22
+
23
+ def compute_divergence(
24
+ student_log_probs: torch.Tensor,
25
+ teacher_log_probs: torch.Tensor,
26
+ alpha: float,
27
+ ) -> torch.Tensor:
28
+ if alpha == 0.0:
29
+ kl = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True)
30
+ elif alpha == 1.0:
31
+ kl = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True)
32
+ else:
33
+ alpha_t = torch.tensor(alpha, dtype=student_log_probs.dtype, device=student_log_probs.device)
34
+ mixture = torch.logsumexp(
35
+ torch.stack([student_log_probs + torch.log(1 - alpha_t), teacher_log_probs + torch.log(alpha_t)]),
36
+ dim=0,
37
+ )
38
+ kl_teacher = F.kl_div(mixture, teacher_log_probs, reduction="none", log_target=True)
39
+ kl_student = F.kl_div(mixture, student_log_probs, reduction="none", log_target=True)
40
+ kl = torch.lerp(kl_student, kl_teacher, alpha)
41
+ return kl.sum(-1)
42
+
43
+
44
+ def add_tail_bucket(log_probs: torch.Tensor) -> torch.Tensor:
45
+ """Append a bucket holding the leftover probability mass to a top-k log-prob support.
46
+
47
+ `log_probs` are true log-probabilities over a top-k subset, so they sum to the captured mass `P_topk <= 1`. This
48
+ appends one extra category equal to the tail mass `1 - P_topk`, yielding a distribution that sums to exactly 1.
49
+ """
50
+ log_s = torch.logsumexp(log_probs, dim=-1, keepdim=True)
51
+ log_s = torch.clamp(log_s, max=-1e-7)
52
+ tail_log = torch.log(-torch.expm1(log_s))
53
+ return torch.cat([log_probs, tail_log], dim=-1)
54
+
55
+
56
+ def apply_importance_sampling_clipping(
57
+ per_token_loss: torch.Tensor,
58
+ student_log_probs: torch.Tensor,
59
+ old_log_probs: torch.Tensor,
60
+ clip_coeff: float,
61
+ ) -> torch.Tensor:
62
+ negative_approx_kl = (student_log_probs - old_log_probs).detach()
63
+ negative_approx_kl = torch.clamp(negative_approx_kl, min=-20.0, max=20.0)
64
+ ratio = torch.exp(negative_approx_kl).clamp(max=clip_coeff)
65
+ return per_token_loss * ratio
66
+
67
+
68
+ def compute_topk_self_distillation_loss(
69
+ student_logits: torch.Tensor,
70
+ teacher_logits: torch.Tensor,
71
+ *,
72
+ distillation_topk: int,
73
+ distillation_alpha: float,
74
+ distillation_add_tail: bool,
75
+ ) -> torch.Tensor:
76
+ """Compute distillation loss on the student's top-k token support.
77
+
78
+ The student's top-k logits define the support. The teacher distribution is projected onto the same token indices.
79
+ The selected support is then either renormalized or augmented with a tail bucket before the divergence is computed.
80
+ """
81
+ student_logsumexp = torch.logsumexp(student_logits, dim=-1, keepdim=True)
82
+ topk_student_logits, topk_indices = torch.topk(student_logits, k=distillation_topk, dim=-1)
83
+ topk_student_log_probs = topk_student_logits - student_logsumexp
84
+
85
+ teacher_logsumexp = torch.logsumexp(teacher_logits, dim=-1, keepdim=True)
86
+ topk_teacher_logits = torch.gather(teacher_logits, dim=-1, index=topk_indices)
87
+ topk_teacher_log_probs = topk_teacher_logits - teacher_logsumexp
88
+
89
+ # Top-k log-probs sum to the captured mass P_topk <= 1; the rest (1 - P_topk) is the "tail".
90
+ if distillation_add_tail:
91
+ # Lump the tail into one bucket so the divergence approximates the full-vocab divergence.
92
+ topk_student_log_probs = add_tail_bucket(topk_student_log_probs)
93
+ topk_teacher_log_probs = add_tail_bucket(topk_teacher_log_probs)
94
+ else:
95
+ # Drop the tail and renormalize the top-k to sum to 1: divergence over the top-k conditional only.
96
+ topk_student_log_probs = topk_student_log_probs - torch.logsumexp(topk_student_log_probs, dim=-1, keepdim=True)
97
+ topk_teacher_log_probs = topk_teacher_log_probs - torch.logsumexp(topk_teacher_log_probs, dim=-1, keepdim=True)
98
+
99
+ return compute_divergence(topk_student_log_probs, topk_teacher_log_probs, distillation_alpha)
100
+
101
+
102
+ def compute_full_logit_self_distillation_loss(
103
+ student_logits: torch.Tensor,
104
+ teacher_logits: torch.Tensor,
105
+ *,
106
+ distillation_alpha: float,
107
+ ) -> torch.Tensor:
108
+ """Compute full-vocabulary self-distillation loss between student and teacher logits."""
109
+ student_log_probs = torch.log_softmax(student_logits, dim=-1)
110
+ teacher_log_probs = torch.log_softmax(teacher_logits, dim=-1)
111
+ return compute_divergence(student_log_probs, teacher_log_probs, distillation_alpha)
112
+
113
+
114
+ def compute_sampled_token_self_distillation_loss(
115
+ student_logits: torch.Tensor,
116
+ teacher_logits: torch.Tensor,
117
+ completion_ids: torch.Tensor,
118
+ *,
119
+ distillation_alpha: float,
120
+ ) -> torch.Tensor:
121
+ """Compute token-level self-distillation loss only on the sampled completion tokens.
122
+
123
+ This path compares student and teacher log-probabilities on the realized completion tokens rather than over a
124
+ larger token support.
125
+ """
126
+ if distillation_alpha != 1.0:
127
+ raise ValueError(
128
+ "Only reverse KL (alpha=1.0) is supported for token-level distillation when "
129
+ f"`distillation_mode='sampled_token'`, got alpha={distillation_alpha}"
130
+ )
131
+
132
+ student_per_token_logps = selective_log_softmax(student_logits, completion_ids)
133
+ teacher_per_token_logps = selective_log_softmax(teacher_logits, completion_ids)
134
+ log_ratio = student_per_token_logps - teacher_per_token_logps
135
+ return log_ratio.detach() * student_per_token_logps
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdft/sdft_config.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+ from typing import Any, Literal
17
+
18
+ from transformers import TrainingArguments
19
+
20
+ from ...trainer.base_config import _BaseConfig
21
+
22
+
23
+ @dataclass
24
+ class SDFTConfig(_BaseConfig):
25
+ r"""
26
+ Configuration class for the [`SDFTTrainer`].
27
+
28
+ Parameters:
29
+ > Parameters that control the SDFT loss
30
+
31
+ distillation_alpha (`float`, *optional*, defaults to `0.5`):
32
+ Divergence interpolation coefficient for SDFT top-k logit distillation.
33
+ distillation_mode (`Literal["sampled_token", "full_logits", "topk_logits"]`, *optional*, defaults to `"topk_logits"`):
34
+ Distillation objective mode. SDFT defaults to top-k logit distillation.
35
+ distillation_topk (`int`, *optional*, defaults to `100`):
36
+ Number of top tokens used by the default SDFT top-k logit objective.
37
+ distillation_is_clip (`float`, *optional*, defaults to `2.0`):
38
+ Clipping coefficient for importance sampling in self-distillation. `None` disables clipping.
39
+ distillation_add_tail (`bool`, *optional*, defaults to `False`):
40
+ Whether to add a tail bucket for non-top-k probability mass.
41
+ num_loss_tokens_to_skip (`int`, *optional*, defaults to `0`):
42
+ Number of initial completion tokens to exclude from the distillation loss.
43
+
44
+ > Parameters that control the teacher
45
+
46
+ teacher_model_kind (`str`, *optional*, defaults to `"base"`):
47
+ Semantic teacher choice for SDFT. `base` uses the initial student, `live` uses the current student, and
48
+ `ema` uses an exponentially averaged teacher.
49
+ teacher_update_rate (`float`, *optional*, defaults to `0.05`):
50
+ EMA update rate used when `teacher_model_kind="ema"`. A value of `1.0` reduces the update to a hard
51
+ overwrite, periodically resyncing the teacher to the current student weights.
52
+ teacher_sync_steps (`int`, *optional*, defaults to `1`):
53
+ Number of optimizer steps between teacher updates.
54
+
55
+ > Parameters that control teacher-conditioned generation
56
+
57
+ generate_from_teacher (`bool`, *optional*, defaults to `False`):
58
+ Whether on-policy generation should use the teacher-conditioned prompt instead of the student prompt.
59
+ teacher_prompt_template (`str`, *optional*, defaults to `"{prompt}\n\n{privileged_context}"`):
60
+ Template used to combine the student prompt and privileged context into the teacher prompt.
61
+
62
+ > Parameters that control the model
63
+
64
+ model_init_kwargs (`dict[str, Any]`, *optional*):
65
+ Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument
66
+ of the `SDFTTrainer` is provided as a string.
67
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
68
+ Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to
69
+ [`~transformers.AutoModelForCausalLM.from_pretrained`] and [`~transformers.AutoProcessor.from_pretrained`],
70
+ for both the student and teacher.
71
+ disable_dropout (`bool`, *optional*, defaults to `True`):
72
+ Whether to disable dropout in the student and teacher models.
73
+
74
+ > Parameters that control data preprocessing
75
+
76
+ remove_unused_columns (`bool`, *optional*, defaults to `False`):
77
+ Whether to only keep the columns required by the trainer in the dataset. Keep this to `False` if you
78
+ provide extra columns (such as `privileged_context`) that the trainer needs.
79
+ max_prompt_length (`int`, *optional*, defaults to `512`):
80
+ Maximum prompt length. Longer prompts are truncated from the left.
81
+ shuffle_dataset (`bool`, *optional*, defaults to `True`):
82
+ Whether to shuffle the training dataset.
83
+
84
+ > Parameters that control generation
85
+
86
+ num_generations (`int`, *optional*, defaults to `8`):
87
+ Number of generations to sample. The effective batch size (num_processes * per_device_batch_size *
88
+ gradient_accumulation_steps) must be evenly divisible by this value.
89
+ num_generations_eval (`int`, *optional*):
90
+ Number of generations to sample during evaluation. This allows using fewer generations during evaluation to
91
+ save computation. If `None`, uses the value of `num_generations`.
92
+ max_completion_length (`int`, *optional*, defaults to `256`):
93
+ Maximum length of the generated completion.
94
+ temperature (`float`, *optional*, defaults to `1.0`):
95
+ Temperature for sampling. The higher the temperature, the more random the completions.
96
+ top_p (`float`, *optional*, defaults to `1.0`):
97
+ Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to 1.0
98
+ to consider all tokens.
99
+ top_k (`int`, *optional*, defaults to `0`):
100
+ Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is
101
+ disabled and all tokens are considered.
102
+ min_p (`float`, *optional*):
103
+ Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
104
+ value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range.
105
+ repetition_penalty (`float`, *optional*, defaults to `1.0`):
106
+ Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far.
107
+ Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model to repeat
108
+ tokens.
109
+ cache_implementation (`str`, *optional*):
110
+ Implementation of the cache method for faster generation when use_vllm is set to False.
111
+ generation_kwargs (`dict[str, Any]`, *optional*):
112
+ Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or `SamplingParams` (if
113
+ using vLLM) when sampling completions. This can be used to further customize the generation behavior, such
114
+ as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict with the other generation
115
+ parameters (like `min_p`, `top_p`, etc.), they will override them.
116
+ chat_template_kwargs (`dict[str, Any]`, *optional*):
117
+ Additional keyword arguments to pass to the `apply_chat_template` function when generating completions.
118
+ ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
119
+ This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
120
+ improving generation speed. However, disabling this option allows training models that exceed the VRAM
121
+ capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible
122
+ with vLLM generation.
123
+
124
+ > Parameters that control generation acceleration powered by vLLM
125
+
126
+ use_vllm (`bool`, *optional*, defaults to `False`):
127
+ Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation
128
+ instead of the default model.generate(). Requires `vllm` to be installed.
129
+ use_teacher_server (`bool`, *optional*, defaults to `False`):
130
+ Compute teacher logprobs from the running vLLM generation server instead of a local teacher forward. Only
131
+ supported for `teacher_model_kind='live'` with `use_vllm=True` and `vllm_mode='server'`, and
132
+ `distillation_mode` in {'sampled_token', 'topk_logits'} (the server returns the teacher's top-k logprobs,
133
+ not the full vocabulary; `topk_logits` distills over the teacher's own top-k support).
134
+ vllm_mode (`str`, *optional*, defaults to `"colocate"`):
135
+ Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or
136
+ `'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure a
137
+ TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same process
138
+ and share the training GPUs. This avoids the need for a separate server but may cause resource contention
139
+ with training.
140
+ vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
141
+ Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: Use the
142
+ `transformers` backend for model implementation. `vllm`: Use the `vllm` library for model implementation.
143
+ vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
144
+ Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but
145
+ waking the engine adds host–device transfer latency.
146
+ vllm_server_base_url (`str`, *optional*):
147
+ Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` and
148
+ `vllm_server_port` are ignored.
149
+ vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
150
+ Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided.
151
+ vllm_server_port (`int`, *optional*, defaults to `8000`):
152
+ Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided.
153
+ vllm_group_port (`int`, *optional*, defaults to `51216`):
154
+ Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port
155
+ is occupied, there is no need to change it.
156
+ vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
157
+ Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the
158
+ timeout, a `ConnectionError` is raised.
159
+ vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
160
+ Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to
161
+ `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when
162
+ launching the vLLM server via the `--vllm_tensor_parallel_size` flag.
163
+ vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`):
164
+ Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to
165
+ `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when
166
+ launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.
167
+ vllm_max_model_length (`int`, *optional*):
168
+ Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus
169
+ `max_completion_length`; if omitted, it is inferred from the model config.
170
+
171
+ > Parameters that control the training
172
+
173
+ num_iterations (`int`, *optional*, defaults to `1`):
174
+ Number of iterations per batch (denoted as μ in the algorithm).
175
+ generation_batch_size (`int`, *optional*):
176
+ Batch size to use for generation. If `None`, it defaults to the effective training batch size:
177
+ `per_device_train_batch_size * num_processes * steps_per_generation`.
178
+ steps_per_generation (`int`, *optional*):
179
+ Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`.
180
+ """
181
+
182
+ _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs"]
183
+
184
+ model_init_kwargs: dict[str, Any] | None = field(
185
+ default=None,
186
+ metadata={
187
+ "help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the `SDFTTrainer` is provided as a string."
188
+ },
189
+ )
190
+ trust_remote_code: bool = field(
191
+ default=False,
192
+ metadata={
193
+ "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
194
+ "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`, for both the "
195
+ "student and teacher."
196
+ },
197
+ )
198
+ disable_dropout: bool = field(
199
+ default=True,
200
+ metadata={"help": "Whether to disable dropout in the student and teacher models."},
201
+ )
202
+ remove_unused_columns: bool = field(
203
+ default=False,
204
+ metadata={
205
+ "help": "Whether to only keep the columns required by the trainer in the dataset. Keep this to `False` if you provide extra columns (such as `privileged_context`) that the trainer needs."
206
+ },
207
+ )
208
+ max_prompt_length: int | None = field(
209
+ default=512,
210
+ metadata={"help": "Maximum prompt length. Longer prompts are truncated from the left."},
211
+ )
212
+ num_generations: int = field(
213
+ default=8,
214
+ metadata={
215
+ "help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size * gradient_accumulation_steps) must be evenly divisible by this value."
216
+ },
217
+ )
218
+ num_generations_eval: int | None = field(
219
+ default=None,
220
+ metadata={
221
+ "help": "Number of generations to sample during evaluation. This allows using fewer generations during evaluation to save computation. If `None`, uses the value of `num_generations`."
222
+ },
223
+ )
224
+ max_completion_length: int | None = field(
225
+ default=256,
226
+ metadata={"help": "Maximum length of the generated completion."},
227
+ )
228
+ ds3_gather_for_generation: bool = field(
229
+ default=True,
230
+ metadata={
231
+ "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, improving generation speed. However, disabling this option allows training models that exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible with vLLM generation."
232
+ },
233
+ )
234
+ shuffle_dataset: bool = field(
235
+ default=True,
236
+ metadata={"help": "Whether to shuffle the training dataset."},
237
+ )
238
+ generation_batch_size: int | None = field(
239
+ default=None,
240
+ metadata={
241
+ "help": "Batch size to use for generation. If `None`, it defaults to the effective training batch size: `per_device_train_batch_size * num_processes * steps_per_generation`."
242
+ },
243
+ )
244
+ steps_per_generation: int | None = field(
245
+ default=None,
246
+ metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."},
247
+ )
248
+ temperature: float = field(
249
+ default=1.0,
250
+ metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."},
251
+ )
252
+ top_p: float = field(
253
+ default=1.0,
254
+ metadata={
255
+ "help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to 1.0 to consider all tokens."
256
+ },
257
+ )
258
+ top_k: int = field(
259
+ default=0,
260
+ metadata={
261
+ "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is disabled and all tokens are considered."
262
+ },
263
+ )
264
+ min_p: float | None = field(
265
+ default=None,
266
+ metadata={
267
+ "help": "Minimum token probability, which will be scaled by the probability of the most likely token. It must be a value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range."
268
+ },
269
+ )
270
+ generation_kwargs: dict[str, Any] | None = field(
271
+ default=None,
272
+ metadata={
273
+ "help": "Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or `SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them."
274
+ },
275
+ )
276
+ chat_template_kwargs: dict[str, Any] | None = field(
277
+ default=None,
278
+ metadata={
279
+ "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating completions."
280
+ },
281
+ )
282
+ repetition_penalty: float = field(
283
+ default=1.0,
284
+ metadata={
285
+ "help": "Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far. Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model to repeat tokens."
286
+ },
287
+ )
288
+ cache_implementation: str | None = field(
289
+ default=None,
290
+ metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."},
291
+ )
292
+ use_vllm: bool = field(
293
+ default=False,
294
+ metadata={
295
+ "help": "Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation instead of the default model.generate(). Requires `vllm` to be installed."
296
+ },
297
+ )
298
+ use_teacher_server: bool = field(
299
+ default=False,
300
+ metadata={
301
+ "help": "Compute teacher logprobs from the running vLLM generation server instead of a local teacher "
302
+ "forward. Only supported for `teacher_model_kind='live'` with `use_vllm=True` and `vllm_mode='server'`, "
303
+ "and `distillation_mode` in {'sampled_token', 'topk_logits'} (the server returns the teacher's top-k "
304
+ "logprobs, not the full vocabulary; `topk_logits` distills over the teacher's own top-k support)."
305
+ },
306
+ )
307
+ vllm_mode: str = field(
308
+ default="colocate",
309
+ metadata={
310
+ "help": "Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or `'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same process and share the training GPUs. This avoids the need for a separate server but may cause resource contention with training."
311
+ },
312
+ )
313
+ vllm_model_impl: str = field(
314
+ default="vllm",
315
+ metadata={
316
+ "help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for model implementation."
317
+ },
318
+ )
319
+ vllm_enable_sleep_mode: bool = field(
320
+ default=False,
321
+ metadata={
322
+ "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but waking the engine adds host–device transfer latency."
323
+ },
324
+ )
325
+ vllm_server_base_url: str | None = field(
326
+ default=None,
327
+ metadata={
328
+ "help": "Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` and `vllm_server_port` are ignored."
329
+ },
330
+ )
331
+ vllm_server_host: str = field(
332
+ default="0.0.0.0",
333
+ metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
334
+ )
335
+ vllm_server_port: int = field(
336
+ default=8000,
337
+ metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
338
+ )
339
+ vllm_group_port: int = field(
340
+ default=51216,
341
+ metadata={
342
+ "help": "Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port is occupied, there is no need to change it."
343
+ },
344
+ )
345
+ vllm_server_timeout: float = field(
346
+ default=240.0,
347
+ metadata={
348
+ "help": "Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the timeout, a `ConnectionError` is raised."
349
+ },
350
+ )
351
+ vllm_tensor_parallel_size: int = field(
352
+ default=1,
353
+ metadata={
354
+ "help": "Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when launching the vLLM server via the `--vllm_tensor_parallel_size` flag."
355
+ },
356
+ )
357
+ vllm_gpu_memory_utilization: float = field(
358
+ default=0.3,
359
+ metadata={
360
+ "help": "Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when launching the vLLM server via the `--vllm_gpu_memory_utilization` flag."
361
+ },
362
+ )
363
+ vllm_max_model_length: int | None = field(
364
+ default=None,
365
+ metadata={
366
+ "help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus `max_completion_length`; if omitted, it is inferred from the model config."
367
+ },
368
+ )
369
+ num_iterations: int = field(
370
+ default=1,
371
+ metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."},
372
+ )
373
+ teacher_model_kind: str = field(
374
+ default="base",
375
+ metadata={
376
+ "help": "Semantic teacher choice for SDFT. `base` uses the initial student, `live` uses the current "
377
+ "student, and `ema` uses an exponentially averaged teacher."
378
+ },
379
+ )
380
+ teacher_update_rate: float = field(
381
+ default=0.05,
382
+ metadata={
383
+ "help": 'EMA update rate used when `teacher_model_kind="ema"`. A value of `1.0` reduces the update '
384
+ "to a hard overwrite, periodically resyncing the teacher to the current student weights."
385
+ },
386
+ )
387
+ teacher_sync_steps: int = field(
388
+ default=1,
389
+ metadata={"help": "Number of optimizer steps between teacher updates."},
390
+ )
391
+ distillation_alpha: float = field(
392
+ default=0.5,
393
+ metadata={"help": "Divergence interpolation coefficient for SDFT top-k logit distillation."},
394
+ )
395
+ distillation_mode: Literal["sampled_token", "full_logits", "topk_logits"] = field(
396
+ default="topk_logits",
397
+ metadata={"help": "Distillation objective mode. SDFT defaults to top-k logit distillation."},
398
+ )
399
+ distillation_topk: int | None = field(
400
+ default=100,
401
+ metadata={"help": "Number of top tokens used by the default SDFT top-k logit objective."},
402
+ )
403
+ distillation_is_clip: float | None = field(
404
+ default=2.0,
405
+ metadata={
406
+ "help": "Clipping coefficient for importance sampling in self-distillation. `None` disables clipping."
407
+ },
408
+ )
409
+ distillation_add_tail: bool = field(
410
+ default=False,
411
+ metadata={"help": "Whether to add a tail bucket for non-top-k probability mass."},
412
+ )
413
+ generate_from_teacher: bool = field(
414
+ default=False,
415
+ metadata={
416
+ "help": "Whether on-policy generation should use the teacher-conditioned prompt instead of the student prompt."
417
+ },
418
+ )
419
+ teacher_prompt_template: str = field(
420
+ default="{prompt}\n\n{privileged_context}",
421
+ metadata={
422
+ "help": "Template used to combine the student prompt and privileged context into the teacher prompt."
423
+ },
424
+ )
425
+ num_loss_tokens_to_skip: int = field(
426
+ default=0,
427
+ metadata={"help": "Number of initial completion tokens to exclude from the distillation loss."},
428
+ )
429
+
430
+ def __post_init__(self):
431
+ super().__post_init__()
432
+ if self.distillation_mode == "sampled_token" and self.distillation_alpha != 1.0:
433
+ raise ValueError(
434
+ "`distillation_mode='sampled_token'` only supports reverse KL, so it requires "
435
+ f"`distillation_alpha=1.0`, got {self.distillation_alpha}."
436
+ )
437
+ num_processes = self.world_size
438
+ if self.generation_batch_size is None and self.steps_per_generation is None:
439
+ self.steps_per_generation = self.gradient_accumulation_steps
440
+ self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
441
+ elif self.generation_batch_size is not None and self.steps_per_generation is None:
442
+ global_batch_size = self.per_device_train_batch_size * num_processes
443
+ if self.generation_batch_size % global_batch_size != 0:
444
+ raise ValueError(
445
+ f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size ({global_batch_size})."
446
+ )
447
+ self.steps_per_generation = self.generation_batch_size // global_batch_size
448
+ elif self.generation_batch_size is None and self.steps_per_generation is not None:
449
+ self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
450
+ else:
451
+ raise ValueError("'generation_batch_size' and 'steps_per_generation' can not both be configured")
452
+
453
+ if self.generation_batch_size % self.num_generations != 0:
454
+ raise ValueError(
455
+ f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations ({self.num_generations})."
456
+ )
457
+
458
+ if self.do_eval and self.eval_strategy != "no":
459
+ num_generations_eval = self.num_generations_eval or self.num_generations
460
+ if (self.per_device_eval_batch_size * num_processes) % num_generations_eval != 0:
461
+ raise ValueError(
462
+ f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be "
463
+ f"divisible by the number of generations used for evaluation ({num_generations_eval})."
464
+ )
465
+
466
+ if (
467
+ "{prompt}" not in self.teacher_prompt_template
468
+ or "{privileged_context}" not in self.teacher_prompt_template
469
+ ):
470
+ raise ValueError(
471
+ "teacher_prompt_template must contain both `{prompt}` and `{privileged_context}` placeholders"
472
+ )
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdft/sdft_trainer.py ADDED
@@ -0,0 +1,1311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import textwrap
17
+ from collections import defaultdict
18
+ from contextlib import nullcontext
19
+ from dataclasses import dataclass
20
+ from functools import partial
21
+ from typing import Any
22
+
23
+ import datasets
24
+ import torch
25
+ from accelerate.logging import get_logger
26
+ from accelerate.utils import is_peft_model
27
+ from datasets import Dataset, IterableDataset
28
+ from torch import nn
29
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
30
+ from torch.utils.data import DataLoader, Sampler
31
+ from transformers import (
32
+ AutoProcessor,
33
+ GenerationConfig,
34
+ PreTrainedModel,
35
+ PreTrainedTokenizerBase,
36
+ ProcessorMixin,
37
+ TrainerCallback,
38
+ )
39
+ from transformers.trainer_utils import seed_worker
40
+ from transformers.utils import is_datasets_available, is_liger_kernel_available, is_peft_available
41
+
42
+ from ...data_utils import is_conversational
43
+ from ...models import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation
44
+ from ...models.utils import _ForwardRedirection
45
+ from ...trainer.base_trainer import _BaseTrainer
46
+ from ...trainer.utils import (
47
+ RepeatSampler,
48
+ create_model_from_path,
49
+ disable_dropout_in_model,
50
+ get_config_model_id,
51
+ identity,
52
+ pad,
53
+ selective_log_softmax,
54
+ split_tensor_dict,
55
+ use_adapter,
56
+ )
57
+ from ..utils import prepare_peft_model
58
+ from .loss_utils import (
59
+ add_tail_bucket,
60
+ apply_importance_sampling_clipping,
61
+ compute_divergence,
62
+ compute_full_logit_self_distillation_loss,
63
+ compute_sampled_token_self_distillation_loss,
64
+ compute_topk_self_distillation_loss,
65
+ )
66
+ from .sdft_config import SDFTConfig
67
+ from .teacher_sync import PEFTAdapterEMACallback, SyncTeacherModelCallback, is_pure_lora_training
68
+
69
+
70
+ if is_peft_available():
71
+ from peft import PeftConfig
72
+
73
+ if is_liger_kernel_available():
74
+ from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss
75
+
76
+
77
+ logger = get_logger(__name__)
78
+
79
+
80
+ TrainingBatch = dict[str, torch.Tensor | Any]
81
+
82
+
83
+ def build_teacher_request_inputs(
84
+ input_ids: torch.Tensor,
85
+ attention_mask: torch.Tensor,
86
+ prompt_attention_mask: torch.Tensor,
87
+ ) -> tuple[list[list[int]], list[int], list[int]]:
88
+ """Trim padded batch tensors into per-sample (prompt+completion) sequences for teacher-server requests."""
89
+ if input_ids.shape != attention_mask.shape:
90
+ raise ValueError(
91
+ f"input_ids and attention_mask must have the same shape, got {input_ids.shape} and {attention_mask.shape}."
92
+ )
93
+
94
+ input_ids_cpu = input_ids.detach().cpu()
95
+ attention_mask_cpu = attention_mask.detach().cpu().bool()
96
+ prompt_lengths = prompt_attention_mask.detach().cpu().sum(dim=1).to(torch.long)
97
+
98
+ trimmed_input_ids: list[list[int]] = []
99
+ prompt_lengths_list: list[int] = []
100
+ completion_lengths_list: list[int] = []
101
+ for row, mask, prompt_length in zip(input_ids_cpu, attention_mask_cpu, prompt_lengths, strict=True):
102
+ trimmed_row = row[mask]
103
+ prompt_len = int(prompt_length.item())
104
+ if prompt_len < 0 or prompt_len > trimmed_row.numel():
105
+ raise ValueError(
106
+ f"Invalid prompt length {prompt_len} for trimmed sequence of length {trimmed_row.numel()}."
107
+ )
108
+ trimmed_input_ids.append(trimmed_row.tolist())
109
+ prompt_lengths_list.append(prompt_len)
110
+ completion_lengths_list.append(int(trimmed_row.numel()) - prompt_len)
111
+ return trimmed_input_ids, prompt_lengths_list, completion_lengths_list
112
+
113
+
114
+ @dataclass
115
+ class DistillationLogits:
116
+ """Aligned logits and masks used to compute a self-distillation objective."""
117
+
118
+ completion_ids: torch.Tensor
119
+ loss_mask: torch.Tensor
120
+ student_logits: torch.Tensor
121
+ teacher_logits: torch.Tensor
122
+
123
+
124
+ def _extract_last_user_text(messages: list[dict[str, Any]]) -> str:
125
+ """Extract the text content from the last user message in a conversational prompt."""
126
+ last_message = messages[-1]
127
+ if last_message.get("role") != "user":
128
+ raise ValueError(
129
+ f"Self-distillation teacher prompt construction expects the conversation to end with a user turn, "
130
+ f"but the last message has role '{last_message.get('role')}'. "
131
+ f"Prompts ending with assistant prefills or tool turns are not supported."
132
+ )
133
+ content = last_message.get("content", "")
134
+ if isinstance(content, list):
135
+ return " ".join(part.get("text", "") for part in content if part.get("type") == "text")
136
+ return content
137
+
138
+
139
+ class DemonstrationTeacherContextBuilder:
140
+ """Builds student and teacher contexts from prompts plus privileged context"""
141
+
142
+ def __init__(self, trainer):
143
+ self.trainer = trainer
144
+
145
+ def _stringify_privileged_context(self, privileged_context: Any) -> str:
146
+ if privileged_context is None:
147
+ raise ValueError(
148
+ "`privileged_context` must not be None for self-distillation teacher prompt construction."
149
+ )
150
+ if isinstance(privileged_context, str):
151
+ return privileged_context
152
+ if isinstance(privileged_context, list) and privileged_context and isinstance(privileged_context[0], dict):
153
+ chunks = []
154
+ for message in privileged_context:
155
+ content = message.get("content", "")
156
+ if isinstance(content, list):
157
+ text = " ".join(part.get("text", "") for part in content if part.get("type") == "text")
158
+ else:
159
+ text = str(content)
160
+ if text:
161
+ chunks.append(text)
162
+ return "\n".join(chunks)
163
+ return str(privileged_context)
164
+
165
+ def _compose_teacher_prompt(self, prompt: Any, privileged_context: Any) -> Any:
166
+ privileged_text = self._stringify_privileged_context(privileged_context)
167
+ if isinstance(prompt, list):
168
+ system_messages = prompt[:-1]
169
+ prompt_text = _extract_last_user_text(prompt)
170
+ teacher_text = self.trainer.args.teacher_prompt_template.format(
171
+ prompt=prompt_text,
172
+ privileged_context=privileged_text,
173
+ )
174
+ return system_messages + [{"role": "user", "content": teacher_text}]
175
+ return self.trainer.args.teacher_prompt_template.format(prompt=prompt, privileged_context=privileged_text)
176
+
177
+ def select_generation_prompts(self, prompts: list[Any], privileged_contexts: list[Any]) -> list[Any]:
178
+ return [
179
+ self._compose_teacher_prompt(prompt, privileged_context)
180
+ for prompt, privileged_context in zip(prompts, privileged_contexts, strict=True)
181
+ ]
182
+
183
+ def build(
184
+ self,
185
+ prompts: list[Any],
186
+ privileged_contexts: list[Any],
187
+ completion_ids: torch.Tensor,
188
+ completion_mask: torch.Tensor,
189
+ ) -> dict[str, torch.Tensor]:
190
+ teacher_prompts = [
191
+ self._compose_teacher_prompt(prompt, privileged_context)
192
+ for prompt, privileged_context in zip(prompts, privileged_contexts, strict=True)
193
+ ]
194
+ teacher_prompt_ids_list = self.trainer._tokenize_prompts(teacher_prompts)
195
+ device = completion_ids.device
196
+ teacher_prompt_ids = [torch.tensor(ids) for ids in teacher_prompt_ids_list]
197
+ teacher_prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in teacher_prompt_ids]
198
+ teacher_prompt_ids = pad(
199
+ teacher_prompt_ids, padding_value=self.trainer._tokenizer.pad_token_id, padding_side="left"
200
+ ).to(device=device)
201
+ teacher_prompt_mask = pad(teacher_prompt_mask, padding_value=0, padding_side="left").to(device=device)
202
+ teacher_input_ids = torch.cat([teacher_prompt_ids, completion_ids], dim=1)
203
+ teacher_attention_mask = torch.cat([teacher_prompt_mask, completion_mask], dim=1)
204
+ return {
205
+ "teacher_input_ids": teacher_input_ids,
206
+ "teacher_attention_mask": teacher_attention_mask,
207
+ }
208
+
209
+
210
+ class SDFTTrainer(_BaseTrainer):
211
+ """Trainer for SDFT-style on-policy self-distillation with explicit teacher prompts."""
212
+
213
+ _tag_names = ["trl", "sdft"]
214
+ _name = "SDFT"
215
+ config_cls = SDFTConfig
216
+ # docstyle-ignore
217
+ _paper = {
218
+ "title": "Self-Distillation Enables Continual Learning",
219
+ "id": "2601.19897",
220
+ "citation": textwrap.dedent("""\
221
+ @article{shenfeld2026selfdistillation,
222
+ title = {{Self-Distillation Enables Continual Learning}},
223
+ author = {Idan Shenfeld and Mehul Damani and Jonas H\\"ubotter and Pulkit Agrawal},
224
+ year = 2026,
225
+ eprint = {arXiv:2601.19897}
226
+ }"""),
227
+ }
228
+
229
+ def __init__(
230
+ self,
231
+ model: str | PreTrainedModel | nn.Module,
232
+ args: SDFTConfig | None = None,
233
+ train_dataset: Dataset | IterableDataset | None = None,
234
+ eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
235
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
236
+ callbacks: list[TrainerCallback] | None = None,
237
+ optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
238
+ peft_config: PeftConfig | None = None,
239
+ ):
240
+ if isinstance(train_dataset, IterableDataset):
241
+ raise NotImplementedError("Iterable datasets are not yet supported in SDFTTrainer.")
242
+ if isinstance(eval_dataset, IterableDataset) or (
243
+ isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values())
244
+ ):
245
+ raise NotImplementedError("Iterable eval datasets are not yet supported in SDFTTrainer.")
246
+
247
+ self.num_loss_tokens_to_skip = args.num_loss_tokens_to_skip
248
+ self.teacher_context_builder = DemonstrationTeacherContextBuilder(self)
249
+
250
+ if train_dataset is None:
251
+ raise ValueError("`train_dataset` is required")
252
+
253
+ if isinstance(model, str):
254
+ model_init_kwargs = args.model_init_kwargs or {}
255
+ if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
256
+ model_init_kwargs["device_map"] = None
257
+ model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
258
+ model = create_model_from_path(model, **model_init_kwargs)
259
+ elif args.model_init_kwargs is not None:
260
+ logger.warning(
261
+ "You passed `model_init_kwargs` to the self-distillation config, but `model` is already "
262
+ "instantiated. The `model_init_kwargs` will be ignored."
263
+ )
264
+
265
+ self.model_kwarg_keys = (
266
+ inspect.signature(model.forward).parameters.keys()
267
+ if not hasattr(model, "get_base_model")
268
+ else inspect.signature(model.get_base_model().forward).parameters.keys()
269
+ )
270
+
271
+ if peft_config is None and getattr(model, "peft_config", None) is not None:
272
+ logger.warning(
273
+ "The provided self-distillation student model already contains a PEFT adapter. "
274
+ "This setup is accepted but not directly supported. In particular, `teacher_model_kind='base'` "
275
+ "may refer to the underlying base weights rather than the exact initially loaded student state "
276
+ "including its adapter. For unambiguous teacher behavior, start from a merged/non-adapter model "
277
+ "or manage separate adapters explicitly."
278
+ )
279
+ if peft_config is not None:
280
+ if not is_peft_available():
281
+ raise ImportError(
282
+ "You passed `peft_config` but the `peft` library is not installed. "
283
+ "Install it with `pip install trl[peft]`."
284
+ )
285
+ if not isinstance(peft_config, PeftConfig):
286
+ raise TypeError(
287
+ f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
288
+ f"got {type(peft_config).__name__}."
289
+ )
290
+ if is_peft_model(model):
291
+ raise ValueError(
292
+ "You passed a `PeftModel` instance together with a `peft_config`. Pass either a base "
293
+ "model with `peft_config`, or a pre-wrapped PEFT model."
294
+ )
295
+ if peft_config is not None or (is_peft_available() and getattr(model, "peft_config", None) is not None):
296
+ model = prepare_peft_model(model, peft_config, args)
297
+
298
+ if processing_class is None:
299
+ processing_class = AutoProcessor.from_pretrained(
300
+ get_config_model_id(model.config),
301
+ truncation_side="left",
302
+ padding_side="left",
303
+ trust_remote_code=args.trust_remote_code,
304
+ )
305
+
306
+ if isinstance(processing_class, ProcessorMixin):
307
+ self._tokenizer = processing_class.tokenizer
308
+ elif isinstance(processing_class, PreTrainedTokenizerBase):
309
+ self._tokenizer = processing_class
310
+ else:
311
+ raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
312
+
313
+ if self._tokenizer.pad_token is None:
314
+ self._tokenizer.pad_token = self._tokenizer.eos_token
315
+
316
+ self.max_prompt_length = args.max_prompt_length
317
+ self.max_completion_length = args.max_completion_length
318
+ self.num_generations = args.num_generations
319
+ self.num_generations_eval = args.num_generations_eval or args.num_generations
320
+ self.num_iterations = args.num_iterations
321
+ self.shuffle_dataset = args.shuffle_dataset
322
+ self.temperature = args.temperature
323
+ self.generate_from_teacher = args.generate_from_teacher
324
+ self.use_vllm = args.use_vllm
325
+ self.chat_template_kwargs = args.chat_template_kwargs or {}
326
+ self._step = 0
327
+ self._buffered_inputs = None
328
+ self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
329
+
330
+ self.generation_kwargs = {
331
+ "max_new_tokens": self.max_completion_length,
332
+ "do_sample": True,
333
+ "pad_token_id": self._tokenizer.pad_token_id,
334
+ "bos_token_id": self._tokenizer.bos_token_id,
335
+ "eos_token_id": self._tokenizer.eos_token_id,
336
+ "temperature": args.temperature,
337
+ "top_p": args.top_p,
338
+ "top_k": args.top_k,
339
+ "min_p": args.min_p,
340
+ "repetition_penalty": args.repetition_penalty,
341
+ "cache_implementation": args.cache_implementation,
342
+ }
343
+ if args.generation_kwargs is not None:
344
+ self.generation_kwargs.update(args.generation_kwargs)
345
+ self.generation_config = GenerationConfig(**self.generation_kwargs, disable_compile=True)
346
+
347
+ if hasattr(model, "warnings_issued"):
348
+ model.warnings_issued["estimate_tokens"] = True
349
+
350
+ # Teacher logprobs from the running vLLM generation server (reuses the synced student weights) instead of a
351
+ # local teacher forward. MVP: `live` teacher only — the generation server holds the current student weights.
352
+ self.use_teacher_server = args.use_teacher_server
353
+ if self.use_teacher_server:
354
+ if not (args.use_vllm and args.vllm_mode == "server"):
355
+ raise ValueError(
356
+ "`use_teacher_server=True` requires `use_vllm=True` and `vllm_mode='server'`: teacher logprobs are "
357
+ "served by the same vLLM server used for generation."
358
+ )
359
+ if args.teacher_model_kind != "live":
360
+ raise ValueError(
361
+ "`use_teacher_server=True` only supports `teacher_model_kind='live'` (the generation server holds "
362
+ f"the current student weights), got {args.teacher_model_kind!r}."
363
+ )
364
+ if args.distillation_mode not in ("sampled_token", "topk_logits"):
365
+ raise ValueError(
366
+ "`use_teacher_server=True` only supports `distillation_mode` in {'sampled_token', 'topk_logits'}, "
367
+ f"got {args.distillation_mode!r}. The server returns the teacher's top-k logprobs, not the full "
368
+ "vocabulary, so `full_logits` is unavailable. Note `topk_logits` distills over the teacher's own "
369
+ "top-k support (the server cannot score the student's top-k indices)."
370
+ )
371
+ if args.use_liger_kernel:
372
+ raise ValueError(
373
+ "`use_teacher_server=True` is incompatible with `use_liger_kernel`: the server returns top-k "
374
+ "logprobs while the Liger fused loss needs full-vocabulary hidden states."
375
+ )
376
+ # Liger fused JSD loss for `full_logits`: same generalized JSD as `compute_divergence`, so alpha maps to beta.
377
+ self.use_liger_loss = False
378
+ if args.use_liger_kernel:
379
+ if not is_liger_kernel_available():
380
+ raise ImportError(
381
+ "Liger is required to use `use_liger_kernel` as the self-distillation loss. Run "
382
+ "`pip install liger-kernel`."
383
+ )
384
+ if args.distillation_mode != "full_logits":
385
+ raise ValueError(
386
+ "`use_liger_kernel` only supports `distillation_mode='full_logits'`, got "
387
+ f"{args.distillation_mode!r}. The fused JSD kernel operates on the full vocabulary and cannot "
388
+ "express the top-k support or sampled-token objectives."
389
+ )
390
+ if args.distillation_is_clip is not None:
391
+ raise ValueError(
392
+ "`use_liger_kernel` is incompatible with `distillation_is_clip`: the fused kernel does not expose "
393
+ "per-token losses for importance-sampling clipping."
394
+ )
395
+ self.liger_jsd_loss = LigerFusedLinearJSDLoss(
396
+ beta=args.distillation_alpha,
397
+ ignore_index=-100,
398
+ temperature=args.temperature,
399
+ compiled=False,
400
+ weight_hard_loss=0.0,
401
+ weight_soft_loss=1.0,
402
+ )
403
+ self._forward_redirection = _ForwardRedirection()
404
+ self.use_liger_loss = True
405
+
406
+ super().__init__(
407
+ model=model,
408
+ args=args,
409
+ data_collator=identity,
410
+ train_dataset=train_dataset,
411
+ eval_dataset=eval_dataset,
412
+ processing_class=processing_class,
413
+ callbacks=callbacks,
414
+ optimizers=optimizers,
415
+ compute_loss_func="non-None value to disable scaling",
416
+ )
417
+
418
+ self._last_loaded_step = -1 if self.use_vllm else 0
419
+ if self.use_vllm:
420
+ from ...generation.vllm_generation import VLLMGeneration
421
+
422
+ self.vllm_generation = VLLMGeneration(
423
+ model=self.model,
424
+ accelerator=self.accelerator,
425
+ processing_class=self.processing_class,
426
+ mode=args.vllm_mode,
427
+ server_base_url=args.vllm_server_base_url,
428
+ server_host=args.vllm_server_host,
429
+ server_port=args.vllm_server_port,
430
+ group_port=args.vllm_group_port,
431
+ server_timeout=args.vllm_server_timeout,
432
+ tensor_parallel_size=args.vllm_tensor_parallel_size,
433
+ gpu_memory_utilization=args.vllm_gpu_memory_utilization,
434
+ max_model_length=args.vllm_max_model_length,
435
+ max_num_seqs=args.per_device_train_batch_size
436
+ * args.vllm_tensor_parallel_size
437
+ * args.steps_per_generation,
438
+ enable_sleep_mode=args.vllm_enable_sleep_mode,
439
+ model_impl=args.vllm_model_impl,
440
+ repetition_penalty=args.repetition_penalty,
441
+ temperature=self.temperature,
442
+ top_p=args.top_p,
443
+ top_k=args.top_k,
444
+ min_p=args.min_p,
445
+ max_completion_length=self.max_completion_length,
446
+ logprobs=None,
447
+ generation_kwargs=args.generation_kwargs,
448
+ )
449
+
450
+ # Per-rank read-only client to the same generation server for teacher scoring (weights are synced there by
451
+ # `VLLMGeneration`; scoring needs no weight-update communicator). Mirrors the distillation trainer's
452
+ # `teacher_client`.
453
+ self.teacher_client = None
454
+ if self.use_teacher_server:
455
+ from ...generation.vllm_client import VLLMClient
456
+
457
+ base_url = args.vllm_server_base_url or f"http://{args.vllm_server_host}:{args.vllm_server_port}"
458
+ self.teacher_client = VLLMClient(base_url=base_url, connection_timeout=args.vllm_server_timeout)
459
+
460
+ if args.disable_dropout:
461
+ disable_dropout_in_model(self.model)
462
+
463
+ if hasattr(self.model, "add_model_tags"):
464
+ self.model.add_model_tags(self._tag_names)
465
+
466
+ self._setup_teacher_model()
467
+ self.model_accepts_loss_kwargs = False
468
+
469
+ def _set_signature_columns_if_needed(self):
470
+ if self._signature_columns is None:
471
+ self._signature_columns = ["prompt", "privileged_context"]
472
+
473
+ def _dispatch_self_distillation_callback(self, event_name: str, **payload) -> None:
474
+ for callback in self.callback_handler.callbacks:
475
+ callback_fn = getattr(callback, event_name, None)
476
+ if callback_fn is not None:
477
+ callback_fn(
478
+ args=self.args,
479
+ state=self.state,
480
+ control=self.control,
481
+ model=self.model,
482
+ processing_class=self.processing_class,
483
+ **payload,
484
+ )
485
+
486
+ def _setup_teacher_model(self) -> None:
487
+ """Prepare teacher state according to the semantic teacher choice.
488
+
489
+ Resolve `teacher_model_kind` × PEFT state into the effective teacher:
490
+
491
+ - `"live"` (any model):
492
+ Teacher is the student. No divergence, no callback.
493
+ - `"base"` + PEFT model:
494
+ Teacher reuses `self.model`; the base weights are recovered downstream by disabling the adapter via
495
+ `use_adapter` during teacher forward.
496
+ - `"base"` + non-PEFT model:
497
+ Teacher is a frozen deepcopy of the initial student (falls through to the copy branch below).
498
+ - `"ema"` + pure-LoRA training:
499
+ Teacher reuses `self.model`; a dedicated `"teacher"` LoRA adapter is attached and updated by
500
+ `PEFTAdapterEMACallback`. Teacher forward switches to that adapter downstream.
501
+ - `"ema"` (otherwise):
502
+ Teacher is a frozen deepcopy synchronized each step by `SyncTeacherModelCallback`.
503
+
504
+ Must be called after `super().__init__` so that `self.callback_handler` is available.
505
+ """
506
+
507
+ teacher_model_kind = self.args.teacher_model_kind
508
+
509
+ if teacher_model_kind == "live":
510
+ self.teacher_model = self.model
511
+ return
512
+
513
+ if teacher_model_kind == "base" and is_peft_model(self.model):
514
+ self.teacher_model = self.model
515
+ return
516
+
517
+ if self._use_peft_ema_teacher_adapter():
518
+ # Must run after super().__init__ so self.callback_handler exists.
519
+ self.add_callback(
520
+ PEFTAdapterEMACallback(
521
+ model=self.model,
522
+ teacher_adapter_name="teacher",
523
+ update_rate=self.args.teacher_update_rate,
524
+ sync_steps=self.args.teacher_sync_steps,
525
+ accelerator=self.accelerator,
526
+ )
527
+ )
528
+ self.teacher_model = self.model
529
+ return
530
+
531
+ if is_peft_model(self.model):
532
+ raise ValueError(
533
+ "`teacher_model_kind='ema'` with a non-pure-LoRA PEFT model is not supported: the separate EMA "
534
+ "teacher cannot be parameter-matched to the PEFT student. Use pure-LoRA training, a non-PEFT model, "
535
+ "or `teacher_model_kind` in {'live', 'base'}."
536
+ )
537
+
538
+ # Build the teacher from the model path (like the GRPO/DPO reference model) rather than deep-copying the
539
+ # student: under ZeRO-3 the student params are already sharded, so a deep copy would clone empty shards.
540
+ model_init_kwargs = self.args.model_init_kwargs or {}
541
+ if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
542
+ model_init_kwargs["device_map"] = None
543
+ model_init_kwargs.setdefault("trust_remote_code", self.args.trust_remote_code)
544
+ self.teacher_model = create_model_from_path(get_config_model_id(self.model.config), **model_init_kwargs)
545
+ self.teacher_model.requires_grad_(False)
546
+ self.teacher_model.eval()
547
+ if self.is_deepspeed_enabled:
548
+ self.teacher_model = prepare_deepspeed(self.teacher_model, self.accelerator)
549
+ elif self.is_fsdp_enabled:
550
+ self.teacher_model = prepare_fsdp(self.teacher_model, self.accelerator)
551
+ else:
552
+ self.teacher_model = self.accelerator.prepare_model(self.teacher_model, evaluation_mode=True)
553
+
554
+ if teacher_model_kind == "ema":
555
+ self.add_callback(SyncTeacherModelCallback(teacher_model=self.teacher_model, accelerator=self.accelerator))
556
+
557
+ def _use_peft_ema_teacher_adapter(self) -> bool:
558
+ return self.args.teacher_model_kind == "ema" and is_pure_lora_training(self.model, self.accelerator)
559
+
560
+ def get_train_dataloader(self):
561
+ if self.train_dataset is None:
562
+ raise ValueError("Trainer: training requires a train_dataset.")
563
+
564
+ train_dataset = self.train_dataset
565
+ data_collator = self.data_collator
566
+ if is_datasets_available() and isinstance(train_dataset, datasets.Dataset):
567
+ train_dataset = self._remove_unused_columns(train_dataset, description="training")
568
+ else:
569
+ data_collator = self._get_collator_with_removed_columns(data_collator, description="training")
570
+
571
+ dataloader_params = {
572
+ "batch_size": self._train_batch_size * self.args.steps_per_generation,
573
+ "collate_fn": data_collator,
574
+ "num_workers": self.args.dataloader_num_workers,
575
+ "pin_memory": self.args.dataloader_pin_memory,
576
+ "persistent_workers": self.args.dataloader_persistent_workers,
577
+ }
578
+ if not isinstance(train_dataset, torch.utils.data.IterableDataset):
579
+ dataloader_params["sampler"] = self._get_train_sampler()
580
+ dataloader_params["drop_last"] = self.args.dataloader_drop_last
581
+ dataloader_params["worker_init_fn"] = partial(
582
+ seed_worker, num_workers=self.args.dataloader_num_workers, rank=self.args.process_index
583
+ )
584
+ dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor
585
+ return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params))
586
+
587
+ def _get_train_sampler(self, dataset=None) -> Sampler:
588
+ if dataset is None:
589
+ dataset = self.train_dataset
590
+ return RepeatSampler(
591
+ data_source=dataset,
592
+ mini_repeat_count=self.num_generations,
593
+ batch_size=self.args.generation_batch_size // self.num_generations,
594
+ repeat_count=self.num_iterations * self.args.steps_per_generation,
595
+ shuffle=self.shuffle_dataset,
596
+ seed=self.args.seed,
597
+ )
598
+
599
+ def _get_eval_sampler(self, eval_dataset) -> Sampler:
600
+ return RepeatSampler(
601
+ data_source=eval_dataset,
602
+ mini_repeat_count=self.num_generations_eval,
603
+ seed=self.args.seed,
604
+ )
605
+
606
+ def training_step(self, model, inputs, num_items_in_batch):
607
+ # Gather spans forward+backward: the fused JSD computes the lm_head grad in backward.
608
+ with self._get_liger_zero3_lm_head_gather_ctx(model):
609
+ output = super().training_step(model, inputs, num_items_in_batch)
610
+ self._step += 1
611
+ return output
612
+
613
+ def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None):
614
+ if not isinstance(inputs, dict):
615
+ inputs = self._prepare_inputs(inputs)
616
+ with torch.no_grad():
617
+ with self.compute_loss_context_manager():
618
+ loss = self.compute_loss(model, inputs)
619
+ return loss.detach(), None, None
620
+
621
+ def _prepare_inputs(self, generation_batch):
622
+ """Return the per-step training batch, regenerating rollouts and buffering them for reuse in train mode.
623
+
624
+ In train mode, rollouts are generated once every `steps_per_generation * num_iterations` steps and split into
625
+ per-step slices reused until the next regeneration. In eval mode, every batch is freshly prepared.
626
+ """
627
+ mode = "train" if self.model.training else "eval"
628
+ if mode == "train":
629
+ generate_every = self.args.steps_per_generation * self.num_iterations
630
+ if self._step % generate_every == 0 or self._buffered_inputs is None:
631
+ buffered_batch = self._prepare_training_batch(generation_batch)
632
+ self._buffered_inputs = split_tensor_dict(buffered_batch, self.args.steps_per_generation)
633
+ self._dispatch_self_distillation_callback(
634
+ "on_generation_batch_built",
635
+ generate_every=generate_every,
636
+ steps_per_generation=self.args.steps_per_generation,
637
+ )
638
+ return self._buffered_inputs[self._step % self.args.steps_per_generation]
639
+ return self._prepare_training_batch(generation_batch)
640
+
641
+ def _prepare_training_batch(self, inputs: list[dict[str, Any]]) -> TrainingBatch:
642
+ """Sample student rollouts and construct teacher prompts"""
643
+ batch = self.sample_rollouts(inputs)
644
+ mode = "train" if self.model.training else "eval"
645
+ self._record_completion_metrics(mode, batch)
646
+ prompts = [example["prompt"] for example in inputs]
647
+ privileged_contexts = [example.get("privileged_context") for example in inputs]
648
+ teacher_batch = self.teacher_context_builder.build(
649
+ prompts,
650
+ privileged_contexts,
651
+ batch["completion_ids"],
652
+ batch["completion_mask"],
653
+ )
654
+ batch.update(
655
+ {
656
+ "teacher_input_ids": teacher_batch["teacher_input_ids"],
657
+ "teacher_attention_mask": teacher_batch["teacher_attention_mask"],
658
+ }
659
+ )
660
+
661
+ self._dispatch_self_distillation_callback(
662
+ "on_self_distillation_batch_prepared",
663
+ old_per_token_logps=batch.get("old_per_token_logps"),
664
+ prompt_ids=batch["prompt_ids"],
665
+ completion_ids=batch["completion_ids"],
666
+ teacher_input_ids=batch["teacher_input_ids"],
667
+ teacher_attention_mask=batch["teacher_attention_mask"],
668
+ )
669
+ return batch
670
+
671
+ def sample_rollouts(self, inputs: list[dict[str, Any]]) -> TrainingBatch:
672
+ """Generate completions for a batch of prompts and assemble the training batch."""
673
+ prompts = [example["prompt"] for example in inputs]
674
+ privileged_contexts = [example.get("privileged_context") for example in inputs]
675
+
676
+ student_prompt_ids_list = self._tokenize_prompts(prompts)
677
+ if self.generate_from_teacher:
678
+ generation_prompts = self.teacher_context_builder.select_generation_prompts(prompts, privileged_contexts)
679
+ generation_prompt_ids_list = self._tokenize_prompts(generation_prompts)
680
+ else:
681
+ generation_prompts = prompts
682
+ generation_prompt_ids_list = student_prompt_ids_list
683
+
684
+ self._dispatch_self_distillation_callback(
685
+ "on_generation_prompts_selected",
686
+ generation_prompts=generation_prompts,
687
+ generation_prompt_text=None,
688
+ )
689
+
690
+ _, completion_ids_list = self._generate(generation_prompt_ids_list)
691
+ device = self.accelerator.device
692
+ prompt_ids = [torch.tensor(ids) for ids in student_prompt_ids_list]
693
+ prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids]
694
+ prompt_ids = pad(prompt_ids, padding_value=self._tokenizer.pad_token_id, padding_side="left").to(device=device)
695
+ prompt_mask = pad(prompt_mask, padding_value=0, padding_side="left").to(device=device)
696
+
697
+ completion_ids = [torch.tensor(ids) for ids in completion_ids_list]
698
+ completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids]
699
+ completion_ids = pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right").to(
700
+ device=device
701
+ )
702
+ completion_mask = pad(completion_mask, padding_value=0, padding_side="right").to(device=device)
703
+
704
+ old_per_token_logps = None
705
+ if not self.generate_from_teacher:
706
+ old_per_token_logps = self._compute_rollout_logps(
707
+ prompt_ids=prompt_ids,
708
+ prompt_mask=prompt_mask,
709
+ completion_ids=completion_ids,
710
+ completion_mask=completion_mask,
711
+ )
712
+ batch: TrainingBatch = {
713
+ "prompt_ids": prompt_ids,
714
+ "prompt_mask": prompt_mask,
715
+ "completion_ids": completion_ids,
716
+ "completion_mask": completion_mask,
717
+ "raw_completion_lengths": torch.tensor(
718
+ [len(ids) for ids in completion_ids_list], device=device, dtype=torch.long
719
+ ),
720
+ }
721
+ if old_per_token_logps is not None:
722
+ batch["old_per_token_logps"] = old_per_token_logps
723
+ return batch
724
+
725
+ def _get_completion_ids_list(self, batch: TrainingBatch) -> list[list[int]]:
726
+ raw_completion_lengths = batch["raw_completion_lengths"].detach().cpu().tolist()
727
+ return [
728
+ ids[:length].tolist()
729
+ for ids, length in zip(batch["completion_ids"].detach().cpu(), raw_completion_lengths, strict=True)
730
+ ]
731
+
732
+ def _tokenize_prompts(self, prompts: list[Any]) -> list[list[int]]:
733
+ if is_conversational({"prompt": prompts[0]}):
734
+ tokenized = self.processing_class.apply_chat_template(
735
+ conversation=prompts,
736
+ add_generation_prompt=True,
737
+ tokenize=True,
738
+ return_dict=True,
739
+ **self.chat_template_kwargs,
740
+ )
741
+ prompt_ids = tokenized["input_ids"]
742
+ else:
743
+ prompt_ids = self.processing_class(text=prompts)["input_ids"]
744
+ if self.max_prompt_length is not None:
745
+ prompt_ids = [ids[-self.max_prompt_length :] for ids in prompt_ids]
746
+ return prompt_ids
747
+
748
+ def _generate(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]:
749
+ if self.use_vllm:
750
+ return self._generate_vllm(prompt_ids)
751
+ return self._generate_transformers(prompt_ids)
752
+
753
+ def _generate_vllm(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]:
754
+ if self.state.global_step != self._last_loaded_step:
755
+ self.vllm_generation.sync_weights()
756
+ self._last_loaded_step = self.state.global_step
757
+
758
+ mode = "train" if self.model.training else "eval"
759
+ num_generations = self.num_generations if mode == "train" else self.num_generations_eval
760
+ prompt_ids_out, completion_ids_list, _, _ = self.vllm_generation.generate(
761
+ prompts=prompt_ids,
762
+ images=None,
763
+ num_generations=num_generations,
764
+ )
765
+ return prompt_ids_out, completion_ids_list
766
+
767
+ def _generate_transformers(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]:
768
+ device = self.accelerator.device
769
+ prompt_tensors = [torch.tensor(ids) for ids in prompt_ids]
770
+ padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left").to(
771
+ device=device
772
+ )
773
+ attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left").to(
774
+ device=device
775
+ )
776
+ generate_inputs: dict[str, torch.Tensor | Any] = {"input_ids": padded_ids, "attention_mask": attention_mask}
777
+
778
+ with (
779
+ unwrap_model_for_generation(
780
+ self.model_wrapped,
781
+ self.accelerator,
782
+ gather_deepspeed3_params=self.args.ds3_gather_for_generation,
783
+ generation_kwargs=self.generation_kwargs,
784
+ ) as unwrapped_model,
785
+ torch.no_grad(),
786
+ FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(),
787
+ ):
788
+ prompt_completion_ids = unwrapped_model.generate(
789
+ **generate_inputs, generation_config=self.generation_config
790
+ )
791
+
792
+ prompt_length = generate_inputs["input_ids"].size(1)
793
+ completion_ids = prompt_completion_ids[:, prompt_length:]
794
+ is_eos = completion_ids == self._tokenizer.eos_token_id
795
+ eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device)
796
+ eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)]
797
+ seq_idx = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1)
798
+ completion_mask = (seq_idx <= eos_idx.unsqueeze(1)).int()
799
+ completion_ids_list = [
800
+ c[m].tolist() for c, m in zip(completion_ids.cpu(), completion_mask.bool().cpu(), strict=True)
801
+ ]
802
+ return prompt_ids, completion_ids_list
803
+
804
+ def _compute_rollout_logps(
805
+ self,
806
+ prompt_ids: torch.Tensor,
807
+ prompt_mask: torch.Tensor,
808
+ completion_ids: torch.Tensor,
809
+ completion_mask: torch.Tensor,
810
+ ) -> torch.Tensor | None:
811
+ generate_every = self.args.steps_per_generation * self.num_iterations
812
+ old_per_token_logps = None
813
+
814
+ if self.args.gradient_accumulation_steps % generate_every != 0:
815
+ prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1)
816
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
817
+ logits_to_keep = completion_ids.size(1)
818
+ with torch.no_grad():
819
+ logits = self._forward_logits(
820
+ self.model,
821
+ prompt_completion_ids,
822
+ attention_mask,
823
+ logits_to_keep,
824
+ )
825
+ old_per_token_logps = selective_log_softmax(logits, completion_ids)
826
+
827
+ return old_per_token_logps
828
+
829
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
830
+ if return_outputs:
831
+ raise ValueError("The SDFTTrainer does not support returning outputs")
832
+
833
+ if self.use_teacher_server:
834
+ loss = self._compute_server_distillation_loss(model, inputs)
835
+ elif self.use_liger_loss:
836
+ loss = self._compute_liger_loss(model, inputs)
837
+ else:
838
+ distillation_logits = self._compute_teacher_student_logits(model, self.teacher_model, inputs)
839
+ loss = self._compute_self_distillation_loss(model, inputs, distillation_logits)
840
+ accumulation_scale = self.current_gradient_accumulation_steps if self.model.training else 1.0
841
+ return loss / accumulation_scale
842
+
843
+ def _compute_self_distillation_loss(
844
+ self,
845
+ model,
846
+ inputs: TrainingBatch,
847
+ distillation_logits: DistillationLogits,
848
+ ) -> torch.Tensor:
849
+ """Compute the per-token distillation loss and aggregate by normalizing over sequence length.
850
+
851
+ Dispatches between three objectives based on `distillation_mode`:
852
+
853
+ - `"topk_logits"`: top-k approximation of the divergence, optionally with a tail bucket for the remaining
854
+ probability mass (`distillation_add_tail`).
855
+ - `"full_logits"`: full-vocab divergence.
856
+ - `"sampled_token"`: token-level (reverse-KL) distillation on sampled `completion_ids`.
857
+
858
+ When `distillation_is_clip` is set and `old_per_token_logps` are available, the loss is corrected by a clipped
859
+ importance-sampling ratio between the current student and the student at rollout time.
860
+ """
861
+ if distillation_logits.loss_mask.sum() == 0:
862
+ mode = "train" if model.training else "eval"
863
+ self._log_self_distillation_metric(mode, 0.0)
864
+ # Keep the zero loss attached to the student graph so backward produces zero gradients instead of stopping.
865
+ return distillation_logits.student_logits.sum() * 0.0
866
+
867
+ if self.args.distillation_mode == "topk_logits":
868
+ if self.args.distillation_topk is None:
869
+ raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.")
870
+ per_token_loss = compute_topk_self_distillation_loss(
871
+ distillation_logits.student_logits,
872
+ distillation_logits.teacher_logits,
873
+ distillation_topk=self.args.distillation_topk,
874
+ distillation_alpha=self.args.distillation_alpha,
875
+ distillation_add_tail=self.args.distillation_add_tail,
876
+ )
877
+ elif self.args.distillation_mode == "full_logits":
878
+ per_token_loss = compute_full_logit_self_distillation_loss(
879
+ distillation_logits.student_logits,
880
+ distillation_logits.teacher_logits,
881
+ distillation_alpha=self.args.distillation_alpha,
882
+ )
883
+ elif self.args.distillation_mode == "sampled_token":
884
+ per_token_loss = compute_sampled_token_self_distillation_loss(
885
+ distillation_logits.student_logits,
886
+ distillation_logits.teacher_logits,
887
+ distillation_logits.completion_ids,
888
+ distillation_alpha=self.args.distillation_alpha,
889
+ )
890
+ else:
891
+ raise ValueError(
892
+ "distillation_mode must be one of: 'sampled_token', 'full_logits', 'topk_logits', "
893
+ f"got {self.args.distillation_mode!r}"
894
+ )
895
+
896
+ old_per_token_logps = inputs.get("old_per_token_logps")
897
+ if self.args.distillation_is_clip is not None and old_per_token_logps is not None:
898
+ student_per_token_logps = selective_log_softmax(
899
+ distillation_logits.student_logits,
900
+ distillation_logits.completion_ids,
901
+ )
902
+ per_token_loss = apply_importance_sampling_clipping(
903
+ per_token_loss,
904
+ student_per_token_logps,
905
+ old_per_token_logps,
906
+ self.args.distillation_is_clip,
907
+ )
908
+
909
+ loss = (per_token_loss * distillation_logits.loss_mask).sum(-1) / distillation_logits.loss_mask.sum(-1).clamp(
910
+ min=1.0
911
+ )
912
+ loss = loss.mean()
913
+
914
+ mode = "train" if model.training else "eval"
915
+ mean_distill_loss = (
916
+ per_token_loss * distillation_logits.loss_mask
917
+ ).sum() / distillation_logits.loss_mask.sum().clamp(min=1.0)
918
+ self._log_self_distillation_metric(
919
+ mode,
920
+ self.accelerator.gather(mean_distill_loss).mean().item(),
921
+ )
922
+ return loss
923
+
924
+ def _compute_server_distillation_loss(self, model, inputs: TrainingBatch) -> torch.Tensor:
925
+ """Distillation loss with teacher logprobs served by the vLLM generation server (`teacher_model_kind='live'`).
926
+
927
+ The student is forwarded locally (grad) for its logits; the teacher logprobs are fetched from the server (no
928
+ local teacher forward). `sampled_token` distills the realized token (reverse KL); `topk_logits` distills over
929
+ the teacher's own top-k support (the server cannot score the student's top-k indices).
930
+ """
931
+ # Buffered batches are reused across optimizer steps (`num_iterations > 1`), so the server weights can lag the
932
+ # live student; re-sync before scoring.
933
+ if self.state.global_step != self._last_loaded_step:
934
+ self.vllm_generation.sync_weights()
935
+ # Only the main process pushes weights to the server, so hold every rank here until the push completes;
936
+ # otherwise non-main ranks could score against half-updated weights.
937
+ self.accelerator.wait_for_everyone()
938
+ self._last_loaded_step = self.state.global_step
939
+
940
+ completion_ids = inputs["completion_ids"]
941
+ completion_mask = inputs["completion_mask"]
942
+ logits_to_keep = completion_ids.size(1)
943
+
944
+ # SDFT skips the first few completion tokens in the distillation loss to suppress teacher-prompt artifacts.
945
+ loss_mask = completion_mask
946
+ if self.num_loss_tokens_to_skip > 0:
947
+ token_positions = torch.arange(completion_mask.size(1), device=completion_mask.device).unsqueeze(0)
948
+ loss_mask = completion_mask * (token_positions >= self.num_loss_tokens_to_skip).long()
949
+
950
+ student_input_ids = torch.cat([inputs["prompt_ids"], completion_ids], dim=1)
951
+ student_attention_mask = torch.cat([inputs["prompt_mask"], completion_mask], dim=1)
952
+ student_logits = self._forward_logits(
953
+ model=model,
954
+ input_ids=student_input_ids,
955
+ attention_mask=student_attention_mask,
956
+ logits_to_keep=logits_to_keep,
957
+ )
958
+
959
+ mode = "train" if model.training else "eval"
960
+ teacher = self._get_teacher_token_logprobs_from_server(inputs, logits_to_keep)
961
+ # Padding positions come back as `-inf`; the masked-out positions are neutralized to finite values below so the
962
+ # divergence does not leak `+inf` through them (mirrors the distillation trainer).
963
+ required = loss_mask.bool()
964
+ student_per_token_logps = selective_log_softmax(student_logits, completion_ids)
965
+
966
+ teacher_per_token_logps = teacher["actual_logprobs"]
967
+ if (required & ~torch.isfinite(teacher_per_token_logps)).any():
968
+ raise ValueError("Teacher server returned no logprob for a required completion token.")
969
+ teacher_per_token_logps = torch.where(
970
+ required, teacher_per_token_logps, torch.zeros_like(teacher_per_token_logps)
971
+ )
972
+
973
+ # Diagnostic for disagreement between local student scores and server teacher scores on realized tokens.
974
+ # Sudden jumps can indicate stale server weights or numerical drift.
975
+ abs_diff = ((student_per_token_logps.detach() - teacher_per_token_logps).abs() * loss_mask).sum() / (
976
+ loss_mask.sum().clamp(min=1.0)
977
+ )
978
+ self._metrics[mode]["self_distillation/server_logprob_abs_diff"].append(
979
+ self.accelerator.gather(abs_diff).mean().item()
980
+ )
981
+
982
+ if self.args.distillation_mode == "sampled_token":
983
+ # Reverse-KL token-level objective, matching `compute_sampled_token_self_distillation_loss`.
984
+ per_token_loss = (student_per_token_logps - teacher_per_token_logps).detach() * student_per_token_logps
985
+ else:
986
+ teacher_topk_logps = teacher["topk_logprobs"]
987
+ teacher_topk_ids = teacher["topk_token_ids"]
988
+ # Project the student onto the teacher's top-k support, then renormalize (or add a tail bucket) before the
989
+ # divergence, matching `compute_topk_self_distillation_loss` on the teacher's support.
990
+ keep = required.unsqueeze(-1)
991
+ student_topk_logps = torch.gather(
992
+ torch.log_softmax(student_logits, dim=-1), dim=-1, index=teacher_topk_ids
993
+ )
994
+ student_topk_logps = torch.where(keep, student_topk_logps, torch.zeros_like(student_topk_logps))
995
+ teacher_topk_logps = torch.where(keep, teacher_topk_logps, torch.zeros_like(teacher_topk_logps))
996
+ if self.args.distillation_add_tail:
997
+ student_topk_logps = add_tail_bucket(student_topk_logps)
998
+ teacher_topk_logps = add_tail_bucket(teacher_topk_logps)
999
+ else:
1000
+ student_topk_logps = student_topk_logps - torch.logsumexp(student_topk_logps, dim=-1, keepdim=True)
1001
+ teacher_topk_logps = teacher_topk_logps - torch.logsumexp(teacher_topk_logps, dim=-1, keepdim=True)
1002
+ per_token_loss = compute_divergence(student_topk_logps, teacher_topk_logps, self.args.distillation_alpha)
1003
+
1004
+ old_per_token_logps = inputs.get("old_per_token_logps")
1005
+ if self.args.distillation_is_clip is not None and old_per_token_logps is not None:
1006
+ per_token_loss = apply_importance_sampling_clipping(
1007
+ per_token_loss, student_per_token_logps, old_per_token_logps, self.args.distillation_is_clip
1008
+ )
1009
+
1010
+ loss = (per_token_loss * loss_mask).sum(-1) / loss_mask.sum(-1).clamp(min=1.0)
1011
+ loss = loss.mean()
1012
+ mean_distill_loss = (per_token_loss * loss_mask).sum() / loss_mask.sum().clamp(min=1.0)
1013
+ self._log_self_distillation_metric(mode, self.accelerator.gather(mean_distill_loss).mean().item())
1014
+ return loss
1015
+
1016
+ def _get_teacher_token_logprobs_from_server(
1017
+ self, inputs: TrainingBatch, logits_to_keep: int
1018
+ ) -> dict[str, torch.Tensor]:
1019
+ """Per-token teacher logprobs from the vLLM server.
1020
+
1021
+ Returns a dict with `actual_logprobs` (`(B, T)`, the realized-token logprob for reverse KL) and `topk_logprobs`
1022
+ / `topk_token_ids` (`(B, T, K)`, the teacher's top-k support for top-k logit distillation). Completions are
1023
+ right-padded, so server values fill the leading positions of each row and the trailing padding keeps the `-inf`
1024
+ / `0` sentinels (neutralized by the caller).
1025
+ """
1026
+ import numpy as np
1027
+
1028
+ teacher_input_ids = inputs["teacher_input_ids"]
1029
+ teacher_attention_mask = inputs["teacher_attention_mask"]
1030
+ device = teacher_input_ids.device
1031
+ batch_size = teacher_input_ids.size(0)
1032
+ prompt_attention_mask = teacher_attention_mask[:, : teacher_attention_mask.size(1) - logits_to_keep]
1033
+ if self.args.distillation_mode == "topk_logits" and self.args.distillation_topk is None:
1034
+ raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.")
1035
+ top_logprobs = self.args.distillation_topk if self.args.distillation_mode == "topk_logits" else 1
1036
+
1037
+ sequences, prompt_lengths, _ = build_teacher_request_inputs(
1038
+ teacher_input_ids, teacher_attention_mask, prompt_attention_mask
1039
+ )
1040
+ result = self.teacher_client.get_sequence_logprobs(
1041
+ sequences=sequences,
1042
+ prompt_lengths=prompt_lengths,
1043
+ top_logprobs=top_logprobs,
1044
+ temperature=self.temperature,
1045
+ )
1046
+
1047
+ actual = np.full((batch_size, logits_to_keep), float("-inf"), dtype=np.float32)
1048
+ topk = np.full((batch_size, logits_to_keep, top_logprobs), float("-inf"), dtype=np.float32)
1049
+ topk_ids = np.zeros((batch_size, logits_to_keep, top_logprobs), dtype=np.int64)
1050
+ for i in range(batch_size):
1051
+ seq_actual = result["actual_logprobs"][i]
1052
+ n = min(len(seq_actual), logits_to_keep)
1053
+ if n:
1054
+ actual[i, :n] = np.array(seq_actual, dtype=np.float32)[:n, 0]
1055
+ topk[i, :n] = np.array(result["logprobs"][i], dtype=np.float32)[:n]
1056
+ topk_ids[i, :n] = np.array(result["logprob_token_ids"][i], dtype=np.int64)[:n]
1057
+ return {
1058
+ "actual_logprobs": torch.from_numpy(actual).to(device),
1059
+ "topk_logprobs": torch.from_numpy(topk).to(device),
1060
+ "topk_token_ids": torch.from_numpy(topk_ids).to(device),
1061
+ }
1062
+
1063
+ def _compute_teacher_student_logits(
1064
+ self,
1065
+ model,
1066
+ teacher_model,
1067
+ inputs: TrainingBatch,
1068
+ ) -> DistillationLogits:
1069
+ """Compute the per-token logits of the student and teacher over the completion tokens.
1070
+
1071
+ The student is forwarded on its own input (original prompt plus the sampled completion) while the teacher is
1072
+ forwarded on its input (prompt, privileged context, and the same completion). Both sets of logits are aligned
1073
+ to the completion tokens so they can be compared position-by-position in the distillation loss.
1074
+
1075
+ The teacher forward runs under `torch.no_grad()` and the context resolved by
1076
+ `_get_teacher_context_for_self_distillation`, which routes it to the correct weights.
1077
+ """
1078
+ prompt_ids = inputs["prompt_ids"]
1079
+ prompt_mask = inputs["prompt_mask"]
1080
+ completion_ids = inputs["completion_ids"]
1081
+ completion_mask = inputs["completion_mask"]
1082
+ logits_to_keep = completion_ids.size(1)
1083
+
1084
+ # SDFT skips the first few completion tokens in the distillation loss to suppress teacher-prompt artifacts.
1085
+ loss_mask = completion_mask
1086
+ if self.num_loss_tokens_to_skip > 0:
1087
+ token_positions = torch.arange(completion_mask.size(1), device=completion_mask.device).unsqueeze(0)
1088
+ loss_mask = completion_mask * (token_positions >= self.num_loss_tokens_to_skip).long()
1089
+
1090
+ student_input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
1091
+ student_attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
1092
+ student_logits = self._forward_logits(
1093
+ model=model,
1094
+ input_ids=student_input_ids,
1095
+ attention_mask=student_attention_mask,
1096
+ logits_to_keep=logits_to_keep,
1097
+ )
1098
+
1099
+ with torch.no_grad(), self._get_teacher_context_for_self_distillation():
1100
+ teacher_logits = self._forward_logits(
1101
+ model=teacher_model,
1102
+ input_ids=inputs["teacher_input_ids"],
1103
+ attention_mask=inputs["teacher_attention_mask"],
1104
+ logits_to_keep=logits_to_keep,
1105
+ )
1106
+
1107
+ return DistillationLogits(
1108
+ completion_ids=completion_ids,
1109
+ loss_mask=loss_mask,
1110
+ student_logits=student_logits,
1111
+ teacher_logits=teacher_logits,
1112
+ )
1113
+
1114
+ def _forward_logits(
1115
+ self,
1116
+ model,
1117
+ input_ids: torch.Tensor,
1118
+ attention_mask: torch.Tensor,
1119
+ logits_to_keep: int,
1120
+ ) -> torch.Tensor:
1121
+ """Forward the model and return temperature-scaled logits aligned to the completion tokens."""
1122
+ model_inputs = {
1123
+ "input_ids": input_ids,
1124
+ "attention_mask": attention_mask,
1125
+ "use_cache": False,
1126
+ }
1127
+ if "logits_to_keep" in self.model_kwarg_keys:
1128
+ model_inputs["logits_to_keep"] = logits_to_keep + 1
1129
+
1130
+ logits = model(**model_inputs).logits
1131
+ logits = logits[:, :-1, :]
1132
+ logits = logits[:, -logits_to_keep:, :]
1133
+ return logits / self.temperature
1134
+
1135
+ def _compute_liger_loss(self, model, inputs: TrainingBatch) -> torch.Tensor:
1136
+ """`full_logits` distillation via the Liger fused JSD kernel: forwards the base models for hidden states and
1137
+ fuses the lm_head projection with the divergence, never materializing the full-vocab logits.
1138
+
1139
+ Each model is forwarded through its own wrapper via `_forward_redirection` so FSDP2/DeepSpeed materialize the
1140
+ sharded params during the unwrapped base forward. The fused kernel needs both lm_head weights live at once, so
1141
+ the frozen teacher weight is captured while the teacher is materialized and handed to the student pass.
1142
+ """
1143
+ logits_to_keep = inputs["completion_ids"].size(1)
1144
+ completion_mask = inputs["completion_mask"]
1145
+ loss_mask = completion_mask
1146
+ if self.num_loss_tokens_to_skip > 0:
1147
+ token_positions = torch.arange(completion_mask.size(1), device=completion_mask.device).unsqueeze(0)
1148
+ loss_mask = completion_mask * (token_positions >= self.num_loss_tokens_to_skip).long()
1149
+
1150
+ unwrapped_student = self.accelerator.unwrap_model(model)
1151
+ unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model)
1152
+
1153
+ with torch.no_grad(), self._get_teacher_context_for_self_distillation():
1154
+ teacher_hidden, teacher_weight, teacher_bias = self._forward_redirection(
1155
+ self.teacher_model,
1156
+ unwrapped_teacher,
1157
+ self._liger_teacher_side,
1158
+ unwrapped_teacher,
1159
+ inputs,
1160
+ logits_to_keep,
1161
+ )
1162
+
1163
+ return self._forward_redirection(
1164
+ model,
1165
+ unwrapped_student,
1166
+ self._liger_student_loss,
1167
+ unwrapped_student,
1168
+ inputs,
1169
+ logits_to_keep,
1170
+ loss_mask,
1171
+ teacher_hidden,
1172
+ teacher_weight,
1173
+ teacher_bias,
1174
+ )
1175
+
1176
+ def _liger_teacher_side(self, teacher, inputs: TrainingBatch, logits_to_keep: int):
1177
+ """Teacher hidden states + frozen lm_head weight, captured while the teacher params are materialized."""
1178
+ hidden = teacher.get_decoder()(
1179
+ input_ids=inputs["teacher_input_ids"],
1180
+ attention_mask=inputs["teacher_attention_mask"],
1181
+ use_cache=False,
1182
+ ).last_hidden_state
1183
+ hidden = hidden[:, :-1][:, -logits_to_keep:]
1184
+ head = teacher.get_output_embeddings()
1185
+ # Clone so the weight survives re-sharding once this forward context exits.
1186
+ weight = head.weight.detach().clone()
1187
+ bias = head.bias.detach().clone() if head.bias is not None else None
1188
+ return hidden, weight, bias
1189
+
1190
+ def _liger_student_loss(
1191
+ self,
1192
+ student,
1193
+ inputs: TrainingBatch,
1194
+ logits_to_keep,
1195
+ loss_mask,
1196
+ teacher_hidden,
1197
+ teacher_weight,
1198
+ teacher_bias,
1199
+ ):
1200
+ student_input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1)
1201
+ student_attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1)
1202
+ student_hidden = student.get_decoder()(
1203
+ input_ids=student_input_ids,
1204
+ attention_mask=student_attention_mask,
1205
+ use_cache=False,
1206
+ ).last_hidden_state
1207
+ # Align hidden states to the completion-predicting positions, matching `_forward_logits`.
1208
+ student_hidden = student_hidden[:, :-1][:, -logits_to_keep:]
1209
+
1210
+ # `ignore_index` masks non-response positions; the token values only feed the disabled hard-CE term.
1211
+ completion_ids = inputs["completion_ids"]
1212
+ true_labels = torch.where(loss_mask.bool(), completion_ids, torch.full_like(completion_ids, -100))
1213
+
1214
+ student_head = student.get_output_embeddings()
1215
+ # Per-sequence then batch mean (grpo), matching the non-Liger path: the fused kernel reduces by total tokens
1216
+ # (bnpo), so we call it per sequence and average.
1217
+ seq_losses = [
1218
+ self.liger_jsd_loss(
1219
+ student_input=student_hidden[i],
1220
+ student_weight=student_head.weight,
1221
+ teacher_input=teacher_hidden[i],
1222
+ teacher_weight=teacher_weight,
1223
+ true_labels=true_labels[i],
1224
+ student_bias=student_head.bias,
1225
+ teacher_bias=teacher_bias,
1226
+ )
1227
+ for i in range(student_hidden.size(0))
1228
+ ]
1229
+ loss = torch.stack(seq_losses).mean()
1230
+
1231
+ mode = "train" if student.training else "eval"
1232
+ self._log_self_distillation_metric(mode, self.accelerator.gather(loss.detach()).mean().item())
1233
+ return loss
1234
+
1235
+ def _get_liger_zero3_lm_head_gather_ctx(self, model):
1236
+ """Gather the sharded student/teacher lm_head weights for the fused matmul under ZeRO-3. Liger reads
1237
+ `lm_head.weight` by attribute, so the gather hook never fires; the decoder forward gathers itself. No-op
1238
+ outside ZeRO-3."""
1239
+ if not self.use_liger_loss:
1240
+ return nullcontext()
1241
+
1242
+ deepspeed_plugin = self.accelerator.state.deepspeed_plugin
1243
+ if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3:
1244
+ return nullcontext()
1245
+
1246
+ import deepspeed
1247
+
1248
+ unwrapped_student = self.accelerator.unwrap_model(model)
1249
+ unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model)
1250
+ student_head = unwrapped_student.get_output_embeddings()
1251
+ teacher_head = unwrapped_teacher.get_output_embeddings()
1252
+ params = [student_head.weight, teacher_head.weight]
1253
+ if student_head.bias is not None:
1254
+ params.append(student_head.bias)
1255
+ if teacher_head.bias is not None:
1256
+ params.append(teacher_head.bias)
1257
+ return deepspeed.zero.GatheredParameters(params, modifier_rank=None)
1258
+
1259
+ def _get_teacher_context_for_self_distillation(self):
1260
+ """Return the context manager that routes the teacher forward to the correct weights.
1261
+
1262
+ For non-PEFT models this is a no-op. For PEFT models:
1263
+
1264
+ - `teacher_model_kind == "base"`: disable the student adapter so the teacher forward uses the base weights.
1265
+ - `teacher_model_kind == "ema"` under pure-LoRA training: switch to the `"teacher"` LoRA adapter.
1266
+ - otherwise: no-op; the teacher is a separate deepcopy.
1267
+ """
1268
+ teacher_model_kind = self.args.teacher_model_kind
1269
+ if not is_peft_model(self.model):
1270
+ return nullcontext()
1271
+
1272
+ target_model = self.accelerator.unwrap_model(self.teacher_model)
1273
+
1274
+ if teacher_model_kind == "base":
1275
+ return use_adapter(target_model, adapter_name=None)
1276
+ if teacher_model_kind == "ema" and self._use_peft_ema_teacher_adapter():
1277
+ return use_adapter(target_model, adapter_name="teacher")
1278
+ return nullcontext()
1279
+
1280
+ def _record_completion_metrics(self, mode: str, batch: TrainingBatch) -> None:
1281
+ device = self.accelerator.device
1282
+ completion_ids_list = self._get_completion_ids_list(batch)
1283
+ agg_completion_lengths = self.accelerator.gather(batch["raw_completion_lengths"])
1284
+ self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item())
1285
+ self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item())
1286
+ self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item())
1287
+
1288
+ eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id]
1289
+ is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device)
1290
+ agg_is_truncated = self.accelerator.gather(is_truncated)
1291
+ self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item())
1292
+ term_completion_lengths = agg_completion_lengths[~agg_is_truncated]
1293
+ if len(term_completion_lengths) == 0:
1294
+ term_completion_lengths = torch.zeros(1, device=device)
1295
+ self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item())
1296
+ self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item())
1297
+ self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item())
1298
+
1299
+ def _log_self_distillation_metric(self, mode: str, value: float) -> None:
1300
+ metric_prefix = self._name.lower().replace(" ", "_")
1301
+ self._metrics[mode]["self_distillation/distillation_loss"].append(value)
1302
+ self._metrics[mode][f"{metric_prefix}/distillation_loss"].append(value)
1303
+
1304
+ def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
1305
+ mode = "train" if self.model.training else "eval"
1306
+ metrics = {k: sum(v) / len(v) for k, v in self._metrics[mode].items() if v}
1307
+ if mode == "eval":
1308
+ metrics = {f"eval_{k}": v for k, v in metrics.items()}
1309
+ logs = {**logs, **metrics}
1310
+ super().log(logs, start_time)
1311
+ self._metrics[mode].clear()
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdft/teacher_sync.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+
17
+ import torch
18
+ from accelerate.utils import is_peft_model
19
+ from transformers import (
20
+ TrainerCallback,
21
+ TrainerControl,
22
+ TrainerState,
23
+ TrainingArguments,
24
+ )
25
+
26
+ from ...trainer.callbacks import SyncRefModelCallback
27
+
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ def is_pure_lora_training(model, accelerator=None) -> bool:
33
+ """Return `True` when the active adapter is LoRA and every trainable parameter is a LoRA parameter."""
34
+ if not is_peft_model(model):
35
+ return False
36
+
37
+ if accelerator is not None:
38
+ model = accelerator.unwrap_model(model)
39
+
40
+ adapter_name = model.active_adapter
41
+ if adapter_name is None:
42
+ adapter_name = "default"
43
+ adapter_config = model.peft_config.get(adapter_name)
44
+ peft_type = adapter_config.peft_type
45
+ if peft_type is None or str(peft_type).split(".")[-1] != "LORA":
46
+ return False
47
+
48
+ for name, param in model.named_parameters():
49
+ if param.requires_grad and "lora_" not in name:
50
+ return False
51
+ return True
52
+
53
+
54
+ class SyncTeacherModelCallback(SyncRefModelCallback):
55
+ """Synchronize an EMA teacher model with the student model on each configured sync step."""
56
+
57
+ def __init__(self, teacher_model, accelerator=None):
58
+ super().__init__(ref_model=teacher_model, accelerator=accelerator)
59
+
60
+ def on_step_end(self, args, state, control, **kwargs):
61
+ model = kwargs["model"]
62
+ if self.ref_model is not None and state.global_step % args.teacher_sync_steps == 0:
63
+ if self.accelerator:
64
+ model = self.accelerator.unwrap_model(model)
65
+ self.sync_target_model(model, self.ref_model, args.teacher_update_rate)
66
+
67
+
68
+ class PEFTAdapterEMACallback(TrainerCallback):
69
+ """
70
+ Callback that maintains an EMA copy of PEFT adapter weights for use as a teacher model in self-distillation.
71
+
72
+ The callback creates a secondary adapter ("teacher") with zero-initialized weights and maintains shadow weights
73
+ that are updated via exponential moving average: `teacher_weight = (1-α) * teacher_weight + α * student_weight`
74
+
75
+ Usage:
76
+ ```python
77
+ trainer.add_callback(
78
+ PEFTAdapterEMACallback(
79
+ model=model,
80
+ teacher_adapter_name="teacher",
81
+ update_rate=0.05,
82
+ )
83
+ )
84
+ ```
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ model,
90
+ teacher_adapter_name: str = "teacher",
91
+ update_rate: float = 0.05,
92
+ sync_steps: int = 1,
93
+ accelerator=None,
94
+ ):
95
+ self.model = model
96
+ self.teacher_adapter_name = teacher_adapter_name
97
+ self.update_rate = update_rate
98
+ self.sync_steps = sync_steps
99
+ self.accelerator = accelerator
100
+ self.shadow_weights: dict[str, torch.Tensor] | None = None
101
+ self.teacher_adapter_config = None
102
+ self._initialized = False
103
+
104
+ def _get_student_state_dict(self):
105
+ """Get student adapter state dict using PEFT keys (without adapter name)."""
106
+ from peft import get_peft_model_state_dict
107
+
108
+ if self.accelerator is not None:
109
+ model = self.accelerator.unwrap_model(self.model)
110
+ else:
111
+ model = self.model
112
+ return get_peft_model_state_dict(model)
113
+
114
+ def _initialize_teacher_adapter(self):
115
+ """Create teacher adapter with zero weights initialized from student adapter."""
116
+ from peft import get_peft_model_state_dict, set_peft_model_state_dict
117
+
118
+ if self._initialized:
119
+ return
120
+
121
+ if self.accelerator is not None:
122
+ model = self.accelerator.unwrap_model(self.model)
123
+ else:
124
+ model = self.model
125
+
126
+ adapter_name = model.active_adapter
127
+ if adapter_name is None:
128
+ adapter_name = "default"
129
+
130
+ self.teacher_adapter_config = model.peft_config.get(adapter_name)
131
+
132
+ student_state = get_peft_model_state_dict(model)
133
+
134
+ teacher_state = {k: torch.zeros_like(v) for k, v in student_state.items()}
135
+
136
+ model.add_adapter(self.teacher_adapter_name, self.teacher_adapter_config)
137
+
138
+ model.set_adapter(self.teacher_adapter_name)
139
+ set_peft_model_state_dict(model, teacher_state, adapter_name=self.teacher_adapter_name)
140
+
141
+ model.set_adapter(adapter_name)
142
+
143
+ self.shadow_weights = {k: v.clone().zero_() for k, v in teacher_state.items()}
144
+
145
+ self._initialized = True
146
+ logger.info(f"Initialized PEFT adapter EMA teacher with adapter name: {self.teacher_adapter_name}")
147
+
148
+ @torch.no_grad()
149
+ def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
150
+ if state.global_step % self.sync_steps != 0:
151
+ return
152
+
153
+ if not self._initialized:
154
+ self._initialize_teacher_adapter()
155
+
156
+ if self.shadow_weights is None:
157
+ return
158
+
159
+ if self.accelerator is None and "accelerator" in kwargs:
160
+ self.accelerator = kwargs["accelerator"]
161
+
162
+ student_state = self._get_student_state_dict()
163
+
164
+ for key, student_param in student_state.items():
165
+ if key in self.shadow_weights:
166
+ shadow = self.shadow_weights[key]
167
+ shadow.data = (1 - self.update_rate) * shadow.data + self.update_rate * student_param.data
168
+
169
+ from peft import set_peft_model_state_dict
170
+
171
+ if self.accelerator is not None:
172
+ unwrapped_model = self.accelerator.unwrap_model(self.model)
173
+ else:
174
+ unwrapped_model = self.model
175
+
176
+ original_adapter = unwrapped_model.active_adapter
177
+ unwrapped_model.set_adapter(self.teacher_adapter_name)
178
+ set_peft_model_state_dict(unwrapped_model, self.shadow_weights, adapter_name=self.teacher_adapter_name)
179
+ unwrapped_model.set_adapter(original_adapter)
180
+
181
+ def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
182
+ if self.accelerator is None and "accelerator" in kwargs:
183
+ self.accelerator = kwargs["accelerator"]
184
+ self._initialize_teacher_adapter()
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdpo/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .sdpo_config import SDPOConfig
16
+ from .sdpo_trainer import SDPOTrainer
17
+
18
+
19
+ __all__ = ["SDPOConfig", "SDPOTrainer"]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdpo/loss_utils.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Pure helper functions for self-distillation loss computation."""
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+
20
+ from ...trainer.utils import selective_log_softmax
21
+
22
+
23
+ def compute_divergence(
24
+ student_log_probs: torch.Tensor,
25
+ teacher_log_probs: torch.Tensor,
26
+ alpha: float,
27
+ ) -> torch.Tensor:
28
+ if alpha == 0.0:
29
+ kl = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True)
30
+ elif alpha == 1.0:
31
+ kl = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True)
32
+ else:
33
+ alpha_t = torch.tensor(alpha, dtype=student_log_probs.dtype, device=student_log_probs.device)
34
+ mixture = torch.logsumexp(
35
+ torch.stack([student_log_probs + torch.log(1 - alpha_t), teacher_log_probs + torch.log(alpha_t)]),
36
+ dim=0,
37
+ )
38
+ kl_teacher = F.kl_div(mixture, teacher_log_probs, reduction="none", log_target=True)
39
+ kl_student = F.kl_div(mixture, student_log_probs, reduction="none", log_target=True)
40
+ kl = torch.lerp(kl_student, kl_teacher, alpha)
41
+ return kl.sum(-1)
42
+
43
+
44
+ def add_tail_bucket(log_probs: torch.Tensor) -> torch.Tensor:
45
+ """Append a bucket holding the leftover probability mass to a top-k log-prob support.
46
+
47
+ `log_probs` are true log-probabilities over a top-k subset, so they sum to the captured mass `P_topk <= 1`. This
48
+ appends one extra category equal to the tail mass `1 - P_topk`, yielding a distribution that sums to exactly 1.
49
+ """
50
+ log_s = torch.logsumexp(log_probs, dim=-1, keepdim=True)
51
+ log_s = torch.clamp(log_s, max=-1e-7)
52
+ tail_log = torch.log(-torch.expm1(log_s))
53
+ return torch.cat([log_probs, tail_log], dim=-1)
54
+
55
+
56
+ def apply_importance_sampling_clipping(
57
+ per_token_loss: torch.Tensor,
58
+ student_log_probs: torch.Tensor,
59
+ old_log_probs: torch.Tensor,
60
+ clip_coeff: float,
61
+ ) -> torch.Tensor:
62
+ negative_approx_kl = (student_log_probs - old_log_probs).detach()
63
+ negative_approx_kl = torch.clamp(negative_approx_kl, min=-20.0, max=20.0)
64
+ ratio = torch.exp(negative_approx_kl).clamp(max=clip_coeff)
65
+ return per_token_loss * ratio
66
+
67
+
68
+ def compute_topk_self_distillation_loss(
69
+ student_logits: torch.Tensor,
70
+ teacher_logits: torch.Tensor,
71
+ *,
72
+ distillation_topk: int,
73
+ distillation_alpha: float,
74
+ distillation_add_tail: bool,
75
+ ) -> torch.Tensor:
76
+ """Compute distillation loss on the student's top-k token support.
77
+
78
+ The student's top-k logits define the support. The teacher distribution is projected onto the same token indices.
79
+ The selected support is then either renormalized or augmented with a tail bucket before the divergence is computed.
80
+ """
81
+ student_logsumexp = torch.logsumexp(student_logits, dim=-1, keepdim=True)
82
+ topk_student_logits, topk_indices = torch.topk(student_logits, k=distillation_topk, dim=-1)
83
+ topk_student_log_probs = topk_student_logits - student_logsumexp
84
+
85
+ teacher_logsumexp = torch.logsumexp(teacher_logits, dim=-1, keepdim=True)
86
+ topk_teacher_logits = torch.gather(teacher_logits, dim=-1, index=topk_indices)
87
+ topk_teacher_log_probs = topk_teacher_logits - teacher_logsumexp
88
+
89
+ # Top-k log-probs sum to the captured mass P_topk <= 1; the rest (1 - P_topk) is the "tail".
90
+ if distillation_add_tail:
91
+ # Lump the tail into one bucket so the divergence approximates the full-vocab divergence.
92
+ topk_student_log_probs = add_tail_bucket(topk_student_log_probs)
93
+ topk_teacher_log_probs = add_tail_bucket(topk_teacher_log_probs)
94
+ else:
95
+ # Drop the tail and renormalize the top-k to sum to 1: divergence over the top-k conditional only.
96
+ topk_student_log_probs = topk_student_log_probs - torch.logsumexp(topk_student_log_probs, dim=-1, keepdim=True)
97
+ topk_teacher_log_probs = topk_teacher_log_probs - torch.logsumexp(topk_teacher_log_probs, dim=-1, keepdim=True)
98
+
99
+ return compute_divergence(topk_student_log_probs, topk_teacher_log_probs, distillation_alpha)
100
+
101
+
102
+ def compute_full_logit_self_distillation_loss(
103
+ student_logits: torch.Tensor,
104
+ teacher_logits: torch.Tensor,
105
+ *,
106
+ distillation_alpha: float,
107
+ ) -> torch.Tensor:
108
+ """Compute full-vocabulary self-distillation loss between student and teacher logits."""
109
+ student_log_probs = torch.log_softmax(student_logits, dim=-1)
110
+ teacher_log_probs = torch.log_softmax(teacher_logits, dim=-1)
111
+ return compute_divergence(student_log_probs, teacher_log_probs, distillation_alpha)
112
+
113
+
114
+ def compute_sampled_token_self_distillation_loss(
115
+ student_logits: torch.Tensor,
116
+ teacher_logits: torch.Tensor,
117
+ completion_ids: torch.Tensor,
118
+ *,
119
+ distillation_alpha: float,
120
+ ) -> torch.Tensor:
121
+ """Compute token-level self-distillation loss only on the sampled completion tokens.
122
+
123
+ This path compares student and teacher log-probabilities on the realized completion tokens rather than over a
124
+ larger token support.
125
+ """
126
+ if distillation_alpha != 1.0:
127
+ raise ValueError(
128
+ "Only reverse KL (alpha=1.0) is supported for token-level distillation when "
129
+ f"`distillation_mode='sampled_token'`, got alpha={distillation_alpha}"
130
+ )
131
+
132
+ student_per_token_logps = selective_log_softmax(student_logits, completion_ids)
133
+ teacher_per_token_logps = selective_log_softmax(teacher_logits, completion_ids)
134
+ log_ratio = student_per_token_logps - teacher_per_token_logps
135
+ return log_ratio.detach() * student_per_token_logps
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdpo/sdpo_config.py ADDED
@@ -0,0 +1,644 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+ from typing import Any, Literal
17
+
18
+ from transformers import TrainingArguments
19
+
20
+ from ...trainer.base_config import _BaseConfig
21
+
22
+
23
+ @dataclass
24
+ class SDPOConfig(_BaseConfig):
25
+ r"""
26
+ Configuration class for the [`SDPOTrainer`].
27
+
28
+ Parameters:
29
+ > Parameters that control the online policy objective
30
+
31
+ beta (`float`, *optional*, defaults to `0.0`):
32
+ KL coefficient. If `0.0` (default), the reference model is not loaded, reducing memory usage and improving
33
+ training speed. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement
34
+ learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`.
35
+ epsilon (`float`, *optional*, defaults to `0.2`):
36
+ Epsilon value for clipping.
37
+ epsilon_high (`float`, *optional*):
38
+ Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound
39
+ specified in argument `epsilon`. Paper DAPO recommends `0.28`.
40
+ importance_sampling_level (`str`, *optional*, defaults to `"token"`):
41
+ Controls whether importance sampling ratios are computed at the `'token'` or `'sequence'` level. `'token'`
42
+ keeps the raw per-token log-probability ratios (one weight per token). `'sequence'` averages the
43
+ log-probability ratios across valid tokens to produce a single ratio per sequence. The GSPO paper shows
44
+ that sequence-level sampling often yields more stable training and better alignment with sequence-level
45
+ rewards.
46
+ reward_weights (`list[float]`, *optional*):
47
+ Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are
48
+ weighted equally with weight `1.0`.
49
+ scale_rewards (`str` or `bool`, *optional*, defaults to `"group"`):
50
+ Specifies the scaling strategy for rewards. Supported values are: `True` or `'group'` (default): rewards
51
+ are scaled by the standard deviation within each group, ensuring unit variance within a group. `'batch'`:
52
+ rewards are scaled by the standard deviation across the entire batch, as recommended in the PPO Lite paper.
53
+ `False` or `'none'`: no scaling is applied. The Dr. GRPO paper recommends not scaling rewards, as scaling
54
+ by the standard deviation introduces a question-level difficulty bias.
55
+
56
+ > Parameters that control the SDPO loss
57
+
58
+ distillation_weight (`float`, *optional*, defaults to `1.0`):
59
+ Convex combination weight between the policy and self-distillation objectives. The loss is `(1 -
60
+ distillation_weight) * policy_loss + distillation_weight * distillation_loss`. Must be in `[0, 1]`. `1.0`
61
+ (default) trains purely on self-distillation, `0.0` falls back to the standard GRPO-style policy gradient,
62
+ and intermediate values blend both.
63
+ distillation_alpha (`float`, *optional*, defaults to `1.0`):
64
+ Divergence interpolation coefficient. Sampled-token SDPO requires the official reverse-KL setting
65
+ `distillation_alpha=1.0`.
66
+ distillation_mode (`Literal["sampled_token", "full_logits", "topk_logits"]`, *optional*, defaults to `"sampled_token"`):
67
+ Distillation objective mode. `sampled_token` is the default SDPO mode and requires
68
+ `distillation_alpha=1.0`.
69
+ distillation_topk (`int`, *optional*):
70
+ Top-k approximation for logit-level SDPO. Must be set when `distillation_mode=topk_logits` and left unset
71
+ otherwise.
72
+ distillation_is_clip (`float`, *optional*, defaults to `2.0`):
73
+ Clipping coefficient for importance sampling in self-distillation. `None` disables clipping.
74
+ distillation_add_tail (`bool`, *optional*, defaults to `False`):
75
+ Whether to add a tail bucket for non-top-k probability mass.
76
+
77
+ > Parameters that control the teacher
78
+
79
+ teacher_model_kind (`str`, *optional*, defaults to `"ema"`):
80
+ Semantic teacher choice. `base` uses the initial student, `live` uses the current student, and `ema` uses
81
+ an exponentially averaged teacher.
82
+ teacher_update_rate (`float`, *optional*, defaults to `0.05`):
83
+ Teacher update rate used for EMA teacher synchronization.
84
+ teacher_sync_steps (`int`, *optional*, defaults to `1`):
85
+ How often to synchronize the EMA teacher model.
86
+
87
+ > Parameters that control reprompting
88
+
89
+ use_successful_as_teacher (`bool`, *optional*, defaults to `True`):
90
+ Use successful rollouts as implicit feedback for self-distillation.
91
+ success_reward_threshold (`float`, *optional*, defaults to `1.0`):
92
+ Minimum reward for a rollout to be considered a successful demonstration.
93
+ dont_reprompt_on_self_success (`bool`, *optional*, defaults to `True`):
94
+ Skip reprompting when model generates correct response.
95
+ max_reprompt_len (`int`, *optional*, defaults to `10240`):
96
+ Maximum length for reprompting in self-distillation.
97
+ reprompt_template (`str`, *optional*, defaults to `"{prompt}{solution}{feedback}\n\nCorrectly solve the original question.\n"`):
98
+ Template for reprompting the teacher with a successful demonstration.
99
+ solution_template (`str`, *optional*, defaults to `"\nCorrect solution:
100
+ \n\n{successful_previous_attempt}\n\n"`): Template for formatting the successful demonstration text.
101
+ feedback_template (`str`, *optional*, defaults to `"\nThe following is feedback from your unsuccessful earlier attempt:
102
+ \n\n{feedback_raw}\n\n"`): Template for formatting environment feedback for reprompting.
103
+ include_environment_feedback (`bool`, *optional*, defaults to `False`):
104
+ Whether to include environment feedback in teacher reprompts when available.
105
+ environment_feedback_only_without_solution (`bool`, *optional*, defaults to `False`):
106
+ Whether to use feedback only when no successful solution is available.
107
+ remove_thinking_from_demonstration (`bool`, *optional*, defaults to `False`):
108
+ Whether to remove <think>...</think> blocks from the demonstration text.
109
+
110
+ > Parameters that control diagnostics
111
+
112
+ diagnostics_warning_interval (`int`, *optional*, defaults to `10`):
113
+ Emit repeated trainer diagnostics every N consecutive degenerate steps. Set to 0 to disable.
114
+ diagnostics_flat_tolerance (`float`, *optional*, defaults to `1e-8`):
115
+ Tolerance used to decide whether reward variance or reprompt activity is effectively zero.
116
+
117
+ > Parameters that control the model
118
+
119
+ model_init_kwargs (`dict[str, Any]`, *optional*):
120
+ Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument
121
+ of the `SDPOTrainer` is provided as a string.
122
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
123
+ Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to
124
+ [`~transformers.AutoModelForCausalLM.from_pretrained`] and [`~transformers.AutoProcessor.from_pretrained`].
125
+ Also applied to reward-model and reward-tokenizer loads.
126
+ disable_dropout (`bool`, *optional*, defaults to `True`):
127
+ Whether to disable dropout in the model. This is useful for training with a reference model, as it prevents
128
+ the model from generating different logprobs for the same input.
129
+
130
+ > Parameters that control data preprocessing
131
+
132
+ remove_unused_columns (`bool`, *optional*, defaults to `False`):
133
+ Whether to only keep the column 'prompt' in the dataset. If you use a custom reward function that requires
134
+ any column other than 'prompts' and 'completions', you should keep this to `False`.
135
+ max_prompt_length (`int`, *optional*, defaults to `512`):
136
+ Maximum prompt length. Longer prompts are truncated from the left.
137
+ shuffle_dataset (`bool`, *optional*, defaults to `True`):
138
+ Whether to shuffle the training dataset.
139
+
140
+ > Parameters that control generation
141
+
142
+ num_generations (`int`, *optional*, defaults to `8`):
143
+ Number of generations to sample. The effective batch size (num_processes * per_device_batch_size *
144
+ gradient_accumulation_steps) must be evenly divisible by this value.
145
+ num_generations_eval (`int`, *optional*):
146
+ Number of generations to sample during evaluation. This allows using fewer generations during evaluation to
147
+ save computation. If `None`, uses the value of `num_generations`.
148
+ max_completion_length (`int`, *optional*, defaults to `256`):
149
+ Maximum length of the generated completion.
150
+ temperature (`float`, *optional*, defaults to `1.0`):
151
+ Temperature for sampling. The higher the temperature, the more random the completions.
152
+ top_p (`float`, *optional*, defaults to `1.0`):
153
+ Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to 1.0
154
+ to consider all tokens.
155
+ top_k (`int`, *optional*, defaults to `0`):
156
+ Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is
157
+ disabled and all tokens are considered.
158
+ min_p (`float`, *optional*):
159
+ Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
160
+ value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range.
161
+ repetition_penalty (`float`, *optional*, defaults to `1.0`):
162
+ Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far.
163
+ Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model to repeat
164
+ tokens.
165
+ cache_implementation (`str`, *optional*):
166
+ Implementation of the cache method for faster generation when use_vllm is set to False.
167
+ generation_kwargs (`dict[str, Any]`, *optional*):
168
+ Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or `SamplingParams` (if
169
+ using vLLM) when sampling completions. This can be used to further customize the generation behavior, such
170
+ as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict with the other generation
171
+ parameters (like `min_p`, `top_p`, etc.), they will override them.
172
+ chat_template_kwargs (`dict[str, Any]`, *optional*):
173
+ Additional keyword arguments to pass to the `apply_chat_template` function when generating completions.
174
+ ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
175
+ This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
176
+ improving generation speed. However, disabling this option allows training models that exceed the VRAM
177
+ capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible
178
+ with vLLM generation.
179
+
180
+ > Parameters that control generation acceleration powered by vLLM
181
+
182
+ use_vllm (`bool`, *optional*, defaults to `False`):
183
+ Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation
184
+ instead of the default model.generate(). Requires `vllm` to be installed.
185
+ use_teacher_server (`bool`, *optional*, defaults to `False`):
186
+ Compute teacher logprobs from the running vLLM generation server instead of a local teacher forward. Only
187
+ supported for `teacher_model_kind='live'` with `use_vllm=True`, `vllm_mode='server'`,
188
+ `distillation_weight=1.0` (pure distillation), and `distillation_mode` in {'sampled_token', 'topk_logits'}
189
+ (the server returns the teacher's top-k logprobs, not the full vocabulary; `topk_logits` distills over the
190
+ teacher's own top-k support).
191
+ vllm_mode (`str`, *optional*, defaults to `"colocate"`):
192
+ Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or
193
+ `'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure a
194
+ TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same process
195
+ and share the training GPUs. This avoids the need for a separate server but may cause resource contention
196
+ with training.
197
+ vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
198
+ Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: Use the
199
+ `transformers` backend for model implementation. `vllm`: Use the `vllm` library for model implementation.
200
+ vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
201
+ Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but
202
+ waking the engine adds host–device transfer latency.
203
+ vllm_server_base_url (`str`, *optional*):
204
+ Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` and
205
+ `vllm_server_port` are ignored.
206
+ vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
207
+ Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided.
208
+ vllm_server_port (`int`, *optional*, defaults to `8000`):
209
+ Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided.
210
+ vllm_group_port (`int`, *optional*, defaults to `51216`):
211
+ Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port
212
+ is occupied, there is no need to change it.
213
+ vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
214
+ Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the
215
+ timeout, a `ConnectionError` is raised.
216
+ vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
217
+ Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to
218
+ `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when
219
+ launching the vLLM server via the `--vllm_tensor_parallel_size` flag.
220
+ vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`):
221
+ Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to
222
+ `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when
223
+ launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.
224
+ vllm_max_model_length (`int`, *optional*):
225
+ Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus
226
+ `max_completion_length`; if omitted, it is inferred from the model config.
227
+
228
+ > Parameters that control the training
229
+
230
+ loss_type (`str`, *optional*, defaults to `"dapo"`):
231
+ Specifies the loss formulation to use. Supported values are 'grpo', 'bnpo', 'dr_grpo', and 'dapo'. 'grpo':
232
+ Aggregates token-level losses by normalizing over sequence length. Not recommended due to length bias—this
233
+ approach tends to prefer shorter completions with positive advantages and longer ones with negative
234
+ advantages. 'dapo' (default): Aggregates token-level losses by normalizing with the number of active tokens
235
+ in the global accumulated batch. This method was introduced in the DAPO paper to eliminate length bias.
236
+ 'dr_grpo': Aggregates token-level losses by normalizing with a global constant. This method was introduced
237
+ in the Dr. GRPO paper to eliminate length bias. The value of the constant corresponds to
238
+ `max_completion_length`. 'bnpo': Aggregates token-level losses by normalizing with the number of active
239
+ tokens in the local batch. Note that normalization is performed over the local batch only, so results may
240
+ slightly vary depending on the local batch size, despite a constant effective batch size. When using
241
+ `per_device_train_batch_size==1`, the loss is equivalent to the GRPO loss.
242
+ num_iterations (`int`, *optional*, defaults to `1`):
243
+ Number of iterations per batch (denoted as μ in the algorithm).
244
+ generation_batch_size (`int`, *optional*):
245
+ Batch size to use for generation. If `None`, it defaults to the effective training batch size:
246
+ `per_device_train_batch_size * num_processes * steps_per_generation`.
247
+ steps_per_generation (`int`, *optional*):
248
+ Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`.
249
+ mask_truncated_completions (`bool`, *optional*, defaults to `False`):
250
+ When enabled, truncated completions are excluded from the loss calculation, preventing them from being
251
+ incorrectly penalized and introducing noise during training. According to the DAPO paper, this is a good
252
+ practice for training stability.
253
+ """
254
+
255
+ _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs"]
256
+
257
+ model_init_kwargs: dict[str, Any] | None = field(
258
+ default=None,
259
+ metadata={
260
+ "help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the `SDPOTrainer` is provided as a string."
261
+ },
262
+ )
263
+ trust_remote_code: bool = field(
264
+ default=False,
265
+ metadata={
266
+ "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
267
+ "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`. Also applied to "
268
+ "reward-model and reward-tokenizer loads."
269
+ },
270
+ )
271
+ disable_dropout: bool = field(
272
+ default=True,
273
+ metadata={
274
+ "help": "Whether to disable dropout in the model. This is useful for training with a reference model, as it prevents the model from generating different logprobs for the same input."
275
+ },
276
+ )
277
+ remove_unused_columns: bool = field(
278
+ default=False,
279
+ metadata={
280
+ "help": "Whether to only keep the column 'prompt' in the dataset. If you use a custom reward function that requires any column other than 'prompts' and 'completions', you should keep this to `False`."
281
+ },
282
+ )
283
+ max_prompt_length: int | None = field(
284
+ default=512,
285
+ metadata={"help": "Maximum prompt length. Longer prompts are truncated from the left."},
286
+ )
287
+ num_generations: int = field(
288
+ default=8,
289
+ metadata={
290
+ "help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size * gradient_accumulation_steps) must be evenly divisible by this value."
291
+ },
292
+ )
293
+ num_generations_eval: int | None = field(
294
+ default=None,
295
+ metadata={
296
+ "help": "Number of generations to sample during evaluation. This allows using fewer generations during evaluation to save computation. If `None`, uses the value of `num_generations`."
297
+ },
298
+ )
299
+ max_completion_length: int | None = field(
300
+ default=256,
301
+ metadata={"help": "Maximum length of the generated completion."},
302
+ )
303
+ ds3_gather_for_generation: bool = field(
304
+ default=True,
305
+ metadata={
306
+ "help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation, improving generation speed. However, disabling this option allows training models that exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible with vLLM generation."
307
+ },
308
+ )
309
+ shuffle_dataset: bool = field(
310
+ default=True,
311
+ metadata={"help": "Whether to shuffle the training dataset."},
312
+ )
313
+ generation_batch_size: int | None = field(
314
+ default=None,
315
+ metadata={
316
+ "help": "Batch size to use for generation. If `None`, it defaults to the effective training batch size: `per_device_train_batch_size * num_processes * steps_per_generation`."
317
+ },
318
+ )
319
+ steps_per_generation: int | None = field(
320
+ default=None,
321
+ metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."},
322
+ )
323
+ temperature: float = field(
324
+ default=1.0,
325
+ metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."},
326
+ )
327
+ top_p: float = field(
328
+ default=1.0,
329
+ metadata={
330
+ "help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to 1.0 to consider all tokens."
331
+ },
332
+ )
333
+ top_k: int = field(
334
+ default=0,
335
+ metadata={
336
+ "help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is disabled and all tokens are considered."
337
+ },
338
+ )
339
+ min_p: float | None = field(
340
+ default=None,
341
+ metadata={
342
+ "help": "Minimum token probability, which will be scaled by the probability of the most likely token. It must be a value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range."
343
+ },
344
+ )
345
+ generation_kwargs: dict[str, Any] | None = field(
346
+ default=None,
347
+ metadata={
348
+ "help": "Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or `SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them."
349
+ },
350
+ )
351
+ chat_template_kwargs: dict[str, Any] | None = field(
352
+ default=None,
353
+ metadata={
354
+ "help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating completions."
355
+ },
356
+ )
357
+ repetition_penalty: float = field(
358
+ default=1.0,
359
+ metadata={
360
+ "help": "Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far. Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model to repeat tokens."
361
+ },
362
+ )
363
+ cache_implementation: str | None = field(
364
+ default=None,
365
+ metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."},
366
+ )
367
+ use_vllm: bool = field(
368
+ default=False,
369
+ metadata={
370
+ "help": "Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation instead of the default model.generate(). Requires `vllm` to be installed."
371
+ },
372
+ )
373
+ use_teacher_server: bool = field(
374
+ default=False,
375
+ metadata={
376
+ "help": "Compute teacher logprobs from the running vLLM generation server instead of a local teacher "
377
+ "forward. Only supported for `teacher_model_kind='live'` with `use_vllm=True`, `vllm_mode='server'`, "
378
+ "`distillation_weight=1.0` (pure distillation), and `distillation_mode` in {'sampled_token', "
379
+ "'topk_logits'} (the server returns the teacher's top-k logprobs, not the full vocabulary; `topk_logits` "
380
+ "distills over the teacher's own top-k support)."
381
+ },
382
+ )
383
+ vllm_mode: str = field(
384
+ default="colocate",
385
+ metadata={
386
+ "help": "Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or `'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same process and share the training GPUs. This avoids the need for a separate server but may cause resource contention with training."
387
+ },
388
+ )
389
+ vllm_model_impl: str = field(
390
+ default="vllm",
391
+ metadata={
392
+ "help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for model implementation."
393
+ },
394
+ )
395
+ vllm_enable_sleep_mode: bool = field(
396
+ default=False,
397
+ metadata={
398
+ "help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but waking the engine adds host–device transfer latency."
399
+ },
400
+ )
401
+ vllm_server_base_url: str | None = field(
402
+ default=None,
403
+ metadata={
404
+ "help": "Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` and `vllm_server_port` are ignored."
405
+ },
406
+ )
407
+ vllm_server_host: str = field(
408
+ default="0.0.0.0",
409
+ metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
410
+ )
411
+ vllm_server_port: int = field(
412
+ default=8000,
413
+ metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
414
+ )
415
+ vllm_group_port: int = field(
416
+ default=51216,
417
+ metadata={
418
+ "help": "Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port is occupied, there is no need to change it."
419
+ },
420
+ )
421
+ vllm_server_timeout: float = field(
422
+ default=240.0,
423
+ metadata={
424
+ "help": "Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the timeout, a `ConnectionError` is raised."
425
+ },
426
+ )
427
+ vllm_tensor_parallel_size: int = field(
428
+ default=1,
429
+ metadata={
430
+ "help": "Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when launching the vLLM server via the `--vllm_tensor_parallel_size` flag."
431
+ },
432
+ )
433
+ vllm_gpu_memory_utilization: float = field(
434
+ default=0.3,
435
+ metadata={
436
+ "help": "Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when launching the vLLM server via the `--vllm_gpu_memory_utilization` flag."
437
+ },
438
+ )
439
+ vllm_max_model_length: int | None = field(
440
+ default=None,
441
+ metadata={
442
+ "help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus `max_completion_length`; if omitted, it is inferred from the model config."
443
+ },
444
+ )
445
+ num_iterations: int = field(
446
+ default=1,
447
+ metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."},
448
+ )
449
+ loss_type: str = field(
450
+ default="dapo",
451
+ metadata={
452
+ "help": "Specifies the loss formulation to use. Supported values are 'grpo', 'bnpo', 'dr_grpo', and 'dapo'. 'grpo': Aggregates token-level losses by normalizing over sequence length. Not recommended due to length bias—this approach tends to prefer shorter completions with positive advantages and longer ones with negative advantages. 'dapo' (default): Aggregates token-level losses by normalizing with the number of active tokens in the global accumulated batch. This method was introduced in the DAPO paper to eliminate length bias. 'dr_grpo': Aggregates token-level losses by normalizing with a global constant. This method was introduced in the Dr. GRPO paper to eliminate length bias. The value of the constant corresponds to `max_completion_length`. 'bnpo': Aggregates token-level losses by normalizing with the number of active tokens in the local batch. Note that normalization is performed over the local batch only, so results may slightly vary depending on the local batch size, despite a constant effective batch size. When using `per_device_train_batch_size==1`, the loss is equivalent to the GRPO loss."
453
+ },
454
+ )
455
+ mask_truncated_completions: bool = field(
456
+ default=False,
457
+ metadata={
458
+ "help": "When enabled, truncated completions are excluded from the loss calculation, preventing them from being incorrectly penalized and introducing noise during training. According to the DAPO paper, this is a good practice for training stability."
459
+ },
460
+ )
461
+ dont_reprompt_on_self_success: bool = field(
462
+ default=True,
463
+ metadata={"help": "Skip reprompting when model generates correct response."},
464
+ )
465
+ beta: float = field(
466
+ default=0.0,
467
+ metadata={
468
+ "help": "KL coefficient. If `0.0` (default), the reference model is not loaded, reducing memory usage and improving training speed. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`."
469
+ },
470
+ )
471
+ epsilon: float = field(
472
+ default=0.2,
473
+ metadata={"help": "Epsilon value for clipping."},
474
+ )
475
+ epsilon_high: float | None = field(
476
+ default=None,
477
+ metadata={
478
+ "help": "Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound specified in argument `epsilon`. Paper DAPO recommends `0.28`."
479
+ },
480
+ )
481
+ importance_sampling_level: str = field(
482
+ default="token",
483
+ metadata={
484
+ "help": "Controls whether importance sampling ratios are computed at the `'token'` or `'sequence'` level. `'token'` keeps the raw per-token log-probability ratios (one weight per token). `'sequence'` averages the log-probability ratios across valid tokens to produce a single ratio per sequence. The GSPO paper shows that sequence-level sampling often yields more stable training and better alignment with sequence-level rewards."
485
+ },
486
+ )
487
+ reward_weights: list[float] | None = field(
488
+ default=None,
489
+ metadata={
490
+ "help": "Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are weighted equally with weight `1.0`."
491
+ },
492
+ )
493
+ scale_rewards: str | bool = field(
494
+ default="group",
495
+ metadata={
496
+ "help": "Specifies the scaling strategy for rewards. Supported values are: `True` or `'group'` (default): rewards are scaled by the standard deviation within each group, ensuring unit variance within a group. `'batch'`: rewards are scaled by the standard deviation across the entire batch, as recommended in the PPO Lite paper. `False` or `'none'`: no scaling is applied. The Dr. GRPO paper recommends not scaling rewards, as scaling by the standard deviation introduces a question-level difficulty bias."
497
+ },
498
+ )
499
+ distillation_alpha: float = field(
500
+ default=1.0,
501
+ metadata={
502
+ "help": "Divergence interpolation coefficient. Sampled-token SDPO requires the official reverse-KL setting "
503
+ "`distillation_alpha=1.0`."
504
+ },
505
+ )
506
+ distillation_mode: Literal["sampled_token", "full_logits", "topk_logits"] = field(
507
+ default="sampled_token",
508
+ metadata={
509
+ "help": "Distillation objective mode. `sampled_token` is the default SDPO mode and requires "
510
+ "`distillation_alpha=1.0`."
511
+ },
512
+ )
513
+ distillation_topk: int | None = field(
514
+ default=None,
515
+ metadata={
516
+ "help": "Top-k approximation for logit-level SDPO. Must be set when `distillation_mode=topk_logits` and left "
517
+ "unset otherwise."
518
+ },
519
+ )
520
+ distillation_is_clip: float | None = field(
521
+ default=2.0,
522
+ metadata={
523
+ "help": "Clipping coefficient for importance sampling in self-distillation. `None` disables clipping."
524
+ },
525
+ )
526
+ distillation_add_tail: bool = field(
527
+ default=False,
528
+ metadata={"help": "Whether to add a tail bucket for non-top-k probability mass."},
529
+ )
530
+ distillation_weight: float = field(
531
+ default=1.0,
532
+ metadata={
533
+ "help": "Convex combination weight between the policy and self-distillation objectives. The loss is "
534
+ "`(1 - distillation_weight) * policy_loss + distillation_weight * distillation_loss`. Must be in `[0, 1]`. "
535
+ "`1.0` (default) trains purely on self-distillation, `0.0` falls back to the standard GRPO-style policy "
536
+ "gradient, and intermediate values blend both."
537
+ },
538
+ )
539
+ teacher_model_kind: str = field(
540
+ default="ema",
541
+ metadata={
542
+ "help": "Semantic teacher choice. `base` uses the initial student, `live` uses the current student, "
543
+ "and `ema` uses an exponentially averaged teacher."
544
+ },
545
+ )
546
+ teacher_update_rate: float = field(
547
+ default=0.05,
548
+ metadata={"help": "Teacher update rate used for EMA teacher synchronization."},
549
+ )
550
+ teacher_sync_steps: int = field(
551
+ default=1,
552
+ metadata={"help": "How often to synchronize the EMA teacher model."},
553
+ )
554
+ max_reprompt_len: int = field(
555
+ default=10240,
556
+ metadata={"help": "Maximum length for reprompting in self-distillation."},
557
+ )
558
+ use_successful_as_teacher: bool = field(
559
+ default=True,
560
+ metadata={"help": "Use successful rollouts as implicit feedback for self-distillation."},
561
+ )
562
+ success_reward_threshold: float = field(
563
+ default=1.0,
564
+ metadata={"help": "Minimum reward for a rollout to be considered a successful demonstration."},
565
+ )
566
+ reprompt_template: str = field(
567
+ default="{prompt}{solution}{feedback}\n\nCorrectly solve the original question.\n",
568
+ metadata={"help": "Template for reprompting the teacher with a successful demonstration."},
569
+ )
570
+ solution_template: str = field(
571
+ default="\nCorrect solution:\n\n{successful_previous_attempt}\n\n",
572
+ metadata={"help": "Template for formatting the successful demonstration text."},
573
+ )
574
+ feedback_template: str = field(
575
+ default="\nThe following is feedback from your unsuccessful earlier attempt:\n\n{feedback_raw}\n\n",
576
+ metadata={"help": "Template for formatting environment feedback for reprompting."},
577
+ )
578
+ include_environment_feedback: bool = field(
579
+ default=False,
580
+ metadata={"help": "Whether to include environment feedback in teacher reprompts when available."},
581
+ )
582
+ environment_feedback_only_without_solution: bool = field(
583
+ default=False,
584
+ metadata={"help": "Whether to use feedback only when no successful solution is available."},
585
+ )
586
+ remove_thinking_from_demonstration: bool = field(
587
+ default=False,
588
+ metadata={"help": "Whether to remove <think>...</think> blocks from the demonstration text."},
589
+ )
590
+ diagnostics_warning_interval: int = field(
591
+ default=10,
592
+ metadata={
593
+ "help": "Emit repeated trainer diagnostics every N consecutive degenerate steps. Set to 0 to disable."
594
+ },
595
+ )
596
+ diagnostics_flat_tolerance: float = field(
597
+ default=1e-8,
598
+ metadata={
599
+ "help": "Tolerance used to decide whether reward variance or reprompt activity is effectively zero."
600
+ },
601
+ )
602
+
603
+ def __post_init__(self):
604
+ super().__post_init__()
605
+ if not 0.0 <= self.distillation_weight <= 1.0:
606
+ raise ValueError(f"`distillation_weight` must be in [0, 1], got {self.distillation_weight}.")
607
+ if self.distillation_mode == "sampled_token" and self.distillation_alpha != 1.0:
608
+ raise ValueError(
609
+ "`distillation_mode='sampled_token'` only supports reverse KL, so it requires "
610
+ f"`distillation_alpha=1.0`, got {self.distillation_alpha}."
611
+ )
612
+ num_processes = self.world_size
613
+ if self.generation_batch_size is None and self.steps_per_generation is None:
614
+ self.steps_per_generation = self.gradient_accumulation_steps
615
+ self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
616
+ elif self.generation_batch_size is not None and self.steps_per_generation is None:
617
+ global_batch_size = self.per_device_train_batch_size * num_processes
618
+ if self.generation_batch_size % global_batch_size != 0:
619
+ raise ValueError(
620
+ f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size ({global_batch_size})."
621
+ )
622
+ self.steps_per_generation = self.generation_batch_size // global_batch_size
623
+ elif self.generation_batch_size is None and self.steps_per_generation is not None:
624
+ self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
625
+ else:
626
+ raise ValueError("'generation_batch_size' and 'steps_per_generation' can not both be configured")
627
+
628
+ if self.generation_batch_size % self.num_generations != 0:
629
+ raise ValueError(
630
+ f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations ({self.num_generations})."
631
+ )
632
+
633
+ if self.do_eval and self.eval_strategy != "no":
634
+ num_generations_eval = self.num_generations_eval or self.num_generations
635
+ if (self.per_device_eval_batch_size * num_processes) % num_generations_eval != 0:
636
+ raise ValueError(
637
+ f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be "
638
+ f"divisible by the number of generations used for evaluation ({num_generations_eval})."
639
+ )
640
+
641
+ self.scale_rewards = {True: "group", False: "none"}.get(self.scale_rewards, self.scale_rewards)
642
+
643
+ if self.epsilon_high is None:
644
+ self.epsilon_high = self.epsilon
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdpo/sdpo_trainer.py ADDED
@@ -0,0 +1,1773 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import math
17
+ import re
18
+ import textwrap
19
+ from collections import defaultdict
20
+ from contextlib import nullcontext
21
+ from dataclasses import dataclass
22
+ from functools import partial
23
+ from typing import Any
24
+
25
+ import datasets
26
+ import torch
27
+ from accelerate.logging import get_logger
28
+ from accelerate.utils import gather_object, is_peft_model
29
+ from datasets import Dataset, IterableDataset
30
+ from torch import nn
31
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
32
+ from torch.utils.data import DataLoader, Sampler
33
+ from transformers import (
34
+ AutoModelForSequenceClassification,
35
+ AutoProcessor,
36
+ AutoTokenizer,
37
+ GenerationConfig,
38
+ PreTrainedModel,
39
+ PreTrainedTokenizerBase,
40
+ ProcessorMixin,
41
+ TrainerCallback,
42
+ )
43
+ from transformers.trainer_utils import seed_worker
44
+ from transformers.utils import is_datasets_available, is_liger_kernel_available, is_peft_available
45
+
46
+ from ...data_utils import apply_chat_template, is_conversational
47
+ from ...models import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation
48
+ from ...models.utils import _ForwardRedirection
49
+ from ...trainer.base_trainer import _BaseTrainer
50
+ from ...trainer.utils import (
51
+ RepeatSampler,
52
+ create_model_from_path,
53
+ disable_dropout_in_model,
54
+ get_config_model_id,
55
+ identity,
56
+ pad,
57
+ selective_log_softmax,
58
+ split_tensor_dict,
59
+ use_adapter,
60
+ )
61
+ from ..utils import prepare_peft_model
62
+ from .loss_utils import (
63
+ add_tail_bucket,
64
+ apply_importance_sampling_clipping,
65
+ compute_divergence,
66
+ compute_full_logit_self_distillation_loss,
67
+ compute_sampled_token_self_distillation_loss,
68
+ compute_topk_self_distillation_loss,
69
+ )
70
+ from .sdpo_config import SDPOConfig
71
+ from .teacher_sync import PEFTAdapterEMACallback, SyncTeacherModelCallback, is_pure_lora_training
72
+
73
+
74
+ logger = get_logger(__name__)
75
+
76
+
77
+ if is_peft_available():
78
+ from peft import PeftConfig
79
+
80
+ if is_liger_kernel_available():
81
+ from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss
82
+
83
+
84
+ TrainingBatch = dict[str, torch.Tensor | Any]
85
+
86
+
87
+ def build_teacher_request_inputs(
88
+ input_ids: torch.Tensor,
89
+ attention_mask: torch.Tensor,
90
+ prompt_attention_mask: torch.Tensor,
91
+ ) -> tuple[list[list[int]], list[int], list[int]]:
92
+ """Trim padded batch tensors into per-sample (prompt+completion) sequences for teacher-server requests."""
93
+ if input_ids.shape != attention_mask.shape:
94
+ raise ValueError(
95
+ f"input_ids and attention_mask must have the same shape, got {input_ids.shape} and {attention_mask.shape}."
96
+ )
97
+
98
+ input_ids_cpu = input_ids.detach().cpu()
99
+ attention_mask_cpu = attention_mask.detach().cpu().bool()
100
+ prompt_lengths = prompt_attention_mask.detach().cpu().sum(dim=1).to(torch.long)
101
+
102
+ trimmed_input_ids: list[list[int]] = []
103
+ prompt_lengths_list: list[int] = []
104
+ completion_lengths_list: list[int] = []
105
+ for row, mask, prompt_length in zip(input_ids_cpu, attention_mask_cpu, prompt_lengths, strict=True):
106
+ trimmed_row = row[mask]
107
+ prompt_len = int(prompt_length.item())
108
+ if prompt_len < 0 or prompt_len > trimmed_row.numel():
109
+ raise ValueError(
110
+ f"Invalid prompt length {prompt_len} for trimmed sequence of length {trimmed_row.numel()}."
111
+ )
112
+ trimmed_input_ids.append(trimmed_row.tolist())
113
+ prompt_lengths_list.append(prompt_len)
114
+ completion_lengths_list.append(int(trimmed_row.numel()) - prompt_len)
115
+ return trimmed_input_ids, prompt_lengths_list, completion_lengths_list
116
+
117
+
118
+ @dataclass
119
+ class DistillationLogits:
120
+ """Aligned logits and masks used to compute a self-distillation objective."""
121
+
122
+ completion_ids: torch.Tensor
123
+ completion_mask: torch.Tensor
124
+ loss_mask: torch.Tensor
125
+ student_logits: torch.Tensor
126
+ teacher_logits: torch.Tensor
127
+
128
+
129
+ def _extract_last_user_text(messages: list[dict[str, Any]]) -> str:
130
+ """Extract the text content from the last user message in a conversational prompt."""
131
+ last_message = messages[-1]
132
+ if last_message.get("role") != "user":
133
+ raise ValueError(
134
+ f"Self-distillation teacher prompt construction expects the conversation to end with a user turn, "
135
+ f"but the last message has role '{last_message.get('role')}'. "
136
+ f"Prompts ending with assistant prefills or tool turns are not supported."
137
+ )
138
+ content = last_message.get("content", "")
139
+ if isinstance(content, list):
140
+ return " ".join(part.get("text", "") for part in content if part.get("type") == "text")
141
+ return content
142
+
143
+
144
+ class SuccessfulRolloutTeacherContextBuilder:
145
+ """Builds teacher contexts from successful rollouts"""
146
+
147
+ def __init__(self, trainer):
148
+ self.trainer = trainer
149
+ self.last_metrics: dict[str, float] = {}
150
+
151
+ def _build_reprompt_text(self, prompt_text: str, solution_text: str, feedback_text: str) -> str:
152
+ return self.trainer.args.reprompt_template.format(
153
+ prompt=prompt_text,
154
+ solution=solution_text,
155
+ feedback=feedback_text,
156
+ )
157
+
158
+ def _tokenize_teacher_messages(
159
+ self, teacher_messages_list: list[str | list[dict[str, Any]]]
160
+ ) -> dict[str, torch.Tensor]:
161
+ device = self.trainer.accelerator.device
162
+ teacher_prompt_ids_list = self.trainer._tokenize_prompts_untruncated(teacher_messages_list)
163
+ teacher_prompt_ids = [
164
+ torch.as_tensor(ids[-self.trainer.args.max_reprompt_len :], device=device)
165
+ for ids in teacher_prompt_ids_list
166
+ ]
167
+ teacher_prompt_mask = [torch.ones(len(ids), dtype=torch.long, device=device) for ids in teacher_prompt_ids]
168
+ return {
169
+ "prompt_ids": pad(
170
+ teacher_prompt_ids, padding_value=self.trainer._tokenizer.pad_token_id, padding_side="left"
171
+ ),
172
+ "prompt_mask": pad(teacher_prompt_mask, padding_value=0, padding_side="left"),
173
+ }
174
+
175
+ def build(
176
+ self,
177
+ output: dict[str, torch.Tensor | Any],
178
+ prompts: list[Any],
179
+ rewards: torch.Tensor,
180
+ feedbacks: list[Any] | None = None,
181
+ ) -> dict[str, torch.Tensor]:
182
+ device = self.trainer.accelerator.device
183
+ mode = "train" if self.trainer.model.training else "eval"
184
+ num_generations = self.trainer.num_generations if mode == "train" else self.trainer.num_generations_eval
185
+ completion_ids = output["completion_ids"]
186
+ completion_mask = output["completion_mask"]
187
+
188
+ num_local = len(prompts)
189
+ process_start = self.trainer.accelerator.process_index * num_local
190
+ process_slice = slice(process_start, process_start + num_local)
191
+
192
+ # Rewards arrive already locally sliced (per-process) from the rollout mixin; re-gather them so
193
+ # the mining loop can find successful rollouts across all processes within each generation group.
194
+ all_rewards = self.trainer.accelerator.gather(rewards)
195
+ # Completion tensors are padded to the local max length per rank; align shapes before gathering.
196
+ # Use separate variables so the original completion_ids/completion_mask stay unpadded for the
197
+ # teacher concat (they must match the student's sequence length for logits_to_keep alignment).
198
+ padded_completion_ids = self.trainer.accelerator.pad_across_processes(
199
+ completion_ids, dim=1, pad_index=self.trainer._tokenizer.pad_token_id
200
+ )
201
+ all_completion_ids = self.trainer.accelerator.gather(padded_completion_ids)
202
+ all_prompts = gather_object(prompts)
203
+ total_samples = all_rewards.shape[0]
204
+ all_feedbacks = gather_object(feedbacks) if feedbacks is not None else [None] * total_samples
205
+
206
+ threshold = self.trainer.args.success_reward_threshold
207
+ dont_reprompt_self = self.trainer.args.dont_reprompt_on_self_success
208
+ feedback_only_without_solution = self.trainer.args.environment_feedback_only_without_solution
209
+ self_distillation_mask = torch.zeros(total_samples, device=device)
210
+ num_with_solution = 0
211
+ num_with_feedback_available = 0
212
+ num_with_feedback_used = 0
213
+ success_group_count = 0
214
+ successful_demo_indices: list[int | None] = [None] * total_samples
215
+ use_feedback_flags: list[bool] = [False] * total_samples
216
+ has_solution_flags: list[bool] = [False] * total_samples
217
+
218
+ for i in range(total_samples):
219
+ group_start = (i // num_generations) * num_generations
220
+ group_end = group_start + num_generations
221
+
222
+ successful = []
223
+ if self.trainer.args.use_successful_as_teacher:
224
+ for j in range(group_start, group_end):
225
+ if dont_reprompt_self and j == i:
226
+ continue
227
+ if all_rewards[j].item() >= threshold:
228
+ successful.append(j)
229
+
230
+ if i % num_generations == 0:
231
+ # Count groups with any successful rollout, ignoring self-exclusion which only
232
+ # affects per-sample teacher assignment, not whether the group has successes.
233
+ group_has_success = any(all_rewards[j].item() >= threshold for j in range(group_start, group_end))
234
+ if group_has_success:
235
+ success_group_count += 1
236
+
237
+ raw_feedback = all_feedbacks[i]
238
+ has_feedback = isinstance(raw_feedback, str) and raw_feedback.strip() != ""
239
+ if has_feedback:
240
+ num_with_feedback_available += 1
241
+
242
+ has_solution = len(successful) > 0
243
+ has_solution_flags[i] = has_solution
244
+ if has_solution:
245
+ successful_demo_indices[i] = successful[0]
246
+ use_feedback = (
247
+ self.trainer.args.include_environment_feedback
248
+ and has_feedback
249
+ and (not feedback_only_without_solution or not has_solution)
250
+ )
251
+ use_feedback_flags[i] = use_feedback
252
+ if use_feedback:
253
+ num_with_feedback_used += 1
254
+ if has_solution or use_feedback:
255
+ self_distillation_mask[i] = 1.0
256
+ if has_solution:
257
+ num_with_solution += 1
258
+
259
+ local_teacher_messages = []
260
+ local_self_distillation_mask = self_distillation_mask[process_slice]
261
+ for global_idx in range(process_start, process_start + num_local):
262
+ original_prompt = all_prompts[global_idx]
263
+ raw_feedback = all_feedbacks[global_idx]
264
+ has_solution = has_solution_flags[global_idx]
265
+ use_feedback = use_feedback_flags[global_idx]
266
+
267
+ if not has_solution and not use_feedback:
268
+ local_teacher_messages.append(original_prompt)
269
+ continue
270
+
271
+ solution_text = ""
272
+ if has_solution:
273
+ demo_idx = successful_demo_indices[global_idx]
274
+ if demo_idx is None:
275
+ raise RuntimeError("Expected a successful demonstration index for an active SDPO teacher prompt.")
276
+ demo_ids = all_completion_ids[demo_idx]
277
+ demo_ids = demo_ids[demo_ids != self.trainer._tokenizer.pad_token_id]
278
+ demo_text = self.trainer.processing_class.decode(demo_ids, skip_special_tokens=True)
279
+
280
+ if self.trainer.args.remove_thinking_from_demonstration:
281
+ demo_text = re.sub(r"<think>.*?</think>", "", demo_text, flags=re.DOTALL).strip()
282
+
283
+ solution_text = self.trainer.args.solution_template.format(successful_previous_attempt=demo_text)
284
+
285
+ feedback_text = ""
286
+ if use_feedback:
287
+ feedback_text = self.trainer.args.feedback_template.format(feedback_raw=raw_feedback)
288
+
289
+ if isinstance(original_prompt, list):
290
+ system_messages = original_prompt[:-1]
291
+ prompt_text = _extract_last_user_text(original_prompt)
292
+ reprompt_text = self._build_reprompt_text(prompt_text, solution_text, feedback_text)
293
+ local_teacher_messages.append(system_messages + [{"role": "user", "content": reprompt_text}])
294
+ else:
295
+ local_teacher_messages.append(self._build_reprompt_text(original_prompt, solution_text, feedback_text))
296
+
297
+ teacher_batch = self._tokenize_teacher_messages(local_teacher_messages)
298
+ teacher_input_ids = torch.cat([teacher_batch["prompt_ids"], completion_ids], dim=1)
299
+ teacher_attention_mask = torch.cat([teacher_batch["prompt_mask"], completion_mask], dim=1)
300
+
301
+ batch_size = total_samples if total_samples > 0 else 1
302
+ num_groups = max(1, total_samples // max(1, num_generations))
303
+ self.last_metrics = {
304
+ "self_distillation/success_group_fraction": success_group_count / num_groups,
305
+ "self_distillation/success_sample_fraction": num_with_solution / batch_size,
306
+ "self_distillation/feedback_available_fraction": num_with_feedback_available / batch_size,
307
+ "self_distillation/feedback_used_fraction": num_with_feedback_used / batch_size,
308
+ "self_distillation/reprompt_sample_fraction": self_distillation_mask.float().mean().item(),
309
+ }
310
+
311
+ return {
312
+ "teacher_input_ids": teacher_input_ids,
313
+ "teacher_attention_mask": teacher_attention_mask,
314
+ "self_distillation_mask": local_self_distillation_mask,
315
+ }
316
+
317
+
318
+ class SDPOTrainer(_BaseTrainer):
319
+ """
320
+ Trainer for Self-Distillation Policy Optimization (SDPO).
321
+
322
+ SDPO augments on-policy optimization with self-distillation from the model's own high-reward trajectories. It
323
+ converts tokenized feedback into a dense learning signal without any external teacher or explicit reward model.
324
+ SDPO treats the current model conditioned on feedback as a self-teacher and distills its feedback-informed
325
+ next-token predictions back into the policy.
326
+ """
327
+
328
+ config_cls = SDPOConfig
329
+ _tag_names = ["trl", "sdpo"]
330
+ _name = "SDPO"
331
+ # docstyle-ignore
332
+ _paper = {
333
+ "title": "Reinforcement Learning via Self-Distillation",
334
+ "id": "2601.20802",
335
+ "citation": textwrap.dedent("""\
336
+ @article{hubotter2026sdpo,
337
+ title = {{Reinforcement Learning via Self-Distillation}},
338
+ author = {Jonas H\\"ubotter and Frederike L\\"ubeck and Lejs Behric and Anton Baumann and Marco Bagatella and Daniel Marta and Ido Hakimi and Idan Shenfeld and Thomas Kleine Buening and Carlos Guestrin and Andreas Krause},
339
+ year = 2026,
340
+ eprint = {arXiv:2601.20802}
341
+ }"""),
342
+ }
343
+
344
+ def __init__(
345
+ self,
346
+ model: str | PreTrainedModel | nn.Module,
347
+ reward_funcs: Any | list[Any] | None = None,
348
+ args: SDPOConfig | None = None,
349
+ train_dataset: Dataset | IterableDataset | None = None,
350
+ eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
351
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
352
+ reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
353
+ callbacks: list[TrainerCallback] | None = None,
354
+ optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
355
+ peft_config=None,
356
+ ):
357
+ if reward_funcs is None or (isinstance(reward_funcs, list) and len(reward_funcs) == 0):
358
+ raise ValueError("`reward_funcs` is required for SDPOTrainer because SDPO must score rollouts.")
359
+ if train_dataset is None:
360
+ raise ValueError("`train_dataset` is required")
361
+
362
+ if isinstance(model, str):
363
+ model_init_kwargs = args.model_init_kwargs or {}
364
+ if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
365
+ model_init_kwargs["device_map"] = None
366
+ model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
367
+ model = create_model_from_path(model, **model_init_kwargs)
368
+ elif args.model_init_kwargs is not None:
369
+ logger.warning(
370
+ "You passed `model_init_kwargs` to the self-distillation config, but `model` is already "
371
+ "instantiated. The `model_init_kwargs` will be ignored."
372
+ )
373
+
374
+ self.model_kwarg_keys = (
375
+ inspect.signature(model.forward).parameters.keys()
376
+ if not hasattr(model, "get_base_model")
377
+ else inspect.signature(model.get_base_model().forward).parameters.keys()
378
+ )
379
+
380
+ if peft_config is None and getattr(model, "peft_config", None) is not None:
381
+ logger.warning(
382
+ "The provided self-distillation student model already contains a PEFT adapter. "
383
+ "This setup is accepted but not directly supported. In particular, `teacher_model_kind='base'` "
384
+ "may refer to the underlying base weights rather than the exact initially loaded student state "
385
+ "including its adapter. For unambiguous teacher behavior, start from a merged/non-adapter model "
386
+ "or manage separate adapters explicitly."
387
+ )
388
+ if peft_config is not None:
389
+ if not is_peft_available():
390
+ raise ImportError(
391
+ "You passed `peft_config` but the `peft` library is not installed. "
392
+ "Install it with `pip install trl[peft]`."
393
+ )
394
+ if not isinstance(peft_config, PeftConfig):
395
+ raise TypeError(
396
+ f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
397
+ f"got {type(peft_config).__name__}."
398
+ )
399
+ if is_peft_model(model):
400
+ raise ValueError(
401
+ "You passed a `PeftModel` instance together with a `peft_config`. Pass either a base "
402
+ "model with `peft_config`, or a pre-wrapped PEFT model."
403
+ )
404
+ if peft_config is not None or (is_peft_available() and getattr(model, "peft_config", None) is not None):
405
+ model = prepare_peft_model(model, peft_config, args)
406
+
407
+ if processing_class is None:
408
+ processing_class = AutoProcessor.from_pretrained(
409
+ get_config_model_id(model.config),
410
+ truncation_side="left",
411
+ padding_side="left",
412
+ trust_remote_code=args.trust_remote_code,
413
+ )
414
+
415
+ if isinstance(processing_class, ProcessorMixin):
416
+ self._tokenizer = processing_class.tokenizer
417
+ elif isinstance(processing_class, PreTrainedTokenizerBase):
418
+ self._tokenizer = processing_class
419
+ else:
420
+ raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
421
+
422
+ if self._tokenizer.pad_token is None:
423
+ self._tokenizer.pad_token = self._tokenizer.eos_token
424
+
425
+ self.max_prompt_length = args.max_prompt_length
426
+ self.max_completion_length = args.max_completion_length
427
+ self.num_generations = args.num_generations
428
+ self.num_generations_eval = args.num_generations_eval or args.num_generations
429
+ self.num_iterations = args.num_iterations
430
+ self.shuffle_dataset = args.shuffle_dataset
431
+ self.loss_type = args.loss_type
432
+ self.mask_truncated_completions = args.mask_truncated_completions
433
+ self.temperature = args.temperature
434
+ self.use_vllm = args.use_vllm
435
+ self.chat_template_kwargs = args.chat_template_kwargs or {}
436
+ self._step = 0
437
+ self._buffered_inputs = None
438
+ self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
439
+ self._diagnostic_counters = {
440
+ "train": defaultdict(int),
441
+ "eval": defaultdict(int),
442
+ }
443
+
444
+ self.generation_kwargs = {
445
+ "max_new_tokens": self.max_completion_length,
446
+ "do_sample": True,
447
+ "pad_token_id": self._tokenizer.pad_token_id,
448
+ "bos_token_id": self._tokenizer.bos_token_id,
449
+ "eos_token_id": self._tokenizer.eos_token_id,
450
+ "temperature": args.temperature,
451
+ "top_p": args.top_p,
452
+ "top_k": args.top_k,
453
+ "min_p": args.min_p,
454
+ "repetition_penalty": args.repetition_penalty,
455
+ "cache_implementation": args.cache_implementation,
456
+ }
457
+ if args.generation_kwargs is not None:
458
+ self.generation_kwargs.update(args.generation_kwargs)
459
+ self.generation_config = GenerationConfig(**self.generation_kwargs, disable_compile=True)
460
+
461
+ if hasattr(model, "warnings_issued"):
462
+ model.warnings_issued["estimate_tokens"] = True
463
+
464
+ # Teacher logprobs from the running vLLM generation server (reuses the synced student weights) instead of a
465
+ # local teacher forward. MVP: `live` teacher only — the generation server holds the current student weights.
466
+ self.use_teacher_server = args.use_teacher_server
467
+ if self.use_teacher_server:
468
+ if not (args.use_vllm and args.vllm_mode == "server"):
469
+ raise ValueError(
470
+ "`use_teacher_server=True` requires `use_vllm=True` and `vllm_mode='server'`: teacher logprobs are "
471
+ "served by the same vLLM server used for generation."
472
+ )
473
+ if args.teacher_model_kind != "live":
474
+ raise ValueError(
475
+ "`use_teacher_server=True` only supports `teacher_model_kind='live'` (the generation server holds "
476
+ f"the current student weights), got {args.teacher_model_kind!r}."
477
+ )
478
+ if args.distillation_weight != 1.0:
479
+ raise ValueError(
480
+ "`use_teacher_server=True` only supports pure self-distillation with `distillation_weight=1.0`, "
481
+ f"got {args.distillation_weight}. A convex blend with the policy loss needs the full-vocabulary "
482
+ "logits, which the server does not return."
483
+ )
484
+ if args.distillation_mode not in ("sampled_token", "topk_logits"):
485
+ raise ValueError(
486
+ "`use_teacher_server=True` only supports `distillation_mode` in {'sampled_token', 'topk_logits'}, "
487
+ f"got {args.distillation_mode!r}. The server returns the teacher's top-k logprobs, not the full "
488
+ "vocabulary, so `full_logits` is unavailable. Note `topk_logits` distills over the teacher's own "
489
+ "top-k support (the server cannot score the student's top-k indices)."
490
+ )
491
+ if args.use_liger_kernel:
492
+ raise ValueError(
493
+ "`use_teacher_server=True` is incompatible with `use_liger_kernel`: the server returns top-k "
494
+ "logprobs while the Liger fused loss needs full-vocabulary hidden states."
495
+ )
496
+ # Liger fused JSD loss for `full_logits`: same generalized JSD as `compute_divergence`, so alpha maps to beta.
497
+ self.use_liger_loss = False
498
+ if args.use_liger_kernel:
499
+ if not is_liger_kernel_available():
500
+ raise ImportError(
501
+ "Liger is required to use `use_liger_kernel` as the self-distillation loss. Run "
502
+ "`pip install liger-kernel`."
503
+ )
504
+ if args.distillation_weight != 1.0:
505
+ raise ValueError(
506
+ "`use_liger_kernel` only supports pure self-distillation with `distillation_weight=1.0`, got "
507
+ f"{args.distillation_weight}. A convex blend with the policy loss needs the policy-gradient term, "
508
+ "so the fused distillation kernel offers no benefit there."
509
+ )
510
+ if args.distillation_mode != "full_logits":
511
+ raise ValueError(
512
+ "`use_liger_kernel` only supports `distillation_mode='full_logits'`, got "
513
+ f"{args.distillation_mode!r}. The fused JSD kernel operates on the full vocabulary and cannot "
514
+ "express the top-k support or sampled-token objectives."
515
+ )
516
+ if args.distillation_is_clip is not None:
517
+ raise ValueError(
518
+ "`use_liger_kernel` is incompatible with `distillation_is_clip`: the fused kernel does not expose "
519
+ "per-token losses for importance-sampling clipping."
520
+ )
521
+ if args.loss_type != "bnpo":
522
+ logger.warning(
523
+ "The Liger fused loss reduces with a token-level mean (equivalent to `loss_type='bnpo'`); the "
524
+ f"configured `loss_type={args.loss_type!r}` is ignored on the Liger path."
525
+ )
526
+ self.liger_jsd_loss = LigerFusedLinearJSDLoss(
527
+ beta=args.distillation_alpha,
528
+ ignore_index=-100,
529
+ temperature=args.temperature,
530
+ compiled=False,
531
+ weight_hard_loss=0.0,
532
+ weight_soft_loss=1.0,
533
+ )
534
+ self._forward_redirection = _ForwardRedirection()
535
+ self.use_liger_loss = True
536
+
537
+ super().__init__(
538
+ model=model,
539
+ args=args,
540
+ data_collator=identity,
541
+ train_dataset=train_dataset,
542
+ eval_dataset=eval_dataset,
543
+ processing_class=processing_class,
544
+ callbacks=callbacks,
545
+ optimizers=optimizers,
546
+ compute_loss_func="non-None value to disable scaling",
547
+ )
548
+
549
+ self._last_loaded_step = -1 if self.use_vllm else 0
550
+ if self.use_vllm:
551
+ from ...generation.vllm_generation import VLLMGeneration
552
+
553
+ self.vllm_generation = VLLMGeneration(
554
+ model=self.model,
555
+ accelerator=self.accelerator,
556
+ processing_class=self.processing_class,
557
+ mode=args.vllm_mode,
558
+ server_base_url=args.vllm_server_base_url,
559
+ server_host=args.vllm_server_host,
560
+ server_port=args.vllm_server_port,
561
+ group_port=args.vllm_group_port,
562
+ server_timeout=args.vllm_server_timeout,
563
+ tensor_parallel_size=args.vllm_tensor_parallel_size,
564
+ gpu_memory_utilization=args.vllm_gpu_memory_utilization,
565
+ max_model_length=args.vllm_max_model_length,
566
+ max_num_seqs=args.per_device_train_batch_size
567
+ * args.vllm_tensor_parallel_size
568
+ * args.steps_per_generation,
569
+ enable_sleep_mode=args.vllm_enable_sleep_mode,
570
+ model_impl=args.vllm_model_impl,
571
+ repetition_penalty=args.repetition_penalty,
572
+ temperature=self.temperature,
573
+ top_p=args.top_p,
574
+ top_k=args.top_k,
575
+ min_p=args.min_p,
576
+ max_completion_length=self.max_completion_length,
577
+ logprobs=None,
578
+ generation_kwargs=args.generation_kwargs,
579
+ )
580
+
581
+ # Per-rank read-only client to the same generation server for teacher scoring (weights are synced there by
582
+ # `VLLMGeneration`; scoring needs no weight-update communicator). Mirrors the distillation trainer's
583
+ # `teacher_client`.
584
+ self.teacher_client = None
585
+ if self.use_teacher_server:
586
+ from ...generation.vllm_client import VLLMClient
587
+
588
+ base_url = args.vllm_server_base_url or f"http://{args.vllm_server_host}:{args.vllm_server_port}"
589
+ self.teacher_client = VLLMClient(base_url=base_url, connection_timeout=args.vllm_server_timeout)
590
+
591
+ if args.disable_dropout:
592
+ disable_dropout_in_model(self.model)
593
+
594
+ if hasattr(self.model, "add_model_tags"):
595
+ self.model.add_model_tags(self._tag_names)
596
+
597
+ self._setup_teacher_model()
598
+ self.model_accepts_loss_kwargs = False
599
+
600
+ self.importance_sampling_level = args.importance_sampling_level
601
+ self.scale_rewards = args.scale_rewards
602
+ self.epsilon_low = args.epsilon
603
+ self.epsilon_high = args.epsilon_high
604
+ self.beta = args.beta
605
+
606
+ if not isinstance(reward_funcs, list):
607
+ reward_funcs = [reward_funcs]
608
+ self.reward_func_names = []
609
+ for i, reward_func in enumerate(reward_funcs):
610
+ if isinstance(reward_func, str):
611
+ reward_model_init_kwargs = args.model_init_kwargs or {}
612
+ if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
613
+ reward_model_init_kwargs["device_map"] = None
614
+ reward_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
615
+ reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained(
616
+ reward_func,
617
+ num_labels=1,
618
+ **reward_model_init_kwargs,
619
+ )
620
+ if isinstance(reward_funcs[i], nn.Module):
621
+ self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1])
622
+ else:
623
+ self.reward_func_names.append(reward_funcs[i].__name__)
624
+ self.reward_funcs = reward_funcs
625
+
626
+ if args.reward_weights is not None:
627
+ if len(args.reward_weights) != len(self.reward_funcs):
628
+ raise ValueError("Number of reward weights must match number of reward functions")
629
+ self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32)
630
+ else:
631
+ self.reward_weights = torch.ones(len(self.reward_funcs), dtype=torch.float32)
632
+
633
+ if reward_processing_classes is None:
634
+ reward_processing_classes = [None] * len(self.reward_funcs)
635
+ elif not isinstance(reward_processing_classes, list):
636
+ reward_processing_classes = [reward_processing_classes]
637
+ if len(reward_processing_classes) != len(self.reward_funcs):
638
+ raise ValueError("Number of reward processing classes must match number of reward functions")
639
+
640
+ for i, (reward_processing_class, reward_func) in enumerate(
641
+ zip(reward_processing_classes, self.reward_funcs, strict=True)
642
+ ):
643
+ if isinstance(reward_func, PreTrainedModel):
644
+ if reward_processing_class is None:
645
+ reward_processing_class = AutoTokenizer.from_pretrained(
646
+ get_config_model_id(reward_func.config), trust_remote_code=args.trust_remote_code
647
+ )
648
+ if reward_processing_class.pad_token_id is None:
649
+ reward_processing_class.pad_token = reward_processing_class.eos_token
650
+ reward_func.config.pad_token_id = reward_processing_class.pad_token_id
651
+ reward_processing_classes[i] = reward_processing_class
652
+ self.reward_processing_classes = reward_processing_classes
653
+
654
+ for i, reward_func in enumerate(self.reward_funcs):
655
+ if isinstance(reward_func, nn.Module):
656
+ if self.is_deepspeed_enabled:
657
+ self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator)
658
+ elif self.is_fsdp_enabled:
659
+ self.reward_funcs[i] = prepare_fsdp(reward_func, self.accelerator)
660
+ else:
661
+ self.reward_funcs[i] = self.accelerator.prepare_model(reward_func, evaluation_mode=True)
662
+
663
+ self.teacher_context_builder = SuccessfulRolloutTeacherContextBuilder(self)
664
+
665
+ def _set_signature_columns_if_needed(self):
666
+ if self._signature_columns is None:
667
+ self._signature_columns = ["prompt", "privileged_context"]
668
+
669
+ def _dispatch_self_distillation_callback(self, event_name: str, **payload) -> None:
670
+ for callback in self.callback_handler.callbacks:
671
+ callback_fn = getattr(callback, event_name, None)
672
+ if callback_fn is not None:
673
+ callback_fn(
674
+ args=self.args,
675
+ state=self.state,
676
+ control=self.control,
677
+ model=self.model,
678
+ processing_class=self.processing_class,
679
+ **payload,
680
+ )
681
+
682
+ def _setup_teacher_model(self) -> None:
683
+ """Prepare teacher state according to the semantic teacher choice.
684
+
685
+ Resolve `teacher_model_kind` × PEFT state into the effective teacher:
686
+
687
+ - `"live"` (any model):
688
+ Teacher is the student. No divergence, no callback.
689
+ - `"base"` + PEFT model:
690
+ Teacher reuses `self.model`; the base weights are recovered downstream by disabling the adapter via
691
+ `use_adapter` during teacher forward.
692
+ - `"base"` + non-PEFT model:
693
+ Teacher is a frozen deepcopy of the initial student (falls through to the copy branch below).
694
+ - `"ema"` + pure-LoRA training:
695
+ Teacher reuses `self.model`; a dedicated `"teacher"` LoRA adapter is attached and updated by
696
+ `PEFTAdapterEMACallback`. Teacher forward switches to that adapter downstream.
697
+ - `"ema"` (otherwise):
698
+ Teacher is a frozen deepcopy synchronized each step by `SyncTeacherModelCallback`.
699
+
700
+ Must be called after `super().__init__` so that `self.callback_handler` is available.
701
+ """
702
+
703
+ teacher_model_kind = self.args.teacher_model_kind
704
+
705
+ if teacher_model_kind == "live":
706
+ self.teacher_model = self.model
707
+ return
708
+
709
+ if teacher_model_kind == "base" and is_peft_model(self.model):
710
+ self.teacher_model = self.model
711
+ return
712
+
713
+ if self._use_peft_ema_teacher_adapter():
714
+ # Must run after super().__init__ so self.callback_handler exists.
715
+ self.add_callback(
716
+ PEFTAdapterEMACallback(
717
+ model=self.model,
718
+ teacher_adapter_name="teacher",
719
+ update_rate=self.args.teacher_update_rate,
720
+ sync_steps=self.args.teacher_sync_steps,
721
+ accelerator=self.accelerator,
722
+ )
723
+ )
724
+ self.teacher_model = self.model
725
+ return
726
+
727
+ if is_peft_model(self.model):
728
+ raise ValueError(
729
+ "`teacher_model_kind='ema'` with a non-pure-LoRA PEFT model is not supported: the separate EMA "
730
+ "teacher cannot be parameter-matched to the PEFT student. Use pure-LoRA training, a non-PEFT model, "
731
+ "or `teacher_model_kind` in {'live', 'base'}."
732
+ )
733
+
734
+ # Build the teacher from the model path (like the GRPO/DPO reference model) rather than deep-copying the
735
+ # student: under ZeRO-3 the student params are already sharded, so a deep copy would clone empty shards.
736
+ model_init_kwargs = self.args.model_init_kwargs or {}
737
+ if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
738
+ model_init_kwargs["device_map"] = None
739
+ model_init_kwargs.setdefault("trust_remote_code", self.args.trust_remote_code)
740
+ self.teacher_model = create_model_from_path(get_config_model_id(self.model.config), **model_init_kwargs)
741
+ self.teacher_model.requires_grad_(False)
742
+ self.teacher_model.eval()
743
+ if self.is_deepspeed_enabled:
744
+ self.teacher_model = prepare_deepspeed(self.teacher_model, self.accelerator)
745
+ elif self.is_fsdp_enabled:
746
+ self.teacher_model = prepare_fsdp(self.teacher_model, self.accelerator)
747
+ else:
748
+ self.teacher_model = self.accelerator.prepare_model(self.teacher_model, evaluation_mode=True)
749
+
750
+ if teacher_model_kind == "ema":
751
+ self.add_callback(SyncTeacherModelCallback(teacher_model=self.teacher_model, accelerator=self.accelerator))
752
+
753
+ def _use_peft_ema_teacher_adapter(self) -> bool:
754
+ return self.args.teacher_model_kind == "ema" and is_pure_lora_training(self.model, self.accelerator)
755
+
756
+ def get_train_dataloader(self):
757
+ if self.train_dataset is None:
758
+ raise ValueError("Trainer: training requires a train_dataset.")
759
+
760
+ train_dataset = self.train_dataset
761
+ data_collator = self.data_collator
762
+ if is_datasets_available() and isinstance(train_dataset, datasets.Dataset):
763
+ train_dataset = self._remove_unused_columns(train_dataset, description="training")
764
+ else:
765
+ data_collator = self._get_collator_with_removed_columns(data_collator, description="training")
766
+
767
+ dataloader_params = {
768
+ "batch_size": self._train_batch_size * self.args.steps_per_generation,
769
+ "collate_fn": data_collator,
770
+ "num_workers": self.args.dataloader_num_workers,
771
+ "pin_memory": self.args.dataloader_pin_memory,
772
+ "persistent_workers": self.args.dataloader_persistent_workers,
773
+ }
774
+ if not isinstance(train_dataset, torch.utils.data.IterableDataset):
775
+ dataloader_params["sampler"] = self._get_train_sampler()
776
+ dataloader_params["drop_last"] = self.args.dataloader_drop_last
777
+ dataloader_params["worker_init_fn"] = partial(
778
+ seed_worker, num_workers=self.args.dataloader_num_workers, rank=self.args.process_index
779
+ )
780
+ dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor
781
+ return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params))
782
+
783
+ def _get_train_sampler(self, dataset=None) -> Sampler:
784
+ if dataset is None:
785
+ dataset = self.train_dataset
786
+ return RepeatSampler(
787
+ data_source=dataset,
788
+ mini_repeat_count=self.num_generations,
789
+ batch_size=self.args.generation_batch_size // self.num_generations,
790
+ repeat_count=self.num_iterations * self.args.steps_per_generation,
791
+ shuffle=self.shuffle_dataset,
792
+ seed=self.args.seed,
793
+ )
794
+
795
+ def _get_eval_sampler(self, eval_dataset) -> Sampler:
796
+ return RepeatSampler(
797
+ data_source=eval_dataset,
798
+ mini_repeat_count=self.num_generations_eval,
799
+ seed=self.args.seed,
800
+ )
801
+
802
+ def training_step(self, model, inputs, num_items_in_batch):
803
+ # Gather spans forward+backward: the fused JSD computes the lm_head grad in backward.
804
+ with self._get_liger_zero3_lm_head_gather_ctx(model):
805
+ output = super().training_step(model, inputs, num_items_in_batch)
806
+ self._step += 1
807
+ return output
808
+
809
+ def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None):
810
+ if not isinstance(inputs, dict):
811
+ inputs = self._prepare_inputs(inputs)
812
+ with torch.no_grad():
813
+ with self.compute_loss_context_manager():
814
+ loss = self.compute_loss(model, inputs)
815
+ return loss.detach(), None, None
816
+
817
+ def _prepare_inputs(self, generation_batch):
818
+ """Return the per-step training batch, regenerating rollouts and buffering them for reuse in train mode.
819
+
820
+ In train mode, rollouts are generated once every `steps_per_generation * num_iterations` steps and split into
821
+ per-step slices reused until the next regeneration. In eval mode, every batch is freshly prepared.
822
+ """
823
+ mode = "train" if self.model.training else "eval"
824
+ if mode == "train":
825
+ generate_every = self.args.steps_per_generation * self.num_iterations
826
+ if self._step % generate_every == 0 or self._buffered_inputs is None:
827
+ buffered_batch = self._prepare_training_batch(generation_batch)
828
+ self._buffered_inputs = split_tensor_dict(buffered_batch, self.args.steps_per_generation)
829
+ self._dispatch_self_distillation_callback(
830
+ "on_generation_batch_built",
831
+ generate_every=generate_every,
832
+ steps_per_generation=self.args.steps_per_generation,
833
+ )
834
+ return self._buffered_inputs[self._step % self.args.steps_per_generation]
835
+ return self._prepare_training_batch(generation_batch)
836
+
837
+ def _prepare_training_batch(self, inputs: list[dict[str, Any]]) -> TrainingBatch:
838
+ """Sample student rollouts, calculate advantage and construct teacher prompts"""
839
+ device = self.accelerator.device
840
+ mode = "train" if self.model.training else "eval"
841
+
842
+ # Generate student rollouts and decode completions for reward functions
843
+ batch = self.sample_rollouts(inputs)
844
+ prompts = [example["prompt"] for example in inputs]
845
+ privileged_contexts = [example.get("privileged_context") for example in inputs]
846
+ completion_ids_list = self._get_completion_ids_list(batch)
847
+ if is_conversational({"prompt": prompts[0]}):
848
+ completions_text = self.processing_class.batch_decode(batch["completion_ids"], skip_special_tokens=True)
849
+ completions = [[{"role": "assistant", "content": content}] for content in completions_text]
850
+ else:
851
+ completions = self.processing_class.batch_decode(batch["completion_ids"], skip_special_tokens=True)
852
+
853
+ # Compute rewards over the globally gathered rollout batch
854
+ rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
855
+ if rewards_per_func.numel() == 0:
856
+ rewards = torch.zeros(self.accelerator.num_processes * len(prompts), device=device)
857
+ else:
858
+ rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
859
+
860
+ # Normalize rewards within generation groups to produce local policy advantages
861
+ num_generations = self.num_generations if mode == "train" else self.num_generations_eval
862
+ mean_grouped_rewards = rewards.view(-1, num_generations).mean(dim=1).repeat_interleave(num_generations, dim=0)
863
+ if self.scale_rewards == "batch":
864
+ std_rewards = rewards.std().expand_as(rewards) if rewards.numel() > 1 else torch.zeros_like(rewards)
865
+ group_std_rewards = rewards.view(-1, num_generations).std(dim=1)
866
+ elif self.scale_rewards == "none":
867
+ std_rewards = torch.ones_like(rewards)
868
+ group_std_rewards = torch.ones(rewards.numel() // num_generations, device=device, dtype=rewards.dtype)
869
+ else:
870
+ group_std_rewards = rewards.view(-1, num_generations).std(dim=1)
871
+ std_rewards = group_std_rewards.repeat_interleave(num_generations, dim=0)
872
+ advantages = (rewards - mean_grouped_rewards) / (std_rewards + 1e-4)
873
+ local_batch_size = batch["completion_ids"].size(0)
874
+ process_start = self.accelerator.process_index * local_batch_size
875
+ process_slice = slice(process_start, process_start + local_batch_size)
876
+ local_rewards = rewards[process_slice]
877
+ local_advantages = advantages[process_slice]
878
+
879
+ self._record_reward_diagnostics(mode, rewards, rewards_per_func, group_std_rewards)
880
+ self._record_completion_metrics(mode, batch)
881
+
882
+ batch["rewards"] = local_rewards
883
+ batch["advantages"] = local_advantages
884
+ teacher_context = self.teacher_context_builder.build(
885
+ batch,
886
+ prompts,
887
+ batch["rewards"],
888
+ feedbacks=privileged_contexts,
889
+ )
890
+
891
+ for key, value in self.teacher_context_builder.last_metrics.items():
892
+ self._metrics[mode][key].append(value)
893
+ self._warn_on_inactive_self_distillation(mode)
894
+
895
+ self._dispatch_self_distillation_callback(
896
+ "on_teacher_context_built",
897
+ teacher_input_ids=teacher_context["teacher_input_ids"],
898
+ teacher_attention_mask=teacher_context["teacher_attention_mask"],
899
+ completion_mask=batch["completion_mask"],
900
+ self_distillation_mask=teacher_context["self_distillation_mask"],
901
+ )
902
+
903
+ batch.update(
904
+ {
905
+ "teacher_input_ids": teacher_context["teacher_input_ids"],
906
+ "teacher_attention_mask": teacher_context["teacher_attention_mask"],
907
+ "self_distillation_mask": teacher_context["self_distillation_mask"],
908
+ }
909
+ )
910
+
911
+ self._dispatch_self_distillation_callback(
912
+ "on_self_distillation_batch_prepared",
913
+ old_per_token_logps=batch.get("old_per_token_logps"),
914
+ prompt_ids=batch["prompt_ids"],
915
+ completion_ids=batch["completion_ids"],
916
+ teacher_input_ids=batch["teacher_input_ids"],
917
+ teacher_attention_mask=batch["teacher_attention_mask"],
918
+ self_distillation_mask=batch.get("self_distillation_mask"),
919
+ )
920
+ return batch
921
+
922
+ def sample_rollouts(self, inputs: list[dict[str, Any]]) -> TrainingBatch:
923
+ """Generate completions for a batch of prompts and assemble the training batch."""
924
+ prompts = [example["prompt"] for example in inputs]
925
+ prompt_ids = self._tokenize_prompts(prompts)
926
+ self._dispatch_self_distillation_callback(
927
+ "on_generation_prompts_selected",
928
+ generation_prompts=prompts,
929
+ generation_prompt_text=None,
930
+ )
931
+
932
+ prompt_ids_list, completion_ids_list = self._generate(prompt_ids)
933
+ device = self.accelerator.device
934
+ prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list]
935
+ prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids]
936
+ prompt_ids = pad(prompt_ids, padding_value=self._tokenizer.pad_token_id, padding_side="left").to(device=device)
937
+ prompt_mask = pad(prompt_mask, padding_value=0, padding_side="left").to(device=device)
938
+
939
+ completion_ids = [torch.tensor(ids) for ids in completion_ids_list]
940
+ completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids]
941
+ completion_ids = pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right").to(
942
+ device=device
943
+ )
944
+ completion_mask = pad(completion_mask, padding_value=0, padding_side="right").to(device=device)
945
+
946
+ if self.mask_truncated_completions:
947
+ eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id]
948
+ is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device)
949
+ completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int()
950
+
951
+ old_per_token_logps = self._compute_rollout_logps(
952
+ prompt_ids=prompt_ids,
953
+ prompt_mask=prompt_mask,
954
+ completion_ids=completion_ids,
955
+ completion_mask=completion_mask,
956
+ )
957
+ batch: TrainingBatch = {
958
+ "prompt_ids": prompt_ids,
959
+ "prompt_mask": prompt_mask,
960
+ "completion_ids": completion_ids,
961
+ "completion_mask": completion_mask,
962
+ "raw_completion_lengths": torch.tensor(
963
+ [len(ids) for ids in completion_ids_list], device=device, dtype=torch.long
964
+ ),
965
+ }
966
+ if old_per_token_logps is not None:
967
+ batch["old_per_token_logps"] = old_per_token_logps
968
+ return batch
969
+
970
+ def _get_completion_ids_list(self, batch: TrainingBatch) -> list[list[int]]:
971
+ raw_completion_lengths = batch["raw_completion_lengths"].detach().cpu().tolist()
972
+ return [
973
+ ids[:length].tolist()
974
+ for ids, length in zip(batch["completion_ids"].detach().cpu(), raw_completion_lengths, strict=True)
975
+ ]
976
+
977
+ def _tokenize_prompts_untruncated(self, prompts: list[Any]) -> list[list[int]]:
978
+ if is_conversational({"prompt": prompts[0]}):
979
+ tokenized = self.processing_class.apply_chat_template(
980
+ conversation=prompts,
981
+ add_generation_prompt=True,
982
+ tokenize=True,
983
+ return_dict=True,
984
+ **self.chat_template_kwargs,
985
+ )
986
+ prompt_ids = tokenized["input_ids"]
987
+ else:
988
+ prompt_ids = self.processing_class(text=prompts)["input_ids"]
989
+ return prompt_ids
990
+
991
+ def _tokenize_prompts(self, prompts: list[Any]) -> list[list[int]]:
992
+ prompt_ids = self._tokenize_prompts_untruncated(prompts)
993
+ if self.max_prompt_length is not None:
994
+ prompt_ids = [ids[-self.max_prompt_length :] for ids in prompt_ids]
995
+ return prompt_ids
996
+
997
+ def _generate(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]:
998
+ if self.use_vllm:
999
+ return self._generate_vllm(prompt_ids)
1000
+ return self._generate_transformers(prompt_ids)
1001
+
1002
+ def _generate_vllm(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]:
1003
+ if self.state.global_step != self._last_loaded_step:
1004
+ self.vllm_generation.sync_weights()
1005
+ self._last_loaded_step = self.state.global_step
1006
+
1007
+ mode = "train" if self.model.training else "eval"
1008
+ num_generations = self.num_generations if mode == "train" else self.num_generations_eval
1009
+ prompt_ids_out, completion_ids_list, _, _ = self.vllm_generation.generate(
1010
+ prompts=prompt_ids,
1011
+ images=None,
1012
+ num_generations=num_generations,
1013
+ )
1014
+ return prompt_ids_out, completion_ids_list
1015
+
1016
+ def _generate_transformers(self, prompt_ids: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]:
1017
+ device = self.accelerator.device
1018
+ prompt_tensors = [torch.tensor(ids) for ids in prompt_ids]
1019
+ padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left").to(
1020
+ device=device
1021
+ )
1022
+ attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left").to(
1023
+ device=device
1024
+ )
1025
+ generate_inputs: dict[str, torch.Tensor | Any] = {"input_ids": padded_ids, "attention_mask": attention_mask}
1026
+
1027
+ with (
1028
+ unwrap_model_for_generation(
1029
+ self.model_wrapped,
1030
+ self.accelerator,
1031
+ gather_deepspeed3_params=self.args.ds3_gather_for_generation,
1032
+ generation_kwargs=self.generation_kwargs,
1033
+ ) as unwrapped_model,
1034
+ torch.no_grad(),
1035
+ FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(),
1036
+ ):
1037
+ prompt_completion_ids = unwrapped_model.generate(
1038
+ **generate_inputs, generation_config=self.generation_config
1039
+ )
1040
+
1041
+ prompt_length = generate_inputs["input_ids"].size(1)
1042
+ completion_ids = prompt_completion_ids[:, prompt_length:]
1043
+ is_eos = completion_ids == self._tokenizer.eos_token_id
1044
+ eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device)
1045
+ eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)]
1046
+ seq_idx = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1)
1047
+ completion_mask = (seq_idx <= eos_idx.unsqueeze(1)).int()
1048
+ completion_ids_list = [
1049
+ c[m].tolist() for c, m in zip(completion_ids.cpu(), completion_mask.bool().cpu(), strict=True)
1050
+ ]
1051
+ return prompt_ids, completion_ids_list
1052
+
1053
+ def _compute_rollout_logps(
1054
+ self,
1055
+ prompt_ids: torch.Tensor,
1056
+ prompt_mask: torch.Tensor,
1057
+ completion_ids: torch.Tensor,
1058
+ completion_mask: torch.Tensor,
1059
+ ) -> torch.Tensor | None:
1060
+ generate_every = self.args.steps_per_generation * self.num_iterations
1061
+ old_per_token_logps = None
1062
+
1063
+ if self.args.gradient_accumulation_steps % generate_every != 0:
1064
+ prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1)
1065
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
1066
+ logits_to_keep = completion_ids.size(1)
1067
+ with torch.no_grad():
1068
+ logits = self._forward_logits(
1069
+ self.model,
1070
+ prompt_completion_ids,
1071
+ attention_mask,
1072
+ logits_to_keep,
1073
+ )
1074
+ old_per_token_logps = selective_log_softmax(logits, completion_ids)
1075
+
1076
+ return old_per_token_logps
1077
+
1078
+ def _calculate_rewards(self, inputs, prompts, completions, completion_ids_list):
1079
+ device = self.accelerator.device
1080
+ if len(self.reward_funcs) == 0:
1081
+ return torch.zeros((len(prompts), 0), device=device)
1082
+
1083
+ rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device)
1084
+ keys = [key for key in inputs[0] if key not in ["prompt", "completion", "completion_ids"]]
1085
+ reward_kwargs = {key: [example[key] for example in inputs] for key in keys}
1086
+ reward_kwargs["trainer_state"] = self.state
1087
+
1088
+ for i, (reward_func, reward_processing_class) in enumerate(
1089
+ zip(self.reward_funcs, self.reward_processing_classes, strict=True)
1090
+ ):
1091
+ if isinstance(reward_func, nn.Module):
1092
+ if is_conversational(inputs[0]):
1093
+ messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)]
1094
+ texts = [
1095
+ apply_chat_template(x, reward_processing_class, **self.chat_template_kwargs)["text"]
1096
+ for x in messages
1097
+ ]
1098
+ else:
1099
+ texts = [p + c for p, c in zip(prompts, completions, strict=True)]
1100
+ reward_inputs = reward_processing_class(
1101
+ text=texts,
1102
+ return_tensors="pt",
1103
+ padding=True,
1104
+ padding_side="right",
1105
+ add_special_tokens=False,
1106
+ )
1107
+ reward_inputs = _BaseTrainer._prepare_inputs(self, reward_inputs)
1108
+ with torch.inference_mode():
1109
+ rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0]
1110
+ else:
1111
+ output_reward_func = reward_func(
1112
+ prompts=prompts,
1113
+ completions=completions,
1114
+ completion_ids=completion_ids_list,
1115
+ **reward_kwargs,
1116
+ )
1117
+ output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func]
1118
+ rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device)
1119
+
1120
+ return self.accelerator.gather(rewards_per_func)
1121
+
1122
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
1123
+ if return_outputs:
1124
+ raise ValueError("The SDPOTrainer does not support returning outputs")
1125
+
1126
+ if self.args.distillation_weight == 1.0:
1127
+ if self.use_teacher_server:
1128
+ loss = self._compute_server_distillation_loss(model, inputs)
1129
+ elif self.use_liger_loss:
1130
+ accumulation_scale = self.current_gradient_accumulation_steps if self.model.training else 1.0
1131
+ return self._compute_liger_loss(model, inputs) / accumulation_scale
1132
+ else:
1133
+ distillation_logits = self._compute_teacher_student_logits(model, self.teacher_model, inputs)
1134
+ loss = self._compute_self_distillation_loss(model, inputs, distillation_logits)
1135
+ elif self.args.distillation_weight == 0.0:
1136
+ student_input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1)
1137
+ student_attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1)
1138
+ student_logits = self._forward_logits(
1139
+ model=model,
1140
+ input_ids=student_input_ids,
1141
+ attention_mask=student_attention_mask,
1142
+ logits_to_keep=inputs["completion_ids"].size(1),
1143
+ )
1144
+ loss = self._compute_policy_loss(inputs, student_logits)
1145
+ else:
1146
+ distillation_logits = self._compute_teacher_student_logits(model, self.teacher_model, inputs)
1147
+ policy_loss = self._compute_policy_loss(inputs, distillation_logits.student_logits)
1148
+ distillation_loss = self._compute_self_distillation_loss(model, inputs, distillation_logits)
1149
+ loss = (
1150
+ 1 - self.args.distillation_weight
1151
+ ) * policy_loss + self.args.distillation_weight * distillation_loss
1152
+
1153
+ accumulation_scale = self.current_gradient_accumulation_steps if self.model.training else 1.0
1154
+ return loss / accumulation_scale
1155
+
1156
+ def _compute_policy_loss(
1157
+ self,
1158
+ inputs,
1159
+ student_logits,
1160
+ ) -> torch.Tensor:
1161
+ completion_ids = inputs["completion_ids"]
1162
+ completion_mask = inputs["completion_mask"]
1163
+ per_token_logps = selective_log_softmax(student_logits, completion_ids)
1164
+ old_per_token_logps = inputs.get("old_per_token_logps")
1165
+ old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps
1166
+ advantages = inputs["advantages"]
1167
+ if advantages.dim() == 1:
1168
+ advantages = advantages.unsqueeze(1)
1169
+ log_ratio = per_token_logps - old_per_token_logps
1170
+ if self.importance_sampling_level == "sequence":
1171
+ log_ratio = (log_ratio * completion_mask).sum(-1, keepdim=True) / completion_mask.sum(
1172
+ -1, keepdim=True
1173
+ ).clamp(min=1.0)
1174
+ coef_1 = torch.exp(log_ratio)
1175
+ coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
1176
+ per_token_loss = -torch.min(coef_1 * advantages, coef_2 * advantages)
1177
+
1178
+ if self.loss_type == "grpo":
1179
+ loss = (per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)
1180
+ loss = loss.mean()
1181
+ elif self.loss_type == "bnpo":
1182
+ loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0)
1183
+ elif self.loss_type == "dr_grpo":
1184
+ loss = (per_token_loss * completion_mask).sum() / (per_token_loss.size(0) * self.max_completion_length)
1185
+ elif self.loss_type == "dapo":
1186
+ loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0)
1187
+ else:
1188
+ raise ValueError(f"Unsupported loss_type: {self.loss_type}")
1189
+
1190
+ mode = "train" if self.model.training else "eval"
1191
+ self._metrics[mode]["self_distillation/policy_loss"].append(
1192
+ self.accelerator.gather(loss.detach()).mean().item()
1193
+ )
1194
+
1195
+ return loss
1196
+
1197
+ def _compute_self_distillation_loss(
1198
+ self,
1199
+ model,
1200
+ inputs: TrainingBatch,
1201
+ distillation_logits: DistillationLogits,
1202
+ ) -> torch.Tensor:
1203
+ """Compute the per-token distillation loss and aggregate by normalizing over sequence length.
1204
+
1205
+ Dispatches between three objectives based on `distillation_mode`:
1206
+
1207
+ - `"topk_logits"`: top-k approximation of the divergence, optionally with a tail bucket for the remaining
1208
+ probability mass (`distillation_add_tail`).
1209
+ - `"full_logits"`: full-vocab divergence.
1210
+ - `"sampled_token"`: token-level (reverse-KL) distillation on sampled `completion_ids`.
1211
+
1212
+ When `distillation_is_clip` is set and `old_per_token_logps` are available, the loss is corrected by a clipped
1213
+ importance-sampling ratio between the current student and the student at rollout time.
1214
+ """
1215
+ if distillation_logits.loss_mask.sum() == 0:
1216
+ mode = "train" if model.training else "eval"
1217
+ self._log_self_distillation_metric(mode, 0.0)
1218
+ # Keep the zero loss attached to the student graph so backward produces zero gradients instead of stopping.
1219
+ return distillation_logits.student_logits.sum() * 0.0
1220
+
1221
+ if self.args.distillation_mode == "topk_logits":
1222
+ if self.args.distillation_topk is None:
1223
+ raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.")
1224
+ per_token_loss = compute_topk_self_distillation_loss(
1225
+ distillation_logits.student_logits,
1226
+ distillation_logits.teacher_logits,
1227
+ distillation_topk=self.args.distillation_topk,
1228
+ distillation_alpha=self.args.distillation_alpha,
1229
+ distillation_add_tail=self.args.distillation_add_tail,
1230
+ )
1231
+ elif self.args.distillation_mode == "full_logits":
1232
+ per_token_loss = compute_full_logit_self_distillation_loss(
1233
+ distillation_logits.student_logits,
1234
+ distillation_logits.teacher_logits,
1235
+ distillation_alpha=self.args.distillation_alpha,
1236
+ )
1237
+ elif self.args.distillation_mode == "sampled_token":
1238
+ per_token_loss = compute_sampled_token_self_distillation_loss(
1239
+ distillation_logits.student_logits,
1240
+ distillation_logits.teacher_logits,
1241
+ distillation_logits.completion_ids,
1242
+ distillation_alpha=self.args.distillation_alpha,
1243
+ )
1244
+ else:
1245
+ raise ValueError(
1246
+ "distillation_mode must be one of: 'sampled_token', 'full_logits', 'topk_logits', "
1247
+ f"got {self.args.distillation_mode!r}"
1248
+ )
1249
+
1250
+ old_per_token_logps = inputs.get("old_per_token_logps")
1251
+ if self.args.distillation_is_clip is not None and old_per_token_logps is not None:
1252
+ student_per_token_logps = selective_log_softmax(
1253
+ distillation_logits.student_logits,
1254
+ distillation_logits.completion_ids,
1255
+ )
1256
+ per_token_loss = apply_importance_sampling_clipping(
1257
+ per_token_loss,
1258
+ student_per_token_logps,
1259
+ old_per_token_logps,
1260
+ self.args.distillation_is_clip,
1261
+ )
1262
+
1263
+ loss = (per_token_loss * distillation_logits.loss_mask).sum(-1) / distillation_logits.loss_mask.sum(-1).clamp(
1264
+ min=1.0
1265
+ )
1266
+ loss = loss.mean()
1267
+
1268
+ mode = "train" if model.training else "eval"
1269
+ mean_distill_loss = (
1270
+ per_token_loss * distillation_logits.loss_mask
1271
+ ).sum() / distillation_logits.loss_mask.sum().clamp(min=1.0)
1272
+ self._log_self_distillation_metric(
1273
+ mode,
1274
+ self.accelerator.gather(mean_distill_loss).mean().item(),
1275
+ )
1276
+ return loss
1277
+
1278
+ def _compute_server_distillation_loss(self, model, inputs: TrainingBatch) -> torch.Tensor:
1279
+ """Distillation loss with teacher logprobs served by the vLLM generation server (`teacher_model_kind='live'`).
1280
+
1281
+ The student is forwarded locally (grad) for its logits; the teacher logprobs are fetched from the server (no
1282
+ local teacher forward). `sampled_token` distills the realized token (reverse KL); `topk_logits` distills over
1283
+ the teacher's own top-k support (the server cannot score the student's top-k indices).
1284
+ """
1285
+ # Buffered batches are reused across optimizer steps (`num_iterations > 1`), so the server weights can lag the
1286
+ # live student; re-sync before scoring.
1287
+ if self.state.global_step != self._last_loaded_step:
1288
+ self.vllm_generation.sync_weights()
1289
+ # Only the main process pushes weights to the server, so hold every rank here until the push completes;
1290
+ # otherwise non-main ranks could score against half-updated weights.
1291
+ self.accelerator.wait_for_everyone()
1292
+ self._last_loaded_step = self.state.global_step
1293
+
1294
+ completion_ids = inputs["completion_ids"]
1295
+ completion_mask = inputs["completion_mask"]
1296
+ logits_to_keep = completion_ids.size(1)
1297
+
1298
+ self_distillation_mask = inputs.get("self_distillation_mask")
1299
+ if self_distillation_mask is None:
1300
+ loss_mask = completion_mask
1301
+ else:
1302
+ loss_mask = completion_mask * self_distillation_mask.unsqueeze(1)
1303
+
1304
+ student_input_ids = torch.cat([inputs["prompt_ids"], completion_ids], dim=1)
1305
+ student_attention_mask = torch.cat([inputs["prompt_mask"], completion_mask], dim=1)
1306
+ student_logits = self._forward_logits(
1307
+ model=model,
1308
+ input_ids=student_input_ids,
1309
+ attention_mask=student_attention_mask,
1310
+ logits_to_keep=logits_to_keep,
1311
+ )
1312
+
1313
+ mode = "train" if model.training else "eval"
1314
+ teacher = self._get_teacher_token_logprobs_from_server(inputs, logits_to_keep)
1315
+ # Padding positions come back as `-inf`; the masked-out positions are neutralized to finite values below so the
1316
+ # divergence does not leak `+inf` through them (mirrors the distillation trainer).
1317
+ required = loss_mask.bool()
1318
+ student_per_token_logps = selective_log_softmax(student_logits, completion_ids)
1319
+
1320
+ teacher_per_token_logps = teacher["actual_logprobs"]
1321
+ if (required & ~torch.isfinite(teacher_per_token_logps)).any():
1322
+ raise ValueError("Teacher server returned no logprob for a required completion token.")
1323
+ teacher_per_token_logps = torch.where(
1324
+ required, teacher_per_token_logps, torch.zeros_like(teacher_per_token_logps)
1325
+ )
1326
+
1327
+ # Diagnostic for disagreement between local student scores and server teacher scores on realized tokens.
1328
+ # Sudden jumps can indicate stale server weights or numerical drift.
1329
+ abs_diff = ((student_per_token_logps.detach() - teacher_per_token_logps).abs() * loss_mask).sum() / (
1330
+ loss_mask.sum().clamp(min=1.0)
1331
+ )
1332
+ self._metrics[mode]["self_distillation/server_logprob_abs_diff"].append(
1333
+ self.accelerator.gather(abs_diff).mean().item()
1334
+ )
1335
+
1336
+ if self.args.distillation_mode == "sampled_token":
1337
+ # Reverse-KL token-level objective, matching `compute_sampled_token_self_distillation_loss`.
1338
+ per_token_loss = (student_per_token_logps - teacher_per_token_logps).detach() * student_per_token_logps
1339
+ else:
1340
+ teacher_topk_logps = teacher["topk_logprobs"]
1341
+ teacher_topk_ids = teacher["topk_token_ids"]
1342
+ # Project the student onto the teacher's top-k support, then renormalize (or add a tail bucket) before the
1343
+ # divergence, matching `compute_topk_self_distillation_loss` on the teacher's support.
1344
+ keep = required.unsqueeze(-1)
1345
+ student_topk_logps = torch.gather(
1346
+ torch.log_softmax(student_logits, dim=-1), dim=-1, index=teacher_topk_ids
1347
+ )
1348
+ student_topk_logps = torch.where(keep, student_topk_logps, torch.zeros_like(student_topk_logps))
1349
+ teacher_topk_logps = torch.where(keep, teacher_topk_logps, torch.zeros_like(teacher_topk_logps))
1350
+ if self.args.distillation_add_tail:
1351
+ student_topk_logps = add_tail_bucket(student_topk_logps)
1352
+ teacher_topk_logps = add_tail_bucket(teacher_topk_logps)
1353
+ else:
1354
+ student_topk_logps = student_topk_logps - torch.logsumexp(student_topk_logps, dim=-1, keepdim=True)
1355
+ teacher_topk_logps = teacher_topk_logps - torch.logsumexp(teacher_topk_logps, dim=-1, keepdim=True)
1356
+ per_token_loss = compute_divergence(student_topk_logps, teacher_topk_logps, self.args.distillation_alpha)
1357
+
1358
+ old_per_token_logps = inputs.get("old_per_token_logps")
1359
+ if self.args.distillation_is_clip is not None and old_per_token_logps is not None:
1360
+ per_token_loss = apply_importance_sampling_clipping(
1361
+ per_token_loss, student_per_token_logps, old_per_token_logps, self.args.distillation_is_clip
1362
+ )
1363
+
1364
+ loss = (per_token_loss * loss_mask).sum(-1) / loss_mask.sum(-1).clamp(min=1.0)
1365
+ loss = loss.mean()
1366
+ mean_distill_loss = (per_token_loss * loss_mask).sum() / loss_mask.sum().clamp(min=1.0)
1367
+ self._log_self_distillation_metric(mode, self.accelerator.gather(mean_distill_loss).mean().item())
1368
+ return loss
1369
+
1370
+ def _get_teacher_token_logprobs_from_server(
1371
+ self, inputs: TrainingBatch, logits_to_keep: int
1372
+ ) -> dict[str, torch.Tensor]:
1373
+ """Per-token teacher logprobs from the vLLM server.
1374
+
1375
+ Returns a dict with `actual_logprobs` (`(B, T)`, the realized-token logprob for reverse KL) and `topk_logprobs`
1376
+ / `topk_token_ids` (`(B, T, K)`, the teacher's top-k support for top-k logit distillation). Completions are
1377
+ right-padded, so server values fill the leading positions of each row and the trailing padding keeps the `-inf`
1378
+ / `0` sentinels (neutralized by the caller).
1379
+ """
1380
+ import numpy as np
1381
+
1382
+ teacher_input_ids = inputs["teacher_input_ids"]
1383
+ teacher_attention_mask = inputs["teacher_attention_mask"]
1384
+ device = teacher_input_ids.device
1385
+ batch_size = teacher_input_ids.size(0)
1386
+ prompt_attention_mask = teacher_attention_mask[:, : teacher_attention_mask.size(1) - logits_to_keep]
1387
+ if self.args.distillation_mode == "topk_logits" and self.args.distillation_topk is None:
1388
+ raise ValueError("`distillation_mode='topk_logits'` requires `distillation_topk` to be set.")
1389
+ top_logprobs = self.args.distillation_topk if self.args.distillation_mode == "topk_logits" else 1
1390
+
1391
+ sequences, prompt_lengths, _ = build_teacher_request_inputs(
1392
+ teacher_input_ids, teacher_attention_mask, prompt_attention_mask
1393
+ )
1394
+ result = self.teacher_client.get_sequence_logprobs(
1395
+ sequences=sequences,
1396
+ prompt_lengths=prompt_lengths,
1397
+ top_logprobs=top_logprobs,
1398
+ temperature=self.temperature,
1399
+ )
1400
+
1401
+ actual = np.full((batch_size, logits_to_keep), float("-inf"), dtype=np.float32)
1402
+ topk = np.full((batch_size, logits_to_keep, top_logprobs), float("-inf"), dtype=np.float32)
1403
+ topk_ids = np.zeros((batch_size, logits_to_keep, top_logprobs), dtype=np.int64)
1404
+ for i in range(batch_size):
1405
+ seq_actual = result["actual_logprobs"][i]
1406
+ n = min(len(seq_actual), logits_to_keep)
1407
+ if n:
1408
+ actual[i, :n] = np.array(seq_actual, dtype=np.float32)[:n, 0]
1409
+ topk[i, :n] = np.array(result["logprobs"][i], dtype=np.float32)[:n]
1410
+ topk_ids[i, :n] = np.array(result["logprob_token_ids"][i], dtype=np.int64)[:n]
1411
+ return {
1412
+ "actual_logprobs": torch.from_numpy(actual).to(device),
1413
+ "topk_logprobs": torch.from_numpy(topk).to(device),
1414
+ "topk_token_ids": torch.from_numpy(topk_ids).to(device),
1415
+ }
1416
+
1417
+ def _compute_teacher_student_logits(
1418
+ self,
1419
+ model,
1420
+ teacher_model,
1421
+ inputs: TrainingBatch,
1422
+ ) -> DistillationLogits:
1423
+ """Compute the per-token logits of the student and teacher over the completion tokens.
1424
+
1425
+ The student is forwarded on its own input (original prompt plus the sampled completion) while the teacher is
1426
+ forwarded on its input (prompt, privileged context, and the same completion). Both sets of logits are aligned
1427
+ to the completion tokens so they can be compared position-by-position in the distillation loss.
1428
+
1429
+ The teacher forward runs under `torch.no_grad()` and the context resolved by
1430
+ `_get_teacher_context_for_self_distillation`, which routes it to the correct weights.
1431
+ """
1432
+ prompt_ids = inputs["prompt_ids"]
1433
+ prompt_mask = inputs["prompt_mask"]
1434
+ completion_ids = inputs["completion_ids"]
1435
+ completion_mask = inputs["completion_mask"]
1436
+ logits_to_keep = completion_ids.size(1)
1437
+
1438
+ self_distillation_mask = inputs.get("self_distillation_mask")
1439
+ if self_distillation_mask is None:
1440
+ loss_mask = completion_mask
1441
+ else:
1442
+ loss_mask = completion_mask * self_distillation_mask.unsqueeze(1)
1443
+ student_input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
1444
+ student_attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
1445
+ student_logits = self._forward_logits(
1446
+ model=model,
1447
+ input_ids=student_input_ids,
1448
+ attention_mask=student_attention_mask,
1449
+ logits_to_keep=logits_to_keep,
1450
+ )
1451
+
1452
+ with torch.no_grad(), self._get_teacher_context_for_self_distillation():
1453
+ teacher_logits = self._forward_logits(
1454
+ model=teacher_model,
1455
+ input_ids=inputs["teacher_input_ids"],
1456
+ attention_mask=inputs["teacher_attention_mask"],
1457
+ logits_to_keep=logits_to_keep,
1458
+ )
1459
+
1460
+ return DistillationLogits(
1461
+ completion_ids=completion_ids,
1462
+ completion_mask=completion_mask,
1463
+ loss_mask=loss_mask,
1464
+ student_logits=student_logits,
1465
+ teacher_logits=teacher_logits,
1466
+ )
1467
+
1468
+ def _forward_logits(
1469
+ self,
1470
+ model,
1471
+ input_ids: torch.Tensor,
1472
+ attention_mask: torch.Tensor,
1473
+ logits_to_keep: int,
1474
+ ) -> torch.Tensor:
1475
+ """Forward the model and return temperature-scaled logits aligned to the completion tokens."""
1476
+ model_inputs = {
1477
+ "input_ids": input_ids,
1478
+ "attention_mask": attention_mask,
1479
+ "use_cache": False,
1480
+ }
1481
+ if "logits_to_keep" in self.model_kwarg_keys:
1482
+ model_inputs["logits_to_keep"] = logits_to_keep + 1
1483
+
1484
+ logits = model(**model_inputs).logits
1485
+ logits = logits[:, :-1, :]
1486
+ logits = logits[:, -logits_to_keep:, :]
1487
+ return logits / self.temperature
1488
+
1489
+ def _compute_liger_loss(self, model, inputs: TrainingBatch) -> torch.Tensor:
1490
+ """`full_logits` distillation via the Liger fused JSD kernel: forwards the base models for hidden states and
1491
+ fuses the lm_head projection with the divergence, never materializing the full-vocab logits.
1492
+
1493
+ Each model is forwarded through its own wrapper via `_forward_redirection` so FSDP2/DeepSpeed materialize the
1494
+ sharded params during the unwrapped base forward. The fused kernel needs both lm_head weights live at once, so
1495
+ the frozen teacher weight is captured while the teacher is materialized and handed to the student pass.
1496
+ """
1497
+ logits_to_keep = inputs["completion_ids"].size(1)
1498
+ self_distillation_mask = inputs.get("self_distillation_mask")
1499
+ if self_distillation_mask is None:
1500
+ loss_mask = inputs["completion_mask"]
1501
+ else:
1502
+ loss_mask = inputs["completion_mask"] * self_distillation_mask.unsqueeze(1)
1503
+
1504
+ unwrapped_student = self.accelerator.unwrap_model(model)
1505
+ unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model)
1506
+
1507
+ with torch.no_grad(), self._get_teacher_context_for_self_distillation():
1508
+ teacher_hidden, teacher_weight, teacher_bias = self._forward_redirection(
1509
+ self.teacher_model,
1510
+ unwrapped_teacher,
1511
+ self._liger_teacher_side,
1512
+ unwrapped_teacher,
1513
+ inputs,
1514
+ logits_to_keep,
1515
+ )
1516
+
1517
+ return self._forward_redirection(
1518
+ model,
1519
+ unwrapped_student,
1520
+ self._liger_student_loss,
1521
+ unwrapped_student,
1522
+ inputs,
1523
+ logits_to_keep,
1524
+ loss_mask,
1525
+ teacher_hidden,
1526
+ teacher_weight,
1527
+ teacher_bias,
1528
+ )
1529
+
1530
+ def _liger_teacher_side(self, teacher, inputs: TrainingBatch, logits_to_keep: int):
1531
+ """Teacher hidden states + frozen lm_head weight, captured while the teacher params are materialized."""
1532
+ hidden = teacher.get_decoder()(
1533
+ input_ids=inputs["teacher_input_ids"],
1534
+ attention_mask=inputs["teacher_attention_mask"],
1535
+ use_cache=False,
1536
+ ).last_hidden_state
1537
+ hidden = hidden[:, :-1][:, -logits_to_keep:]
1538
+ head = teacher.get_output_embeddings()
1539
+ # Clone so the weight survives re-sharding once this forward context exits.
1540
+ weight = head.weight.detach().clone()
1541
+ bias = head.bias.detach().clone() if head.bias is not None else None
1542
+ return hidden, weight, bias
1543
+
1544
+ def _liger_student_loss(
1545
+ self,
1546
+ student,
1547
+ inputs: TrainingBatch,
1548
+ logits_to_keep,
1549
+ loss_mask,
1550
+ teacher_hidden,
1551
+ teacher_weight,
1552
+ teacher_bias,
1553
+ ):
1554
+ student_input_ids = torch.cat([inputs["prompt_ids"], inputs["completion_ids"]], dim=1)
1555
+ student_attention_mask = torch.cat([inputs["prompt_mask"], inputs["completion_mask"]], dim=1)
1556
+ student_hidden = student.get_decoder()(
1557
+ input_ids=student_input_ids,
1558
+ attention_mask=student_attention_mask,
1559
+ use_cache=False,
1560
+ ).last_hidden_state
1561
+ # Align hidden states to the completion-predicting positions, matching `_forward_logits`.
1562
+ student_hidden = student_hidden[:, :-1][:, -logits_to_keep:]
1563
+
1564
+ # `ignore_index` masks non-response positions; the token values only feed the disabled hard-CE term.
1565
+ completion_ids = inputs["completion_ids"]
1566
+ true_labels = torch.where(loss_mask.bool(), completion_ids, torch.full_like(completion_ids, -100))
1567
+
1568
+ student_head = student.get_output_embeddings()
1569
+ # Per-sequence then batch mean (grpo), matching the non-Liger path: the fused kernel reduces by total tokens
1570
+ # (bnpo), so we call it per sequence and average.
1571
+ seq_losses = [
1572
+ self.liger_jsd_loss(
1573
+ student_input=student_hidden[i],
1574
+ student_weight=student_head.weight,
1575
+ teacher_input=teacher_hidden[i],
1576
+ teacher_weight=teacher_weight,
1577
+ true_labels=true_labels[i],
1578
+ student_bias=student_head.bias,
1579
+ teacher_bias=teacher_bias,
1580
+ )
1581
+ for i in range(student_hidden.size(0))
1582
+ ]
1583
+ loss = torch.stack(seq_losses).mean()
1584
+
1585
+ mode = "train" if student.training else "eval"
1586
+ self._log_self_distillation_metric(mode, self.accelerator.gather(loss.detach()).mean().item())
1587
+ return loss
1588
+
1589
+ def _get_liger_zero3_lm_head_gather_ctx(self, model):
1590
+ """Gather the sharded student/teacher lm_head weights for the fused matmul under ZeRO-3. Liger reads
1591
+ `lm_head.weight` by attribute, so the gather hook never fires; the decoder forward gathers itself. No-op
1592
+ outside ZeRO-3."""
1593
+ if not self.use_liger_loss:
1594
+ return nullcontext()
1595
+
1596
+ deepspeed_plugin = self.accelerator.state.deepspeed_plugin
1597
+ if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3:
1598
+ return nullcontext()
1599
+
1600
+ import deepspeed
1601
+
1602
+ unwrapped_student = self.accelerator.unwrap_model(model)
1603
+ unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model)
1604
+ student_head = unwrapped_student.get_output_embeddings()
1605
+ teacher_head = unwrapped_teacher.get_output_embeddings()
1606
+ params = [student_head.weight, teacher_head.weight]
1607
+ if student_head.bias is not None:
1608
+ params.append(student_head.bias)
1609
+ if teacher_head.bias is not None:
1610
+ params.append(teacher_head.bias)
1611
+ return deepspeed.zero.GatheredParameters(params, modifier_rank=None)
1612
+
1613
+ def _get_teacher_context_for_self_distillation(self):
1614
+ """Return the context manager that routes the teacher forward to the correct weights.
1615
+
1616
+ For non-PEFT models this is a no-op. For PEFT models:
1617
+
1618
+ - `teacher_model_kind == "base"`: disable the student adapter so the teacher forward uses the base weights.
1619
+ - `teacher_model_kind == "ema"` under pure-LoRA training: switch to the `"teacher"` LoRA adapter.
1620
+ - otherwise: no-op; the teacher is a separate deepcopy.
1621
+ """
1622
+ teacher_model_kind = self.args.teacher_model_kind
1623
+ if not is_peft_model(self.model):
1624
+ return nullcontext()
1625
+
1626
+ target_model = self.accelerator.unwrap_model(self.teacher_model)
1627
+
1628
+ if teacher_model_kind == "base":
1629
+ return use_adapter(target_model, adapter_name=None)
1630
+ if teacher_model_kind == "ema" and self._use_peft_ema_teacher_adapter():
1631
+ return use_adapter(target_model, adapter_name="teacher")
1632
+ return nullcontext()
1633
+
1634
+ def _record_completion_metrics(self, mode: str, batch: TrainingBatch) -> None:
1635
+ device = self.accelerator.device
1636
+ completion_ids_list = self._get_completion_ids_list(batch)
1637
+ agg_completion_lengths = self.accelerator.gather(batch["raw_completion_lengths"])
1638
+ self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item())
1639
+ self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item())
1640
+ self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item())
1641
+
1642
+ eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id]
1643
+ is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device)
1644
+ agg_is_truncated = self.accelerator.gather(is_truncated)
1645
+ self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item())
1646
+ term_completion_lengths = agg_completion_lengths[~agg_is_truncated]
1647
+ if len(term_completion_lengths) == 0:
1648
+ term_completion_lengths = torch.zeros(1, device=device)
1649
+ self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item())
1650
+ self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item())
1651
+ self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item())
1652
+
1653
+ def _log_self_distillation_metric(self, mode: str, value: float) -> None:
1654
+ metric_prefix = self._name.lower().replace(" ", "_")
1655
+ self._metrics[mode]["self_distillation/distillation_loss"].append(value)
1656
+ self._metrics[mode][f"{metric_prefix}/distillation_loss"].append(value)
1657
+
1658
+ def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
1659
+ mode = "train" if self.model.training else "eval"
1660
+ # Average the metrics
1661
+ metrics = {}
1662
+ for key, val in self._metrics[mode].items():
1663
+ # Filter out NaN values before averaging. A reward function that returns None for all samples
1664
+ # in a batch produces NaN for that batch's metric. With logging_steps > 1, a naive sum()/len()
1665
+ # would let a single NaN contaminate valid data from other batches. Only return None when no
1666
+ # valid values remain (e.g. JSON loggers crash on float NaN).
1667
+ valid = [v for v in val if not math.isnan(v)]
1668
+ metrics[key] = sum(valid) / len(valid) if valid else None
1669
+
1670
+ # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
1671
+ # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
1672
+ if mode == "eval":
1673
+ metrics = {f"eval_{key}": val for key, val in metrics.items()}
1674
+
1675
+ logs.update(metrics)
1676
+ super().log(logs, start_time)
1677
+ self._metrics[mode].clear()
1678
+
1679
+ def _record_reward_diagnostics(
1680
+ self,
1681
+ mode: str,
1682
+ rewards: torch.Tensor,
1683
+ rewards_per_func: torch.Tensor,
1684
+ group_std_rewards: torch.Tensor,
1685
+ ) -> None:
1686
+ tolerance = self.args.diagnostics_flat_tolerance
1687
+
1688
+ reward_mean = rewards.mean() if rewards.numel() > 0 else torch.tensor(0.0, device=self.accelerator.device)
1689
+ reward_std = rewards.std() if rewards.numel() > 1 else torch.tensor(0.0, device=self.accelerator.device)
1690
+ reward_min = rewards.min() if rewards.numel() > 0 else torch.tensor(0.0, device=self.accelerator.device)
1691
+ reward_max = rewards.max() if rewards.numel() > 0 else torch.tensor(0.0, device=self.accelerator.device)
1692
+ flat_group_fraction = (
1693
+ (group_std_rewards <= tolerance).float().mean()
1694
+ if group_std_rewards.numel() > 0
1695
+ else torch.tensor(1.0, device=self.accelerator.device)
1696
+ )
1697
+
1698
+ self._metrics[mode]["self_distillation/reward_mean"].append(self.accelerator.gather(reward_mean).mean().item())
1699
+ self._metrics[mode]["self_distillation/reward_std"].append(self.accelerator.gather(reward_std).mean().item())
1700
+ self._metrics[mode]["self_distillation/reward_min"].append(self.accelerator.gather(reward_min).min().item())
1701
+ self._metrics[mode]["self_distillation/reward_max"].append(self.accelerator.gather(reward_max).max().item())
1702
+ self._metrics[mode]["self_distillation/group_reward_std_mean"].append(
1703
+ self.accelerator.gather(group_std_rewards.mean() if group_std_rewards.numel() > 0 else reward_std)
1704
+ .mean()
1705
+ .item()
1706
+ )
1707
+ self._metrics[mode]["self_distillation/flat_group_fraction"].append(
1708
+ self.accelerator.gather(flat_group_fraction).mean().item()
1709
+ )
1710
+
1711
+ if rewards_per_func.numel() > 0:
1712
+ reward_func_means = rewards_per_func.nanmean(dim=0)
1713
+ gathered_means = self.accelerator.gather(reward_func_means).view(-1, reward_func_means.numel()).mean(dim=0)
1714
+ for reward_name, reward_func_mean in zip(self.reward_func_names, gathered_means.tolist(), strict=True):
1715
+ self._metrics[mode][f"self_distillation/rewards/{reward_name}"].append(reward_func_mean)
1716
+
1717
+ reward_is_flat = reward_std.item() <= tolerance
1718
+ grouped_rewards_are_flat = flat_group_fraction.item() >= 1.0 - tolerance
1719
+ if reward_is_flat and grouped_rewards_are_flat:
1720
+ self._warn_on_degenerate_diagnostics(
1721
+ mode=mode,
1722
+ counter_key="flat_rewards",
1723
+ message=(
1724
+ "Observed flat SDPO rewards across all sampled generations. "
1725
+ "Policy advantages will collapse to zero, and SDPO will not learn. "
1726
+ "Check reward density, reward shaping, or `success_reward_threshold`."
1727
+ ),
1728
+ )
1729
+ else:
1730
+ self._diagnostic_counters[mode]["flat_rewards"] = 0
1731
+
1732
+ def _warn_on_inactive_self_distillation(self, mode: str) -> None:
1733
+ metrics = self.teacher_context_builder.last_metrics
1734
+ tolerance = self.args.diagnostics_flat_tolerance
1735
+
1736
+ reprompt_fraction = metrics.get("self_distillation/reprompt_sample_fraction", 0.0)
1737
+ success_fraction = metrics.get("self_distillation/success_group_fraction", 0.0)
1738
+
1739
+ if reprompt_fraction <= tolerance:
1740
+ self._warn_on_degenerate_diagnostics(
1741
+ mode=mode,
1742
+ counter_key="inactive_self_distillation",
1743
+ message=(
1744
+ "SDPO self-distillation is inactive because no reprompted samples were constructed. "
1745
+ "This usually means no rollout exceeded `success_reward_threshold` and no usable privileged "
1746
+ "feedback was available."
1747
+ ),
1748
+ )
1749
+ else:
1750
+ self._diagnostic_counters[mode]["inactive_self_distillation"] = 0
1751
+
1752
+ if success_fraction <= tolerance:
1753
+ self._warn_on_degenerate_diagnostics(
1754
+ mode=mode,
1755
+ counter_key="no_successful_rollouts",
1756
+ message=(
1757
+ "SDPO did not find any successful rollouts in the current generation groups. "
1758
+ "If this persists, reduce task difficulty, adjust reward shaping, or lower "
1759
+ "`success_reward_threshold`."
1760
+ ),
1761
+ )
1762
+ else:
1763
+ self._diagnostic_counters[mode]["no_successful_rollouts"] = 0
1764
+
1765
+ def _warn_on_degenerate_diagnostics(self, mode: str, counter_key: str, message: str) -> None:
1766
+ interval = self.args.diagnostics_warning_interval
1767
+ if interval == 0:
1768
+ return
1769
+
1770
+ self._diagnostic_counters[mode][counter_key] += 1
1771
+ count = self._diagnostic_counters[mode][counter_key]
1772
+ if count == 1 or count % interval == 0:
1773
+ logger.warning("%s Consecutive degenerate steps: %s.", message, count)
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/sdpo/teacher_sync.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import logging
16
+
17
+ import torch
18
+ from accelerate.utils import is_peft_model
19
+ from transformers import (
20
+ TrainerCallback,
21
+ TrainerControl,
22
+ TrainerState,
23
+ TrainingArguments,
24
+ )
25
+
26
+ from ...trainer.callbacks import SyncRefModelCallback
27
+
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ def is_pure_lora_training(model, accelerator=None) -> bool:
33
+ """Return `True` when the active adapter is LoRA and every trainable parameter is a LoRA parameter."""
34
+ if not is_peft_model(model):
35
+ return False
36
+
37
+ if accelerator is not None:
38
+ model = accelerator.unwrap_model(model)
39
+
40
+ adapter_name = model.active_adapter
41
+ if adapter_name is None:
42
+ adapter_name = "default"
43
+ adapter_config = model.peft_config.get(adapter_name)
44
+ peft_type = adapter_config.peft_type
45
+ if peft_type is None or str(peft_type).split(".")[-1] != "LORA":
46
+ return False
47
+
48
+ for name, param in model.named_parameters():
49
+ if param.requires_grad and "lora_" not in name:
50
+ return False
51
+ return True
52
+
53
+
54
+ class SyncTeacherModelCallback(SyncRefModelCallback):
55
+ """Synchronize an EMA teacher model with the student model on each configured sync step."""
56
+
57
+ def __init__(self, teacher_model, accelerator=None):
58
+ super().__init__(ref_model=teacher_model, accelerator=accelerator)
59
+
60
+ def on_step_end(self, args, state, control, **kwargs):
61
+ model = kwargs["model"]
62
+ if self.ref_model is not None and state.global_step % args.teacher_sync_steps == 0:
63
+ if self.accelerator:
64
+ model = self.accelerator.unwrap_model(model)
65
+ self.sync_target_model(model, self.ref_model, args.teacher_update_rate)
66
+
67
+
68
+ class PEFTAdapterEMACallback(TrainerCallback):
69
+ """
70
+ Callback that maintains an EMA copy of PEFT adapter weights for use as a teacher model in self-distillation.
71
+
72
+ The callback creates a secondary adapter ("teacher") with zero-initialized weights and maintains shadow weights
73
+ that are updated via exponential moving average: `teacher_weight = (1-α) * teacher_weight + α * student_weight`
74
+
75
+ Usage:
76
+ ```python
77
+ trainer.add_callback(
78
+ PEFTAdapterEMACallback(
79
+ model=model,
80
+ teacher_adapter_name="teacher",
81
+ update_rate=0.05,
82
+ )
83
+ )
84
+ ```
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ model,
90
+ teacher_adapter_name: str = "teacher",
91
+ update_rate: float = 0.05,
92
+ sync_steps: int = 1,
93
+ accelerator=None,
94
+ ):
95
+ self.model = model
96
+ self.teacher_adapter_name = teacher_adapter_name
97
+ self.update_rate = update_rate
98
+ self.sync_steps = sync_steps
99
+ self.accelerator = accelerator
100
+ self.shadow_weights: dict[str, torch.Tensor] | None = None
101
+ self.teacher_adapter_config = None
102
+ self._initialized = False
103
+
104
+ def _get_student_state_dict(self):
105
+ """Get student adapter state dict using PEFT keys (without adapter name)."""
106
+ from peft import get_peft_model_state_dict
107
+
108
+ if self.accelerator is not None:
109
+ model = self.accelerator.unwrap_model(self.model)
110
+ else:
111
+ model = self.model
112
+ return get_peft_model_state_dict(model)
113
+
114
+ def _initialize_teacher_adapter(self):
115
+ """Create teacher adapter with zero weights initialized from student adapter."""
116
+ from peft import get_peft_model_state_dict, set_peft_model_state_dict
117
+
118
+ if self._initialized:
119
+ return
120
+
121
+ if self.accelerator is not None:
122
+ model = self.accelerator.unwrap_model(self.model)
123
+ else:
124
+ model = self.model
125
+
126
+ adapter_name = model.active_adapter
127
+ if adapter_name is None:
128
+ adapter_name = "default"
129
+
130
+ self.teacher_adapter_config = model.peft_config.get(adapter_name)
131
+
132
+ student_state = get_peft_model_state_dict(model)
133
+
134
+ teacher_state = {k: torch.zeros_like(v) for k, v in student_state.items()}
135
+
136
+ model.add_adapter(self.teacher_adapter_name, self.teacher_adapter_config)
137
+
138
+ model.set_adapter(self.teacher_adapter_name)
139
+ set_peft_model_state_dict(model, teacher_state, adapter_name=self.teacher_adapter_name)
140
+
141
+ model.set_adapter(adapter_name)
142
+
143
+ self.shadow_weights = {k: v.clone().zero_() for k, v in teacher_state.items()}
144
+
145
+ self._initialized = True
146
+ logger.info(f"Initialized PEFT adapter EMA teacher with adapter name: {self.teacher_adapter_name}")
147
+
148
+ @torch.no_grad()
149
+ def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
150
+ if state.global_step % self.sync_steps != 0:
151
+ return
152
+
153
+ if not self._initialized:
154
+ self._initialize_teacher_adapter()
155
+
156
+ if self.shadow_weights is None:
157
+ return
158
+
159
+ if self.accelerator is None and "accelerator" in kwargs:
160
+ self.accelerator = kwargs["accelerator"]
161
+
162
+ student_state = self._get_student_state_dict()
163
+
164
+ for key, student_param in student_state.items():
165
+ if key in self.shadow_weights:
166
+ shadow = self.shadow_weights[key]
167
+ shadow.data = (1 - self.update_rate) * shadow.data + self.update_rate * student_param.data
168
+
169
+ from peft import set_peft_model_state_dict
170
+
171
+ if self.accelerator is not None:
172
+ unwrapped_model = self.accelerator.unwrap_model(self.model)
173
+ else:
174
+ unwrapped_model = self.model
175
+
176
+ original_adapter = unwrapped_model.active_adapter
177
+ unwrapped_model.set_adapter(self.teacher_adapter_name)
178
+ set_peft_model_state_dict(unwrapped_model, self.shadow_weights, adapter_name=self.teacher_adapter_name)
179
+ unwrapped_model.set_adapter(original_adapter)
180
+
181
+ def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs):
182
+ if self.accelerator is None and "accelerator" in kwargs:
183
+ self.accelerator = kwargs["accelerator"]
184
+ self._initialize_teacher_adapter()
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ssd/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .ssd_config import SSDConfig
16
+ from .ssd_trainer import SSDTrainer
17
+
18
+
19
+ __all__ = ["SSDConfig", "SSDTrainer"]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ssd/ssd_config.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ from transformers import TrainingArguments
19
+
20
+ from ...trainer.base_config import _BaseConfig
21
+
22
+
23
+ @dataclass
24
+ class SSDConfig(_BaseConfig):
25
+ r"""
26
+ Configuration class for [`SSDTrainer`].
27
+
28
+ Implements Simple Self-Distillation (SSD) from [*Embarrassingly Simple Self-Distillation Improves Code
29
+ Generation*](https://huggingface.co/papers/2604.01193). SSD samples completions from the model at a training-time
30
+ temperature and truncation configuration, then fine-tunes on those raw, unverified samples with standard
31
+ cross-entropy loss.
32
+
33
+ The `temperature`, `top_k`, and `top_p` parameters control the training-time sampling configuration (T_train,
34
+ rho_train in the paper). The evaluation-time configuration (T_eval, rho_eval) is set independently at inference
35
+ time.
36
+
37
+ Parameters:
38
+ > Parameters that control generation and rollout reuse
39
+
40
+ model_init_kwargs (`dict[str, Any]`, *optional*):
41
+ Keyword arguments used when the `model` argument is passed as a string.
42
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
43
+ Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to
44
+ [`~transformers.AutoModelForCausalLM.from_pretrained`] and [`~transformers.AutoProcessor.from_pretrained`].
45
+ max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
46
+ Maximum prompt length. Longer prompts are truncated from the left.
47
+ max_completion_length (`int` or `None`, *optional*, defaults to `256`):
48
+ Maximum generated completion length.
49
+ generation_batch_size (`int` or `None`, *optional*):
50
+ Global batch size used for generation. Mutually exclusive with `steps_per_generation`.
51
+ steps_per_generation (`int` or `None`, *optional*):
52
+ Number of optimizer steps that reuse one generated batch. Mutually exclusive with `generation_batch_size`.
53
+
54
+ > Parameters that control sampling
55
+
56
+ temperature (`float`, *optional*, defaults to `1.0`):
57
+ Sampling temperature (T_train in the paper).
58
+ top_k (`int`, *optional*, defaults to `0`):
59
+ Top-k sampling parameter. `0` disables top-k filtering.
60
+ top_p (`float`, *optional*, defaults to `1.0`):
61
+ Top-p (nucleus) sampling parameter.
62
+ min_p (`float` or `None`, *optional*):
63
+ Minimum token probability for sampling.
64
+ repetition_penalty (`float`, *optional*, defaults to `1.0`):
65
+ Repetition penalty used during generation.
66
+ generation_kwargs (`dict[str, Any]` or `None`, *optional*):
67
+ Extra generation kwargs passed to `GenerationConfig`.
68
+
69
+ > Parameters that control vLLM generation
70
+
71
+ use_vllm (`bool`, *optional*, defaults to `False`):
72
+ Whether to use vLLM for generation instead of the training model.
73
+ vllm_mode (`str`, *optional*, defaults to `"colocate"`):
74
+ vLLM mode: `"colocate"` (shared GPU) or `"server"` (separate vLLM server).
75
+ vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
76
+ Model implementation for vLLM: `"vllm"`, `"transformers"`, or `"auto"`.
77
+ vllm_server_base_url (`str` or `None`, *optional*):
78
+ Base URL for the vLLM server. If provided, `vllm_server_host` and `vllm_server_port` are ignored.
79
+ vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
80
+ Host of the vLLM server (server mode only).
81
+ vllm_server_port (`int`, *optional*, defaults to `8000`):
82
+ Port of the vLLM server (server mode only).
83
+ vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
84
+ Timeout in seconds to wait for the vLLM server.
85
+ vllm_group_port (`int`, *optional*, defaults to `51216`):
86
+ Port for the weight update group (server mode only).
87
+ vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
88
+ Tensor parallel size for colocated vLLM.
89
+ vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`):
90
+ GPU memory utilization ratio for colocated vLLM.
91
+ vllm_max_model_length (`int` or `None`, *optional*):
92
+ Model context length for vLLM. Inferred from model config if not set.
93
+ vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
94
+ Whether to enable sleep mode for colocated vLLM engine.
95
+
96
+ > Parameters that control training behavior
97
+
98
+ disable_dropout (`bool`, *optional*, defaults to `True`):
99
+ Whether to disable dropout in the model during training.
100
+ filter_empty (`bool`, *optional*, defaults to `True`):
101
+ Whether to filter out empty or single-line stub completions from the generated data.
102
+ num_iterations (`int`, *optional*, defaults to `1`):
103
+ Number of optimization iterations per generated batch.
104
+ shuffle_dataset (`bool`, *optional*, defaults to `True`):
105
+ Whether to shuffle the training dataset.
106
+ ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
107
+ Whether to gather ZeRO-3 weights for generation.
108
+ cache_implementation (`str` or `None`, *optional*):
109
+ Cache implementation used by transformers generation.
110
+ chat_template_kwargs (`dict[str, Any]` or `None`, *optional*):
111
+ Extra kwargs forwarded to chat template application.
112
+ """
113
+
114
+ _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs"]
115
+
116
+ model_init_kwargs: dict[str, Any] | None = field(
117
+ default=None,
118
+ metadata={"help": "Keyword arguments for model initialization when `model` is passed as a string."},
119
+ )
120
+ trust_remote_code: bool = field(
121
+ default=False,
122
+ metadata={
123
+ "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
124
+ "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`."
125
+ },
126
+ )
127
+ max_prompt_length: int | None = field(
128
+ default=512,
129
+ metadata={"help": "Maximum prompt length. Longer prompts are truncated from the left."},
130
+ )
131
+ max_completion_length: int | None = field(
132
+ default=256,
133
+ metadata={"help": "Maximum generated completion length."},
134
+ )
135
+ generation_batch_size: int | None = field(
136
+ default=None,
137
+ metadata={"help": "Global batch size used for generation. Mutually exclusive with `steps_per_generation`."},
138
+ )
139
+ steps_per_generation: int | None = field(
140
+ default=None,
141
+ metadata={"help": "Number of optimizer steps that reuse one generated batch."},
142
+ )
143
+ temperature: float = field(
144
+ default=1.0,
145
+ metadata={"help": "Sampling temperature (T_train in the paper)."},
146
+ )
147
+ top_k: int = field(
148
+ default=0,
149
+ metadata={"help": "Top-k sampling parameter. `0` disables top-k filtering."},
150
+ )
151
+ top_p: float = field(
152
+ default=1.0,
153
+ metadata={"help": "Top-p (nucleus) sampling parameter."},
154
+ )
155
+ min_p: float | None = field(
156
+ default=None,
157
+ metadata={"help": "Minimum token probability for sampling."},
158
+ )
159
+ repetition_penalty: float = field(
160
+ default=1.0,
161
+ metadata={"help": "Repetition penalty used during generation."},
162
+ )
163
+ generation_kwargs: dict[str, Any] | None = field(
164
+ default=None,
165
+ metadata={"help": "Extra generation kwargs passed to `GenerationConfig`."},
166
+ )
167
+ cache_implementation: str | None = field(
168
+ default=None,
169
+ metadata={"help": "Cache implementation used by transformers generation."},
170
+ )
171
+ chat_template_kwargs: dict[str, Any] | None = field(
172
+ default=None,
173
+ metadata={"help": "Extra kwargs forwarded to chat template application."},
174
+ )
175
+ use_vllm: bool = field(
176
+ default=False,
177
+ metadata={"help": "Whether to use vLLM for generation."},
178
+ )
179
+ vllm_mode: str = field(
180
+ default="colocate",
181
+ metadata={"help": "vLLM mode: 'colocate' (shared GPU) or 'server' (separate vLLM server)."},
182
+ )
183
+ vllm_model_impl: str = field(
184
+ default="vllm",
185
+ metadata={"help": "Model implementation for vLLM: 'vllm', 'transformers', or 'auto'."},
186
+ )
187
+ vllm_server_base_url: str | None = field(
188
+ default=None,
189
+ metadata={
190
+ "help": "Base URL for the vLLM server. If provided, vllm_server_host and vllm_server_port are ignored."
191
+ },
192
+ )
193
+ vllm_server_host: str = field(
194
+ default="0.0.0.0",
195
+ metadata={"help": "Host of the vLLM server (server mode only)."},
196
+ )
197
+ vllm_server_port: int = field(
198
+ default=8000,
199
+ metadata={"help": "Port of the vLLM server (server mode only)."},
200
+ )
201
+ vllm_server_timeout: float = field(
202
+ default=240.0,
203
+ metadata={"help": "Timeout in seconds to wait for the vLLM server."},
204
+ )
205
+ vllm_group_port: int = field(
206
+ default=51216,
207
+ metadata={"help": "Port for the weight update group (server mode only)."},
208
+ )
209
+ vllm_tensor_parallel_size: int = field(
210
+ default=1,
211
+ metadata={"help": "Tensor parallel size for colocated vLLM."},
212
+ )
213
+ vllm_gpu_memory_utilization: float = field(
214
+ default=0.3,
215
+ metadata={"help": "GPU memory utilization ratio for colocated vLLM."},
216
+ )
217
+ vllm_max_model_length: int | None = field(
218
+ default=None,
219
+ metadata={"help": "Model context length for vLLM. Inferred from model config if not set."},
220
+ )
221
+ vllm_enable_sleep_mode: bool = field(
222
+ default=False,
223
+ metadata={"help": "Whether to enable sleep mode for colocated vLLM engine."},
224
+ )
225
+ disable_dropout: bool = field(
226
+ default=True,
227
+ metadata={"help": "Whether to disable dropout in the model during training."},
228
+ )
229
+ filter_empty: bool = field(
230
+ default=True,
231
+ metadata={"help": "Whether to filter out empty or single-line stub completions."},
232
+ )
233
+ num_iterations: int = field(
234
+ default=1,
235
+ metadata={"help": "Number of optimization iterations per generated batch."},
236
+ )
237
+ shuffle_dataset: bool = field(
238
+ default=True,
239
+ metadata={"help": "Whether to shuffle the training dataset."},
240
+ )
241
+ ds3_gather_for_generation: bool = field(
242
+ default=True,
243
+ metadata={"help": "Whether to gather ZeRO-3 weights for generation."},
244
+ )
245
+
246
+ def __post_init__(self):
247
+ super().__post_init__()
248
+
249
+ num_processes = self.world_size
250
+ if self.generation_batch_size is None and self.steps_per_generation is None:
251
+ self.steps_per_generation = self.gradient_accumulation_steps
252
+ self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
253
+ elif self.generation_batch_size is not None and self.steps_per_generation is None:
254
+ global_batch_size = self.per_device_train_batch_size * num_processes
255
+ if self.generation_batch_size % global_batch_size != 0:
256
+ raise ValueError(
257
+ f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size ({global_batch_size})."
258
+ )
259
+ self.steps_per_generation = self.generation_batch_size // global_batch_size
260
+ elif self.generation_batch_size is None and self.steps_per_generation is not None:
261
+ self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
262
+ else:
263
+ raise ValueError("'generation_batch_size' and 'steps_per_generation' can not both be configured")
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/ssd/ssd_trainer.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Trainer for Simple Self-Distillation (SSD).
16
+
17
+ Implements the method from *Embarrassingly Simple Self-Distillation Improves Code Generation* (Zhang et al., 2026):
18
+ sample completions from the frozen model at a training-time temperature and truncation configuration, then fine-tune on
19
+ those raw, unverified samples with standard cross-entropy loss. No reward model, verifier, teacher model, or
20
+ reinforcement learning is needed.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import inspect
26
+ import math
27
+ import textwrap
28
+ from collections import defaultdict
29
+ from functools import partial
30
+ from typing import Any
31
+
32
+ import datasets
33
+ import torch
34
+ from accelerate.logging import get_logger
35
+ from accelerate.utils import is_peft_model
36
+ from datasets import Dataset, IterableDataset
37
+ from torch import nn
38
+ from torch.utils.data import DataLoader, Sampler
39
+ from transformers import (
40
+ AutoProcessor,
41
+ GenerationConfig,
42
+ PreTrainedModel,
43
+ PreTrainedTokenizerBase,
44
+ ProcessorMixin,
45
+ TrainerCallback,
46
+ )
47
+ from transformers.trainer_utils import seed_worker
48
+ from transformers.utils import is_datasets_available, is_peft_available
49
+
50
+ from ...data_utils import maybe_apply_chat_template
51
+ from ...models import unwrap_model_for_generation
52
+ from ...trainer.base_trainer import _BaseTrainer
53
+ from ...trainer.utils import (
54
+ RepeatSampler,
55
+ create_model_from_path,
56
+ disable_dropout_in_model,
57
+ get_config_model_id,
58
+ identity,
59
+ pad,
60
+ selective_log_softmax,
61
+ split_tensor_dict,
62
+ )
63
+ from ..utils import prepare_peft_model
64
+ from .ssd_config import SSDConfig
65
+
66
+
67
+ if is_peft_available():
68
+ from peft import PeftConfig
69
+
70
+
71
+ logger = get_logger(__name__)
72
+
73
+
74
+ class SSDTrainer(_BaseTrainer):
75
+ """Trainer for SSD-style on-policy self-distillation with cross-entropy loss.
76
+
77
+ SSD generates completions from the model at a specified training-time temperature and truncation configuration,
78
+ then fine-tunes on those raw, unverified samples using standard cross-entropy loss. The dataset only requires a
79
+ ``prompt`` column.
80
+ """
81
+
82
+ _tag_names = ["trl", "ssd"]
83
+ _name = "SSD"
84
+ config_cls = SSDConfig
85
+ # docstyle-ignore
86
+ _paper = {
87
+ "title": "Embarrassingly Simple Self-Distillation Improves Code Generation",
88
+ "id": "2604.01193",
89
+ "citation": textwrap.dedent("""\
90
+ @article{zhang2026ssd,
91
+ title = {{Embarrassingly Simple Self-Distillation Improves Code Generation}},
92
+ author = {Ruixiang Zhang and Richard He Bai and Huangjie Zheng and Navdeep Jaitly and Ronan Collobert and Yizhe Zhang},
93
+ year = 2026,
94
+ eprint = {arXiv:2604.01193}
95
+ }"""),
96
+ }
97
+
98
+ def __init__(
99
+ self,
100
+ model: str | PreTrainedModel | nn.Module,
101
+ args: SSDConfig | None = None,
102
+ train_dataset: Dataset | IterableDataset | None = None,
103
+ eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
104
+ processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
105
+ callbacks: list[TrainerCallback] | None = None,
106
+ optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
107
+ peft_config: PeftConfig | None = None,
108
+ ):
109
+ if train_dataset is None:
110
+ raise ValueError("`train_dataset` is required")
111
+ if isinstance(train_dataset, IterableDataset):
112
+ raise NotImplementedError("Iterable datasets are not yet supported in SSDTrainer.")
113
+ if isinstance(eval_dataset, IterableDataset) or (
114
+ isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values())
115
+ ):
116
+ raise NotImplementedError("Iterable eval datasets are not yet supported in SSDTrainer.")
117
+ if args is None:
118
+ model_name = model if isinstance(model, str) else get_config_model_id(model.config)
119
+ model_name = model_name.split("/")[-1]
120
+ args = SSDConfig(f"{model_name}-SSD")
121
+ if isinstance(model, str):
122
+ model_init_kwargs = args.model_init_kwargs or {}
123
+ if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
124
+ model_init_kwargs["device_map"] = None
125
+ model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
126
+ model = create_model_from_path(model, **model_init_kwargs)
127
+ elif args.model_init_kwargs is not None:
128
+ logger.warning(
129
+ "You passed `model_init_kwargs` to `SSDConfig`, but `model` is already instantiated. "
130
+ "The `model_init_kwargs` will be ignored."
131
+ )
132
+
133
+ self.model_kwarg_keys = (
134
+ inspect.signature(model.forward).parameters.keys()
135
+ if not hasattr(model, "get_base_model")
136
+ else inspect.signature(model.get_base_model().forward).parameters.keys()
137
+ )
138
+
139
+ # PEFT
140
+ if peft_config is not None:
141
+ if not is_peft_available():
142
+ raise ImportError(
143
+ "You passed `peft_config` but the `peft` library is not installed. "
144
+ "Install it with `pip install trl[peft]`."
145
+ )
146
+ if not isinstance(peft_config, PeftConfig):
147
+ raise TypeError(
148
+ f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
149
+ f"got {type(peft_config).__name__}."
150
+ )
151
+ if is_peft_model(model):
152
+ raise ValueError(
153
+ "You passed a `PeftModel` instance together with a `peft_config` to SSDTrainer. Pass either a base "
154
+ "model with `peft_config`, or a pre-wrapped PEFT model."
155
+ )
156
+ if peft_config is not None or (is_peft_available() and getattr(model, "peft_config", None) is not None):
157
+ model = prepare_peft_model(model, peft_config, args)
158
+
159
+ if processing_class is None:
160
+ processing_class = AutoProcessor.from_pretrained(
161
+ get_config_model_id(model.config),
162
+ truncation_side="left",
163
+ padding_side="left",
164
+ trust_remote_code=args.trust_remote_code,
165
+ )
166
+
167
+ if isinstance(processing_class, ProcessorMixin):
168
+ self._tokenizer = processing_class.tokenizer
169
+ elif isinstance(processing_class, PreTrainedTokenizerBase):
170
+ self._tokenizer = processing_class
171
+ else:
172
+ raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
173
+
174
+ if self._tokenizer.pad_token is None:
175
+ self._tokenizer.pad_token = self._tokenizer.eos_token
176
+
177
+ self.max_prompt_length = args.max_prompt_length
178
+ self.max_completion_length = args.max_completion_length
179
+ # SSD always samples a single completion per prompt (N=1 in the paper).
180
+ self.num_generations = 1
181
+ self.num_iterations = args.num_iterations
182
+ self.temperature = args.temperature
183
+ self.shuffle_dataset = args.shuffle_dataset
184
+ self.filter_empty = args.filter_empty
185
+ self.use_vllm = args.use_vllm
186
+ self.chat_template_kwargs = args.chat_template_kwargs or {}
187
+ self._step = 0
188
+ self._buffered_inputs = None
189
+ self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
190
+
191
+ generation_kwargs = {
192
+ "max_new_tokens": self.max_completion_length,
193
+ "do_sample": True,
194
+ "pad_token_id": self._tokenizer.pad_token_id,
195
+ "bos_token_id": self._tokenizer.bos_token_id,
196
+ "eos_token_id": self._tokenizer.eos_token_id,
197
+ "temperature": args.temperature,
198
+ "top_p": args.top_p,
199
+ "top_k": args.top_k,
200
+ "min_p": args.min_p,
201
+ "repetition_penalty": args.repetition_penalty,
202
+ "cache_implementation": args.cache_implementation,
203
+ }
204
+ if args.generation_kwargs is not None:
205
+ generation_kwargs.update(args.generation_kwargs)
206
+ self.generation_config = GenerationConfig(**generation_kwargs, disable_compile=True)
207
+
208
+ if hasattr(model, "warnings_issued"):
209
+ model.warnings_issued["estimate_tokens"] = True
210
+
211
+ super().__init__(
212
+ model=model,
213
+ args=args,
214
+ data_collator=identity,
215
+ train_dataset=train_dataset,
216
+ eval_dataset=eval_dataset,
217
+ processing_class=processing_class,
218
+ callbacks=callbacks,
219
+ optimizers=optimizers,
220
+ compute_loss_func="non-None value to disable scaling",
221
+ )
222
+
223
+ if args.disable_dropout:
224
+ disable_dropout_in_model(self.model)
225
+
226
+ self.model.add_model_tags(self._tag_names)
227
+
228
+ self.model_accepts_loss_kwargs = False
229
+
230
+ if self.use_vllm:
231
+ from ...generation.vllm_generation import VLLMGeneration
232
+
233
+ self.vllm_generation = VLLMGeneration(
234
+ model=self.model,
235
+ accelerator=self.accelerator,
236
+ processing_class=self.processing_class,
237
+ mode=args.vllm_mode,
238
+ server_base_url=args.vllm_server_base_url,
239
+ server_host=args.vllm_server_host,
240
+ server_port=args.vllm_server_port,
241
+ group_port=args.vllm_group_port,
242
+ server_timeout=args.vllm_server_timeout,
243
+ tensor_parallel_size=args.vllm_tensor_parallel_size,
244
+ gpu_memory_utilization=args.vllm_gpu_memory_utilization,
245
+ max_model_length=args.vllm_max_model_length,
246
+ max_num_seqs=args.per_device_train_batch_size
247
+ * args.vllm_tensor_parallel_size
248
+ * args.steps_per_generation,
249
+ enable_sleep_mode=args.vllm_enable_sleep_mode,
250
+ model_impl=args.vllm_model_impl,
251
+ repetition_penalty=args.repetition_penalty,
252
+ temperature=self.temperature,
253
+ top_p=args.top_p,
254
+ top_k=args.top_k,
255
+ min_p=args.min_p,
256
+ max_completion_length=self.max_completion_length,
257
+ logprobs=None,
258
+ generation_kwargs=args.generation_kwargs,
259
+ )
260
+ self._last_loaded_step = -1
261
+
262
+ def _set_signature_columns_if_needed(self):
263
+ if self._signature_columns is None:
264
+ self._signature_columns = ["prompt"]
265
+
266
+ def _apply_prompt_template(self, prompts):
267
+ return [
268
+ maybe_apply_chat_template({"prompt": prompt}, self.processing_class, **self.chat_template_kwargs)["prompt"]
269
+ for prompt in prompts
270
+ ]
271
+
272
+ # ------------------------------------------------------------------
273
+ # DataLoader
274
+ # ------------------------------------------------------------------
275
+
276
+ def get_train_dataloader(self):
277
+ if self.train_dataset is None:
278
+ raise ValueError("Trainer: training requires a train_dataset.")
279
+
280
+ train_dataset = self.train_dataset
281
+ data_collator = self.data_collator
282
+ if is_datasets_available() and isinstance(train_dataset, datasets.Dataset):
283
+ train_dataset = self._remove_unused_columns(train_dataset, description="training")
284
+ else:
285
+ data_collator = self._get_collator_with_removed_columns(data_collator, description="training")
286
+
287
+ dataloader_params = {
288
+ "batch_size": self._train_batch_size * self.args.steps_per_generation,
289
+ "collate_fn": data_collator,
290
+ "num_workers": self.args.dataloader_num_workers,
291
+ "pin_memory": self.args.dataloader_pin_memory,
292
+ "persistent_workers": self.args.dataloader_persistent_workers,
293
+ }
294
+ if not isinstance(train_dataset, torch.utils.data.IterableDataset):
295
+ dataloader_params["sampler"] = self._get_train_sampler()
296
+ dataloader_params["drop_last"] = self.args.dataloader_drop_last
297
+ dataloader_params["worker_init_fn"] = partial(
298
+ seed_worker, num_workers=self.args.dataloader_num_workers, rank=self.args.process_index
299
+ )
300
+ dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor
301
+ return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params))
302
+
303
+ def _get_train_sampler(self, dataset=None) -> Sampler:
304
+ if dataset is None:
305
+ dataset = self.train_dataset
306
+ return RepeatSampler(
307
+ data_source=dataset,
308
+ mini_repeat_count=self.num_generations,
309
+ batch_size=self.args.generation_batch_size // self.num_generations,
310
+ repeat_count=self.num_iterations * self.args.steps_per_generation,
311
+ shuffle=self.shuffle_dataset,
312
+ seed=self.args.seed,
313
+ )
314
+
315
+ def _get_eval_sampler(self, eval_dataset) -> Sampler:
316
+ return RepeatSampler(
317
+ data_source=eval_dataset,
318
+ mini_repeat_count=self.num_generations,
319
+ seed=self.args.seed,
320
+ )
321
+
322
+ # ------------------------------------------------------------------
323
+ # Training step management
324
+ # ------------------------------------------------------------------
325
+
326
+ def training_step(self, model, inputs, num_items_in_batch):
327
+ output = super().training_step(model, inputs, num_items_in_batch)
328
+ self._step += 1
329
+ return output
330
+
331
+ def _prepare_inputs(self, generation_batch):
332
+ mode = "train" if self.model.training else "eval"
333
+ if mode == "train":
334
+ generate_every = self.args.steps_per_generation * self.num_iterations
335
+ if self._step % generate_every == 0 or self._buffered_inputs is None:
336
+ generation_batch = self._build_buffered_batch(generation_batch)
337
+ self._buffered_inputs = split_tensor_dict(generation_batch, self.args.steps_per_generation)
338
+ return self._buffered_inputs[self._step % self.args.steps_per_generation]
339
+ return self._build_buffered_batch(generation_batch)
340
+
341
+ # ------------------------------------------------------------------
342
+ # Generation
343
+ # ------------------------------------------------------------------
344
+
345
+ def _generate_completion_ids(self, prompts: list[Any]) -> tuple[torch.Tensor, torch.Tensor]:
346
+ """Generate completions from the model at the configured training-time temperature and truncation."""
347
+ if self.use_vllm:
348
+ return self._generate_completion_ids_vllm(prompts)
349
+ return self._generate_completion_ids_transformers(prompts)
350
+
351
+ def _generate_completion_ids_vllm(self, prompts: list[Any]) -> tuple[torch.Tensor, torch.Tensor]:
352
+ """Generate completions using vLLM."""
353
+ if self.state.global_step != self._last_loaded_step:
354
+ self.vllm_generation.sync_weights()
355
+ self._last_loaded_step = self.state.global_step
356
+
357
+ prompts_text = self._apply_prompt_template(prompts)
358
+ tokenized = self.processing_class(
359
+ text=prompts_text,
360
+ return_tensors=None,
361
+ padding=False,
362
+ max_length=self.max_prompt_length,
363
+ truncation=True,
364
+ add_special_tokens=False,
365
+ )
366
+ prompt_ids = tokenized["input_ids"]
367
+
368
+ _, completion_ids_list, _, _ = self.vllm_generation.generate(
369
+ prompts=prompt_ids,
370
+ images=None,
371
+ num_generations=self.num_generations,
372
+ )
373
+
374
+ device = self.accelerator.device
375
+ completion_ids = [torch.tensor(ids, device=device) for ids in completion_ids_list]
376
+ completion_mask = [torch.ones(len(ids), dtype=torch.long, device=device) for ids in completion_ids_list]
377
+ return (
378
+ pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right"),
379
+ pad(completion_mask, padding_value=0, padding_side="right"),
380
+ )
381
+
382
+ def _generate_completion_ids_transformers(self, prompts: list[Any]) -> tuple[torch.Tensor, torch.Tensor]:
383
+ """Generate completions using the training model with transformers."""
384
+ generate_inputs = self.processing_class(
385
+ text=self._apply_prompt_template(prompts),
386
+ return_tensors="pt",
387
+ padding=True,
388
+ padding_side="left",
389
+ max_length=self.max_prompt_length,
390
+ truncation=True,
391
+ add_special_tokens=False,
392
+ )
393
+ # Use the base Trainer tensor preparation instead of re-entering the buffered outer training hook.
394
+ generate_inputs = _BaseTrainer._prepare_inputs(self, generate_inputs)
395
+
396
+ with (
397
+ unwrap_model_for_generation(
398
+ self.model_wrapped,
399
+ self.accelerator,
400
+ gather_deepspeed3_params=self.args.ds3_gather_for_generation,
401
+ ) as unwrapped_model,
402
+ torch.no_grad(),
403
+ ):
404
+ prompt_completion_ids = unwrapped_model.generate(
405
+ **generate_inputs, generation_config=self.generation_config
406
+ )
407
+
408
+ prompt_length = generate_inputs["input_ids"].size(1)
409
+ completion_ids = prompt_completion_ids[:, prompt_length:]
410
+ is_eos = completion_ids == self._tokenizer.eos_token_id
411
+ eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=completion_ids.device)
412
+ eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)]
413
+ seq_idx = torch.arange(is_eos.size(1), device=completion_ids.device).expand(is_eos.size(0), -1)
414
+ completion_mask = (seq_idx <= eos_idx.unsqueeze(1)).long()
415
+
416
+ completion_ids_list = [c[m].tolist() for c, m in zip(completion_ids, completion_mask.bool(), strict=True)]
417
+ completion_ids = [torch.tensor(ids, device=self.accelerator.device) for ids in completion_ids_list]
418
+ completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids]
419
+ return (
420
+ pad(completion_ids, padding_value=self._tokenizer.pad_token_id, padding_side="right"),
421
+ pad(completion_mask, padding_value=0, padding_side="right"),
422
+ )
423
+
424
+ # ------------------------------------------------------------------
425
+ # Batch construction
426
+ # ------------------------------------------------------------------
427
+
428
+ def _build_buffered_batch(self, inputs: list[dict[str, Any]]) -> dict[str, torch.Tensor | Any]:
429
+ """Generate completions and build the training batch."""
430
+ prompts = [example["prompt"] for example in inputs]
431
+ completion_ids, completion_mask = self._generate_completion_ids(prompts)
432
+
433
+ # Optionally filter empty or single-line stub completions (the paper applies minimal syntactic filtering)
434
+ if self.filter_empty:
435
+ completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
436
+ keep = torch.ones(len(completions_text), dtype=torch.bool, device=completion_ids.device)
437
+ for i, text in enumerate(completions_text):
438
+ stripped = text.strip()
439
+ if len(stripped) == 0 or stripped.count("\n") == 0 and len(stripped) < 10:
440
+ keep[i] = False
441
+ completion_mask = completion_mask * keep.unsqueeze(1).long()
442
+
443
+ # Tokenize prompts for the training forward pass
444
+ prompt_text = self._apply_prompt_template(prompts)
445
+ prompt_inputs = self.processing_class(
446
+ text=prompt_text,
447
+ return_tensors="pt",
448
+ padding=True,
449
+ padding_side="left",
450
+ max_length=self.max_prompt_length,
451
+ truncation=True,
452
+ add_special_tokens=False,
453
+ )
454
+ prompt_inputs = _BaseTrainer._prepare_inputs(self, prompt_inputs)
455
+ prompt_ids = prompt_inputs["input_ids"]
456
+ prompt_mask = prompt_inputs["attention_mask"]
457
+
458
+ # Log completion statistics
459
+ mode = "train" if self.model.training else "eval"
460
+ completion_lengths = completion_mask.sum(dim=1).float()
461
+ agg_lengths = self.accelerator.gather(completion_lengths)
462
+ self._metrics[mode]["completions/mean_length"].append(agg_lengths.mean().item())
463
+ self._metrics[mode]["completions/min_length"].append(agg_lengths.min().item())
464
+ self._metrics[mode]["completions/max_length"].append(agg_lengths.max().item())
465
+ active_ratio = (completion_mask.sum(dim=1) > 0).float().mean()
466
+ self._metrics[mode]["ssd/active_sample_ratio"].append(self.accelerator.gather(active_ratio).mean().item())
467
+
468
+ return {
469
+ "prompt_ids": prompt_ids,
470
+ "prompt_mask": prompt_mask,
471
+ "completion_ids": completion_ids,
472
+ "completion_mask": completion_mask,
473
+ }
474
+
475
+ # ------------------------------------------------------------------
476
+ # Loss computation
477
+ # ------------------------------------------------------------------
478
+
479
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
480
+ if return_outputs:
481
+ raise ValueError("The SSDTrainer does not support returning outputs")
482
+
483
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
484
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
485
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
486
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
487
+ logits_to_keep = completion_ids.size(1)
488
+
489
+ # Forward pass
490
+ model_inputs = {"input_ids": input_ids, "attention_mask": attention_mask, "use_cache": False}
491
+ if "logits_to_keep" in self.model_kwarg_keys:
492
+ model_inputs["logits_to_keep"] = logits_to_keep + 1
493
+ logits = model(**model_inputs).logits
494
+ logits = logits[:, :-1, :]
495
+ logits = logits[:, -logits_to_keep:, :]
496
+
497
+ # Standard cross-entropy loss: -log p(y_t | x, y<t)
498
+ per_token_logps = selective_log_softmax(logits, completion_ids)
499
+ per_token_loss = -per_token_logps
500
+
501
+ # Aggregate with mask
502
+ loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0)
503
+
504
+ mode = "train" if self.model.training else "eval"
505
+ self._metrics[mode]["ssd/cross_entropy_loss"].append(self.accelerator.gather(loss.detach()).mean().item())
506
+
507
+ accumulation_scale = self.current_gradient_accumulation_steps if self.model.training else 1.0
508
+ return loss / accumulation_scale
509
+
510
+ def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None):
511
+ if not isinstance(inputs, dict):
512
+ inputs = self._prepare_inputs(inputs)
513
+ with torch.no_grad():
514
+ with self.compute_loss_context_manager():
515
+ loss = self.compute_loss(model, inputs)
516
+ return loss.detach(), None, None
517
+
518
+ def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
519
+ mode = "train" if self.model.training else "eval"
520
+ metrics = {}
521
+ for key, val in self._metrics[mode].items():
522
+ valid = [v for v in val if not math.isnan(v)]
523
+ metrics[key] = sum(valid) / len(valid) if valid else None
524
+
525
+ # When called in evaluation, the keys in `logs` start with "eval_". We need to add the prefix "eval_" to the
526
+ # keys in `metrics` to match the format.
527
+ if mode == "eval":
528
+ metrics = {f"eval_{key}": val for key, val in metrics.items()}
529
+
530
+ logs.update(metrics)
531
+ super().log(logs, start_time)
532
+ self._metrics[mode].clear()
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/tpo/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .tpo_config import TPOConfig
16
+ from .tpo_trainer import TPOTrainer
17
+
18
+
19
+ __all__ = ["TPOConfig", "TPOTrainer"]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/tpo/tpo_config.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ from ...trainer.base_config import _BaseConfig
19
+
20
+
21
+ @dataclass
22
+ class TPOConfig(_BaseConfig):
23
+ # docstyle-ignore
24
+ r"""
25
+ Configuration class for the [`experimental.tpo.TPOTrainer`].
26
+
27
+ This class includes only the parameters that are specific to TPO training. For a full list of training arguments,
28
+ please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
29
+ differ from those in [`~transformers.TrainingArguments`].
30
+
31
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
32
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
33
+ command line.
34
+
35
+ Parameters:
36
+ > Parameters that control the model
37
+
38
+ model_init_kwargs (`dict[str, Any]`, *optional*):
39
+ Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
40
+ argument of the [`experimental.tpo.TPOTrainer`] is provided as a string.
41
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
42
+ Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to
43
+ [`~transformers.AutoModelForCausalLM.from_pretrained`] and
44
+ [`~transformers.AutoProcessor.from_pretrained`].
45
+ disable_dropout (`bool`, *optional*, defaults to `True`):
46
+ Whether to disable dropout in the model.
47
+
48
+ > Parameters that control the data preprocessing
49
+
50
+ dataset_num_proc (`int`, *optional*):
51
+ Number of processes to use for processing the dataset.
52
+ max_length (`int` or `None`, *optional*, defaults to `1024`):
53
+ Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the left or
54
+ right depending on the `truncation_mode`. If `None`, no truncation is applied.
55
+ truncation_mode (`str`, *optional*, defaults to `"keep_start"`):
56
+ Truncation mode to use when the sequence exceeds `max_length`. Possible values are `"keep_start"` and
57
+ `"keep_end"`.
58
+ pad_to_multiple_of (`int`, *optional*):
59
+ If set, the sequences will be padded to a multiple of this value.
60
+
61
+ > Parameters that control the training
62
+
63
+ loss_type (`str`, *optional*, defaults to `"sigmoid"`):
64
+ Type of loss to use. Possible values are:
65
+
66
+ - `"sigmoid"`: sigmoid loss from the original [TPO](https://huggingface.co/papers/2405.16681) paper.
67
+ - `"hinge"`: hinge loss on the normalized likelihood from the
68
+ [SLiC](https://huggingface.co/papers/2305.10425) paper.
69
+ - `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper.
70
+ - `"tpo-l"`: length-normalized TPO variant from the
71
+ [TPO](https://huggingface.co/papers/2405.16681) paper, which adds a target reward margin
72
+ `tpo_l_gamma` to the Bradley-Terry objective.
73
+
74
+ beta (`float`, *optional*, defaults to `0.01`):
75
+ Parameter controlling the temperature of the TPO loss. For the IPO loss (`loss_type="ipo"`), β is the
76
+ regularization parameter denoted by τ in the [paper](https://huggingface.co/papers/2310.12036).
77
+ label_smoothing (`float`, *optional*, defaults to `0.0`):
78
+ Label smoothing factor.
79
+ tpo_alpha (`float`, *optional*, defaults to `1.0`):
80
+ Weight of the supervised negative log-likelihood term computed on the gold (`reference`) response in TPO
81
+ training. Setting `tpo_alpha=0.0` disables the NLL term and skips the corresponding forward pass.
82
+ tpo_l_gamma (`float`, *optional*, defaults to `0.5`):
83
+ Target reward margin γ for the TPO-L loss, used only when `loss_type="tpo-l"`.
84
+
85
+ > [!NOTE]
86
+ > These parameters have default values different from [`~transformers.TrainingArguments`]:
87
+ > - `logging_steps`: Defaults to `10` instead of `500`.
88
+ > - `gradient_checkpointing`: Defaults to `True` instead of `False`.
89
+ > - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
90
+ > - `learning_rate`: Defaults to `5e-7` instead of `5e-5`.
91
+ """
92
+
93
+ _VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
94
+
95
+ # Parameters whose default values are overridden from TrainingArguments
96
+ learning_rate: float = field(
97
+ default=5e-7,
98
+ metadata={"help": "The initial learning rate for AdamW."},
99
+ )
100
+
101
+ # Parameters that control the model
102
+ model_init_kwargs: dict[str, Any] | str | None = field(
103
+ default=None,
104
+ metadata={
105
+ "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of "
106
+ "the `TPOTrainer` is provided as a string."
107
+ },
108
+ )
109
+ trust_remote_code: bool = field(
110
+ default=False,
111
+ metadata={
112
+ "help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
113
+ "Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`."
114
+ },
115
+ )
116
+ disable_dropout: bool = field(
117
+ default=True,
118
+ metadata={"help": "Whether to disable dropout in the model."},
119
+ )
120
+
121
+ # Parameters that control the data preprocessing
122
+ dataset_num_proc: int | None = field(
123
+ default=None,
124
+ metadata={"help": "Number of processes to use for processing the dataset."},
125
+ )
126
+ max_length: int | None = field(
127
+ default=1024,
128
+ metadata={
129
+ "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from "
130
+ "the left or right depending on the `truncation_mode`. If `None`, no truncation is applied."
131
+ },
132
+ )
133
+ truncation_mode: str = field(
134
+ default="keep_start",
135
+ metadata={
136
+ "help": "Truncation mode to use when the sequence exceeds `max_length`.",
137
+ "choices": ["keep_end", "keep_start"],
138
+ },
139
+ )
140
+ pad_to_multiple_of: int | None = field(
141
+ default=None,
142
+ metadata={"help": "If set, the sequences will be padded to a multiple of this value."},
143
+ )
144
+
145
+ # Parameters that control the training
146
+ loss_type: str = field(
147
+ default="sigmoid",
148
+ metadata={
149
+ "help": "Type of loss to use.",
150
+ "choices": ["sigmoid", "hinge", "ipo", "tpo-l"],
151
+ },
152
+ )
153
+ beta: float = field(
154
+ default=0.01,
155
+ metadata={
156
+ "help": "Parameter controlling the temperature of the TPO loss. For the IPO loss (`loss_type='ipo'`), this "
157
+ "value is the regularization parameter denoted by τ in the IPO paper."
158
+ },
159
+ )
160
+ label_smoothing: float = field(
161
+ default=0.0,
162
+ metadata={"help": "Label smoothing factor."},
163
+ )
164
+ tpo_alpha: float = field(
165
+ default=1.0,
166
+ metadata={
167
+ "help": "Weight of the supervised NLL term computed on the gold (`reference`) response in TPO training. "
168
+ "Setting `tpo_alpha=0.0` disables the NLL term and skips the corresponding forward pass."
169
+ },
170
+ )
171
+ tpo_l_gamma: float = field(
172
+ default=0.5,
173
+ metadata={"help": "Target reward margin γ for the TPO-L loss, used only when `loss_type='tpo-l'`."},
174
+ )
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/tpo/tpo_trainer.py ADDED
@@ -0,0 +1,790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import json
16
+ import textwrap
17
+ from collections import defaultdict
18
+ from collections.abc import Callable
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import transformers
26
+ from accelerate import PartialState
27
+ from accelerate.logging import get_logger
28
+ from accelerate.utils import is_peft_model
29
+ from datasets import Dataset, IterableDataset
30
+ from packaging.version import Version
31
+ from transformers import (
32
+ AutoProcessor,
33
+ DataCollator,
34
+ PreTrainedModel,
35
+ PreTrainedTokenizerBase,
36
+ )
37
+ from transformers.data.data_collator import DataCollatorMixin
38
+ from transformers.trainer_callback import TrainerCallback
39
+ from transformers.trainer_utils import EvalPrediction
40
+ from transformers.utils import is_peft_available
41
+
42
+ from ...data_utils import extract_prompt, is_conversational
43
+ from ...trainer.base_trainer import _BaseTrainer
44
+ from ...trainer.utils import (
45
+ create_model_from_path,
46
+ disable_dropout_in_model,
47
+ entropy_from_logits,
48
+ get_config_model_id,
49
+ pad,
50
+ selective_log_softmax,
51
+ )
52
+ from .tpo_config import TPOConfig
53
+
54
+
55
+ if is_peft_available():
56
+ from peft import PeftConfig, PeftModel, get_peft_model
57
+
58
+
59
+ logger = get_logger(__name__)
60
+
61
+
62
+ def _extract_triple_prompt(example: dict) -> dict:
63
+ """Extract the shared prompt from `chosen`/`rejected` and also strip it from `reference`.
64
+
65
+ Wraps [`~trl.data_utils.extract_prompt`] — which only rewrites `chosen` and `rejected` — and additionally strips
66
+ the extracted prompt prefix from the `reference` (gold) completion. This is specific to TPO and assumes that the
67
+ `reference` completion shares the same implicit prompt prefix as `chosen` and `rejected`. If it does not, a
68
+ `ValueError` is raised asking the caller to provide an explicit `prompt` column.
69
+ """
70
+ extracted = extract_prompt(example)
71
+ prompt = extracted["prompt"]
72
+ reference = example["reference"]
73
+ if reference[: len(prompt)] != prompt:
74
+ raise ValueError(
75
+ "The `reference` completion does not start with the implicit prompt extracted from `chosen`/`rejected`. "
76
+ "Either provide an explicit `prompt` column, or make sure the `reference` completion shares the same "
77
+ "prompt prefix as the `chosen` and `rejected` completions."
78
+ )
79
+ extracted["reference"] = reference[len(prompt) :]
80
+ return extracted
81
+
82
+
83
+ @dataclass
84
+ class DataCollatorForTriplePreference(DataCollatorMixin):
85
+ """
86
+ Data collator used for triple-preference data. Inputs are dynamically padded to the maximum length of a batch.
87
+
88
+ This collator expects each example in the input list to be a dictionary containing the keys `"prompt_ids"`,
89
+ `"chosen_ids"` and `"rejected_ids"`. When `include_reference=True` (the default) each example must additionally
90
+ contain `"reference_ids"`. The collator returns a dictionary containing the following keys:
91
+ - `"input_ids"`: Tensor of input IDs, padded to the maximum length of the batch. When
92
+ `include_reference=True`, the first third of the batch corresponds to the `"chosen_ids"`, the second third to
93
+ the `"rejected_ids"` and the last third to the `"reference_ids"`. When `include_reference=False`, the first
94
+ half corresponds to the `"chosen_ids"` and the second half to the `"rejected_ids"` (matching the layout of
95
+ [`~trl.trainer.dpo_trainer.DataCollatorForPreference`]).
96
+ - `"attention_mask"`: Tensor of attention mask, padded to the maximum length of the batch.
97
+ - `"completion_mask"`: Tensor indicating the positions of the completion tokens, padded to the maximum length of
98
+ the batch.
99
+
100
+ Args:
101
+ pad_token_id (`int`):
102
+ Token ID to use for padding.
103
+ max_length (`int`, *optional*):
104
+ Maximum length of the sequences after concatenation. Sequences longer than `max_length` are truncated
105
+ before padding, which avoids allocating oversized tensors for batches containing very long sequences.
106
+ truncation_mode (`str`, *optional*, defaults to `"keep_start"`):
107
+ Truncation mode when a concatenated sequence exceeds `max_length`. Possible values are `"keep_end"` and
108
+ `"keep_start"`.
109
+ pad_to_multiple_of (`int`, *optional*):
110
+ If set, the sequences will be padded to a multiple of this value.
111
+ return_tensors (`str`, *optional*, defaults to `"pt"`):
112
+ Type of Tensor to return. Only `"pt"` is currently supported.
113
+ include_reference (`bool`, *optional*, defaults to `True`):
114
+ Whether to include the `"reference_ids"` branch in the collated batch. When `False`, the collator emits
115
+ only the chosen/rejected halves and skips the gold-response sequences entirely, which matches the behavior
116
+ expected when `tpo_alpha=0.0` (no NLL term).
117
+
118
+ Examples:
119
+ ```python
120
+ >>> from trl.experimental.tpo.tpo_trainer import DataCollatorForTriplePreference
121
+
122
+ >>> collator = DataCollatorForTriplePreference(pad_token_id=0)
123
+ >>> examples = [
124
+ ... {"prompt_ids": [1, 2, 3], "chosen_ids": [4, 5], "rejected_ids": [6], "reference_ids": [7, 8]},
125
+ ... {"prompt_ids": [9, 10], "chosen_ids": [11], "rejected_ids": [12, 13], "reference_ids": [14]},
126
+ ... ]
127
+ >>> collator(examples)
128
+ {'input_ids': tensor([[ 1, 2, 3, 4, 5],
129
+ [ 9, 10, 11, 0, 0],
130
+ [ 1, 2, 3, 6, 0],
131
+ [ 9, 10, 12, 13, 0],
132
+ [ 1, 2, 3, 7, 8],
133
+ [ 9, 10, 14, 0, 0]]),
134
+ 'attention_mask': tensor([[1, 1, 1, 1, 1],
135
+ [1, 1, 1, 0, 0],
136
+ [1, 1, 1, 1, 0],
137
+ [1, 1, 1, 1, 0],
138
+ [1, 1, 1, 1, 1],
139
+ [1, 1, 1, 0, 0]]),
140
+ 'completion_mask': tensor([[0, 0, 0, 1, 1],
141
+ [0, 0, 1, 0, 0],
142
+ [0, 0, 0, 1, 0],
143
+ [0, 0, 1, 1, 0],
144
+ [0, 0, 0, 1, 1],
145
+ [0, 0, 1, 0, 0]])}
146
+ ```
147
+ """
148
+
149
+ pad_token_id: int
150
+ max_length: int | None = None
151
+ truncation_mode: str = "keep_start"
152
+ pad_to_multiple_of: int | None = None
153
+ return_tensors: str = "pt"
154
+ include_reference: bool = True
155
+
156
+ def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
157
+ prompt_chosen_ids = [example["prompt_ids"] + example["chosen_ids"] for example in examples]
158
+ prompt_rejected_ids = [example["prompt_ids"] + example["rejected_ids"] for example in examples]
159
+ chosen_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["chosen_ids"]) for example in examples]
160
+ rejected_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["rejected_ids"]) for example in examples]
161
+ if self.include_reference:
162
+ prompt_reference_ids = [example["prompt_ids"] + example["reference_ids"] for example in examples]
163
+ reference_mask = [
164
+ [0] * len(example["prompt_ids"]) + [1] * len(example["reference_ids"]) for example in examples
165
+ ]
166
+
167
+ if self.max_length is not None:
168
+ if self.truncation_mode == "keep_start":
169
+ sl = slice(None, self.max_length)
170
+ elif self.truncation_mode == "keep_end":
171
+ sl = slice(-self.max_length, None)
172
+ else:
173
+ raise ValueError(
174
+ f"Unsupported truncation mode: {self.truncation_mode}, expected 'keep_start' or 'keep_end'"
175
+ )
176
+ prompt_chosen_ids = [ids[sl] for ids in prompt_chosen_ids]
177
+ prompt_rejected_ids = [ids[sl] for ids in prompt_rejected_ids]
178
+ chosen_mask = [m[sl] for m in chosen_mask]
179
+ rejected_mask = [m[sl] for m in rejected_mask]
180
+ if self.include_reference:
181
+ prompt_reference_ids = [ids[sl] for ids in prompt_reference_ids]
182
+ reference_mask = [m[sl] for m in reference_mask]
183
+
184
+ chosen_attention_mask = [[1] * len(ids) for ids in prompt_chosen_ids]
185
+ rejected_attention_mask = [[1] * len(ids) for ids in prompt_rejected_ids]
186
+ input_ids = prompt_chosen_ids + prompt_rejected_ids
187
+ attention_mask = chosen_attention_mask + rejected_attention_mask
188
+ completion_mask = chosen_mask + rejected_mask
189
+ if self.include_reference:
190
+ reference_attention_mask = [[1] * len(ids) for ids in prompt_reference_ids]
191
+ input_ids = input_ids + prompt_reference_ids
192
+ attention_mask = attention_mask + reference_attention_mask
193
+ completion_mask = completion_mask + reference_mask
194
+
195
+ # Convert to tensor
196
+ input_ids = [torch.tensor(ids) for ids in input_ids]
197
+ attention_mask = [torch.tensor(m, dtype=torch.long) for m in attention_mask]
198
+ completion_mask = [torch.tensor(m, dtype=torch.long) for m in completion_mask]
199
+
200
+ # Pad
201
+ output = {}
202
+ output["input_ids"] = pad(
203
+ input_ids,
204
+ padding_value=self.pad_token_id,
205
+ padding_side="right",
206
+ pad_to_multiple_of=self.pad_to_multiple_of,
207
+ )
208
+ output["attention_mask"] = pad(
209
+ attention_mask,
210
+ padding_value=0,
211
+ padding_side="right",
212
+ pad_to_multiple_of=self.pad_to_multiple_of,
213
+ )
214
+ output["completion_mask"] = pad(
215
+ completion_mask,
216
+ padding_value=0,
217
+ padding_side="right",
218
+ pad_to_multiple_of=self.pad_to_multiple_of,
219
+ )
220
+ return output
221
+
222
+
223
+ class TPOTrainer(_BaseTrainer):
224
+ """
225
+ Trainer for Triple Preference Optimization (TPO) method. This algorithm was initially proposed in the paper [Triple
226
+ Preference Optimization: Achieving Better Alignment using a Single Step
227
+ Optimization](https://huggingface.co/papers/2405.16681). This class is a wrapper around the
228
+ [`~transformers.Trainer`] class and inherits all of its attributes and methods.
229
+
230
+ Args:
231
+ model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]):
232
+ Model to be trained. Can be either:
233
+
234
+ - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
235
+ path to a *directory* containing model weights saved using
236
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
237
+ using `<ModelArchitecture>.from_pretrained` (where `<ModelArchitecture>` is derived from the model
238
+ config) with the keyword arguments in `args.model_init_kwargs`.
239
+ - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
240
+ - A [`~peft.PeftModel`] object. Only causal language models are supported.
241
+ args ([`experimental.tpo.TPOConfig`], *optional*):
242
+ Configuration for this trainer. If `None`, a default configuration is used.
243
+ data_collator ([`~transformers.DataCollator`], *optional*):
244
+ Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`.
245
+ Will default to [`~trl.experimental.tpo.tpo_trainer.DataCollatorForTriplePreference`]. Custom collators
246
+ must truncate sequences before padding; the trainer does not apply post-collation truncation.
247
+ train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
248
+ Dataset to use for training. TPO requires a *triple-preference* dataset: each sample must contain a
249
+ `"chosen"`, a `"rejected"` and a `"reference"` (gold) completion. The format of the samples can be either:
250
+
251
+ - [Standard](dataset_formats#standard): Each sample contains plain text.
252
+ - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
253
+ and content).
254
+ eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
255
+ Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
256
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*):
257
+ Processing class used to process the data. If `None`, the processing class is loaded from the model's name
258
+ with [`~transformers.AutoProcessor.from_pretrained`]. A padding token, `tokenizer.pad_token`, must be set.
259
+ If the processing class has not set a padding token, `tokenizer.eos_token` will be used as the default.
260
+ compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
261
+ The function that will be used to compute metrics at evaluation. Must take a
262
+ [`~transformers.EvalPrediction`] and return a dictionary string to metric values.
263
+ callbacks (list of [`~transformers.TrainerCallback`], *optional*):
264
+ List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
265
+ in [here](https://huggingface.co/docs/transformers/main_classes/callback).
266
+
267
+ If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
268
+ method.
269
+ optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`):
270
+ A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your
271
+ model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`.
272
+ peft_config ([`~peft.PeftConfig`], *optional*):
273
+ PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
274
+ """
275
+
276
+ _tag_names = ["trl", "tpo"]
277
+ _name = "TPO"
278
+ _paper = {
279
+ "title": "Triple Preference Optimization: Achieving Better Alignment using a Single Step Optimization",
280
+ "id": "2405.16681",
281
+ # docstyle-ignore
282
+ "citation": textwrap.dedent("""\
283
+ @misc{saeidi2025triplepreferenceoptimizationachieving,
284
+ title = {{Triple Preference Optimization: Achieving Better Alignment using a Single Step Optimization}},
285
+ author = {Amir Saeidi and Shivanshu Verma and Aswin RRV and Kashif Rasul and Chitta Baral},
286
+ year = 2025,
287
+ eprint = {2405.16681},
288
+ archivePrefix= {arXiv},
289
+ primaryClass = {cs.CL},
290
+ url = {https://arxiv.org/abs/2405.16681},
291
+ }"""),
292
+ }
293
+
294
+ def __init__(
295
+ self,
296
+ model: "str | PreTrainedModel | PeftModel",
297
+ args: TPOConfig | None = None,
298
+ data_collator: DataCollator | None = None,
299
+ train_dataset: Dataset | IterableDataset | None = None,
300
+ eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
301
+ processing_class: PreTrainedTokenizerBase | None = None,
302
+ compute_metrics: Callable[[EvalPrediction], dict] | None = None,
303
+ callbacks: list[TrainerCallback] | None = None,
304
+ optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
305
+ peft_config: "PeftConfig | None" = None,
306
+ ):
307
+ # Args
308
+ if args is None:
309
+ model_name = model if isinstance(model, str) else get_config_model_id(model.config)
310
+ model_name = model_name.split("/")[-1]
311
+ args = TPOConfig(f"{model_name}-TPO")
312
+
313
+ if train_dataset is None:
314
+ raise ValueError("`train_dataset` is required")
315
+ elif isinstance(train_dataset, IterableDataset):
316
+ # IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate
317
+ # batches from multiple processes, leading to mismatch errors.
318
+ if args.accelerator_config.dispatch_batches is True:
319
+ logger.warning(
320
+ "You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` "
321
+ "is forced to `False` when using an `IterableDataset`. To remove this warning, unset "
322
+ "`dispatch_batches` in `TPOConfig` or set it to `False`."
323
+ )
324
+ args.accelerator_config.dispatch_batches = False
325
+
326
+ # Model
327
+ if isinstance(model, str):
328
+ model_init_kwargs = args.model_init_kwargs or {}
329
+ # Distributed training requires device_map=None ("auto" fails)
330
+ if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
331
+ model_init_kwargs["device_map"] = None
332
+ model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
333
+ model = create_model_from_path(model, **model_init_kwargs)
334
+ else:
335
+ if args.model_init_kwargs is not None:
336
+ logger.warning(
337
+ "You passed `model_init_kwargs` to the `TPOConfig`, but your model is already instantiated. "
338
+ "The `model_init_kwargs` will be ignored."
339
+ )
340
+
341
+ # Processing class
342
+ if processing_class is None:
343
+ processing_class = AutoProcessor.from_pretrained(
344
+ get_config_model_id(model.config), trust_remote_code=args.trust_remote_code
345
+ )
346
+ if not isinstance(processing_class, PreTrainedTokenizerBase):
347
+ raise TypeError(
348
+ "The `processing_class` must be a `PreTrainedTokenizerBase`. `TPOTrainer` does not currently "
349
+ "support vision-language models."
350
+ )
351
+ self._tokenizer = processing_class
352
+
353
+ if self._tokenizer.pad_token is None:
354
+ self._tokenizer.pad_token = self._tokenizer.eos_token
355
+
356
+ # PEFT
357
+ if peft_config is not None:
358
+ if not is_peft_available():
359
+ raise ImportError(
360
+ "You passed `peft_config` but the `peft` library is not installed. "
361
+ "Install it with `pip install trl[peft]`."
362
+ )
363
+ if not isinstance(peft_config, PeftConfig):
364
+ raise TypeError(
365
+ f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
366
+ f"got {type(peft_config).__name__}."
367
+ )
368
+ if is_peft_model(model):
369
+ raise ValueError(
370
+ "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge "
371
+ "and unload the existing adapter, save the resulting base model, and then pass that base model along "
372
+ "with the new `peft_config` to the trainer."
373
+ )
374
+ # Create PEFT model
375
+ model = get_peft_model(model, peft_config)
376
+
377
+ # When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally
378
+ # handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489
379
+ if is_peft_model(model) and args.gradient_checkpointing:
380
+ model.enable_input_require_grads()
381
+
382
+ # Data collator. When `tpo_alpha=0.0`, the NLL term on the gold response is disabled, so we can drop the
383
+ # reference branch from the batch entirely — this spares the model from computing logits for a third of
384
+ # each step.
385
+ if data_collator is None:
386
+ data_collator = DataCollatorForTriplePreference(
387
+ pad_token_id=self._tokenizer.pad_token_id,
388
+ max_length=args.max_length,
389
+ truncation_mode=args.truncation_mode,
390
+ pad_to_multiple_of=args.pad_to_multiple_of,
391
+ include_reference=args.tpo_alpha != 0.0,
392
+ )
393
+
394
+ # Training arguments
395
+ self.beta = args.beta
396
+ self.loss_type = args.loss_type
397
+ self.label_smoothing = args.label_smoothing
398
+ self.tpo_alpha = args.tpo_alpha
399
+ self.tpo_l_gamma = args.tpo_l_gamma
400
+ if self.loss_type in ["hinge", "ipo"] and self.label_smoothing > 0:
401
+ logger.warning(
402
+ f"You are using the {self.loss_type} loss type that does not support label smoothing. The "
403
+ "`label_smoothing` parameter will be ignored. Set `label_smoothing` to `0.0` to remove this warning."
404
+ )
405
+
406
+ # Dataset
407
+ train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train")
408
+ if eval_dataset is not None:
409
+ if isinstance(eval_dataset, dict):
410
+ eval_dataset = {
411
+ key: self._prepare_dataset(dataset, processing_class, args, key)
412
+ for key, dataset in eval_dataset.items()
413
+ }
414
+ else:
415
+ eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval")
416
+
417
+ # Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
418
+ # never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
419
+ # (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
420
+ # default to the recommended non-reentrant behavior here, while preserving any user-provided value.
421
+ if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
422
+ args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
423
+ args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
424
+
425
+ super().__init__(
426
+ model=model,
427
+ args=args,
428
+ data_collator=data_collator,
429
+ train_dataset=train_dataset,
430
+ eval_dataset=eval_dataset,
431
+ processing_class=processing_class,
432
+ compute_metrics=compute_metrics,
433
+ callbacks=callbacks,
434
+ optimizers=optimizers,
435
+ )
436
+
437
+ # Disable dropout in the model
438
+ if args.disable_dropout:
439
+ disable_dropout_in_model(model)
440
+
441
+ # Initialize the metrics
442
+ self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
443
+ self._total_train_tokens = 0
444
+
445
+ # Add tags to the model
446
+ self.model.add_model_tags(self._tag_names)
447
+
448
+ def _tokenize(
449
+ self,
450
+ processing_class: PreTrainedTokenizerBase,
451
+ input: str | list,
452
+ **kwargs,
453
+ ) -> dict[str, list]:
454
+ """Tokenize a single example for dataset preprocessing.
455
+
456
+ Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for
457
+ non-conversational input (str).
458
+
459
+ Args:
460
+ processing_class ([`~transformers.PreTrainedTokenizerBase`]):
461
+ The tokenizer to use.
462
+ input (`str` or `list`):
463
+ A string for non-conversational input, or a list of message dicts for conversational input.
464
+ **kwargs:
465
+ Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`).
466
+
467
+ Returns:
468
+ `dict` with at least an `"input_ids"` key mapping to a flat `list[int]`.
469
+ """
470
+ if isinstance(input, list): # conversational: list of message dicts
471
+ return processing_class.apply_chat_template(input, tokenize=True, return_dict=True, **kwargs)
472
+ # non-conversational: plain text string
473
+ return processing_class(text=input)
474
+
475
+ def _prepare_dataset(
476
+ self,
477
+ dataset: Dataset | IterableDataset,
478
+ processing_class: PreTrainedTokenizerBase,
479
+ args: TPOConfig,
480
+ dataset_name: str,
481
+ ) -> Dataset | IterableDataset:
482
+ # Validate that the triple-preference columns are present
483
+ first_example = next(iter(dataset))
484
+ if "chosen" not in first_example or "rejected" not in first_example:
485
+ raise ValueError(
486
+ "TPO requires a triple-preference dataset with `chosen`, `rejected` and `reference` columns, but the "
487
+ f"dataset is missing `chosen` or `rejected`. Got columns: {list(first_example.keys())}."
488
+ )
489
+ if "reference" not in first_example:
490
+ raise ValueError(
491
+ "TPO requires a triple-preference dataset with `chosen`, `rejected` and `reference` columns, but the "
492
+ f"dataset is missing the `reference` (gold) column. Got columns: {list(first_example.keys())}."
493
+ )
494
+
495
+ # Build the kwargs for the `map` function
496
+ map_kwargs = {}
497
+ if isinstance(dataset, Dataset): # IterableDataset does not support num_proc
498
+ map_kwargs["num_proc"] = args.dataset_num_proc
499
+
500
+ with PartialState().main_process_first():
501
+ # Extract the prompt if needed. Unlike DPO, we must also strip the extracted prompt from the reference
502
+ # column (see `_extract_triple_prompt`), which assumes the reference shares the same implicit prompt.
503
+ first_example = next(iter(dataset))
504
+ if "prompt" not in first_example:
505
+ if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
506
+ map_kwargs["desc"] = f"Extracting prompt from {dataset_name} dataset"
507
+ dataset = dataset.map(_extract_triple_prompt, **map_kwargs)
508
+
509
+ # Add EOS to completions for non-conversational data
510
+ first_example = next(iter(dataset))
511
+ if not is_conversational(first_example):
512
+ if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
513
+ map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset"
514
+
515
+ def add_eos(example, eos_token):
516
+ if not example["chosen"].endswith(eos_token):
517
+ example["chosen"] = example["chosen"] + eos_token
518
+ if not example["rejected"].endswith(eos_token):
519
+ example["rejected"] = example["rejected"] + eos_token
520
+ if not example["reference"].endswith(eos_token):
521
+ example["reference"] = example["reference"] + eos_token
522
+ return example
523
+
524
+ dataset = dataset.map(add_eos, fn_kwargs={"eos_token": processing_class.eos_token}, **map_kwargs)
525
+
526
+ # Tokenize the dataset
527
+ if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
528
+ map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset"
529
+
530
+ def tokenize_fn(example, processing_class):
531
+ tools = example.get("tools")
532
+ tools = json.loads(tools) if isinstance(tools, str) else tools
533
+ output = {}
534
+ if is_conversational(example):
535
+ prompt_ids = self._tokenize(
536
+ processing_class,
537
+ example["prompt"],
538
+ tools=tools,
539
+ add_generation_prompt=True,
540
+ **example.get("chat_template_kwargs", {}),
541
+ )["input_ids"]
542
+ prompt_chosen_ids = self._tokenize(
543
+ processing_class,
544
+ example["prompt"] + example["chosen"],
545
+ tools=tools,
546
+ **example.get("chat_template_kwargs", {}),
547
+ )["input_ids"]
548
+ prompt_rejected_ids = self._tokenize(
549
+ processing_class,
550
+ example["prompt"] + example["rejected"],
551
+ tools=tools,
552
+ **example.get("chat_template_kwargs", {}),
553
+ )["input_ids"]
554
+ prompt_reference_ids = self._tokenize(
555
+ processing_class,
556
+ example["prompt"] + example["reference"],
557
+ tools=tools,
558
+ **example.get("chat_template_kwargs", {}),
559
+ )["input_ids"]
560
+ else:
561
+ prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"]
562
+ prompt_chosen_ids = self._tokenize(processing_class, example["prompt"] + example["chosen"])[
563
+ "input_ids"
564
+ ]
565
+ prompt_rejected_ids = self._tokenize(processing_class, example["prompt"] + example["rejected"])[
566
+ "input_ids"
567
+ ]
568
+ prompt_reference_ids = self._tokenize(processing_class, example["prompt"] + example["reference"])[
569
+ "input_ids"
570
+ ]
571
+
572
+ # Check if the tokenized prompt starts with the tokenized prompt+completion
573
+ if not prompt_chosen_ids[: len(prompt_ids)] == prompt_ids:
574
+ logger.warning(
575
+ "Mismatch between tokenized prompt and the start of tokenized prompt+chosen. "
576
+ "This may be due to unexpected tokenizer behavior, whitespace issues, or special "
577
+ "token handling. Verify that the tokenizer is processing text consistently."
578
+ )
579
+ if not prompt_rejected_ids[: len(prompt_ids)] == prompt_ids:
580
+ logger.warning(
581
+ "Mismatch between tokenized prompt and the start of tokenized prompt+rejected. "
582
+ "This may be due to unexpected tokenizer behavior, whitespace issues, or special "
583
+ "token handling. Verify that the tokenizer is processing text consistently."
584
+ )
585
+ if not prompt_reference_ids[: len(prompt_ids)] == prompt_ids:
586
+ logger.warning(
587
+ "Mismatch between tokenized prompt and the start of tokenized prompt+reference. "
588
+ "This may be due to unexpected tokenizer behavior, whitespace issues, or special "
589
+ "token handling. Verify that the tokenizer is processing text consistently."
590
+ )
591
+
592
+ output["prompt_ids"] = prompt_ids
593
+ output["chosen_ids"] = prompt_chosen_ids[len(prompt_ids) :]
594
+ output["rejected_ids"] = prompt_rejected_ids[len(prompt_ids) :]
595
+ output["reference_ids"] = prompt_reference_ids[len(prompt_ids) :]
596
+ return output
597
+
598
+ dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs)
599
+
600
+ return dataset
601
+
602
+ def _set_signature_columns_if_needed(self):
603
+ # If `self.args.remove_unused_columns` is True, non-signature columns are removed.
604
+ # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids"
605
+ # and "attention_mask").
606
+ if self._signature_columns is None:
607
+ self._signature_columns = ["prompt_ids", "chosen_ids", "rejected_ids", "reference_ids"]
608
+
609
+ def _compute_loss(self, model, inputs, return_outputs):
610
+ mode = "train" if self.model.training else "eval"
611
+
612
+ # When `tpo_alpha=0.0` the NLL term is disabled and the collator drops the reference branch, so the batch
613
+ # is laid out as `[chosen, rejected]` (n_branches=2). Otherwise it is `[chosen, rejected, reference]`
614
+ # (n_branches=3).
615
+ n_branches = 3 if self.tpo_alpha != 0.0 else 2
616
+
617
+ _non_model_keys = {"completion_mask"}
618
+ model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys}
619
+ model_kwargs["use_cache"] = False
620
+ outputs = model(**model_kwargs)
621
+
622
+ input_ids = inputs["input_ids"]
623
+ completion_mask = inputs["completion_mask"]
624
+ shift_logits = outputs.logits[..., :-1, :]
625
+ shift_labels = input_ids[..., 1:]
626
+ shift_completion_mask = completion_mask[..., 1:]
627
+ per_token_logps = selective_log_softmax(shift_logits, shift_labels)
628
+ per_token_logps[shift_completion_mask == 0] = 0.0 # mask out non-completion tokens
629
+
630
+ # Length-normalized for IPO and TPO-L (matches the SimPO-style implicit reward used by the TPO paper);
631
+ # summed otherwise.
632
+ if self.loss_type in ("ipo", "tpo-l"):
633
+ completion_lengths = shift_completion_mask.sum(dim=1).clamp(min=1)
634
+ logps = per_token_logps.sum(dim=1) / completion_lengths
635
+ else:
636
+ logps = per_token_logps.sum(dim=1)
637
+ logps_chunks = logps.chunk(n_branches, dim=0)
638
+ chosen_logps, rejected_logps = logps_chunks[0], logps_chunks[1]
639
+
640
+ # Contrastive loss between chosen and rejected. Unlike DPO, TPO does not subtract reference-model log-probs:
641
+ # the "reference" in TPO is a gold response used in the NLL term below, not a separate reference policy.
642
+ delta_score = chosen_logps - rejected_logps
643
+
644
+ if self.loss_type == "sigmoid":
645
+ per_sequence_loss = (
646
+ -F.logsigmoid(self.beta * delta_score) * (1 - self.label_smoothing)
647
+ - F.logsigmoid(-self.beta * delta_score) * self.label_smoothing
648
+ )
649
+
650
+ elif self.loss_type == "hinge":
651
+ per_sequence_loss = torch.relu(1 - self.beta * delta_score)
652
+
653
+ elif self.loss_type == "ipo":
654
+ # (Eq. 17) of the IPO paper where beta is the regularization parameter for the IPO loss, denoted by τ.
655
+ per_sequence_loss = (delta_score - 1 / (2 * self.beta)) ** 2
656
+
657
+ elif self.loss_type == "tpo-l":
658
+ # Length-normalized TPO-L variant: subtract a target reward margin γ/β before the sigmoid.
659
+ gamma_logratios = self.tpo_l_gamma / self.beta
660
+ shifted_delta = delta_score - gamma_logratios
661
+ per_sequence_loss = (
662
+ -F.logsigmoid(self.beta * shifted_delta) * (1 - self.label_smoothing)
663
+ - F.logsigmoid(-self.beta * shifted_delta) * self.label_smoothing
664
+ )
665
+
666
+ else:
667
+ raise ValueError(
668
+ f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'tpo-l']"
669
+ )
670
+
671
+ loss = per_sequence_loss.mean()
672
+
673
+ # NLL loss on the gold (`reference`) response. Mirrors the `"sft"` loss branch of `DPOTrainer._compute_loss`:
674
+ # we restrict the cross-entropy to the completion tokens of the reference sequence and let `F.cross_entropy`
675
+ # average over them. The NLL contribution is folded into the main `loss` (matching DPO/SFT convention: the
676
+ # individual NLL term is not logged separately).
677
+ if n_branches == 3:
678
+ _, _, ref_logits = shift_logits.chunk(3, dim=0)
679
+ _, _, ref_labels = shift_labels.chunk(3, dim=0)
680
+ _, _, ref_mask = shift_completion_mask.chunk(3, dim=0)
681
+ ref_mask = ref_mask.bool()
682
+ nll_loss = F.cross_entropy(ref_logits[ref_mask], ref_labels[ref_mask])
683
+ loss = loss + self.tpo_alpha * nll_loss
684
+
685
+ # Log the metrics
686
+ # Entropy
687
+ per_token_entropy = entropy_from_logits(shift_logits.detach())
688
+ entropy = per_token_entropy[shift_completion_mask.bool()].mean()
689
+ entropy = self.accelerator.gather_for_metrics(entropy).mean().item()
690
+ self._metrics[mode]["entropy"].append(entropy)
691
+
692
+ # Number of tokens
693
+ if mode == "train":
694
+ num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item()
695
+ self._total_train_tokens += num_tokens_in_batch
696
+ self._metrics[mode]["num_tokens"] = [self._total_train_tokens]
697
+
698
+ # Average logits for chosen and rejected completions
699
+ logits_chunks = shift_logits.detach().chunk(n_branches, dim=0)
700
+ mask_chunks = shift_completion_mask.chunk(n_branches, dim=0)
701
+ labels_chunks = shift_labels.chunk(n_branches, dim=0)
702
+ chosen_logits, rejected_logits = logits_chunks[0], logits_chunks[1]
703
+ chosen_mask, rejected_mask = mask_chunks[0], mask_chunks[1]
704
+ chosen_labels = labels_chunks[0]
705
+ total_chosen_logits = chosen_logits[chosen_mask.bool()].mean(-1).sum()
706
+ total_chosen_tokens = chosen_mask.sum()
707
+ total_rejected_logits = rejected_logits[rejected_mask.bool()].mean(-1).sum()
708
+ total_rejected_tokens = rejected_mask.sum()
709
+ total_chosen_logits = self.accelerator.gather_for_metrics(total_chosen_logits).sum().item()
710
+ total_chosen_tokens = self.accelerator.gather_for_metrics(total_chosen_tokens).sum().item()
711
+ total_rejected_logits = self.accelerator.gather_for_metrics(total_rejected_logits).sum().item()
712
+ total_rejected_tokens = self.accelerator.gather_for_metrics(total_rejected_tokens).sum().item()
713
+ avg_chosen_logits = total_chosen_logits / total_chosen_tokens if total_chosen_tokens > 0 else 0.0
714
+ avg_rejected_logits = total_rejected_logits / total_rejected_tokens if total_rejected_tokens > 0 else 0.0
715
+ self._metrics[mode]["logits/chosen"].append(avg_chosen_logits)
716
+ self._metrics[mode]["logits/rejected"].append(avg_rejected_logits)
717
+
718
+ # Token accuracy for the chosen completions
719
+ predictions = chosen_logits.argmax(dim=-1)
720
+ chosen_bool_mask = chosen_mask.bool()
721
+ correct_predictions = (predictions == chosen_labels) & chosen_bool_mask
722
+ total_tokens = chosen_bool_mask.sum()
723
+ correct_tokens = correct_predictions.sum()
724
+ correct_tokens = self.accelerator.gather_for_metrics(correct_tokens)
725
+ total_tokens = self.accelerator.gather_for_metrics(total_tokens)
726
+ total_sum = total_tokens.sum()
727
+ accuracy = (correct_tokens.sum() / total_sum).item() if total_sum > 0 else 0.0
728
+ self._metrics[mode]["mean_token_accuracy"].append(accuracy)
729
+
730
+ # Rewards for chosen and rejected completions (β · log π_θ as in the SimPO/TPO implicit reward)
731
+ chosen_rewards = self.beta * chosen_logps.detach()
732
+ rejected_rewards = self.beta * rejected_logps.detach()
733
+ agg_chosen_rewards = self.accelerator.gather(chosen_rewards)
734
+ agg_rejected_rewards = self.accelerator.gather(rejected_rewards)
735
+ self._metrics[mode]["rewards/chosen"].append(agg_chosen_rewards.mean().item())
736
+ self._metrics[mode]["rewards/rejected"].append(agg_rejected_rewards.mean().item())
737
+
738
+ # Reward accuracy
739
+ reward_accuracies = (chosen_rewards > rejected_rewards).float()
740
+ agg_reward_accuracies = self.accelerator.gather(reward_accuracies)
741
+ self._metrics[mode]["rewards/accuracies"].append(agg_reward_accuracies.mean().item())
742
+
743
+ # Reward margins
744
+ margins = chosen_rewards - rejected_rewards
745
+ agg_margins = self.accelerator.gather(margins)
746
+ self._metrics[mode]["rewards/margins"].append(agg_margins.mean().item())
747
+
748
+ # Average log probabilities for chosen and rejected completions
749
+ self._metrics[mode]["logps/chosen"].append(self.accelerator.gather(chosen_logps).mean().item())
750
+ self._metrics[mode]["logps/rejected"].append(self.accelerator.gather(rejected_logps).mean().item())
751
+
752
+ return (loss, outputs) if return_outputs else loss
753
+
754
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
755
+ return self._compute_loss(model, inputs, return_outputs)
756
+
757
+ def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
758
+ mode = "train" if self.model.training else "eval"
759
+ metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics
760
+
761
+ # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
762
+ # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
763
+ if mode == "eval":
764
+ metrics = {f"eval_{key}": val for key, val in metrics.items()}
765
+
766
+ logs.update(metrics)
767
+ super().log(logs, start_time)
768
+ self._metrics[mode].clear()
769
+
770
+ # During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and
771
+ # returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels.
772
+ def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None):
773
+ inputs = self._prepare_inputs(inputs)
774
+ with torch.no_grad(), self.compute_loss_context_manager():
775
+ if prediction_loss_only:
776
+ loss = self.compute_loss(model, inputs, return_outputs=False)
777
+ logits, labels = None, None
778
+ else:
779
+ loss, outputs = self.compute_loss(model, inputs, return_outputs=True)
780
+ logits, labels = outputs.logits, inputs["input_ids"]
781
+ return loss, logits, labels
782
+
783
+ # Ensure the model card is saved along with the checkpoint
784
+ def _save_checkpoint(self, model, trial):
785
+ if self.args.hub_model_id is None:
786
+ model_name = Path(self.args.output_dir).name
787
+ else:
788
+ model_name = self.args.hub_model_id.split("/")[-1]
789
+ self.create_model_card(model_name=model_name)
790
+ super()._save_checkpoint(model, trial)
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/utils.py ADDED
@@ -0,0 +1,858 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # This file contains utility classes and functions that are used across more than one experimental trainer or feature.
16
+
17
+ import inspect
18
+ import logging
19
+ from copy import deepcopy
20
+ from dataclasses import dataclass
21
+ from typing import Any
22
+
23
+ import pyarrow as pa
24
+ import pyarrow.types
25
+ import torch
26
+ from accelerate.utils import is_peft_model
27
+ from packaging.version import Version
28
+ from pyarrow import compute as pc
29
+ from torch import nn
30
+ from torch.nn.utils.rnn import pad_sequence
31
+ from transformers import PreTrainedModel, PreTrainedTokenizerBase, TrainingArguments
32
+ from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
33
+ from transformers.utils import (
34
+ is_peft_available,
35
+ is_torch_mlu_available,
36
+ is_torch_mps_available,
37
+ is_torch_npu_available,
38
+ is_torch_xpu_available,
39
+ )
40
+
41
+ from ..data_utils import DatasetType, _get_dataset_format
42
+ from ..trainer.utils import pad
43
+
44
+
45
+ if is_peft_available():
46
+ import peft
47
+ from peft import PeftConfig, PeftModel, get_peft_model
48
+
49
+
50
+ @dataclass
51
+ class DPODataCollatorWithPadding:
52
+ r"""
53
+ DPO DataCollator class that pads the tokenized inputs to the maximum length of the batch.
54
+
55
+ Args:
56
+ pad_token_id (`int` defaults to 0):
57
+ The tokenizer's pad_token_id.
58
+ is_encoder_decoder (`bool` or `None`, `optional`, defaults to `None`):
59
+ Whether you model has an encoder_decoder architecture.
60
+ """
61
+
62
+ pad_token_id: int = 0
63
+ is_encoder_decoder: bool | None = False
64
+
65
+ def __call__(self, features: list[dict[str, Any]]) -> dict[str, Any]:
66
+ # first, pad everything to the same length
67
+ padded_batch = {}
68
+ for k in features[0].keys():
69
+ if k.endswith(("_input_ids", "_attention_mask", "_labels", "_pixel_values")):
70
+ if self.is_encoder_decoder:
71
+ to_pad = [torch.LongTensor(ex[k]) for ex in features]
72
+
73
+ if (k.startswith("prompt")) and (k.endswith("input_ids")):
74
+ if self.pad_token_id is None:
75
+ raise ValueError(
76
+ "Padding is enabled, but the tokenizer is not configured with a padding token."
77
+ " Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)"
78
+ " before calling the trainer."
79
+ )
80
+ padding_value = self.pad_token_id
81
+ elif k.endswith("_attention_mask"):
82
+ padding_value = 0
83
+ elif k.startswith(("chosen", "rejected", "completion")) or ("decoder" in k):
84
+ padding_value = -100
85
+ else:
86
+ raise ValueError(f"Unexpected key in batch '{k}'")
87
+ padded_batch[k] = pad_sequence(to_pad, batch_first=True, padding_value=padding_value)
88
+ else:
89
+ # Set padding value based on the key
90
+ if k.endswith("_input_ids"):
91
+ if self.pad_token_id is None:
92
+ raise ValueError(
93
+ "Padding is enabled, but the tokenizer is not configured with a padding token."
94
+ " Explicitly set `tokenizer.pad_token` (e.g. `tokenizer.pad_token = tokenizer.eos_token`)"
95
+ " before calling the trainer."
96
+ )
97
+ padding_value = self.pad_token_id
98
+ elif k.endswith("_labels"):
99
+ padding_value = -100
100
+ elif k.endswith("_attention_mask"):
101
+ padding_value = 0
102
+ elif k.endswith("_pixel_values"):
103
+ padding_value = 0 # TODO: check if this is correct
104
+ else:
105
+ raise ValueError(f"Unexpected key in batch '{k}'")
106
+
107
+ # Set padding side based on the key
108
+ if k in ["prompt_input_ids", "prompt_attention_mask"]:
109
+ padding_side = "left"
110
+ else:
111
+ padding_side = "right"
112
+
113
+ # Set the dtype
114
+ if k.endswith("_pixel_values"):
115
+ dtype = torch.float32 # will be downcasted if necessary by the Trainer
116
+ else:
117
+ dtype = torch.int64
118
+
119
+ # Convert to tensor and pad
120
+ to_pad = [torch.tensor(ex[k], dtype=dtype) for ex in features]
121
+ padded_batch[k] = pad(to_pad, padding_value=padding_value, padding_side=padding_side)
122
+ elif k.endswith("_logps"):
123
+ # the cached reference model logprobs
124
+ padded_batch[k] = torch.tensor([ex[k] for ex in features])
125
+ else:
126
+ padded_batch[k] = [ex[k] for ex in features]
127
+
128
+ return padded_batch
129
+
130
+
131
+ def pad_byte_offsets(offsets: list[tuple[int, int]], target_length: int, padding_side: str) -> torch.Tensor:
132
+ """Build a ``[target_length, 2]`` long tensor from ``(start, end)`` byte-offset tuples,
133
+ padding with ``(0, 0)`` on the requested side."""
134
+ offs = torch.tensor(offsets, dtype=torch.long).reshape(-1, 2)
135
+ pad_len = target_length - offs.size(0)
136
+ if pad_len <= 0:
137
+ return offs
138
+ pad_block = torch.zeros(pad_len, 2, dtype=torch.long)
139
+ return torch.cat([pad_block, offs], dim=0) if padding_side == "left" else torch.cat([offs, pad_block], dim=0)
140
+
141
+
142
+ def is_byte_level_tokenizer(backend) -> bool:
143
+ """Whether ``backend`` is a ByteLevel BPE tokenizer (Llama-3 family, SmolLM, Qwen, \u2026) \u2014 its pieces are in
144
+ byte\u2192unicode space, one char per source byte. Detected via the pre-tokenizer / decoder repr."""
145
+ return "ByteLevel" in repr(backend.pre_tokenizer) or "ByteLevel" in repr(backend.decoder)
146
+
147
+
148
+ def piece_byte_len(piece: str) -> int:
149
+ """UTF-8 byte length of a ByteLevel BPE token piece \u2014 each char maps 1:1 to one source byte.
150
+
151
+ Cross-tokenizer ULD targets ByteLevel BPE pairs (Llama-3, Qwen, SmolLM, Phi, Mistral v0.3+, \u2026); SentencePiece
152
+ students are out of scope here and would need the loss-level projection from X-Token to align."""
153
+ return len(piece)
154
+
155
+
156
+ def _bytes_to_unicode() -> dict[int, str]:
157
+ bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("\u00a1"), ord("\u00ac") + 1))
158
+ bs += list(range(ord("\u00ae"), ord("\u00ff") + 1))
159
+ cs = bs[:]
160
+ n = 0
161
+ for b in range(256):
162
+ if b not in bs:
163
+ bs.append(b)
164
+ cs.append(256 + n)
165
+ n += 1
166
+ return dict(zip(bs, [chr(n) for n in cs], strict=True))
167
+
168
+
169
+ _BYTE_LEVEL_DECODER = {ch: b for b, ch in _bytes_to_unicode().items()}
170
+
171
+
172
+ def _byte_level_piece_len(piece: str, text_bytes: bytes, start: int) -> int | None:
173
+ piece_bytes = []
174
+ for ch in piece:
175
+ if ch not in _BYTE_LEVEL_DECODER:
176
+ return None
177
+ piece_bytes.append(_BYTE_LEVEL_DECODER[ch])
178
+ if piece_bytes and piece_bytes[0] == ord(" ") and text_bytes[start : start + 1] != b" ":
179
+ piece_bytes = piece_bytes[1:]
180
+ return len(piece_bytes)
181
+
182
+
183
+ def _split_repeated_byte_offsets(byte_offsets: list[tuple[int, int]], tokens: list[str]) -> list[tuple[int, int]]:
184
+ """Split repeated char-derived spans for byte-fallback or byte-level tokens."""
185
+ normalized = list(byte_offsets)
186
+ i = 0
187
+ while i < len(byte_offsets):
188
+ j = i + 1
189
+ while j < len(byte_offsets) and byte_offsets[j] == byte_offsets[i]:
190
+ j += 1
191
+
192
+ if j - i > 1:
193
+ start, end = byte_offsets[i]
194
+ piece_lengths = [piece_byte_len(token) for token in tokens[i:j]]
195
+ if sum(piece_lengths) == end - start:
196
+ cursor = start
197
+ for offset_idx, length in enumerate(piece_lengths, start=i):
198
+ normalized[offset_idx] = (cursor, cursor + length)
199
+ cursor += length
200
+
201
+ i = j
202
+ return normalized
203
+
204
+
205
+ def _normalize_byte_offsets(
206
+ byte_offsets: list[tuple[int, int]], tokens: list[str], text_bytes: bytes
207
+ ) -> list[tuple[int, int]]:
208
+ byte_offsets = _split_repeated_byte_offsets(byte_offsets, tokens)
209
+ normalized = []
210
+ cursor = 0
211
+
212
+ for idx, (start, end) in enumerate(byte_offsets):
213
+ if start == end:
214
+ normalized.append((cursor, cursor))
215
+ continue
216
+
217
+ piece_len = _byte_level_piece_len(tokens[idx], text_bytes, start)
218
+ next_start = byte_offsets[idx + 1][0] if idx + 1 < len(byte_offsets) else None
219
+ has_overlap = start < cursor or (next_start is not None and next_start < end)
220
+
221
+ if piece_len is not None and (has_overlap or piece_len == end - start):
222
+ candidate_start = max(start, cursor)
223
+ candidate_end = candidate_start + piece_len
224
+ if candidate_end <= end:
225
+ start = candidate_start
226
+ end = candidate_end
227
+
228
+ if start < cursor or end < start:
229
+ raise ValueError(
230
+ "Tokenizer produced overlapping byte offsets that could not be normalized. "
231
+ "Cross-tokenizer ULD requires monotonic byte offsets."
232
+ )
233
+
234
+ normalized.append((start, end))
235
+ cursor = end
236
+
237
+ return normalized
238
+
239
+
240
+ def encode_with_byte_offsets(backend, texts: list[str], add_special_tokens: bool = False):
241
+ """Encode ``texts`` and return per-text ``(ids, byte_offsets)`` pairs.
242
+
243
+ Byte offsets are derived from the fast tokenizer's character offsets via an O(N) char-to-byte cumulative table.
244
+ Overlapping spans from byte-level and byte-fallback tokens are split across their byte pieces."""
245
+ if not is_byte_level_tokenizer(backend):
246
+ raise NotImplementedError(
247
+ "Cross-tokenizer ULD currently supports only ByteLevel BPE tokenizers "
248
+ "(Llama-3, Qwen, SmolLM, Phi, Mistral v0.3+, …). The given tokenizer is not ByteLevel."
249
+ )
250
+ encs = backend.encode_batch(texts, add_special_tokens=add_special_tokens)
251
+ out = []
252
+ for text, enc in zip(texts, encs, strict=True):
253
+ char_to_byte = [0]
254
+ for ch in text:
255
+ char_to_byte.append(char_to_byte[-1] + len(ch.encode("utf-8")))
256
+ byte_offsets = [(char_to_byte[s], char_to_byte[e]) for s, e in enc.offsets]
257
+ byte_offsets = _normalize_byte_offsets(byte_offsets, enc.tokens, text.encode("utf-8"))
258
+ out.append((list(enc.ids), byte_offsets))
259
+ return out
260
+
261
+
262
+ @dataclass
263
+ class DataCollatorForChatML:
264
+ """
265
+ Data collator for ChatML format datasets.
266
+ """
267
+
268
+ tokenizer: PreTrainedTokenizerBase
269
+ ignore_index: int = -100
270
+ max_length: int = None
271
+ prompt_key: str = "prompt"
272
+ messages_key: str = "messages"
273
+
274
+ def __post_init__(self):
275
+ if self.tokenizer.pad_token_id is None:
276
+ raise ValueError("The tokenizer does not have a pad token. Please set `pad_token_id` in the tokenizer.")
277
+ if self.max_length is None:
278
+ # set a sensible default
279
+ self.max_length = min(self.tokenizer.model_max_length, 1024)
280
+
281
+ def __call__(self, examples: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
282
+ input_ids = []
283
+ attention_mask = []
284
+ prompts_input_ids = []
285
+ prompt_attention_mask = []
286
+ labels = []
287
+ byte_offsets: list[list[tuple[int, int]]] = []
288
+
289
+ for example in examples:
290
+ formatted_prompt = example.get(self.prompt_key, example.get("original_prompt_text", None))
291
+ if formatted_prompt is None:
292
+ prompt = example[self.messages_key][:-1]
293
+ formatted_prompt = self.tokenizer.apply_chat_template(
294
+ prompt, add_generation_prompt=True, tokenize=False
295
+ )
296
+
297
+ if "input_ids" not in example:
298
+ message = example[self.messages_key]
299
+ formatted_message = self.tokenizer.apply_chat_template(
300
+ message, add_generation_prompt=False, tokenize=False
301
+ )
302
+ if is_byte_level_tokenizer(self.tokenizer.backend_tokenizer):
303
+ [(message_input_ids_full, full_offs)] = encode_with_byte_offsets(
304
+ self.tokenizer.backend_tokenizer, [formatted_message], add_special_tokens=False
305
+ )
306
+ prompt_byte_len = len(formatted_prompt.encode("utf-8"))
307
+ completion_start_idx_full = next(
308
+ (idx for idx, (start, _) in enumerate(full_offs) if start >= prompt_byte_len),
309
+ len(message_input_ids_full),
310
+ )
311
+ else:
312
+ # Non-ByteLevel tokenizer: byte offsets are unnecessary (cross-tokenizer ULD requires ByteLevel
313
+ # anyway). Fall back to plain tokenization so GKD / non-ULD trainers with SentencePiece or
314
+ # Unigram tokenizers still work through this collator.
315
+ message_input_ids_full = self.tokenizer(
316
+ formatted_message, add_special_tokens=False, return_tensors=None
317
+ )["input_ids"]
318
+ completion_start_idx_full = len(
319
+ self.tokenizer(formatted_prompt, add_special_tokens=False, return_tensors=None)["input_ids"]
320
+ )
321
+ full_offs = [(0, 0)] * len(message_input_ids_full)
322
+ prompt_byte_len = 0
323
+
324
+ # Keep the last max_length tokens — drops oldest prompt context first,
325
+ # never drops from the END (the model's recent context).
326
+ if self.max_length is not None and len(message_input_ids_full) > self.max_length:
327
+ sample_ids = message_input_ids_full[-self.max_length :]
328
+ sample_offs = full_offs[-self.max_length :]
329
+ current_prompt_len = max(
330
+ 0, completion_start_idx_full - (len(message_input_ids_full) - self.max_length)
331
+ )
332
+ else:
333
+ sample_ids = message_input_ids_full
334
+ sample_offs = full_offs
335
+ current_prompt_len = completion_start_idx_full
336
+
337
+ # Make completion-relative: prompt positions zeroed, completion offsets shifted. If truncation
338
+ # ate into the completion (no prompt tokens kept and the first kept token is mid-completion),
339
+ # rebase to byte 0 of the kept completion so teacher/student share the same coordinate system.
340
+ kept_completion_offs = sample_offs[current_prompt_len:]
341
+ base = (
342
+ kept_completion_offs[0][0] if kept_completion_offs and current_prompt_len == 0 else prompt_byte_len
343
+ )
344
+ completion_offs = [(s - base, e - base) for s, e in kept_completion_offs]
345
+ sample_offs = [(0, 0)] * current_prompt_len + completion_offs
346
+
347
+ input_ids.append(sample_ids)
348
+ attention_mask.append([1] * len(sample_ids))
349
+ current_prompt_ids = sample_ids[:current_prompt_len]
350
+ byte_offsets.append(sample_offs)
351
+ else:
352
+ sample_ids = example["input_ids"]
353
+ input_ids.append(sample_ids)
354
+ attention_mask.append(example.get("attention_mask", [1] * len(sample_ids)))
355
+ completion_mask = example.get("completion_mask")
356
+ if completion_mask is not None:
357
+ # Use the tracked boundary directly: no re-tokenization, survives truncation.
358
+ prompt_len = completion_mask.index(1) if 1 in completion_mask else len(sample_ids)
359
+ current_prompt_ids = sample_ids[:prompt_len]
360
+ else:
361
+ # No tracked boundary: tokenize the prompt and cap with a slice (avoid `truncation=True`,
362
+ # which would persist on the shared backend used by `encode_with_byte_offsets`).
363
+ tokenized_prompt = self.tokenizer(
364
+ formatted_prompt,
365
+ padding=False,
366
+ return_tensors=None,
367
+ add_special_tokens=False,
368
+ )
369
+ current_prompt_ids = tokenized_prompt["input_ids"][: len(sample_ids)]
370
+ byte_offsets.append(example.get("byte_offsets", [(0, 0)] * len(sample_ids)))
371
+
372
+ prompts_input_ids.append(current_prompt_ids)
373
+ prompt_attention_mask.append([1] * len(current_prompt_ids))
374
+
375
+ label = [self.ignore_index] * len(sample_ids)
376
+ label[len(current_prompt_ids) :] = sample_ids[len(current_prompt_ids) :]
377
+ labels.append(label)
378
+
379
+ input_ids = pad(
380
+ [torch.tensor(x, dtype=torch.long) for x in input_ids],
381
+ padding_side="left",
382
+ padding_value=self.tokenizer.pad_token_id,
383
+ )
384
+ attention_mask = pad(
385
+ [torch.tensor(x, dtype=torch.long) for x in attention_mask], padding_side="left", padding_value=0
386
+ )
387
+ labels = pad(
388
+ [torch.tensor(x, dtype=torch.long) for x in labels], padding_side="left", padding_value=self.ignore_index
389
+ )
390
+ prompts_input_ids = pad(
391
+ [torch.tensor(x, dtype=torch.long) for x in prompts_input_ids],
392
+ padding_side="left",
393
+ padding_value=self.tokenizer.pad_token_id,
394
+ )
395
+ prompt_attention_mask = pad(
396
+ [torch.tensor(x, dtype=torch.long) for x in prompt_attention_mask], padding_side="left", padding_value=0
397
+ )
398
+
399
+ target_len = input_ids.size(1)
400
+ byte_offsets_tensor = torch.stack(
401
+ [pad_byte_offsets(offs, target_len, padding_side="left") for offs in byte_offsets], dim=0
402
+ )
403
+
404
+ out = {
405
+ "input_ids": input_ids,
406
+ "attention_mask": attention_mask,
407
+ "labels": labels,
408
+ "prompts": prompts_input_ids,
409
+ "prompt_attention_mask": prompt_attention_mask,
410
+ "byte_offsets": byte_offsets_tensor,
411
+ }
412
+ # Forward source text for cross-tokenizer ULD, when the dataset has it.
413
+ if "original_prompt_text" in examples[0] and "original_completion_text" in examples[0]:
414
+ out["original_prompt_text"] = [ex["original_prompt_text"] for ex in examples]
415
+ out["original_completion_text"] = [ex["original_completion_text"] for ex in examples]
416
+ return out
417
+
418
+
419
+ def truncate_right(
420
+ input_ids: torch.Tensor, stop_token_id: int, pad_token_id: int
421
+ ) -> tuple[torch.Tensor, torch.Tensor]:
422
+ """
423
+ Truncates the input tensor from the right side after the first occurrence of the stop token.
424
+
425
+ Args:
426
+ input_ids (`torch.Tensor`):
427
+ The tensor containing the responses to be truncated
428
+ stop_token_id (`int`):
429
+ The token ID representing the stop token where truncation occurs
430
+ pad_token_id (`int`):
431
+ The token ID representing the pad token used to fill the truncated responses
432
+
433
+ Returns:
434
+ tuple:
435
+ - `output_ids` (`torch.Tensor`):
436
+ The truncated responses tensor with pad tokens filled after the stop token
437
+ - `mask` (`torch.Tensor`):
438
+ The mask tensor to indicate the padding tokens
439
+ """
440
+ trunc_idxs = first_true_indices(input_ids == stop_token_id).unsqueeze(-1)
441
+ new_size = [1] * (len(input_ids.size()) - 1) + [input_ids.shape[1]]
442
+ idxs = torch.arange(input_ids.shape[1], device=input_ids.device).view(*new_size)
443
+ output_ids = torch.masked_fill(input_ids, idxs > trunc_idxs, pad_token_id)
444
+ mask = torch.masked_fill(torch.ones_like(input_ids), idxs > trunc_idxs, 0)
445
+ return output_ids, mask
446
+
447
+
448
+ def add_bos_token_if_needed(
449
+ bos_token_id: int | None,
450
+ prompt_len_input_ids: int,
451
+ prompt_tokens: dict[str, list[int]],
452
+ chosen_prompt_len_input_ids: int,
453
+ chosen_tokens: dict[str, list[int]],
454
+ rejected_prompt_len_input_ids: int,
455
+ rejected_tokens: dict[str, list[int]],
456
+ ):
457
+ if bos_token_id is not None:
458
+ if prompt_len_input_ids == 0 or bos_token_id != prompt_tokens["prompt_input_ids"][0]:
459
+ prompt_tokens["prompt_input_ids"] = [bos_token_id] + prompt_tokens["prompt_input_ids"]
460
+ prompt_tokens["prompt_attention_mask"] = [1] + prompt_tokens["prompt_attention_mask"]
461
+ if chosen_prompt_len_input_ids == 0 or bos_token_id != chosen_tokens["prompt_input_ids"][0]:
462
+ chosen_tokens["prompt_input_ids"] = [bos_token_id] + chosen_tokens["prompt_input_ids"]
463
+ chosen_tokens["prompt_attention_mask"] = [1] + chosen_tokens["prompt_attention_mask"]
464
+ if rejected_prompt_len_input_ids == 0 or bos_token_id != rejected_tokens["prompt_input_ids"][0]:
465
+ rejected_tokens["prompt_input_ids"] = [bos_token_id] + rejected_tokens["prompt_input_ids"]
466
+ rejected_tokens["prompt_attention_mask"] = [1] + rejected_tokens["prompt_attention_mask"]
467
+ return prompt_tokens, chosen_tokens, rejected_tokens
468
+
469
+
470
+ def add_eos_token_if_needed(
471
+ eos_token_id: int, chosen_tokens: dict[str, list[int]], rejected_tokens: dict[str, list[int]]
472
+ ):
473
+ if len(chosen_tokens["input_ids"]) == 0 or eos_token_id != chosen_tokens["input_ids"][-1]:
474
+ chosen_tokens["input_ids"].append(eos_token_id)
475
+ chosen_tokens["attention_mask"].append(1)
476
+ if len(rejected_tokens["input_ids"]) == 0 or eos_token_id != rejected_tokens["input_ids"][-1]:
477
+ rejected_tokens["input_ids"].append(eos_token_id)
478
+ rejected_tokens["attention_mask"].append(1)
479
+ return chosen_tokens, rejected_tokens
480
+
481
+
482
+ def first_true_indices(bools: torch.Tensor, dtype=torch.long) -> torch.Tensor:
483
+ """
484
+ Takes an N-dimensional bool tensor and returns an (N-1)-dimensional tensor of integers giving the position of the
485
+ first True in each "row".
486
+
487
+ Returns the length of the rows (bools.size(-1)) if no element is True in a given row.
488
+
489
+ Args:
490
+ bools (`torch.Tensor`):
491
+ An N-dimensional boolean tensor.
492
+ dtype (`torch.dtype`, *optional*):
493
+ The desired data type of the output tensor. Defaults to `torch.long`.
494
+
495
+ Returns:
496
+ `torch.Tensor`:
497
+ An (N-1)-dimensional tensor of integers indicating the position of the first True in each row. If no True
498
+ value is found in a row, returns the length of the row.
499
+ """
500
+ row_len = bools.size(-1)
501
+ zero_or_index = row_len * (~bools).type(dtype) + torch.arange(row_len, dtype=dtype, device=bools.device)
502
+ return torch.min(zero_or_index, dim=-1).values
503
+
504
+
505
+ def get_reward(
506
+ model: torch.nn.Module, query_responses: torch.Tensor, pad_token_id: int, context_length: int
507
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
508
+ """
509
+ Computes the reward logits and the rewards for a given model and query responses.
510
+
511
+ Args:
512
+ model (`torch.nn.Module`):
513
+ The model used to compute the reward logits.
514
+ query_responses (`torch.Tensor`):
515
+ The tensor containing the query responses.
516
+ pad_token_id (`int`):
517
+ The token ID representing the pad token.
518
+ context_length (`int`):
519
+ The length of the context in the query responses.
520
+
521
+ Returns:
522
+ tuple:
523
+ - `reward_logits` (`torch.Tensor`):
524
+ The logits for the reward model.
525
+ - `final_rewards` (`torch.Tensor`):
526
+ The final rewards for each query response.
527
+ - `sequence_lengths` (`torch.Tensor`):
528
+ The lengths of the sequences in the query responses.
529
+ """
530
+ attention_mask = query_responses != pad_token_id
531
+ position_ids = attention_mask.cumsum(1) - attention_mask.long() # exclusive cumsum
532
+ lm_backbone = getattr(model, model.base_model_prefix)
533
+ input_ids = torch.masked_fill(query_responses, ~attention_mask, 0)
534
+ output = lm_backbone(
535
+ input_ids=input_ids,
536
+ attention_mask=attention_mask,
537
+ position_ids=position_ids,
538
+ return_dict=True,
539
+ output_hidden_states=True,
540
+ use_cache=False, # otherwise mistral-based RM would error out
541
+ )
542
+ reward_logits = model.score(output.hidden_states[-1])
543
+ sequence_lengths = first_true_indices(query_responses[:, context_length:] == pad_token_id) - 1 + context_length
544
+ # https://github.com/huggingface/transformers/blob/dc68a39c8111217683bf49a4912d0c9018bab33d/src/transformers/models/gpt2/modeling_gpt2.py#L1454
545
+ return (
546
+ reward_logits,
547
+ reward_logits[
548
+ torch.arange(reward_logits.size(0), device=reward_logits.device),
549
+ sequence_lengths,
550
+ ].squeeze(-1),
551
+ sequence_lengths,
552
+ )
553
+
554
+
555
+ def prepare_model_for_kbit_training(model, use_gradient_checkpointing=True, gradient_checkpointing_kwargs=None):
556
+ r"""
557
+ Prepare a k-bit quantized transformers model for training (PEFT/QLoRA).
558
+ """
559
+ loaded_in_kbit = getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False)
560
+ quant_methods = ["gptq", "aqlm", "eetq", "torchao", "hqq"]
561
+ is_quantized = getattr(model, "quantization_method", None) in quant_methods or getattr(
562
+ model, "hqq_quantized", False
563
+ )
564
+
565
+ if gradient_checkpointing_kwargs is None:
566
+ gradient_checkpointing_kwargs = {}
567
+
568
+ for _, param in model.named_parameters():
569
+ # freeze all parameters
570
+ param.requires_grad = False
571
+
572
+ # Enable gradient checkpointing if needed
573
+ if (loaded_in_kbit or is_quantized) and use_gradient_checkpointing:
574
+ if hasattr(model, "enable_input_require_grads"):
575
+ model.enable_input_require_grads()
576
+ else:
577
+ # backward-compatible hook
578
+ def make_inputs_require_grad(module, input, output):
579
+ output.requires_grad_(True)
580
+
581
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
582
+
583
+ supports_gc_kwargs = "gradient_checkpointing_kwargs" in list(
584
+ inspect.signature(model.gradient_checkpointing_enable).parameters
585
+ )
586
+ gc_kwargs = {"gradient_checkpointing_kwargs": gradient_checkpointing_kwargs} if supports_gc_kwargs else {}
587
+ model.gradient_checkpointing_enable(**gc_kwargs)
588
+
589
+ return model
590
+
591
+
592
+ def enable_gradient_checkpointing(
593
+ model: PreTrainedModel, gradient_checkpointing_kwargs: dict | None
594
+ ) -> PreTrainedModel:
595
+ """Enables gradient checkpointing for the model."""
596
+ # Enable gradient checkpointing on the base model for PEFT
597
+ if is_peft_model(model):
598
+ model.base_model.gradient_checkpointing_enable()
599
+ # Enable gradient checkpointing for non-PEFT models
600
+ else:
601
+ model.gradient_checkpointing_enable()
602
+
603
+ gradient_checkpointing_kwargs = gradient_checkpointing_kwargs or {}
604
+ use_reentrant = (
605
+ "use_reentrant" not in gradient_checkpointing_kwargs or gradient_checkpointing_kwargs["use_reentrant"]
606
+ )
607
+
608
+ if use_reentrant:
609
+ if hasattr(model, "enable_input_require_grads"):
610
+ model.enable_input_require_grads()
611
+ else:
612
+
613
+ def make_inputs_require_grad(module, input, output):
614
+ output.requires_grad_(True)
615
+
616
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
617
+
618
+ return model
619
+
620
+
621
+ def prepare_peft_model(
622
+ model: PreTrainedModel, peft_config: "PeftConfig | None", args: TrainingArguments
623
+ ) -> PreTrainedModel:
624
+ """Prepares a model for PEFT training."""
625
+ if not is_peft_available():
626
+ raise ImportError("PEFT is required to use a peft model. Run `pip install peft`.")
627
+
628
+ if isinstance(model, PeftModel) and peft_config is not None:
629
+ raise ValueError(
630
+ "You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge and "
631
+ "unload the existing adapter, save the resulting base model, and then pass that base model along with the "
632
+ "new `peft_config` to the trainer."
633
+ )
634
+
635
+ # Handle quantized models (QLoRA)
636
+ is_qlora = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False)
637
+
638
+ is_sharded_qlora = False
639
+ if getattr(model, "is_loaded_in_4bit", False):
640
+ # Check if model is sharded (FSDP/DS-Zero3)
641
+ for _, param in model.named_parameters():
642
+ if param.__class__.__name__ == "Params4bit":
643
+ is_sharded_qlora = param.data.device.type in {"cpu", "meta"}
644
+ break
645
+
646
+ # Prepare model for kbit training if needed
647
+ if is_qlora and not is_sharded_qlora and not isinstance(model, PeftModel):
648
+ model = prepare_model_for_kbit_training(
649
+ model,
650
+ use_gradient_checkpointing=args.gradient_checkpointing,
651
+ gradient_checkpointing_kwargs=args.gradient_checkpointing_kwargs or {},
652
+ )
653
+ # Disable gradient checkpointing as it's handled by prepare_model_for_kbit_training
654
+ args.gradient_checkpointing = False
655
+ elif args.gradient_checkpointing:
656
+ model = enable_gradient_checkpointing(model, args.gradient_checkpointing_kwargs)
657
+
658
+ # Create PEFT model
659
+ if peft_config is not None:
660
+ if (
661
+ Version(peft.__version__) >= Version("0.12") # autocast_adapter_dtype introduced in 0.12
662
+ and getattr(model, "is_loaded_in_4bit", False)
663
+ and is_sharded_qlora
664
+ ):
665
+ model = get_peft_model(model, peft_config, autocast_adapter_dtype=False)
666
+ else:
667
+ model = get_peft_model(model, peft_config)
668
+
669
+ # Handle bf16 casting for 4-bit models
670
+ if args.bf16 and getattr(model, "is_loaded_in_4bit", False) and not is_sharded_qlora:
671
+ peft_module_casting_to_bf16(model)
672
+
673
+ return model
674
+
675
+
676
+ def pad_to_length(tensor: torch.Tensor, length: int, pad_value: int | float, dim: int = -1) -> torch.Tensor:
677
+ if tensor.size(dim) >= length:
678
+ return tensor
679
+ else:
680
+ pad_size = list(tensor.shape)
681
+ pad_size[dim] = length - tensor.size(dim)
682
+ return torch.cat(
683
+ [
684
+ tensor,
685
+ pad_value * torch.ones(*pad_size, dtype=tensor.dtype, device=tensor.device),
686
+ ],
687
+ dim=dim,
688
+ )
689
+
690
+
691
+ def empty_cache() -> None:
692
+ """Empties the cache of the available torch device.
693
+
694
+ This function checks for the availability of different torch devices (CUDA, MLU, MPS, NPU, XPU) and empties the
695
+ cache of the first available device it finds.
696
+
697
+ If none of the specific devices are available, it defaults to emptying the CUDA cache.
698
+ """
699
+ if is_torch_mlu_available():
700
+ torch.mlu.empty_cache()
701
+ elif is_torch_mps_available():
702
+ torch.mps.empty_cache()
703
+ elif is_torch_npu_available():
704
+ torch.npu.empty_cache()
705
+ elif is_torch_xpu_available():
706
+ torch.xpu.empty_cache()
707
+ else:
708
+ torch.cuda.empty_cache()
709
+
710
+
711
+ def peft_module_casting_to_bf16(model):
712
+ for name, module in model.named_modules():
713
+ if isinstance(module, torch.nn.LayerNorm) or "norm" in name:
714
+ module = module.to(torch.float32)
715
+ elif any(x in name for x in ["lm_head", "embed_tokens", "wte", "wpe"]):
716
+ if hasattr(module, "weight"):
717
+ if module.weight.dtype == torch.float32:
718
+ module = module.to(torch.bfloat16)
719
+
720
+
721
+ LAYER_PATTERNS = [
722
+ "transformer.h.{layer}",
723
+ "model.decoder.layers.{layer}",
724
+ "gpt_neox.layers.{layer}",
725
+ "model.layers.{layer}",
726
+ ]
727
+
728
+
729
+ def create_reference_model(
730
+ model: nn.Module, num_shared_layers: int | None = None, pattern: str | None = None
731
+ ) -> nn.Module:
732
+ """
733
+ Creates a static reference copy of a model. Note that model will be in `.eval()` mode.
734
+
735
+ Args:
736
+ model ([`nn.Module`]): The model to be copied.
737
+ num_shared_layers (`int`, *optional*):
738
+ The number of initial layers that are shared between both models and kept frozen. Shared layers reference
739
+ the same storage as the source model, so they are not duplicated in memory.
740
+ pattern (`str`, *optional*): The shared layers are selected with a string pattern
741
+ (e.g. "transformer.h.{layer}" for GPT2) and if a custom pattern is necessary it can be passed here.
742
+
743
+ Returns:
744
+ [`nn.Module`]
745
+ """
746
+ if is_deepspeed_zero3_enabled():
747
+ raise ValueError(
748
+ "DeepSpeed ZeRO-3 is enabled and is not compatible with `create_reference_model()`. Please instantiate your reference model directly with `AutoModelForCausalLM.from_pretrained()`."
749
+ )
750
+
751
+ parameter_names = [n for n, _ in model.named_parameters()]
752
+ ref_model = deepcopy(model)
753
+
754
+ # if no layers are shared, return copy of model
755
+ if num_shared_layers is None:
756
+ for param_name in parameter_names:
757
+ param = ref_model.get_parameter(param_name)
758
+ param.requires_grad = False
759
+ return ref_model.eval()
760
+
761
+ # identify layer name pattern
762
+ if pattern is not None:
763
+ pattern = pattern.format(layer=num_shared_layers)
764
+ else:
765
+ for pattern_candidate in LAYER_PATTERNS:
766
+ pattern_candidate = pattern_candidate.format(layer=num_shared_layers)
767
+ if any(pattern_candidate in name for name in parameter_names):
768
+ pattern = pattern_candidate
769
+ break
770
+
771
+ if pattern is None:
772
+ raise ValueError("Layer pattern could not be matched.")
773
+
774
+ # divide parameters in shared and unshared parameter lists
775
+ shared_param_list = []
776
+ unshared_param_list = []
777
+
778
+ shared_parameter = True
779
+ for name, _param in model.named_parameters():
780
+ if pattern in name:
781
+ shared_parameter = False
782
+ if shared_parameter:
783
+ shared_param_list.append(name)
784
+ else:
785
+ unshared_param_list.append(name)
786
+
787
+ # Freeze the shared layers in the source model, then point the reference parameter at the same
788
+ # storage instead of keeping the `deepcopy` duplicate. The shared (frozen) layers are thus held in
789
+ # memory only once; because they are frozen in the model, the reference stays static during training.
790
+ for param_name in shared_param_list:
791
+ param = model.get_parameter(param_name)
792
+ param.requires_grad = False
793
+
794
+ ref_param = ref_model.get_parameter(param_name)
795
+ ref_param.data = param.data
796
+ ref_param.requires_grad = False
797
+
798
+ # for all other parameters just make sure they don't use gradients
799
+ for param_name in unshared_param_list:
800
+ param = ref_model.get_parameter(param_name)
801
+ param.requires_grad = False
802
+
803
+ if pattern is not None and len(unshared_param_list) == 0:
804
+ logging.warning("Pattern passed or found, but no layers matched in the model. Check for a typo.")
805
+
806
+ return ref_model.eval()
807
+
808
+
809
+ def truncate_dataset(
810
+ dataset: DatasetType,
811
+ max_length: int,
812
+ map_kwargs: dict[str, Any] | None = None,
813
+ ) -> DatasetType:
814
+ r"""
815
+ Truncate sequences in a dataset to a specified `max_length`.
816
+
817
+ Args:
818
+ dataset ([`~datasets.Dataset`] or [`~datasets.DatasetDict`]):
819
+ Dataset to truncate.
820
+ max_length (`int`):
821
+ Maximum sequence length to truncate to.
822
+ map_kwargs (`dict`, *optional*):
823
+ Additional keyword arguments to pass to the dataset's map method when truncating examples.
824
+
825
+ Returns:
826
+ [`~datasets.Dataset`] or [`~datasets.DatasetDict`]: The dataset with truncated sequences.
827
+
828
+ Example:
829
+ ```python
830
+ >>> from datasets import Dataset
831
+
832
+ >>> examples = {
833
+ ... "input_ids": [[1, 2, 3], [4, 5, 6, 7], [8]],
834
+ ... "attention_mask": [[0, 1, 1], [0, 0, 1, 1], [1]],
835
+ ... }
836
+ >>> dataset = Dataset.from_dict(examples)
837
+ >>> truncated_dataset = truncate_dataset(dataset, max_length=2)
838
+ >>> truncated_dataset[:]
839
+ {'input_ids': [[1, 2], [4, 5], [8]],
840
+ 'attention_mask': [[0, 1], [0, 0], [1]]}
841
+ ```
842
+ """
843
+ if map_kwargs is None:
844
+ map_kwargs = {}
845
+
846
+ def truncate(examples):
847
+ truncated_columns = []
848
+ for column in examples.columns:
849
+ if pyarrow.types.is_list(column.type) or pyarrow.types.is_large_list(column.type):
850
+ column = pc.list_slice(column, 0, max_length)
851
+ truncated_columns.append(column)
852
+ return pa.Table.from_arrays(truncated_columns, names=examples.column_names)
853
+
854
+ format = _get_dataset_format(dataset)
855
+ dataset = dataset.with_format("arrow")
856
+ dataset = dataset.map(truncate, batched=True, **map_kwargs)
857
+ dataset = dataset.with_format(**format)
858
+ return dataset
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/xpo/__init__.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .xpo_config import XPOConfig
16
+ from .xpo_trainer import XPOTrainer
17
+
18
+
19
+ __all__ = ["XPOConfig", "XPOTrainer"]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/xpo/xpo_config.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass, field
16
+
17
+ from ..online_dpo import OnlineDPOConfig
18
+
19
+
20
+ @dataclass
21
+ class XPOConfig(OnlineDPOConfig):
22
+ r"""
23
+ Configuration class for the [`experimental.xpo.XPOTrainer`].
24
+
25
+ Subclass of [`experimental.online_dpo.OnlineDPOConfig`] we can use all its arguments and add the following:
26
+
27
+ Parameters:
28
+ alpha (`float` or `list[float]`, *optional*, defaults to `1e-5`):
29
+ Weight of the XPO loss term. If a list of floats is provided then the alpha is selected for each new epoch
30
+ and the last alpha is used for the rest of the epochs.
31
+ """
32
+
33
+ alpha: list[float] = field(
34
+ default_factory=lambda: [1e-5],
35
+ metadata={
36
+ "help": "Weight of the XPO loss term. If a list of floats is provided then the alpha is selected for each "
37
+ "new epoch and the last alpha is used for the rest of the epochs."
38
+ },
39
+ )
40
+
41
+ def __post_init__(self):
42
+ super().__post_init__()
43
+ if hasattr(self.alpha, "__len__") and len(self.alpha) == 1:
44
+ self.alpha = self.alpha[0]
tasks/tasksmith-03a6a091b12f/tests/source/trl/experimental/xpo/xpo_trainer.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import textwrap
16
+ from collections.abc import Callable
17
+ from typing import Any
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+ from datasets import Dataset, IterableDataset
23
+ from transformers import (
24
+ BaseImageProcessor,
25
+ FeatureExtractionMixin,
26
+ PreTrainedModel,
27
+ PreTrainedTokenizerBase,
28
+ ProcessorMixin,
29
+ TrainerCallback,
30
+ )
31
+ from transformers.trainer_utils import EvalPrediction
32
+ from transformers.training_args import OptimizerNames
33
+ from transformers.utils import is_peft_available
34
+
35
+ from ...data_utils import maybe_apply_chat_template
36
+ from ...models.utils import unwrap_model_for_generation
37
+ from ...trainer.utils import selective_log_softmax
38
+ from ..online_dpo import OnlineDPOTrainer
39
+ from ..utils import empty_cache, get_reward, truncate_right
40
+ from .xpo_config import XPOConfig
41
+
42
+
43
+ if is_peft_available():
44
+ from peft import PeftConfig, PeftModel
45
+
46
+
47
+ class XPOTrainer(OnlineDPOTrainer):
48
+ """
49
+ Trainer for Exploratory Preference Optimization (XPO).
50
+
51
+ It is implemented as a subclass of [`experimental.online_dpo.OnlineDPOTrainer`].
52
+
53
+ Args:
54
+ model ([`~transformers.PreTrainedModel`]):
55
+ The model to train, preferably an `AutoModelForCausalLM`.
56
+ ref_model ([`~transformers.PreTrainedModel`]):
57
+ Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation
58
+ and loss. If no reference model is provided, the trainer will create a reference model with the same
59
+ architecture as the model to be optimized.
60
+ reward_funcs ([`~transformers.PreTrainedModel`]):
61
+ The reward model to score completions with, preferably an
62
+ [`~transformers.AutoModelForSequenceClassification`].
63
+ args ([`experimental.xpo.XPOConfig`]):
64
+ The XPO config arguments to use for training.
65
+ data_collator ([`~transformers.DataCollator`]):
66
+ The data collator to use for training. If None is specified, the default data collator
67
+ ([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the
68
+ maximum length of the sequences in the batch, given a dataset of paired sequences.
69
+ train_dataset ([`~datasets.Dataset`]):
70
+ The dataset to use for training.
71
+ eval_dataset ([`~datasets.Dataset`]):
72
+ The dataset to use for evaluation.
73
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
74
+ Processing class used to process the data. If provided, will be used to automatically process the inputs
75
+ for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
76
+ reuse the fine-tuned model.
77
+ reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*):
78
+ Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
79
+
80
+ - A single processing class: Used when `reward_funcs` contains only one reward function.
81
+ - A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
82
+
83
+ If set to `None`, the tokenizer for each model-based reward function is automatically loaded using
84
+ [`~transformers.AutoTokenizer.from_pretrained`].
85
+ peft_config ([`~peft.PeftConfig`], *optional*):
86
+ The peft config to use for training.
87
+ compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
88
+ The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
89
+ metric values.
90
+ callbacks (`list[transformers.TrainerCallback]`):
91
+ The callbacks to use for training.
92
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
93
+ The optimizer and scheduler to use for training.
94
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
95
+ The function to use to preprocess the logits before computing the metrics.
96
+ """
97
+
98
+ _tag_names = ["trl", "xpo"]
99
+ _name = "XPO"
100
+ _paper = {
101
+ "title": "Exploratory Preference Optimization: Harnessing Implicit Q*-Approximation for Sample-Efficient RLHF",
102
+ "id": "2405.21046",
103
+ # docstyle-ignore
104
+ "citation": textwrap.dedent("""\
105
+ @article{jung2024binary,
106
+ title = {{Exploratory Preference Optimization: Harnessing Implicit Q*-Approximation for Sample-Efficient RLHF}},
107
+ author = {Tengyang Xie and Dylan J. Foster and Akshay Krishnamurthy and Corby Rosset and Ahmed Awadallah and Alexander Rakhlin},
108
+ year = 2024,
109
+ eprint = {arXiv:2405.21046}
110
+ }"""),
111
+ }
112
+
113
+ def __init__(
114
+ self,
115
+ model: PreTrainedModel | nn.Module = None,
116
+ ref_model: PreTrainedModel | nn.Module = None,
117
+ reward_funcs: nn.Module | None = None,
118
+ args: XPOConfig | None = None,
119
+ data_collator: Callable | None = None,
120
+ train_dataset: Dataset | IterableDataset | None = None,
121
+ eval_dataset: Dataset | dict[str, Dataset] | None = None,
122
+ processing_class: PreTrainedTokenizerBase
123
+ | BaseImageProcessor
124
+ | FeatureExtractionMixin
125
+ | ProcessorMixin
126
+ | None = None,
127
+ reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
128
+ peft_config: "PeftConfig | None" = None,
129
+ compute_metrics: Callable[[EvalPrediction], dict] | None = None,
130
+ callbacks: list[TrainerCallback] | None = None,
131
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
132
+ preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
133
+ ) -> None:
134
+ super().__init__(
135
+ model=model,
136
+ ref_model=ref_model,
137
+ reward_funcs=reward_funcs,
138
+ args=args,
139
+ data_collator=data_collator,
140
+ train_dataset=train_dataset,
141
+ eval_dataset=eval_dataset,
142
+ processing_class=processing_class,
143
+ reward_processing_classes=reward_processing_classes,
144
+ peft_config=peft_config,
145
+ compute_metrics=compute_metrics,
146
+ callbacks=callbacks,
147
+ optimizers=optimizers,
148
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
149
+ )
150
+
151
+ self._alpha = self.args.alpha
152
+
153
+ # Overwrite the stats dictionary to include XPO specific statistics
154
+ self.stats = {
155
+ # Remove "non_score_reward", "rlhf_reward", "scores"
156
+ # Add "loss/dpo", "loss/xpo"
157
+ "loss/dpo": [],
158
+ "loss/xpo": [],
159
+ "objective/kl": [],
160
+ "objective/entropy": [],
161
+ "rewards/chosen": [],
162
+ "rewards/rejected": [],
163
+ "rewards/accuracies": [],
164
+ "rewards/margins": [],
165
+ "logps/chosen": [],
166
+ "logps/rejected": [],
167
+ # Replace "contain_eos_token" by "model_contain_eos_token" and "ref_contain_eos_token"
168
+ "val/model_contain_eos_token": [],
169
+ "val/ref_contain_eos_token": [],
170
+ "objective/model_scores": [],
171
+ "objective/ref_scores": [],
172
+ "objective/scores_margin": [],
173
+ "alpha": [],
174
+ "beta": [],
175
+ }
176
+ if len(self.reward_funcs) != 1:
177
+ raise ValueError("XPOTrainer only supports one reward function/model.")
178
+ self.reward_funcs = self.reward_funcs[0]
179
+
180
+ @property
181
+ def alpha(self):
182
+ if isinstance(self._alpha, list):
183
+ epoch = self.state.epoch
184
+ return self._alpha[epoch] if epoch < len(self._alpha) else self._alpha[-1]
185
+ else:
186
+ return self._alpha
187
+
188
+ def _generate_completions(self, prompts, model):
189
+ with (
190
+ unwrap_model_for_generation(
191
+ model,
192
+ self.accelerator,
193
+ generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
194
+ ) as unwrapped_policy_model_for_gen,
195
+ ):
196
+ model_output = unwrapped_policy_model_for_gen.generate(
197
+ input_ids=prompts["input_ids"],
198
+ attention_mask=prompts["attention_mask"],
199
+ generation_config=self.generation_config,
200
+ )
201
+
202
+ actual_model_for_ref_generation: torch.nn.Module
203
+ if self.ref_model is None:
204
+ unwrapped_main_model_for_ref_logic = self.accelerator.unwrap_model(model)
205
+
206
+ if is_peft_available() and isinstance(unwrapped_main_model_for_ref_logic, PeftModel):
207
+ actual_model_for_ref_generation = unwrapped_main_model_for_ref_logic.get_base_model()
208
+ else:
209
+ actual_model_for_ref_generation = unwrapped_main_model_for_ref_logic
210
+ else:
211
+ actual_model_for_ref_generation = self.accelerator.unwrap_model(self.ref_model)
212
+
213
+ with (
214
+ unwrap_model_for_generation(
215
+ actual_model_for_ref_generation,
216
+ self.accelerator,
217
+ generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
218
+ ) as final_ref_model_for_gen,
219
+ ):
220
+ ref_output = final_ref_model_for_gen.generate(
221
+ input_ids=prompts["input_ids"],
222
+ attention_mask=prompts["attention_mask"],
223
+ generation_config=self.generation_config,
224
+ )
225
+
226
+ return model_output, ref_output
227
+
228
+ def _process_completions(self, model_output, ref_output, prompts):
229
+ context_length = prompts["input_ids"].shape[1]
230
+
231
+ # Process model completions
232
+ model_completion_ids = model_output[:, context_length:]
233
+ model_completion_ids, model_completion_mask = truncate_right(
234
+ model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id
235
+ )
236
+ model_data = {
237
+ "input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1),
238
+ "attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1),
239
+ "raw": prompts["raw"],
240
+ }
241
+
242
+ # Process reference model completions
243
+ ref_completion_ids = ref_output[:, context_length:]
244
+ ref_completion_ids, ref_completion_mask = truncate_right(
245
+ ref_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id
246
+ )
247
+ ref_data = {
248
+ "input_ids": torch.cat((prompts["input_ids"], ref_completion_ids), dim=1),
249
+ "attention_mask": torch.cat((prompts["attention_mask"], ref_completion_mask), dim=1),
250
+ "raw": prompts["raw"],
251
+ }
252
+
253
+ return model_data, ref_data
254
+
255
+ def _compute_rewards(self, model_data, ref_data, context_length):
256
+ with torch.no_grad():
257
+ _, model_scores, _ = get_reward(
258
+ self.reward_funcs, model_data["input_ids"], self.processing_class.pad_token_id, context_length
259
+ )
260
+ _, ref_scores, _ = get_reward(
261
+ self.reward_funcs, ref_data["input_ids"], self.processing_class.pad_token_id, context_length
262
+ )
263
+
264
+ # Apply EOS penalty if needed
265
+ if self.args.missing_eos_penalty is not None:
266
+ model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1)
267
+ ref_contain_eos = torch.any(ref_data["input_ids"] == self.processing_class.eos_token_id, dim=-1)
268
+ model_scores[~model_contain_eos] -= self.args.missing_eos_penalty
269
+ ref_scores[~ref_contain_eos] -= self.args.missing_eos_penalty
270
+
271
+ return model_scores, ref_scores
272
+
273
+ def _compute_logprobs(self, model, model_data, ref_data, context_length):
274
+ def compute_logprobs_for_data(m, data):
275
+ output = m(data["input_ids"], attention_mask=data["attention_mask"])
276
+ logits = output.logits[:, context_length - 1 : -1]
277
+ token_logprobs = selective_log_softmax(logits, data["input_ids"][:, context_length:])
278
+ return token_logprobs
279
+
280
+ # Compute logprobs for model completions
281
+ model_logprobs_model_data = compute_logprobs_for_data(model, model_data)
282
+ # Compute logprobs for model on reference completions (for XPO loss)
283
+ model_logprobs_ref_data = compute_logprobs_for_data(model, ref_data)
284
+
285
+ # Compute logprobs for reference model completions
286
+ with torch.no_grad():
287
+ if self.ref_model is None:
288
+ with model.disable_adapter():
289
+ ref_logprobs_model_data = compute_logprobs_for_data(model, model_data)
290
+ ref_logprobs_ref_data = compute_logprobs_for_data(model, ref_data)
291
+ else:
292
+ ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data)
293
+ ref_logprobs_ref_data = compute_logprobs_for_data(self.ref_model, ref_data)
294
+
295
+ # Mask padding tokens
296
+ model_padding_mask = model_data["attention_mask"][:, context_length:] == 0
297
+ ref_padding_mask = ref_data["attention_mask"][:, context_length:] == 0
298
+ model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0)
299
+ model_logprobs_ref_data = model_logprobs_ref_data.masked_fill(ref_padding_mask, 0.0)
300
+ ref_logprobs_ref_data = ref_logprobs_ref_data.masked_fill(ref_padding_mask, 0.0)
301
+ ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0)
302
+
303
+ return model_logprobs_model_data, model_logprobs_ref_data, ref_logprobs_ref_data, ref_logprobs_model_data
304
+
305
+ def _compute_losses(
306
+ self,
307
+ model_logprobs_model_data,
308
+ model_logprobs_ref_data,
309
+ ref_logprobs_ref_data,
310
+ ref_logprobs_model_data,
311
+ chosen_mask,
312
+ ):
313
+ # Compute log probs
314
+ model_logprobs_model_data_sum = model_logprobs_model_data.sum(1)
315
+ model_logprobs_ref_data_sum = model_logprobs_ref_data.sum(1)
316
+ ref_logprobs_ref_data_sum = ref_logprobs_ref_data.sum(1)
317
+ ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1)
318
+
319
+ chosen_model_logprobs = torch.where(chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum)
320
+ chosen_ref_logprobs = torch.where(chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum)
321
+ chosen_log_ratios = chosen_model_logprobs - chosen_ref_logprobs
322
+
323
+ rejected_model_logprobs = torch.where(~chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum)
324
+ rejected_ref_logprobs = torch.where(~chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum)
325
+ rejected_log_ratios = rejected_model_logprobs - rejected_ref_logprobs
326
+
327
+ # Compute logits as the difference between chosen and rejected log ratios
328
+ logits = chosen_log_ratios - rejected_log_ratios
329
+
330
+ if self.args.loss_type == "sigmoid":
331
+ dpo_losses = -F.logsigmoid(self.beta * logits)
332
+ elif self.args.loss_type == "ipo":
333
+ dpo_losses = (logits - 1 / (2 * self.beta)) ** 2
334
+ else:
335
+ raise NotImplementedError(f"invalid loss type {self.args.loss_type}")
336
+
337
+ # Compute XPO specific loss
338
+ xpo_losses = self.alpha * model_logprobs_ref_data_sum
339
+
340
+ # Total loss
341
+ loss = (dpo_losses + xpo_losses).mean()
342
+
343
+ return loss, dpo_losses, xpo_losses
344
+
345
+ def _log_statistics(
346
+ self,
347
+ model_data,
348
+ ref_data,
349
+ model_logprobs_model_data,
350
+ model_logprobs_ref_data,
351
+ ref_logprobs_ref_data,
352
+ ref_logprobs_model_data,
353
+ chosen_mask,
354
+ dpo_losses,
355
+ xpo_losses,
356
+ context_length,
357
+ model_scores,
358
+ ref_scores,
359
+ ):
360
+ # Helper function to gather and compute mean
361
+ def gather_mean(tensor):
362
+ return self.accelerator.gather_for_metrics(tensor).mean().item()
363
+
364
+ # Log losses
365
+ self.stats["loss/dpo"].append(gather_mean(dpo_losses))
366
+ self.stats["loss/xpo"].append(gather_mean(xpo_losses))
367
+
368
+ # Log scores
369
+ self.stats["objective/model_scores"].append(gather_mean(model_scores))
370
+ self.stats["objective/ref_scores"].append(gather_mean(ref_scores))
371
+ self.stats["objective/scores_margin"].append(gather_mean(model_scores - ref_scores))
372
+
373
+ # Log logprobs
374
+ model_logprobs_model_data_sum = model_logprobs_model_data.sum(1)
375
+ model_logprobs_ref_data_sum = model_logprobs_ref_data.sum(1)
376
+ ref_logprobs_ref_data_sum = ref_logprobs_ref_data.sum(1)
377
+ ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1)
378
+
379
+ chosen_model_logprobs = torch.where(chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum)
380
+ chosen_ref_logprobs = torch.where(chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum)
381
+ chosen_log_ratios = chosen_model_logprobs - chosen_ref_logprobs
382
+
383
+ rejected_model_logprobs = torch.where(~chosen_mask, model_logprobs_model_data_sum, model_logprobs_ref_data_sum)
384
+ rejected_ref_logprobs = torch.where(~chosen_mask, ref_logprobs_model_data_sum, ref_logprobs_ref_data_sum)
385
+ rejected_log_ratios = rejected_model_logprobs - rejected_ref_logprobs
386
+
387
+ self.stats["logps/chosen"].append(gather_mean(chosen_model_logprobs.mean() + chosen_ref_logprobs.mean()))
388
+ self.stats["logps/rejected"].append(gather_mean(rejected_model_logprobs.mean() + rejected_ref_logprobs.mean()))
389
+
390
+ # Log rewards
391
+ # Compute various statistics
392
+ chosen_rewards = chosen_log_ratios * self.beta
393
+ rejected_rewards = rejected_log_ratios * self.beta
394
+ self.stats["rewards/chosen"].append(gather_mean(chosen_rewards.mean()))
395
+ self.stats["rewards/rejected"].append(gather_mean(rejected_rewards.mean()))
396
+
397
+ # Calculate KL divergence for model and ref data
398
+ kl_model_data = model_logprobs_model_data - ref_logprobs_model_data
399
+ kl_ref_data = model_logprobs_ref_data - ref_logprobs_ref_data
400
+ mean_kl = (kl_model_data.sum(1) + kl_ref_data.sum(1)).mean() / 2
401
+ self.stats["objective/kl"].append(gather_mean(mean_kl))
402
+
403
+ # Calculate entropy for model and ref data
404
+ entropy_model_data = -model_logprobs_model_data.sum(1)
405
+ entropy_ref_data = -model_logprobs_ref_data.sum(1)
406
+ mean_entropy = (entropy_model_data.mean() + entropy_ref_data.mean()) / 2
407
+ self.stats["objective/entropy"].append(gather_mean(mean_entropy))
408
+
409
+ # Calculate margins
410
+ margin = chosen_rewards - rejected_rewards
411
+ self.stats["rewards/margins"].append(gather_mean(margin.mean()))
412
+
413
+ # Calculate accuracy
414
+ accuracy = (margin > 0).float()
415
+ self.stats["rewards/accuracies"].append(gather_mean(accuracy.mean()))
416
+
417
+ # Log EOS token statistics
418
+ model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1)
419
+ ref_eos = (ref_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1)
420
+ self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float()))
421
+ self.stats["val/ref_contain_eos_token"].append(gather_mean(ref_eos.float()))
422
+
423
+ # Log alpha and beta
424
+ self.stats["alpha"].append(self.alpha)
425
+ self.stats["beta"].append(self.beta)
426
+
427
+ def training_step(
428
+ self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None
429
+ ) -> torch.Tensor:
430
+ model.train()
431
+
432
+ # Apply chat template and tokenize the input
433
+ batch_size = len(next(iter(inputs.values())))
434
+ prompts = inputs["prompt"]
435
+ inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)]
436
+ inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs]
437
+ inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs]
438
+ inputs = self.data_collator(inputs)
439
+
440
+ # need the prompt_ only
441
+ inputs = self._prepare_inputs(inputs)
442
+ context_length = inputs["prompt_input_ids"].shape[1]
443
+ prompts = {
444
+ "input_ids": inputs["prompt_input_ids"],
445
+ "attention_mask": inputs["prompt_attention_mask"],
446
+ "raw": prompts,
447
+ }
448
+ del inputs
449
+
450
+ # Sample completions from both the model and the reference model
451
+ model_output, ref_output = self._generate_completions(prompts, model)
452
+
453
+ # Process model completions
454
+ model_data, ref_data = self._process_completions(model_output, ref_output, prompts)
455
+
456
+ # Compute rewards
457
+ model_scores, ref_scores = self._compute_rewards(model_data, ref_data, context_length)
458
+ chosen_mask = model_scores >= ref_scores
459
+
460
+ # Compute logprobs
461
+ model_logprobs_model_data, model_logprobs_ref_data, ref_logprobs_ref_data, ref_logprobs_model_data = (
462
+ self._compute_logprobs(model, model_data, ref_data, context_length)
463
+ )
464
+
465
+ # Compute loss
466
+ loss, dpo_losses, xpo_losses = self._compute_losses(
467
+ model_logprobs_model_data,
468
+ model_logprobs_ref_data,
469
+ ref_logprobs_ref_data,
470
+ ref_logprobs_model_data,
471
+ chosen_mask,
472
+ )
473
+
474
+ # Log everything
475
+ self._log_statistics(
476
+ model_data,
477
+ ref_data,
478
+ model_logprobs_model_data.detach(),
479
+ model_logprobs_ref_data.detach(),
480
+ ref_logprobs_ref_data,
481
+ ref_logprobs_model_data,
482
+ chosen_mask,
483
+ dpo_losses.detach(),
484
+ xpo_losses.detach(),
485
+ context_length,
486
+ model_scores,
487
+ ref_scores,
488
+ )
489
+
490
+ if (
491
+ self.args.torch_empty_cache_steps is not None
492
+ and self.state.global_step % self.args.torch_empty_cache_steps == 0
493
+ ):
494
+ empty_cache()
495
+
496
+ kwargs = {}
497
+ # For LOMO optimizers you need to explicitly use the learning rate
498
+ if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]:
499
+ kwargs["learning_rate"] = self._get_learning_rate()
500
+
501
+ if self.args.n_gpu > 1:
502
+ loss = loss.mean() # mean() to average on multi-gpu parallel training
503
+
504
+ self.accelerator.backward(loss, **kwargs)
505
+
506
+ return loss.detach() / self.args.gradient_accumulation_steps
tasks/tasksmith-03a6a091b12f/tests/source/trl/extras/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
tasks/tasksmith-03a6a091b12f/tests/source/trl/extras/dataset_formatting.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ import datasets
17
+ from datasets import Value
18
+ from packaging.version import Version
19
+
20
+
21
+ if Version(datasets.__version__) >= Version("4.0.0"):
22
+ from datasets import List
23
+
24
+ FORMAT_MAPPING = {
25
+ "chatml": List({"content": Value(dtype="string", id=None), "role": Value(dtype="string", id=None)}),
26
+ "instruction": {"completion": Value(dtype="string", id=None), "prompt": Value(dtype="string", id=None)},
27
+ }
28
+ else:
29
+ FORMAT_MAPPING = {
30
+ "chatml": [{"content": Value(dtype="string", id=None), "role": Value(dtype="string", id=None)}],
31
+ "instruction": {"completion": Value(dtype="string", id=None), "prompt": Value(dtype="string", id=None)},
32
+ }
tasks/tasksmith-03a6a091b12f/tests/source/trl/extras/profiling.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import functools
16
+ import time
17
+ from collections.abc import Callable
18
+
19
+ from transformers import Trainer
20
+ from transformers.integrations import is_mlflow_available, is_trackio_available, is_wandb_available
21
+
22
+
23
+ if is_wandb_available():
24
+ import wandb
25
+
26
+ if is_mlflow_available():
27
+ import mlflow
28
+
29
+ if is_trackio_available():
30
+ import trackio
31
+
32
+
33
+ class ProfilingContext:
34
+ """
35
+ Context manager for profiling code blocks with configurable logging.
36
+
37
+ This class handles timing of code execution and logging metrics to various backends (Weights & Biases, MLflow,
38
+ Trackio) without being coupled to the Trainer class.
39
+
40
+ Args:
41
+ name (`str`):
42
+ Name of the profiling context. Used in the metric name.
43
+ report_to (`list` of `str`):
44
+ List of integrations to report metrics to (e.g., ["wandb", "mlflow", "trackio"]).
45
+ is_main_process (`bool`, *optional*, defaults to `True`):
46
+ Whether this is the main process in distributed training. Metrics are only logged from the main process.
47
+ step (`int` or `None`, *optional*):
48
+ Training step to associate with the logged metrics.
49
+ metric_prefix (`str`, *optional*, defaults to `"profiling/Time taken"`):
50
+ Prefix for the metric name in logs.
51
+
52
+ Example:
53
+ ```python
54
+ # Direct usage
55
+ from trl.extras.profiling import ProfilingContext
56
+
57
+ with ProfilingContext(
58
+ name="MyClass.expensive_operation",
59
+ report_to=["wandb"],
60
+ is_main_process=True,
61
+ step=100,
62
+ ):
63
+ # Code to profile
64
+ result = expensive_computation()
65
+
66
+ # With Trainer (backwards compatible via profiling_context function)
67
+ from transformers import Trainer
68
+ from trl.extras.profiling import profiling_context
69
+
70
+
71
+ class MyTrainer(Trainer):
72
+ def some_method(self):
73
+ with profiling_context(self, "matrix_multiplication"):
74
+ result = matrix_multiply()
75
+ ```
76
+ """
77
+
78
+ def __init__(
79
+ self,
80
+ name: str,
81
+ report_to: list[str],
82
+ is_main_process: bool = True,
83
+ step: int | None = None,
84
+ metric_prefix: str = "profiling/Time taken",
85
+ ):
86
+ self.name = name
87
+ self.report_to = report_to
88
+ self.is_main_process = is_main_process
89
+ self.step = step
90
+ self.metric_prefix = metric_prefix
91
+ self._start_time = None
92
+
93
+ def __enter__(self):
94
+ """Start timing when entering the context."""
95
+ self._start_time = time.perf_counter()
96
+ return self
97
+
98
+ def __exit__(self, exc_type, exc_val, exc_tb):
99
+ """Stop timing and log metrics when exiting the context."""
100
+ if self._start_time is not None:
101
+ duration = time.perf_counter() - self._start_time
102
+ self._log_metrics(duration)
103
+ return False
104
+
105
+ def _log_metrics(self, duration: float) -> None:
106
+ """
107
+ Log profiling metrics to configured backends.
108
+
109
+ Args:
110
+ duration (`float`):
111
+ Execution time in seconds.
112
+ """
113
+ if not self.is_main_process:
114
+ return
115
+
116
+ metric_name = f"{self.metric_prefix}: {self.name}"
117
+ metrics = {metric_name: duration}
118
+
119
+ # Log to Weights & Biases if configured
120
+ if "wandb" in self.report_to and is_wandb_available() and wandb.run is not None:
121
+ wandb.log(metrics)
122
+
123
+ # Log to MLflow if configured
124
+ if "mlflow" in self.report_to and is_mlflow_available() and mlflow.active_run() is not None:
125
+ mlflow.log_metrics(metrics, step=self.step)
126
+
127
+ # Log to Trackio if configured
128
+ if "trackio" in self.report_to and is_trackio_available():
129
+ trackio.log(metrics, step=self.step)
130
+
131
+
132
+ def profiling_context(trainer: Trainer, name: str) -> ProfilingContext:
133
+ """
134
+ Factory function to create a ProfilingContext from a Trainer instance.
135
+
136
+ This function maintains backwards compatibility with existing code while using the decoupled ProfilingContext class
137
+ internally.
138
+
139
+ Args:
140
+ trainer (`~transformers.Trainer`):
141
+ Trainer object containing configuration for logging.
142
+ name (`str`):
143
+ Name of the block to be profiled. Will be prefixed with the trainer class name.
144
+
145
+ Returns:
146
+ `ProfilingContext`: A configured profiling context manager.
147
+
148
+ Example:
149
+ ```python
150
+ from transformers import Trainer
151
+ from trl.extras.profiling import profiling_context
152
+
153
+
154
+ class MyTrainer(Trainer):
155
+ def some_method(self):
156
+ A = np.random.rand(1000, 1000)
157
+ B = np.random.rand(1000, 1000)
158
+ with profiling_context(self, "matrix_multiplication"):
159
+ # Code to profile: simulate a computationally expensive operation
160
+ result = A @ B # Matrix multiplication
161
+ ```
162
+ """
163
+ context_name = f"{trainer.__class__.__name__}.{name}"
164
+ step = trainer.state.global_step
165
+
166
+ return ProfilingContext(
167
+ name=context_name,
168
+ report_to=trainer.args.report_to,
169
+ is_main_process=trainer.accelerator.is_main_process,
170
+ step=step,
171
+ )
172
+
173
+
174
+ def profiling_decorator(func: Callable) -> Callable:
175
+ """
176
+ Decorator to profile a function and log execution time using [`extras.profiling.profiling_context`].
177
+
178
+ This decorator works with methods that have access to a trainer instance (typically as `self`). For non-Trainer
179
+ objects that have an `accelerator` attribute, it will use that for logging configuration.
180
+
181
+ Args:
182
+ func (`Callable`):
183
+ Function to be profiled.
184
+
185
+ Returns:
186
+ `Callable`: Wrapped function that profiles execution time.
187
+
188
+ Example:
189
+ ```python
190
+ from transformers import Trainer
191
+ from trl.extras.profiling import profiling_decorator
192
+
193
+
194
+ class MyTrainer(Trainer):
195
+ @profiling_decorator
196
+ def some_method(self):
197
+ A = np.random.rand(1000, 1000)
198
+ B = np.random.rand(1000, 1000)
199
+ # Code to profile: simulate a computationally expensive operation
200
+ result = A @ B
201
+ ```
202
+ """
203
+
204
+ @functools.wraps(func)
205
+ def wrapper(self, *args, **kwargs):
206
+ # Check if self is a Trainer-like object with required attributes
207
+ if hasattr(self, "state") and hasattr(self, "args"):
208
+ with profiling_context(self, func.__name__):
209
+ return func(self, *args, **kwargs)
210
+ # For non-Trainer objects (e.g., VLLMGeneration), use ProfilingContext directly
211
+ elif hasattr(self, "accelerator"):
212
+ context_name = f"{self.__class__.__name__}.{func.__name__}"
213
+ with ProfilingContext(
214
+ name=context_name,
215
+ report_to=[], # No reporting for non-Trainer objects without args
216
+ is_main_process=self.accelerator.is_main_process,
217
+ step=None,
218
+ ):
219
+ return func(self, *args, **kwargs)
220
+ else:
221
+ # No profiling available, just run the function
222
+ return func(self, *args, **kwargs)
223
+
224
+ return wrapper
tasks/tasksmith-03a6a091b12f/tests/source/trl/generation/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Generation backends for TRL trainers."""
16
+
17
+ from ..import_utils import is_vllm_available
18
+
19
+
20
+ __all__ = []
21
+
22
+ if is_vllm_available():
23
+ from .vllm_generation import VLLMGeneration
24
+
25
+ __all__.append("VLLMGeneration")
tasks/tasksmith-03a6a091b12f/tests/source/trl/generation/vllm_client.py ADDED
@@ -0,0 +1,764 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020-2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import atexit
16
+ import base64
17
+ import copy
18
+ import logging
19
+ import socket
20
+ import time
21
+ from io import BytesIO
22
+ from urllib.parse import urlparse
23
+
24
+ import torch
25
+ import torch.distributed.distributed_c10d as c10d
26
+ from requests.adapters import HTTPAdapter
27
+ from torch import nn
28
+ from transformers import is_torch_xpu_available
29
+ from transformers.utils import get_json_schema
30
+ from urllib3.util.retry import Retry
31
+
32
+ from ..import_utils import is_requests_available, is_vllm_ascend_available, is_vllm_available
33
+
34
+
35
+ if is_requests_available():
36
+ import requests
37
+ from requests import ConnectionError
38
+
39
+
40
+ if is_vllm_available():
41
+ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
42
+ from vllm.distributed.utils import StatelessProcessGroup
43
+
44
+ if is_vllm_ascend_available():
45
+ from vllm_ascend.distributed.device_communicators.pyhccl import PyHcclCommunicator as PyNcclCommunicator
46
+
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+
51
+ def pil_to_base64(image):
52
+ buffer = BytesIO()
53
+ image.save(buffer, format="PNG")
54
+ img_bytes = buffer.getvalue()
55
+ return base64.b64encode(img_bytes).decode("utf-8")
56
+
57
+
58
+ class VLLMClient:
59
+ """
60
+ A client class to interact with a vLLM server.
61
+
62
+ This class provides methods to generate completions, initialize and manage weight update groups, and update model
63
+ weights in a distributed setting. Before using it, start the vLLM server with `trl vllm-serve`.
64
+
65
+ Args:
66
+ base_url (`str`, *optional*):
67
+ Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `host` and `server_port` are
68
+ ignored.
69
+ host (`str`, *optional*, defaults to `"0.0.0.0"`):
70
+ IP address of the vLLM server. Ignored if `base_url` is provided.
71
+ server_port (`int`, *optional*, defaults to `8000`):
72
+ Port number of the vLLM server. Ignored if `base_url` is provided.
73
+ group_port (`int`, *optional*, defaults to `51216`):
74
+ Port number for the weight update group.
75
+ connection_timeout (`float`, *optional*, defaults to `0.0`):
76
+ Total timeout duration in seconds to wait for the server to be up. If the server is not up after the
77
+ timeout, a `ConnectionError` is raised.
78
+
79
+ Examples:
80
+ Run the vLLM server with the model `Qwen/Qwen2.5-7B`:
81
+
82
+ ```
83
+ $ trl vllm-serve --model Qwen/Qwen2.5-7B
84
+ ...
85
+ INFO: Application startup complete.
86
+ INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
87
+ ```
88
+
89
+ Use the client to generate completions and update model weights:
90
+
91
+ ```python
92
+ >>> from trl.generation.vllm_client import VLLMClient
93
+
94
+ >>> client = VLLMClient()
95
+ >>> client.generate(["Hello, AI!", "Tell me a joke"])
96
+ {'prompt_ids': [[9707, 11, 15235, 0],
97
+ [40451, 752, 264, 21646]],
98
+ 'completion_ids': [[2980, 498, 1492, 752, 448, 264, 13027, 8645, 30, 358, 2776, 4460, 311, 3270, 264, 2025],
99
+ [911, 98072, 2142, 624, 45, 51426, 2142, 374, 279, 16396, 429, 4302, 702, 36988, 7290, 476]],
100
+ 'logprobs': [[[-1.6612], [-0.0081], [-1.5189], [-0.0123], [-1.2045], [-0.6227], [-2.9791], [-2.8387], [-0.1267], [-0.0366], [-2.6528], [-0.3197], [-0.0001], [-1.8174], [-0.0251], [-1.473]],
101
+ [[-0.018], [-10.7331], [-0.1605], [-0.891], [-3.7945], [-0.0127], [-0.3073], [-1.1648], [-1.8025], [-0.409], [-0.0256], [-1.6127], [-2.2935], [-4.1785], [-0.6531], [-0.2629]]],
102
+ 'logprob_token_ids': [[[2980], [498], [1492], [752], [448], [264], [13027], [8645], [30], [358], [2776], [4460], [311], [3270], [264], [2025]],
103
+ [[911], [98072], [2142], [624], [45], [51426], [2142], [374], [279], [16396], [429], [4302], [702], [36988], [7290], [476]]]}
104
+
105
+ >>> from transformers import AutoModelForCausalLM
106
+
107
+ >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-7B", device_map="cuda")
108
+ >>> client.init_communicator(device="cuda")
109
+ >>> client.update_model_params(model)
110
+ ```
111
+
112
+ There are several ways to initialize the client:
113
+
114
+ ```python
115
+ VLLMClient(base_url="http://localhost:8000")
116
+ VLLMClient(base_url="http://192.168.1.100:8000")
117
+ VLLMClient(host="localhost", server_port=8000)
118
+ VLLMClient(host="192.168.1.100", server_port=8000)
119
+ ```
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ base_url: str | None = None,
125
+ host: str = "0.0.0.0",
126
+ server_port: int = 8000,
127
+ group_port: int = 51216,
128
+ connection_timeout: float = 0.0,
129
+ ):
130
+ if not is_requests_available():
131
+ raise ImportError("requests is not installed. Please install it with `pip install requests`.")
132
+ if not is_vllm_available():
133
+ raise ImportError("vLLM is not installed. Please install it with `pip install trl[vllm]`.")
134
+
135
+ self.session = requests.Session()
136
+
137
+ # Configure retries for HTTP requests made through this session.
138
+ # This is not strictly required for correctness, but it helps make training more robust to rare, transient
139
+ # failures (network hiccups, temporary 5xx errors, overloaded servers). Without this, such failures could cause
140
+ # an otherwise healthy training run to fail.
141
+ retry_strategy = Retry(
142
+ total=5, # global cap on the total number of retries across all failure types
143
+ connect=5, # retry connection-level failures (DNS issues, refused connections, etc)
144
+ read=5, # retry failures while reading the response after the connection was successfully established
145
+ status=3, # retry a limited number of times when we receive certain HTTP error responses from the server
146
+ status_forcelist=[500, 502, 503], # only retry on server-side errors that are usually temporary
147
+ backoff_factor=2, # exponential backoff between retries (2s, 4s, 8s, ...)
148
+ allowed_methods=["POST", "GET"], # allow POST as well, even though we're not sure it's safe here
149
+ )
150
+
151
+ adapter = HTTPAdapter(max_retries=retry_strategy)
152
+ self.session.mount("http://", adapter)
153
+ self.session.mount("https://", adapter)
154
+
155
+ if base_url is not None:
156
+ # Parse the base_url to extract host and port
157
+ parsed_url = urlparse(base_url)
158
+ self.host = socket.gethostbyname(parsed_url.hostname)
159
+ scheme = parsed_url.scheme or "http"
160
+ self.base_url = f"{scheme}://{parsed_url.netloc}{parsed_url.path}"
161
+ else:
162
+ self.host = host
163
+ self.server_port = server_port
164
+ self.base_url = f"http://{self.host}:{self.server_port}"
165
+ self.group_port = group_port
166
+ self.check_server(connection_timeout) # check server and fail after timeout
167
+
168
+ def check_server(self, total_timeout: float = 0.0, retry_interval: float = 2.0):
169
+ """
170
+ Check server availability with retries on failure, within a total timeout duration. If the server is not up
171
+ after the total timeout duration, raise a `ConnectionError`.
172
+
173
+ Args:
174
+ retry_interval (`float`, *optional*, defaults to `2.0`):
175
+ Interval in seconds between retries.
176
+ total_timeout (`float`, *optional*, defaults to `0.0`):
177
+ Total timeout duration in seconds.
178
+ """
179
+ url = f"{self.base_url}/health/"
180
+ start_time = time.time() # Record the start time
181
+
182
+ while True:
183
+ try:
184
+ response = requests.get(url)
185
+ except requests.exceptions.RequestException as exc:
186
+ # Check if the total timeout duration has passed
187
+ elapsed_time = time.time() - start_time
188
+ if elapsed_time >= total_timeout:
189
+ raise ConnectionError(
190
+ f"The vLLM server can't be reached at {self.base_url} after {total_timeout} seconds. Make "
191
+ "sure the server is running by running `trl vllm-serve`."
192
+ ) from exc
193
+ else:
194
+ if response.status_code == 200:
195
+ if "X-Forwarded-For" in response.headers:
196
+ self.host = response.headers["X-Forwarded-For"]
197
+ logger.info("Server is up!")
198
+ return None
199
+
200
+ # Retry logic: wait before trying again
201
+ logger.info(f"Server is not up yet. Retrying in {retry_interval} seconds...")
202
+ time.sleep(retry_interval)
203
+
204
+ def generate(
205
+ self,
206
+ prompts: list[str] | list[list[int]],
207
+ images: list | None = None,
208
+ n: int = 1,
209
+ repetition_penalty: float = 1.0,
210
+ temperature: float = 1.0,
211
+ top_p: float = 1.0,
212
+ top_k: int = 0,
213
+ min_p: float = 0.0,
214
+ max_tokens: int = 16,
215
+ logprobs: int | None = 0,
216
+ structured_outputs_regex: str | None = None,
217
+ generation_kwargs: dict | None = None,
218
+ ) -> dict[str, list[list[int]]]:
219
+ """
220
+ Generates model completions for the provided prompts.
221
+
222
+ Args:
223
+ prompts (`list[str]` or `list[list[int]]`):
224
+ List of text prompts or list of token ID lists for which the model will generate completions.
225
+ images (`list[list[PIL.Image] | None]`, *optional*):
226
+ List of image lists for VLM support. Each element is a list of PIL images for the corresponding prompt,
227
+ or `None` if no images for that prompt.
228
+ n (`int`, *optional*, defaults to `1`):
229
+ Number of completions to generate for each prompt.
230
+ repetition_penalty (`float`, *optional*, defaults to `1.0`):
231
+ Parameter for repetition penalty. 1.0 means no penalty.
232
+ temperature (`float`, *optional*, defaults to `1.0`):
233
+ Temperature parameter for sampling. Higher values increase diversity.
234
+ top_p (`float`, *optional*, defaults to `1.0`):
235
+ Top-p sampling parameter.`1.0` means no truncation.
236
+ top_k (`int`, *optional*, defaults to `0`):
237
+ Top-k sampling parameter. `0` means no truncation.
238
+ min_p (`float`, *optional*, defaults to `0.0`):
239
+ Minimum probability for sampling.
240
+ max_tokens (`int`, *optional*, defaults to `16`):
241
+ Maximum number of tokens to generate for each prompt.
242
+ logprobs (`int` or `None`, *optional*, defaults to `0`):
243
+ Number of top logprobs to return per token. When 0, only the sampled token's logprob is returned. When
244
+ N>0, returns up to N+1 logprobs sorted by descending probability, because vLLM always includes the
245
+ sampled token's logprob (which may fall outside the top-N).
246
+ structured_outputs_regex (`str`, *optional*):
247
+ Regular expression to guide the decoding process.
248
+ generation_kwargs (`dict`, *optional*):
249
+ Additional generation parameters to pass to the vLLM `SamplingParams`. This can include parameters like
250
+ `seed`, `frequency_penalty`, etc. If it contains keys that conflict with the other parameters, they
251
+ will override them.
252
+
253
+ Returns:
254
+ `dict` with keys:
255
+ - `prompt_ids` (`list[list[int]]`):
256
+ List of lists of token IDs representing the tokenized input prompts.
257
+ - `completion_ids` (`list[list[int]]`):
258
+ List of lists of token IDs representing the model-generated completions for each prompt.
259
+ - `logprobs` (`list[list[list[float]]]`):
260
+ Per-token logprobs of shape (num_sequences, seq_len, num_logprobs), sorted by descending
261
+ probability.
262
+ - `logprob_token_ids` (`list[list[list[int]]]`):
263
+ Token IDs corresponding to each logprob, same shape as `logprobs`.
264
+ """
265
+ url = f"{self.base_url}/generate/"
266
+
267
+ # Convert PIL images to base64 strings. Each element is a list of images for the corresponding prompt,
268
+ # or None if no images for that prompt.
269
+ if images:
270
+ images = [
271
+ [pil_to_base64(img) for img in img_list] if img_list is not None else None for img_list in images
272
+ ]
273
+
274
+ response = self.session.post(
275
+ url,
276
+ json={
277
+ "prompts": prompts,
278
+ "images": images,
279
+ "n": n,
280
+ "repetition_penalty": repetition_penalty,
281
+ "temperature": temperature,
282
+ "top_p": top_p,
283
+ "top_k": top_k,
284
+ "min_p": min_p,
285
+ "max_tokens": max_tokens,
286
+ "logprobs": logprobs,
287
+ "structured_outputs_regex": structured_outputs_regex,
288
+ "generation_kwargs": generation_kwargs or {},
289
+ },
290
+ )
291
+ if response.status_code == 200:
292
+ json_response = response.json()
293
+ return {
294
+ "prompt_ids": json_response["prompt_ids"],
295
+ "completion_ids": json_response["completion_ids"],
296
+ "logprobs": json_response["logprobs"],
297
+ "logprob_token_ids": json_response["logprob_token_ids"],
298
+ }
299
+ else:
300
+ raise Exception(f"Request failed: {response.status_code}, {response.text}")
301
+
302
+ def chat(
303
+ self,
304
+ messages: list[list[dict]],
305
+ n: int = 1,
306
+ repetition_penalty: float = 1.0,
307
+ temperature: float = 1.0,
308
+ top_p: float = 1.0,
309
+ top_k: int = 0,
310
+ min_p: float = 0.0,
311
+ max_tokens: int = 16,
312
+ logprobs: int | None = 0,
313
+ structured_outputs_regex: str | None = None,
314
+ generation_kwargs: dict | None = None,
315
+ chat_template_kwargs: dict | None = None,
316
+ tools: list | None = None,
317
+ chat_template: str | None = None,
318
+ ) -> dict[str, list[list[int]]]:
319
+ """
320
+ Generates model completions for the provided chat messages.
321
+
322
+ Args:
323
+ messages (`list[list[dict]]`):
324
+ List of message lists for which the model will generate completions. Each message is a dictionary with
325
+ keys like "role" and "content".
326
+ n (`int`, *optional*, defaults to `1`):
327
+ Number of completions to generate for each message list.
328
+ repetition_penalty (`float`, *optional*, defaults to `1.0`):
329
+ Parameter for repetition penalty. 1.0 means no penalty.
330
+ temperature (`float`, *optional*, defaults to `1.0`):
331
+ Temperature parameter for sampling. Higher values increase diversity.
332
+ top_p (`float`, *optional*, defaults to `1.0`):
333
+ Top-p sampling parameter.`1.0` means no truncation.
334
+ top_k (`int`, *optional*, defaults to `0`):
335
+ Top-k sampling parameter. `0` means no truncation.
336
+ min_p (`float`, *optional*, defaults to `0.0`):
337
+ Minimum probability for sampling.
338
+ max_tokens (`int`, *optional*, defaults to `16`):
339
+ Maximum number of tokens to generate for each message list.
340
+ logprobs (`int` or `None`, *optional*, defaults to `0`):
341
+ Number of top logprobs to return per token. When 0, only the sampled token's logprob is returned. When
342
+ N>0, returns up to N+1 logprobs sorted by descending probability, because vLLM always includes the
343
+ sampled token's logprob (which may fall outside the top-N).
344
+ structured_outputs_regex (`str`, *optional*):
345
+ Regular expression to guide the decoding process.
346
+ generation_kwargs (`dict`, *optional*):
347
+ Additional generation parameters to pass to the vLLM `SamplingParams`. This can include parameters like
348
+ `seed`, `frequency_penalty`, etc. If it contains keys that conflict with the other parameters, they
349
+ will override them.
350
+ chat_template_kwargs (`dict`, *optional*):
351
+ Additional keyword arguments to customize the chat template used by the model.
352
+ tools (`list[dict | Callable]`, *optional*):
353
+ List of tool functions available for tool calling during chat generation.
354
+ chat_template (`str`, *optional*):
355
+ Template to use for structuring the chat. If not provided, the model's default chat template will be
356
+ used.
357
+
358
+ Returns:
359
+ `dict` with keys:
360
+ - `prompt_ids` (`list[list[int]]`):
361
+ List of lists of token IDs representing the tokenized input messages.
362
+ - `completion_ids` (`list[list[int]]`):
363
+ List of lists of token IDs representing the model-generated completions for each message list.
364
+ - `logprobs` (`list[list[list[float]]]`):
365
+ Per-token logprobs of shape (num_sequences, seq_len, num_logprobs), sorted by descending
366
+ probability.
367
+ - `logprob_token_ids` (`list[list[list[int]]]`):
368
+ Token IDs corresponding to each logprob, same shape as `logprobs`.
369
+ """
370
+ if chat_template is not None:
371
+ raise NotImplementedError("Custom chat templates are not yet implemented in VLLMClient.chat().")
372
+
373
+ url = f"{self.base_url}/chat/"
374
+
375
+ # Convert PIL images to base64 strings
376
+ messages = copy.deepcopy(messages) # avoid modifying the original messages
377
+ for message_list in messages:
378
+ for message in message_list:
379
+ if isinstance(message["content"], list):
380
+ for part in message["content"]:
381
+ if part["type"] == "image_pil":
382
+ part["image_pil"] = pil_to_base64(part["image_pil"])
383
+
384
+ if isinstance(tools, list) and len(tools) > 0:
385
+ tools = [get_json_schema(tool) if callable(tool) else tool for tool in tools]
386
+
387
+ response = self.session.post(
388
+ url,
389
+ json={
390
+ "messages": messages,
391
+ "n": n,
392
+ "repetition_penalty": repetition_penalty,
393
+ "temperature": temperature,
394
+ "top_p": top_p,
395
+ "top_k": top_k,
396
+ "min_p": min_p,
397
+ "max_tokens": max_tokens,
398
+ "logprobs": logprobs,
399
+ "structured_outputs_regex": structured_outputs_regex,
400
+ "generation_kwargs": generation_kwargs or {},
401
+ "chat_template_kwargs": chat_template_kwargs or {},
402
+ "tools": tools,
403
+ },
404
+ )
405
+ if response.status_code == 200:
406
+ json_response = response.json()
407
+ return {
408
+ "prompt_ids": json_response["prompt_ids"],
409
+ "completion_ids": json_response["completion_ids"],
410
+ "logprobs": json_response["logprobs"],
411
+ "logprob_token_ids": json_response["logprob_token_ids"],
412
+ }
413
+ else:
414
+ raise Exception(f"Request failed: {response.status_code}, {response.text}")
415
+
416
+ def init_communicator(self, device: torch.device | str | int = 0):
417
+ """
418
+ Initializes the weight update group in a distributed setup for model synchronization.
419
+
420
+ Args:
421
+ device (`torch.device`, `str`, or `int`, *optional*, defaults to `0`):
422
+ Device of trainer main process. It's the device that will be used for the weights synchronization. Can
423
+ be a `torch.device` object, a string like `'cuda:0'`, or an integer device index.
424
+ """
425
+ # Get the world size from the server
426
+ url = f"{self.base_url}/get_world_size/"
427
+ response = requests.get(url)
428
+ if response.status_code == 200:
429
+ vllm_world_size = response.json()["world_size"]
430
+ else:
431
+ raise Exception(f"Request failed: {response.status_code}, {response.text}")
432
+
433
+ world_size = vllm_world_size + 1 # add the client to the world
434
+ self.rank = vllm_world_size # the client's rank is the last process
435
+
436
+ # Initialize weight update group
437
+ url = f"{self.base_url}/init_communicator/"
438
+ # Will simplify it after torch xpu 2.9 support get uuid.
439
+ if is_torch_xpu_available():
440
+ if hasattr(torch.xpu.get_device_properties(device), "uuid"):
441
+ client_device_uuid = str(torch.xpu.get_device_properties(device).uuid)
442
+ else:
443
+ client_device_uuid = "42"
444
+ else:
445
+ client_device_uuid = str(torch.cuda.get_device_properties(device).uuid)
446
+
447
+ # Set the weight update group's host to "0.0.0.0" so that
448
+ # clients from different IPs can send updated weights
449
+ response = self.session.post(
450
+ url,
451
+ json={
452
+ "host": "0.0.0.0",
453
+ "port": self.group_port,
454
+ "world_size": world_size,
455
+ "client_device_uuid": client_device_uuid,
456
+ },
457
+ )
458
+ if response.status_code != 200:
459
+ raise Exception(f"Request failed: {response.status_code}, {response.text}")
460
+
461
+ # Brief delay to allow server initialization. While not strictly required (client socket will retry on
462
+ # connection failure), this prevents log warnings like:
463
+ # [W416 23:24:57.460001114 socket.cpp:204] [c10d] The hostname of the client socket cannot be retrieved. err=-3
464
+ time.sleep(0.1)
465
+
466
+ # Set up the communication group for weight broadcasting
467
+ if is_torch_xpu_available():
468
+ store = torch.distributed.TCPStore(
469
+ host_name=self.host, port=self.group_port, world_size=world_size, is_master=(self.rank == 0)
470
+ )
471
+ prefixed_store = c10d.PrefixStore("client2server", store)
472
+ xccl_options = c10d.ProcessGroupXCCL.Options()
473
+ pg = c10d.ProcessGroupXCCL(
474
+ store=prefixed_store,
475
+ rank=self.rank,
476
+ size=world_size,
477
+ options=xccl_options,
478
+ )
479
+ self.communicator = pg
480
+ else:
481
+ pg = StatelessProcessGroup.create(
482
+ host=self.host, port=self.group_port, rank=self.rank, world_size=world_size
483
+ )
484
+ self.communicator = PyNcclCommunicator(pg, device=device)
485
+
486
+ # When the client object is deleted, close the weight update group
487
+ atexit.register(self.close_communicator)
488
+
489
+ def update_named_param(self, name: str, weights: torch.Tensor):
490
+ """
491
+ Updates a specific named parameter in the model and broadcasts it to other processes.
492
+
493
+ Args:
494
+ name (`str`):
495
+ Name of the layer whose weights are being updated.
496
+ weights (`torch.Tensor`):
497
+ Tensor containing the updated weights.
498
+ """
499
+ dtype, shape = str(weights.dtype), tuple(weights.shape)
500
+ url = f"{self.base_url}/update_named_param/"
501
+ response = self.session.post(url, json={"name": name, "dtype": dtype, "shape": shape})
502
+ if response.status_code != 200:
503
+ raise Exception(f"Request failed: {response.status_code}, {response.text}")
504
+
505
+ if is_torch_xpu_available():
506
+ # Use XCCL to broadcast the updated weights from the client (src) to all workers.
507
+ self.communicator.broadcast(weights, root=self.rank)
508
+ self.communicator.barrier()
509
+ else:
510
+ # Use NCCL to broadcast the updated weights from the client (src) to all workers.
511
+ self.communicator.broadcast(weights, src=self.rank)
512
+ self.communicator.group.barrier()
513
+
514
+ def update_model_params(self, model: nn.Module):
515
+ """
516
+ Updates all parameters of the given model by calling `update_named_param` for each parameter in the model.
517
+
518
+ Args:
519
+ model (`nn.Module`):
520
+ Model whose parameters (weights/biases) are to be updated.
521
+ """
522
+ for name, param in model.named_parameters():
523
+ # Update each parameter individually
524
+ self.update_named_param(name, param.data)
525
+
526
+ def get_sequence_logprobs(
527
+ self,
528
+ sequences: list[list[int]],
529
+ prompt_lengths: list[int],
530
+ top_logprobs: int = 100,
531
+ temperature: float = 1.0,
532
+ use_binary: bool = True,
533
+ chunk_size: int = 0,
534
+ max_concurrent_requests: int = 4,
535
+ ) -> dict[str, list]:
536
+ """
537
+ Computes teacher logprobs for existing token sequences without generating new tokens.
538
+
539
+ Sends full sequences (prompt + completion) to the vLLM server and retrieves per-token top-k logprobs for the
540
+ completion region only. This is used for knowledge distillation where the teacher model evaluates existing
541
+ sequences rather than generating new ones.
542
+
543
+ When `chunk_size > 0`, splits the batch into chunks and dispatches them concurrently via a thread pool, keeping
544
+ the server's data-parallel workers busy.
545
+
546
+ When `use_binary=True`, uses base64-encoded numpy arrays for fast serialization instead of nested JSON lists.
547
+
548
+ Args:
549
+ sequences (`list[list[int]]`):
550
+ List of full token ID sequences (prompt + completion).
551
+ prompt_lengths (`list[int]`):
552
+ Number of prompt tokens in each sequence. Logprobs are returned starting from this position.
553
+ top_logprobs (`int`, *optional*, defaults to `100`):
554
+ Number of top logprobs to return per token position.
555
+ temperature (`float`, *optional*, defaults to `1.0`):
556
+ Temperature used when scoring the teacher distribution.
557
+ use_binary (`bool`, *optional*, defaults to `True`):
558
+ Use binary (base64 numpy) response format for faster serialization.
559
+ chunk_size (`int`, *optional*, defaults to `0`):
560
+ If > 0, split batch into chunks of this size and dispatch concurrently. If 0, send the entire batch in
561
+ a single request.
562
+ max_concurrent_requests (`int`, *optional*, defaults to `4`):
563
+ Maximum number of concurrent requests when using chunked dispatch.
564
+
565
+ Returns:
566
+ `dict` with keys:
567
+ - `logprobs` (`list[list[list[float]]]`):
568
+ Per-token logprobs of shape (batch, completion_len, top_logprobs), sorted by descending
569
+ probability.
570
+ - `logprob_token_ids` (`list[list[list[int]]]`):
571
+ Token IDs corresponding to each logprob, same shape as `logprobs`.
572
+ """
573
+ from concurrent.futures import ThreadPoolExecutor, as_completed
574
+
575
+ if temperature <= 0:
576
+ raise ValueError(f"temperature must be positive, got {temperature}")
577
+
578
+ url = f"{self.base_url}/get_sequence_logprobs/"
579
+ response_format = "binary" if use_binary else "json"
580
+
581
+ if chunk_size > 0 and len(sequences) > chunk_size:
582
+ # Chunked concurrent dispatch
583
+ n = len(sequences)
584
+ chunks = []
585
+ for i in range(0, n, chunk_size):
586
+ chunks.append((sequences[i : i + chunk_size], prompt_lengths[i : i + chunk_size]))
587
+
588
+ responses = [None] * len(chunks)
589
+
590
+ def _send_chunk(idx, seqs, plens):
591
+ resp = self.session.post(
592
+ url,
593
+ json={
594
+ "sequences": seqs,
595
+ "prompt_lengths": plens,
596
+ "top_logprobs": top_logprobs,
597
+ "temperature": temperature,
598
+ "response_format": response_format,
599
+ },
600
+ )
601
+ if resp.status_code != 200:
602
+ raise Exception(f"Request failed: {resp.status_code}, {resp.text}")
603
+ return idx, resp.json()
604
+
605
+ with ThreadPoolExecutor(max_workers=min(max_concurrent_requests, len(chunks))) as executor:
606
+ futures = {
607
+ executor.submit(_send_chunk, idx, seqs, plens): idx for idx, (seqs, plens) in enumerate(chunks)
608
+ }
609
+ for future in as_completed(futures):
610
+ idx, result = future.result()
611
+ responses[idx] = result
612
+
613
+ # Merge results
614
+ if use_binary:
615
+ return self._merge_binary_responses(responses, top_logprobs)
616
+ else:
617
+ all_logprobs = []
618
+ all_token_ids = []
619
+ for resp in responses:
620
+ all_logprobs.extend(resp["logprobs"])
621
+ all_token_ids.extend(resp["logprob_token_ids"])
622
+ return {"logprobs": all_logprobs, "logprob_token_ids": all_token_ids}
623
+ else:
624
+ # Single request
625
+ response = self.session.post(
626
+ url,
627
+ json={
628
+ "sequences": sequences,
629
+ "prompt_lengths": prompt_lengths,
630
+ "top_logprobs": top_logprobs,
631
+ "temperature": temperature,
632
+ "response_format": response_format,
633
+ },
634
+ )
635
+ if response.status_code != 200:
636
+ raise Exception(f"Request failed: {response.status_code}, {response.text}")
637
+
638
+ json_response = response.json()
639
+ if use_binary:
640
+ return self._decode_binary_logprobs(json_response)
641
+ else:
642
+ return {
643
+ "logprobs": json_response["logprobs"],
644
+ "logprob_token_ids": json_response["logprob_token_ids"],
645
+ }
646
+
647
+ @staticmethod
648
+ def _decode_binary_logprobs(response: dict) -> dict[str, list]:
649
+ """Decode base64-encoded numpy arrays back to nested lists.
650
+
651
+ Returns a dict with:
652
+ ``logprobs`` / ``logprob_token_ids`` — teacher's sorted top-k logprobs and
653
+ token IDs (shape per sequence: ``(comp_len, top_k)``). Used for the forward KL term.
654
+ ``actual_logprobs`` / ``actual_token_ids`` — teacher logprob for the actual
655
+ token at each position (shape per sequence: ``(comp_len, 1)``). Used for the reverse KL term.
656
+ """
657
+ import numpy as np
658
+
659
+ shape = response["shape"] # [batch, max_comp_len, top_k]
660
+ comp_lengths = response["completion_lengths"]
661
+
662
+ logprobs_arr = np.frombuffer(base64.b64decode(response["logprobs_b64"]), dtype=np.float32).reshape(shape)
663
+ token_ids_arr = np.frombuffer(base64.b64decode(response["token_ids_b64"]), dtype=np.int32).reshape(shape)
664
+
665
+ # Convert back to nested lists, trimming padding
666
+ all_logprobs = []
667
+ all_token_ids = []
668
+ for i, comp_len in enumerate(comp_lengths):
669
+ all_logprobs.append(logprobs_arr[i, :comp_len, :].tolist())
670
+ all_token_ids.append(token_ids_arr[i, :comp_len, :].tolist())
671
+
672
+ result = {"logprobs": all_logprobs, "logprob_token_ids": all_token_ids}
673
+
674
+ # Decode actual-token logprobs (for reverse KL)
675
+ if "actual_logprobs_b64" in response:
676
+ actual_shape = [shape[0], shape[1], 1]
677
+ actual_lp = np.frombuffer(base64.b64decode(response["actual_logprobs_b64"]), dtype=np.float32).reshape(
678
+ actual_shape
679
+ )
680
+ actual_ids = np.frombuffer(base64.b64decode(response["actual_token_ids_b64"]), dtype=np.int32).reshape(
681
+ actual_shape
682
+ )
683
+ all_actual_lps = []
684
+ all_actual_ids = []
685
+ for i, comp_len in enumerate(comp_lengths):
686
+ all_actual_lps.append(actual_lp[i, :comp_len, :].tolist())
687
+ all_actual_ids.append(actual_ids[i, :comp_len, :].tolist())
688
+ result["actual_logprobs"] = all_actual_lps
689
+ result["actual_token_ids"] = all_actual_ids
690
+
691
+ return result
692
+
693
+ @staticmethod
694
+ def _merge_binary_responses(responses: list[dict], top_logprobs: int) -> dict[str, list]:
695
+ """Merge binary responses from multiple chunks into a single result."""
696
+
697
+ all_logprobs = []
698
+ all_token_ids = []
699
+ all_actual_lps = []
700
+ all_actual_ids = []
701
+ for resp in responses:
702
+ decoded = VLLMClient._decode_binary_logprobs(resp)
703
+ all_logprobs.extend(decoded["logprobs"])
704
+ all_token_ids.extend(decoded["logprob_token_ids"])
705
+ if "actual_logprobs" in decoded:
706
+ all_actual_lps.extend(decoded["actual_logprobs"])
707
+ all_actual_ids.extend(decoded["actual_token_ids"])
708
+
709
+ result = {"logprobs": all_logprobs, "logprob_token_ids": all_token_ids}
710
+ if all_actual_lps:
711
+ if len(all_actual_lps) != len(all_logprobs):
712
+ raise ValueError(
713
+ f"Inconsistent chunks: {len(all_actual_lps)} actual_logprobs entries "
714
+ f"but {len(all_logprobs)} logprobs entries."
715
+ )
716
+ result["actual_logprobs"] = all_actual_lps
717
+ result["actual_token_ids"] = all_actual_ids
718
+ return result
719
+
720
+ def reset_prefix_cache(self):
721
+ """
722
+ Resets the prefix cache for the model.
723
+ """
724
+ url = f"{self.base_url}/reset_prefix_cache/"
725
+ response = self.session.post(url)
726
+ if response.status_code != 200:
727
+ raise Exception(f"Request failed: {response.status_code}, {response.text}")
728
+
729
+ def close_communicator(self):
730
+ """
731
+ Closes the weight update group and cleans up the communication group.
732
+ """
733
+ url = f"{self.base_url}/close_communicator/"
734
+
735
+ try:
736
+ response = self.session.post(url)
737
+ except ConnectionError:
738
+ # The server might be already down, so we don't need to close the communicator
739
+ pass
740
+ else:
741
+ if response.status_code != 200:
742
+ raise Exception(f"Request failed: {response.status_code}, {response.text}")
743
+
744
+ if self.communicator is not None:
745
+ self.communicator = None
746
+
747
+
748
+ # Example usage
749
+ if __name__ == "__main__":
750
+ from vllm import SamplingParams
751
+
752
+ device = "xpu" if is_torch_xpu_available() else "cuda"
753
+ client = VLLMClient()
754
+ client.init_communicator(device=device)
755
+
756
+ # Generate completions
757
+ responses = client.generate(["Hello, AI!", "Tell me a joke"], n=4, max_tokens=32, sampling_params=SamplingParams())
758
+ print("Responses:", responses) # noqa
759
+
760
+ # Update model weights
761
+ from transformers import AutoModelForCausalLM
762
+
763
+ model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-7B").to(device)
764
+ client.update_model_params(model)