Stage Harbor release files 5001-5500
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/bema_for_ref_model/callback.py +221 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/bema_for_ref_model/dpo_trainer.py +30 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/cpo/__init__.py +19 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/cpo/cpo_config.py +182 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/cpo/cpo_trainer.py +1102 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/distillation/__init__.py +19 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/distillation/distillation_config.py +454 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/distillation/distillation_trainer.py +1770 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/dppo/__init__.py +17 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/dppo/dppo_config.py +115 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/dppo/dppo_trainer.py +1387 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gfpo/__init__.py +16 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gfpo/gfpo_config.py +35 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gfpo/gfpo_trainer.py +464 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gkd/__init__.py +19 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gkd/gkd_config.py +110 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gkd/gkd_trainer.py +506 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gmpo/__init__.py +16 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gmpo/gmpo_config.py +47 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gmpo/gmpo_trainer.py +152 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gold/__init__.py +19 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gold/gold_config.py +531 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gold/gold_trainer.py +0 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/grpo_with_replay_buffer/__init__.py +16 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py +34 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py +797 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gspo_token/__init__.py +15 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gspo_token/grpo_trainer.py +161 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/harbor/__init__.py +32 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/harbor/_env.py +231 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/harbor/_spec.py +216 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/kto/__init__.py +19 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/kto/kto_config.py +235 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/kto/kto_trainer.py +1559 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/merge_model_callback.py +352 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/minillm/__init__.py +19 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/minillm/minillm_config.py +137 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/minillm/minillm_trainer.py +411 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/nash_md/__init__.py +19 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/nash_md/nash_md_config.py +46 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/nash_md/nash_md_trainer.py +509 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/online_dpo/__init__.py +19 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/online_dpo/online_dpo_config.py +390 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/online_dpo/online_dpo_trainer.py +1357 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/openenv/__init__.py +18 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/openenv/utils.py +214 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/openreward/__init__.py +18 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/openreward/_spec.py +359 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/openreward/environment.py +404 -0
- tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/orpo/__init__.py +19 -0
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/bema_for_ref_model/callback.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 transformers import PreTrainedModel, TrainerControl, TrainerState, TrainingArguments
|
| 19 |
+
from transformers.trainer_callback import CallbackHandler
|
| 20 |
+
|
| 21 |
+
from ...trainer.callbacks import BEMACallback as _BEMACallback
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# Logger for module-level logging
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class CallbackHandlerWithRefModel(CallbackHandler):
|
| 29 |
+
"""
|
| 30 |
+
A [`~transformers.CallbackHandler`] that supports passing a reference model to callbacks.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, callbacks, model, ref_model, processing_class, optimizer, lr_scheduler):
|
| 34 |
+
super().__init__(callbacks, model, processing_class, optimizer, lr_scheduler)
|
| 35 |
+
self.ref_model = ref_model
|
| 36 |
+
|
| 37 |
+
# Copied from CallbackHandler.call_event with the addition of `ref_model` to the callback call.
|
| 38 |
+
def call_event(self, event, args, state, control, **kwargs):
|
| 39 |
+
for callback in self.callbacks:
|
| 40 |
+
result = getattr(callback, event)(
|
| 41 |
+
args,
|
| 42 |
+
state,
|
| 43 |
+
control,
|
| 44 |
+
model=self.model,
|
| 45 |
+
ref_model=self.ref_model, # <- Added ref_model to the callback call
|
| 46 |
+
processing_class=self.processing_class,
|
| 47 |
+
optimizer=self.optimizer,
|
| 48 |
+
lr_scheduler=self.lr_scheduler,
|
| 49 |
+
train_dataloader=self.train_dataloader,
|
| 50 |
+
eval_dataloader=self.eval_dataloader,
|
| 51 |
+
**kwargs,
|
| 52 |
+
)
|
| 53 |
+
# A Callback can skip the return of `control` if it doesn't change it.
|
| 54 |
+
if result is not None:
|
| 55 |
+
control = result
|
| 56 |
+
return control
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class BEMACallback(_BEMACallback):
|
| 60 |
+
# docstyle-ignore
|
| 61 |
+
r"""
|
| 62 |
+
A [`~transformers.TrainerCallback`] that implements [BEMA](https://huggingface.co/papers/2508.00180)
|
| 63 |
+
(Bias-Corrected Exponential Moving Average) by [Adam Block](https://huggingface.co/abblock) and [Cyril
|
| 64 |
+
Zhang](https://huggingface.co/cyrilzhang). Code from https://github.com/abblock/bema under MIT license.
|
| 65 |
+
|
| 66 |
+
BEMA computes model weights that scale like:
|
| 67 |
+
|
| 68 |
+
$$
|
| 69 |
+
\theta_t' = \alpha_t \cdot (\theta_t - \theta_0) + \text{EMA}_t
|
| 70 |
+
$$
|
| 71 |
+
|
| 72 |
+
where \\( \theta_t \\) is the current model weights, \\( \theta_0 \\) is a snapshot of the model weights at the
|
| 73 |
+
first `update_after` step, \\( \text{EMA}_t \\) is the exponential moving average of the model weights, and
|
| 74 |
+
\\( \alpha_t \\) is a scaling factor that decays with the number of steps \\( t \\) as
|
| 75 |
+
|
| 76 |
+
$$
|
| 77 |
+
\alpha_t = (\rho + \gamma \cdot t)^{-\eta}.
|
| 78 |
+
$$
|
| 79 |
+
|
| 80 |
+
The EMA is computed as:
|
| 81 |
+
|
| 82 |
+
$$
|
| 83 |
+
\text{EMA}_t = (1 - \beta_t) \cdot \text{EMA}_{t-1} + \beta_t \cdot \theta_t
|
| 84 |
+
$$
|
| 85 |
+
|
| 86 |
+
where \\( \beta_t \\) is a decay factor that decays with the number of steps \\( t \\) as
|
| 87 |
+
|
| 88 |
+
$$
|
| 89 |
+
\beta_t = (\rho + \gamma \cdot t)^{-\kappa}.
|
| 90 |
+
$$
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
update_freq (`int`, *optional*, defaults to `400`):
|
| 94 |
+
Update the BEMA weights every X steps. Denoted this as \\( \phi \\) in the paper.
|
| 95 |
+
ema_power (`float`, *optional*, defaults to `0.5`):
|
| 96 |
+
Power for the EMA decay factor. Denoted \\( \kappa \\) in the paper. To disable EMA, set this to `0.0`.
|
| 97 |
+
bias_power (`float`, *optional*, defaults to `0.2`):
|
| 98 |
+
Power for the BEMA scaling factor. Denoted \\( \eta \\) in the paper. To disable BEMA, set this to `0.0`.
|
| 99 |
+
lag (`int`, *optional*, defaults to `10`):
|
| 100 |
+
Initial offset in the weight decay schedule that controls early-stage smoothness by acting as a virtual
|
| 101 |
+
starting age for the updates. Denoted as \\( \rho \\) in the paper.
|
| 102 |
+
update_after (`int`, *optional*, defaults to `0`):
|
| 103 |
+
Burn-in time before starting to update the BEMA weights. Denoted \\( \tau \\) in the paper.
|
| 104 |
+
multiplier (`float`, *optional*, defaults to `1.0`):
|
| 105 |
+
Initial value for the EMA decay factor. Denoted as \\( \gamma \\) in the paper.
|
| 106 |
+
min_ema_multiplier (`float`, *optional*, defaults to `0.0`):
|
| 107 |
+
Minimum value for the EMA decay factor.
|
| 108 |
+
device (`str`, *optional*, defaults to `"cpu"`):
|
| 109 |
+
Device to use for the BEMA buffers, e.g. `"cpu"` or `"cuda"`. Note that in most cases, this device SHOULD
|
| 110 |
+
BE DIFFERENT from the device used for training in order to avoid OOM.
|
| 111 |
+
update_ref_model (`bool`, *optional*, defaults to `False`):
|
| 112 |
+
Whether to update the reference model with BEMA weights. This creates a lagged, smoothed version of the
|
| 113 |
+
main model as the reference model.
|
| 114 |
+
ref_model_update_freq (`int`, *optional*, defaults to `400`):
|
| 115 |
+
Update the reference model with BEMA weights every this many steps.
|
| 116 |
+
ref_model_update_after (`int`, *optional*, defaults to `0`):
|
| 117 |
+
Number of steps to wait before starting to update the reference model.
|
| 118 |
+
|
| 119 |
+
Example:
|
| 120 |
+
|
| 121 |
+
```python
|
| 122 |
+
>>> from trl import BEMACallback
|
| 123 |
+
|
| 124 |
+
>>> trainer = Trainer(..., callbacks=[BEMACallback()])
|
| 125 |
+
```
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
def __init__(
|
| 129 |
+
self,
|
| 130 |
+
update_freq: int = 400,
|
| 131 |
+
ema_power: float = 0.5,
|
| 132 |
+
bias_power: float = 0.2,
|
| 133 |
+
lag: int = 10,
|
| 134 |
+
update_after: int = 0,
|
| 135 |
+
multiplier: float = 1.0,
|
| 136 |
+
min_ema_multiplier: float = 0.0,
|
| 137 |
+
device: str = "cpu",
|
| 138 |
+
update_ref_model: bool = False,
|
| 139 |
+
ref_model_update_freq: int = 400,
|
| 140 |
+
ref_model_update_after: int = 0,
|
| 141 |
+
):
|
| 142 |
+
super().__init__(
|
| 143 |
+
update_freq,
|
| 144 |
+
ema_power,
|
| 145 |
+
bias_power,
|
| 146 |
+
lag,
|
| 147 |
+
update_after,
|
| 148 |
+
multiplier,
|
| 149 |
+
min_ema_multiplier,
|
| 150 |
+
device,
|
| 151 |
+
)
|
| 152 |
+
# Reference model update parameters
|
| 153 |
+
self.update_ref_model = update_ref_model
|
| 154 |
+
self.ref_model_update_freq = ref_model_update_freq
|
| 155 |
+
self.ref_model_update_after = ref_model_update_after
|
| 156 |
+
|
| 157 |
+
@torch.no_grad()
|
| 158 |
+
def on_step_end(
|
| 159 |
+
self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model: PreTrainedModel, **kwargs
|
| 160 |
+
):
|
| 161 |
+
super().on_step_end(args, state, control, model, **kwargs)
|
| 162 |
+
|
| 163 |
+
step = state.global_step
|
| 164 |
+
# Update reference model if enabled
|
| 165 |
+
if (
|
| 166 |
+
self.update_ref_model
|
| 167 |
+
and step >= self.ref_model_update_after
|
| 168 |
+
and (step - self.ref_model_update_after) % self.ref_model_update_freq == 0
|
| 169 |
+
):
|
| 170 |
+
if "ref_model" not in kwargs:
|
| 171 |
+
raise ValueError("'ref_model' not found in kwargs.")
|
| 172 |
+
|
| 173 |
+
ref_model = kwargs["ref_model"]
|
| 174 |
+
|
| 175 |
+
# Get the current BEMA state dict
|
| 176 |
+
bema_state_dict = self.running_model.state_dict()
|
| 177 |
+
|
| 178 |
+
# Handle the case where ref_model is None (PEFT case)
|
| 179 |
+
if ref_model is None:
|
| 180 |
+
# In PEFT case, ref_model is None and we need to update the base model of the main model
|
| 181 |
+
main_model = self._unwrap_model(model)
|
| 182 |
+
if hasattr(main_model, "get_base_model"):
|
| 183 |
+
# This is a PEFT model, update the base model
|
| 184 |
+
base_model = main_model.get_base_model()
|
| 185 |
+
self._update_model_with_bema_weights(base_model, bema_state_dict, is_peft_base=True)
|
| 186 |
+
else:
|
| 187 |
+
# Regular model, update directly
|
| 188 |
+
self._update_model_with_bema_weights(main_model, bema_state_dict, is_peft_base=False)
|
| 189 |
+
else:
|
| 190 |
+
# ref_model is provided, unwrap it and update
|
| 191 |
+
ref_model = self._unwrap_model(ref_model)
|
| 192 |
+
if hasattr(ref_model, "get_base_model"):
|
| 193 |
+
# This is a PEFT model, update the base model
|
| 194 |
+
base_model = ref_model.get_base_model()
|
| 195 |
+
self._update_model_with_bema_weights(base_model, bema_state_dict, is_peft_base=True)
|
| 196 |
+
else:
|
| 197 |
+
# Regular model, update directly
|
| 198 |
+
self._update_model_with_bema_weights(ref_model, bema_state_dict, is_peft_base=False)
|
| 199 |
+
|
| 200 |
+
logger.info("BEMACallback: Updated reference model with BEMA weights")
|
| 201 |
+
|
| 202 |
+
def _update_model_with_bema_weights(self, model, bema_state_dict, is_peft_base=False):
|
| 203 |
+
"""Helper method to update a model with BEMA weights, handling PEFT and distributed scenarios."""
|
| 204 |
+
if is_peft_base:
|
| 205 |
+
# For PEFT base models, filter out adapter parameters
|
| 206 |
+
filtered_state_dict = {}
|
| 207 |
+
for key, value in bema_state_dict.items():
|
| 208 |
+
# Skip adapter parameters
|
| 209 |
+
if not key.startswith("lora_") and not key.startswith("adapter_"):
|
| 210 |
+
# Remove 'base_model.' prefix if it exists
|
| 211 |
+
if key.startswith("base_model."):
|
| 212 |
+
base_key = key[len("base_model.") :]
|
| 213 |
+
else:
|
| 214 |
+
base_key = key
|
| 215 |
+
filtered_state_dict[base_key] = value
|
| 216 |
+
|
| 217 |
+
# Update the base model
|
| 218 |
+
model.load_state_dict(filtered_state_dict, strict=False)
|
| 219 |
+
else:
|
| 220 |
+
# Regular model, update directly
|
| 221 |
+
model.load_state_dict(bema_state_dict, strict=False)
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/bema_for_ref_model/dpo_trainer.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 ...trainer.dpo_trainer import DPOTrainer as _DPOTrainer
|
| 16 |
+
from .callback import CallbackHandlerWithRefModel
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class DPOTrainer(_DPOTrainer):
|
| 20 |
+
def __init__(self, *args, **kwargs):
|
| 21 |
+
super().__init__(*args, **kwargs)
|
| 22 |
+
# Replace with a new one that calls the events with the reference model
|
| 23 |
+
self.callback_handler = CallbackHandlerWithRefModel(
|
| 24 |
+
self.callback_handler.callbacks,
|
| 25 |
+
self.model,
|
| 26 |
+
self.ref_model,
|
| 27 |
+
self.processing_class,
|
| 28 |
+
self.optimizer,
|
| 29 |
+
self.lr_scheduler,
|
| 30 |
+
)
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/cpo/__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 .cpo_config import CPOConfig
|
| 16 |
+
from .cpo_trainer import CPOTrainer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = ["CPOConfig", "CPOTrainer"]
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/cpo/cpo_config.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 CPOConfig(_BaseConfig):
|
| 23 |
+
# docstyle-ignore
|
| 24 |
+
r"""
|
| 25 |
+
Configuration class for the [`experimental.cpo.CPOTrainer`].
|
| 26 |
+
|
| 27 |
+
This class includes only the parameters that are specific to CPO 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 deviation from the reference model. Higher β means less deviation from the
|
| 44 |
+
reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in
|
| 45 |
+
the [paper](https://huggingface.co/papers/2310.12036).
|
| 46 |
+
label_smoothing (`float`, *optional*, defaults to `0.0`):
|
| 47 |
+
Label smoothing factor. This argument is required if you want to use the default data collator.
|
| 48 |
+
loss_type (`str`, *optional*, defaults to `"sigmoid"`):
|
| 49 |
+
Type of loss to use. Possible values are:
|
| 50 |
+
|
| 51 |
+
- `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper.
|
| 52 |
+
- `"hinge"`: hinge loss on the normalized likelihood from the
|
| 53 |
+
[SLiC](https://huggingface.co/papers/2305.10425) paper.
|
| 54 |
+
- `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper.
|
| 55 |
+
- `"simpo"`: SimPO loss from the [SimPO](https://huggingface.co/papers/2405.14734) paper.
|
| 56 |
+
- `"alphapo"`: AlphaPO loss from the [AlphaPO](https://huggingface.co/papers/2501.03884) paper. This
|
| 57 |
+
automatically sets `loss_type="simpo"` and `cpo_alpha=0.0`.
|
| 58 |
+
|
| 59 |
+
disable_dropout (`bool`, *optional*, defaults to `True`):
|
| 60 |
+
Whether to disable dropout in the model.
|
| 61 |
+
cpo_alpha (`float`, *optional*, defaults to `1.0`):
|
| 62 |
+
Weight of the BC regularizer in CPO training.
|
| 63 |
+
simpo_gamma (`float`, *optional*, defaults to `0.5`):
|
| 64 |
+
Target reward margin for the SimPO loss, used only when the `loss_type="simpo"`.
|
| 65 |
+
alpha (`float`, *optional*, defaults to `0.0`):
|
| 66 |
+
Alpha parameter that controls reward function shape across all loss types. When alpha=0 (default), uses
|
| 67 |
+
standard log probability rewards. When `alpha != 0`, applies AlphaPO transformation: `r = (1 - p^(-alpha))
|
| 68 |
+
/ alpha` from the [AlphaPO paper](https://huggingface.co/papers/2501.03884). This parameter works with all
|
| 69 |
+
loss types.
|
| 70 |
+
generate_during_eval (`bool`, *optional*, defaults to `False`):
|
| 71 |
+
If `True`, generates and logs completions from the model to W&B or Comet during evaluation.
|
| 72 |
+
is_encoder_decoder (`bool`, *optional*):
|
| 73 |
+
When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument,
|
| 74 |
+
you need to specify if the model returned by the callable is an encoder-decoder model.
|
| 75 |
+
model_init_kwargs (`dict[str, Any]`, *optional*):
|
| 76 |
+
Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a
|
| 77 |
+
string.
|
| 78 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 79 |
+
Whether to allow loading models that ship custom Python code from the Hub. Forwarded to
|
| 80 |
+
[`~transformers.AutoModelForCausalLM.from_pretrained`].
|
| 81 |
+
dataset_num_proc (`int`, *optional*):
|
| 82 |
+
Number of processes to use for processing the dataset.
|
| 83 |
+
|
| 84 |
+
> [!NOTE]
|
| 85 |
+
> These parameters have default values different from [`~transformers.TrainingArguments`]:
|
| 86 |
+
> - `logging_steps`: Defaults to `10` instead of `500`.
|
| 87 |
+
> - `gradient_checkpointing`: Defaults to `True` instead of `False`.
|
| 88 |
+
> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
|
| 89 |
+
> - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
_VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
|
| 93 |
+
|
| 94 |
+
# Parameters whose default values are overridden from TrainingArguments
|
| 95 |
+
learning_rate: float = field(
|
| 96 |
+
default=1e-6,
|
| 97 |
+
metadata={"help": "The initial learning rate for AdamW."},
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
max_length: int | None = field(
|
| 101 |
+
default=1024,
|
| 102 |
+
metadata={"help": "Maximum length of the sequences (prompt + completion) in the batch."},
|
| 103 |
+
)
|
| 104 |
+
max_completion_length: int | None = field(
|
| 105 |
+
default=None,
|
| 106 |
+
metadata={
|
| 107 |
+
"help": "Maximum length of the completion. This argument is required if you want to use the default data "
|
| 108 |
+
"collator and your model is an encoder-decoder."
|
| 109 |
+
},
|
| 110 |
+
)
|
| 111 |
+
beta: float = field(
|
| 112 |
+
default=0.1,
|
| 113 |
+
metadata={
|
| 114 |
+
"help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from "
|
| 115 |
+
"the reference model."
|
| 116 |
+
},
|
| 117 |
+
)
|
| 118 |
+
label_smoothing: float = field(
|
| 119 |
+
default=0.0,
|
| 120 |
+
metadata={"help": "Label smoothing factor."},
|
| 121 |
+
)
|
| 122 |
+
loss_type: str = field(
|
| 123 |
+
default="sigmoid",
|
| 124 |
+
metadata={
|
| 125 |
+
"help": "Type of loss to use.",
|
| 126 |
+
"choices": ["sigmoid", "hinge", "ipo", "simpo", "alphapo"],
|
| 127 |
+
},
|
| 128 |
+
)
|
| 129 |
+
disable_dropout: bool = field(
|
| 130 |
+
default=True,
|
| 131 |
+
metadata={"help": "Whether to disable dropout in the model."},
|
| 132 |
+
)
|
| 133 |
+
cpo_alpha: float = field(
|
| 134 |
+
default=1.0,
|
| 135 |
+
metadata={"help": "Weight of the BC regularizer in CPO training."},
|
| 136 |
+
)
|
| 137 |
+
simpo_gamma: float = field(
|
| 138 |
+
default=0.5,
|
| 139 |
+
metadata={"help": "Target reward margin for the SimPO loss, used only when the `loss_type='simpo'`."},
|
| 140 |
+
)
|
| 141 |
+
alpha: float = field(
|
| 142 |
+
default=0.0,
|
| 143 |
+
metadata={
|
| 144 |
+
"help": "Alpha parameter that controls reward function shape across all loss types. When alpha=0 "
|
| 145 |
+
"(default), uses standard log probability rewards. When `alpha != 0`, applies AlphaPO transformation: "
|
| 146 |
+
"`r = (1 - p^(-alpha)) / alpha` from the AlphaPO paper. This parameter works with all loss types."
|
| 147 |
+
},
|
| 148 |
+
)
|
| 149 |
+
generate_during_eval: bool = field(
|
| 150 |
+
default=False,
|
| 151 |
+
metadata={"help": "If `True`, generates and logs completions from the model to W&B during evaluation."},
|
| 152 |
+
)
|
| 153 |
+
is_encoder_decoder: bool | None = field(
|
| 154 |
+
default=None,
|
| 155 |
+
metadata={"help": "Whether the model is an encoder-decoder model."},
|
| 156 |
+
)
|
| 157 |
+
model_init_kwargs: dict[str, Any] | str | None = field(
|
| 158 |
+
default=None,
|
| 159 |
+
metadata={
|
| 160 |
+
"help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model "
|
| 161 |
+
"from a string."
|
| 162 |
+
},
|
| 163 |
+
)
|
| 164 |
+
trust_remote_code: bool = field(
|
| 165 |
+
default=False,
|
| 166 |
+
metadata={
|
| 167 |
+
"help": "Whether to allow loading models that ship custom Python code from the Hub. Forwarded to "
|
| 168 |
+
"`AutoModelForCausalLM.from_pretrained`."
|
| 169 |
+
},
|
| 170 |
+
)
|
| 171 |
+
dataset_num_proc: int | None = field(
|
| 172 |
+
default=None,
|
| 173 |
+
metadata={"help": "Number of processes to use for processing the dataset."},
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
def __post_init__(self):
|
| 177 |
+
# Syntactic sugar for AlphaPO: set loss_type to "simpo" and cpo_alpha to 0.0
|
| 178 |
+
if self.loss_type == "alphapo":
|
| 179 |
+
self.loss_type = "simpo"
|
| 180 |
+
self.cpo_alpha = 0.0
|
| 181 |
+
|
| 182 |
+
super().__post_init__()
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/cpo/cpo_trainer.py
ADDED
|
@@ -0,0 +1,1102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
AutoTokenizer,
|
| 40 |
+
BaseImageProcessor,
|
| 41 |
+
DataCollator,
|
| 42 |
+
FeatureExtractionMixin,
|
| 43 |
+
PreTrainedModel,
|
| 44 |
+
PreTrainedTokenizerBase,
|
| 45 |
+
ProcessorMixin,
|
| 46 |
+
TrainerCallback,
|
| 47 |
+
is_comet_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 (
|
| 56 |
+
disable_dropout_in_model,
|
| 57 |
+
get_config_model_id,
|
| 58 |
+
log_table_to_comet_experiment,
|
| 59 |
+
selective_log_softmax,
|
| 60 |
+
)
|
| 61 |
+
from ..utils import (
|
| 62 |
+
DPODataCollatorWithPadding,
|
| 63 |
+
add_bos_token_if_needed,
|
| 64 |
+
add_eos_token_if_needed,
|
| 65 |
+
pad_to_length,
|
| 66 |
+
peft_module_casting_to_bf16,
|
| 67 |
+
)
|
| 68 |
+
from .cpo_config import CPOConfig
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if is_peft_available():
|
| 72 |
+
import peft
|
| 73 |
+
from peft import PeftConfig, get_peft_model, prepare_model_for_kbit_training
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if is_wandb_available():
|
| 77 |
+
import wandb
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
logger = get_logger(__name__)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class CPOTrainer(_BaseTrainer):
|
| 84 |
+
r"""
|
| 85 |
+
Initialize CPOTrainer.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
model ([`~transformers.PreTrainedModel`]):
|
| 89 |
+
The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`].
|
| 90 |
+
args ([`experimental.cpo.CPOConfig`]):
|
| 91 |
+
The CPO config arguments to use for training.
|
| 92 |
+
data_collator ([`~transformers.DataCollator`]):
|
| 93 |
+
The data collator to use for training. If None is specified, the default data collator
|
| 94 |
+
([`experimental.utils.DPODataCollatorWithPadding`]) will be used which will pad the sequences to the
|
| 95 |
+
maximum length of the sequences in the batch, given a dataset of paired sequences.
|
| 96 |
+
train_dataset ([`~datasets.Dataset`]):
|
| 97 |
+
The dataset to use for training.
|
| 98 |
+
eval_dataset ([`~datasets.Dataset`]):
|
| 99 |
+
The dataset to use for evaluation.
|
| 100 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
|
| 101 |
+
Processing class used to process the data. If provided, will be used to automatically process the inputs
|
| 102 |
+
for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
|
| 103 |
+
reuse the fine-tuned model.
|
| 104 |
+
model_init (`Callable[[], transformers.PreTrainedModel]`):
|
| 105 |
+
The model initializer to use for training. If None is specified, the default model initializer will be
|
| 106 |
+
used.
|
| 107 |
+
callbacks (`list[transformers.TrainerCallback]`):
|
| 108 |
+
The callbacks to use for training.
|
| 109 |
+
optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
|
| 110 |
+
The optimizer and scheduler to use for training.
|
| 111 |
+
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
|
| 112 |
+
The function to use to preprocess the logits before computing the metrics.
|
| 113 |
+
peft_config ([`~peft.PeftConfig`], *optional*):
|
| 114 |
+
The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in
|
| 115 |
+
a PEFT model.
|
| 116 |
+
compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
|
| 117 |
+
The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
|
| 118 |
+
metric values.
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
_tag_names = ["trl", "cpo"]
|
| 122 |
+
_name = "CPO"
|
| 123 |
+
_paper = {
|
| 124 |
+
"title": "Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation",
|
| 125 |
+
"id": "2401.08417",
|
| 126 |
+
# docstyle-ignore
|
| 127 |
+
"citation": textwrap.dedent("""\
|
| 128 |
+
@inproceedings{xu2024contrastive,
|
| 129 |
+
title = {{Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation}},
|
| 130 |
+
author = {Haoran Xu and Amr Sharaf and Yunmo Chen and Weiting Tan and Lingfeng Shen and Benjamin Van Durme and Kenton Murray and Young Jin Kim},
|
| 131 |
+
year = 2024,
|
| 132 |
+
booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024},
|
| 133 |
+
publisher = {OpenReview.net},
|
| 134 |
+
url = {https://openreview.net/forum?id=51iwkioZpn}
|
| 135 |
+
}"""),
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
def __init__(
|
| 139 |
+
self,
|
| 140 |
+
model: PreTrainedModel | nn.Module | str | None = None,
|
| 141 |
+
args: CPOConfig | None = None,
|
| 142 |
+
data_collator: DataCollator | None = None,
|
| 143 |
+
train_dataset: Dataset | None = None,
|
| 144 |
+
eval_dataset: Dataset | dict[str, Dataset] | None = None,
|
| 145 |
+
processing_class: PreTrainedTokenizerBase
|
| 146 |
+
| BaseImageProcessor
|
| 147 |
+
| FeatureExtractionMixin
|
| 148 |
+
| ProcessorMixin
|
| 149 |
+
| None = None,
|
| 150 |
+
model_init: Callable[[], PreTrainedModel] | None = None,
|
| 151 |
+
callbacks: list[TrainerCallback] | None = None,
|
| 152 |
+
optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
|
| 153 |
+
preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
|
| 154 |
+
peft_config: "PeftConfig | None" = None,
|
| 155 |
+
compute_metrics: Callable[[EvalLoopOutput], dict] | None = None,
|
| 156 |
+
):
|
| 157 |
+
if train_dataset is None:
|
| 158 |
+
raise ValueError("`train_dataset` is required")
|
| 159 |
+
|
| 160 |
+
if args.model_init_kwargs is None:
|
| 161 |
+
model_init_kwargs = {}
|
| 162 |
+
elif not isinstance(model, str):
|
| 163 |
+
raise ValueError("You passed model_kwargs to the CPOTrainer. But your model is already instantiated.")
|
| 164 |
+
else:
|
| 165 |
+
model_init_kwargs = args.model_init_kwargs
|
| 166 |
+
dtype = model_init_kwargs.get("dtype", "auto")
|
| 167 |
+
if dtype is not None:
|
| 168 |
+
# Convert to `torch.dtype` if an str is passed
|
| 169 |
+
if isinstance(dtype, str) and dtype != "auto":
|
| 170 |
+
dtype = getattr(torch, dtype)
|
| 171 |
+
if dtype != "auto" and not isinstance(dtype, torch.dtype):
|
| 172 |
+
raise ValueError(
|
| 173 |
+
f"Invalid `dtype` passed to the CPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {dtype}."
|
| 174 |
+
)
|
| 175 |
+
model_init_kwargs["dtype"] = dtype
|
| 176 |
+
model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto")
|
| 177 |
+
|
| 178 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 179 |
+
|
| 180 |
+
if isinstance(model, str):
|
| 181 |
+
model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
|
| 182 |
+
|
| 183 |
+
# PEFT
|
| 184 |
+
# Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16`
|
| 185 |
+
# has been called in order to properly call autocast if needed.
|
| 186 |
+
self._peft_has_been_casted_to_bf16 = False
|
| 187 |
+
if peft_config is not None:
|
| 188 |
+
if not is_peft_available():
|
| 189 |
+
raise ImportError(
|
| 190 |
+
"You passed `peft_config` but the `peft` library is not installed. "
|
| 191 |
+
"Install it with `pip install trl[peft]`."
|
| 192 |
+
)
|
| 193 |
+
if not isinstance(peft_config, PeftConfig):
|
| 194 |
+
raise TypeError(
|
| 195 |
+
f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
|
| 196 |
+
f"got {type(peft_config).__name__}."
|
| 197 |
+
)
|
| 198 |
+
if is_peft_model(model):
|
| 199 |
+
raise ValueError(
|
| 200 |
+
"You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first "
|
| 201 |
+
"merge and unload the existing adapter, save the resulting base model, and then pass that base "
|
| 202 |
+
"model along with the new `peft_config` to the trainer."
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False):
|
| 206 |
+
_support_gc_kwargs = hasattr(
|
| 207 |
+
args, "gradient_checkpointing_kwargs"
|
| 208 |
+
) and "gradient_checkpointing_kwargs" in list(
|
| 209 |
+
inspect.signature(prepare_model_for_kbit_training).parameters
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing}
|
| 213 |
+
|
| 214 |
+
if _support_gc_kwargs:
|
| 215 |
+
prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs
|
| 216 |
+
|
| 217 |
+
model = prepare_model_for_kbit_training(model, **prepare_model_kwargs)
|
| 218 |
+
elif args.gradient_checkpointing:
|
| 219 |
+
# For backward compatibility with older versions of transformers
|
| 220 |
+
if hasattr(model, "enable_input_require_grads"):
|
| 221 |
+
model.enable_input_require_grads()
|
| 222 |
+
else:
|
| 223 |
+
|
| 224 |
+
def make_inputs_require_grad(module, input, output):
|
| 225 |
+
output.requires_grad_(True)
|
| 226 |
+
|
| 227 |
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
| 228 |
+
|
| 229 |
+
# get peft model with the given config
|
| 230 |
+
# ZeRO-3 + PEFT for non-quantized models:
|
| 231 |
+
# - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16.
|
| 232 |
+
# - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter,
|
| 233 |
+
# so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step.
|
| 234 |
+
# - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch.
|
| 235 |
+
# - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for
|
| 236 |
+
# non-quantized bf16 training.
|
| 237 |
+
# - See:
|
| 238 |
+
# - TRL issue: https://github.com/huggingface/trl/issues/6089
|
| 239 |
+
# - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072
|
| 240 |
+
# - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg
|
| 241 |
+
_is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(
|
| 242 |
+
model, "is_loaded_in_8bit", False
|
| 243 |
+
)
|
| 244 |
+
get_peft_model_kwargs = {}
|
| 245 |
+
if (
|
| 246 |
+
args.deepspeed_plugin is not None
|
| 247 |
+
and args.deepspeed_plugin.zero_stage == 3
|
| 248 |
+
and not _is_quantized_model
|
| 249 |
+
and Version(peft.__version__) >= Version("0.12.0")
|
| 250 |
+
):
|
| 251 |
+
get_peft_model_kwargs["autocast_adapter_dtype"] = False
|
| 252 |
+
model = get_peft_model(model, peft_config, **get_peft_model_kwargs)
|
| 253 |
+
if args.bf16 and getattr(model, "is_loaded_in_4bit", False):
|
| 254 |
+
peft_module_casting_to_bf16(model)
|
| 255 |
+
# If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager
|
| 256 |
+
self._peft_has_been_casted_to_bf16 = True
|
| 257 |
+
|
| 258 |
+
# For models that use gradient_checkpointing, we need to attach a hook that enables input
|
| 259 |
+
# to explicitly have `requires_grad=True`, otherwise training will either silently
|
| 260 |
+
# fail or completely fail.
|
| 261 |
+
elif args.gradient_checkpointing:
|
| 262 |
+
# For backward compatibility with older versions of transformers
|
| 263 |
+
if hasattr(model, "enable_input_require_grads"):
|
| 264 |
+
model.enable_input_require_grads()
|
| 265 |
+
else:
|
| 266 |
+
|
| 267 |
+
def make_inputs_require_grad(module, input, output):
|
| 268 |
+
output.requires_grad_(True)
|
| 269 |
+
|
| 270 |
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
| 271 |
+
|
| 272 |
+
if args.generate_during_eval and not (is_wandb_available() or is_comet_available()):
|
| 273 |
+
raise ValueError(
|
| 274 |
+
"`generate_during_eval=True` requires Weights and Biases or Comet to be installed."
|
| 275 |
+
" Please install `wandb` or `comet-ml` to resolve."
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
if model is not None:
|
| 279 |
+
self.is_encoder_decoder = model.config.is_encoder_decoder
|
| 280 |
+
elif args.is_encoder_decoder is None:
|
| 281 |
+
raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.")
|
| 282 |
+
else:
|
| 283 |
+
self.is_encoder_decoder = args.is_encoder_decoder
|
| 284 |
+
|
| 285 |
+
if self.is_encoder_decoder:
|
| 286 |
+
self.decoder_start_token_id = model.config.decoder_start_token_id
|
| 287 |
+
self.pad_token_id = model.config.pad_token_id
|
| 288 |
+
|
| 289 |
+
if processing_class is None:
|
| 290 |
+
processing_class = AutoTokenizer.from_pretrained(
|
| 291 |
+
get_config_model_id(model.config), trust_remote_code=args.trust_remote_code
|
| 292 |
+
)
|
| 293 |
+
if args.max_length is None:
|
| 294 |
+
logger.warning(
|
| 295 |
+
"`max_length` is not set in the CPOConfig's init"
|
| 296 |
+
" it will default to `512` by default, but you should do it yourself in the future.",
|
| 297 |
+
)
|
| 298 |
+
max_length = 512
|
| 299 |
+
else:
|
| 300 |
+
max_length = args.max_length
|
| 301 |
+
|
| 302 |
+
if args.max_completion_length is None and self.is_encoder_decoder:
|
| 303 |
+
logger.warning(
|
| 304 |
+
"When using an encoder decoder architecture, you should set `max_completion_length` in the CPOConfig's init"
|
| 305 |
+
" it will default to `128` by default, but you should do it yourself in the future.",
|
| 306 |
+
)
|
| 307 |
+
max_completion_length = 128
|
| 308 |
+
else:
|
| 309 |
+
max_completion_length = args.max_completion_length
|
| 310 |
+
|
| 311 |
+
if data_collator is None:
|
| 312 |
+
data_collator = DPODataCollatorWithPadding(
|
| 313 |
+
pad_token_id=processing_class.pad_token_id,
|
| 314 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
if args.remove_unused_columns:
|
| 318 |
+
args.remove_unused_columns = False
|
| 319 |
+
# warn users
|
| 320 |
+
logger.warning(
|
| 321 |
+
"When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments"
|
| 322 |
+
" we have set it for you, but you should do it yourself in the future.",
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
self.use_dpo_data_collator = True
|
| 326 |
+
else:
|
| 327 |
+
self.use_dpo_data_collator = False
|
| 328 |
+
|
| 329 |
+
# Disable dropout in the model
|
| 330 |
+
if args.disable_dropout:
|
| 331 |
+
disable_dropout_in_model(model)
|
| 332 |
+
|
| 333 |
+
self.max_length = max_length
|
| 334 |
+
self.generate_during_eval = args.generate_during_eval
|
| 335 |
+
self.max_completion_length = max_completion_length
|
| 336 |
+
self.processing_class = processing_class
|
| 337 |
+
|
| 338 |
+
if processing_class.pad_token is None:
|
| 339 |
+
processing_class.pad_token = processing_class.eos_token
|
| 340 |
+
self.pad_token_id = processing_class.pad_token_id
|
| 341 |
+
|
| 342 |
+
if args.loss_type in ["hinge", "ipo"] and args.label_smoothing > 0:
|
| 343 |
+
logger.warning(
|
| 344 |
+
f"You are using the {args.loss_type} loss type that does not support label smoothing. The "
|
| 345 |
+
"`label_smoothing` parameter will be ignored. Set `label_smoothing` to `0.0` to remove this warning.",
|
| 346 |
+
)
|
| 347 |
+
if args.loss_type == "kto_pair":
|
| 348 |
+
raise ValueError("Support for kto_pair has been removed in CPOTrainer. Please use KTOTrainer.")
|
| 349 |
+
|
| 350 |
+
self.beta = args.beta
|
| 351 |
+
self.label_smoothing = args.label_smoothing
|
| 352 |
+
self.loss_type = args.loss_type
|
| 353 |
+
self.cpo_alpha = args.cpo_alpha
|
| 354 |
+
self.aux_loss_enabled = getattr(model.config, "output_router_logits", False)
|
| 355 |
+
self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0)
|
| 356 |
+
if self.aux_loss_enabled and self.aux_loss_coef == 0.0:
|
| 357 |
+
logger.warning(
|
| 358 |
+
"You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to "
|
| 359 |
+
"`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value "
|
| 360 |
+
"greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary "
|
| 361 |
+
"loss.",
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
if args.loss_type == "simpo":
|
| 365 |
+
self.simpo_gamma = args.simpo_gamma
|
| 366 |
+
|
| 367 |
+
# AlphaPO parameter for reward shaping
|
| 368 |
+
self.alpha = args.alpha
|
| 369 |
+
|
| 370 |
+
self._stored_metrics = defaultdict(lambda: defaultdict(list))
|
| 371 |
+
|
| 372 |
+
# Compute that only on the main process for faster data processing.
|
| 373 |
+
# see: https://github.com/huggingface/trl/pull/1255
|
| 374 |
+
with PartialState().main_process_first():
|
| 375 |
+
# Extract the prompt if needed, and apply the chat template if needed
|
| 376 |
+
train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc)
|
| 377 |
+
train_dataset = train_dataset.map(
|
| 378 |
+
maybe_apply_chat_template,
|
| 379 |
+
fn_kwargs={"processing_class": processing_class},
|
| 380 |
+
num_proc=args.dataset_num_proc,
|
| 381 |
+
)
|
| 382 |
+
if eval_dataset is not None:
|
| 383 |
+
eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc)
|
| 384 |
+
eval_dataset = eval_dataset.map(
|
| 385 |
+
maybe_apply_chat_template,
|
| 386 |
+
fn_kwargs={"processing_class": processing_class},
|
| 387 |
+
num_proc=args.dataset_num_proc,
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
# tokenize the dataset
|
| 391 |
+
train_dataset = train_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc)
|
| 392 |
+
if eval_dataset is not None:
|
| 393 |
+
eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc)
|
| 394 |
+
|
| 395 |
+
# Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
|
| 396 |
+
# never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
|
| 397 |
+
# (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
|
| 398 |
+
# default to the recommended non-reentrant behavior here, while preserving any user-provided value.
|
| 399 |
+
if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
|
| 400 |
+
args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
|
| 401 |
+
args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
|
| 402 |
+
|
| 403 |
+
super().__init__(
|
| 404 |
+
model=model,
|
| 405 |
+
args=args,
|
| 406 |
+
data_collator=data_collator,
|
| 407 |
+
train_dataset=train_dataset,
|
| 408 |
+
eval_dataset=eval_dataset,
|
| 409 |
+
processing_class=processing_class,
|
| 410 |
+
model_init=model_init,
|
| 411 |
+
compute_metrics=compute_metrics,
|
| 412 |
+
callbacks=callbacks,
|
| 413 |
+
optimizers=optimizers,
|
| 414 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
# Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
|
| 418 |
+
# model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
|
| 419 |
+
# self.model_accepts_loss_kwargs to False to enable scaling.
|
| 420 |
+
self.model_accepts_loss_kwargs = False
|
| 421 |
+
|
| 422 |
+
# Add tags for models that have been loaded with the correct transformers version
|
| 423 |
+
if hasattr(self.model, "add_model_tags"):
|
| 424 |
+
self.model.add_model_tags(self._tag_names)
|
| 425 |
+
|
| 426 |
+
if not hasattr(self, "accelerator"):
|
| 427 |
+
raise AttributeError(
|
| 428 |
+
"Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`."
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
def build_tokenized_answer(self, prompt, answer):
|
| 432 |
+
"""
|
| 433 |
+
Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. It does ensure `enc(a + b) = enc(a) + enc(a +
|
| 434 |
+
b)[len(enc(a)):]`. Reference:
|
| 435 |
+
https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
|
| 436 |
+
"""
|
| 437 |
+
|
| 438 |
+
full_tokenized = self.processing_class(prompt + answer, add_special_tokens=False)
|
| 439 |
+
prompt_input_ids = self.processing_class(prompt, add_special_tokens=False)["input_ids"]
|
| 440 |
+
|
| 441 |
+
answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :]
|
| 442 |
+
answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :]
|
| 443 |
+
|
| 444 |
+
# Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]`
|
| 445 |
+
full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids])
|
| 446 |
+
|
| 447 |
+
# Prepare input tokens for token by token comparison
|
| 448 |
+
full_input_ids = np.array(full_tokenized["input_ids"])
|
| 449 |
+
|
| 450 |
+
if len(full_input_ids) != len(full_concat_input_ids):
|
| 451 |
+
raise ValueError("Prompt input ids and answer input ids should have the same length.")
|
| 452 |
+
|
| 453 |
+
# On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens
|
| 454 |
+
# can be merged together when tokenizing prompt+answer. This could result
|
| 455 |
+
# on the last token from the prompt being different when tokenized on its own
|
| 456 |
+
# vs when done as prompt+answer.
|
| 457 |
+
response_token_ids_start_idx = len(prompt_input_ids)
|
| 458 |
+
|
| 459 |
+
# If tokenized prompt is different than both prompt+answer, then it means the
|
| 460 |
+
# last token has changed due to merging.
|
| 461 |
+
if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]:
|
| 462 |
+
response_token_ids_start_idx -= 1
|
| 463 |
+
|
| 464 |
+
prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx]
|
| 465 |
+
prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx]
|
| 466 |
+
|
| 467 |
+
if len(prompt_input_ids) != len(prompt_attention_mask):
|
| 468 |
+
raise ValueError("Prompt input ids and attention mask should have the same length.")
|
| 469 |
+
|
| 470 |
+
answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:]
|
| 471 |
+
answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:]
|
| 472 |
+
|
| 473 |
+
return dict(
|
| 474 |
+
prompt_input_ids=prompt_input_ids,
|
| 475 |
+
prompt_attention_mask=prompt_attention_mask,
|
| 476 |
+
input_ids=answer_input_ids,
|
| 477 |
+
attention_mask=answer_attention_mask,
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
def tokenize_row(self, feature, model: PreTrainedModel | nn.Module | None = None) -> dict:
|
| 481 |
+
"""Tokenize a single row from a CPO specific dataset.
|
| 482 |
+
|
| 483 |
+
At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt +
|
| 484 |
+
chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long,
|
| 485 |
+
we truncate the chosen/rejected.
|
| 486 |
+
|
| 487 |
+
We also create the labels for the chosen/rejected responses, which are of length equal to the sum of the length
|
| 488 |
+
of the prompt and the chosen/rejected response, with `-100` for the prompt tokens.
|
| 489 |
+
"""
|
| 490 |
+
batch = {}
|
| 491 |
+
prompt = feature["prompt"]
|
| 492 |
+
chosen = feature["chosen"]
|
| 493 |
+
rejected = feature["rejected"]
|
| 494 |
+
|
| 495 |
+
if not self.is_encoder_decoder:
|
| 496 |
+
# Check issues below for more details
|
| 497 |
+
# 1. https://github.com/huggingface/trl/issues/907
|
| 498 |
+
# 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
|
| 499 |
+
# 3. https://github.com/LianjiaTech/BELLE/issues/337
|
| 500 |
+
|
| 501 |
+
if not isinstance(prompt, str):
|
| 502 |
+
raise ValueError(f"prompt should be an str but got {type(prompt)}")
|
| 503 |
+
prompt_tokens = self.processing_class(prompt, add_special_tokens=False)
|
| 504 |
+
prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()}
|
| 505 |
+
|
| 506 |
+
if not isinstance(chosen, str):
|
| 507 |
+
raise ValueError(f"chosen should be an str but got {type(chosen)}")
|
| 508 |
+
chosen_tokens = self.build_tokenized_answer(prompt, chosen)
|
| 509 |
+
|
| 510 |
+
if not isinstance(rejected, str):
|
| 511 |
+
raise ValueError(f"rejected should be an str but got {type(rejected)}")
|
| 512 |
+
rejected_tokens = self.build_tokenized_answer(prompt, rejected)
|
| 513 |
+
|
| 514 |
+
# Last prompt token might get merged by tokenizer and
|
| 515 |
+
# it should not be included for generation if that happens
|
| 516 |
+
prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"])
|
| 517 |
+
|
| 518 |
+
chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"])
|
| 519 |
+
rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"])
|
| 520 |
+
prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids)
|
| 521 |
+
|
| 522 |
+
for k, v in prompt_tokens.items():
|
| 523 |
+
prompt_tokens[k] = v[:prompt_len_input_ids]
|
| 524 |
+
|
| 525 |
+
# Make sure prompts only have one different token at most an
|
| 526 |
+
# and length only differs by 1 at most
|
| 527 |
+
num_diff_tokens = sum(
|
| 528 |
+
a != b
|
| 529 |
+
for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"], strict=False)
|
| 530 |
+
)
|
| 531 |
+
num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids)
|
| 532 |
+
if num_diff_tokens > 1 or num_diff_len > 1:
|
| 533 |
+
raise ValueError(
|
| 534 |
+
"Chosen and rejected prompt_input_ids might only differ on the "
|
| 535 |
+
"last token due to tokenizer merge ops."
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
# add BOS token to head of prompt. Avoid adding if it's already there
|
| 539 |
+
prompt_tokens, chosen_tokens, rejected_tokens = add_bos_token_if_needed(
|
| 540 |
+
self.processing_class.bos_token_id,
|
| 541 |
+
prompt_len_input_ids,
|
| 542 |
+
prompt_tokens,
|
| 543 |
+
chosen_prompt_len_input_ids,
|
| 544 |
+
chosen_tokens,
|
| 545 |
+
rejected_prompt_len_input_ids,
|
| 546 |
+
rejected_tokens,
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
# add EOS token to end of answer. Avoid adding if it's already there
|
| 550 |
+
chosen_tokens, rejected_tokens = add_eos_token_if_needed(
|
| 551 |
+
self.processing_class.eos_token_id, chosen_tokens, rejected_tokens
|
| 552 |
+
)
|
| 553 |
+
|
| 554 |
+
longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"]))
|
| 555 |
+
|
| 556 |
+
# if combined sequence is too long, truncate the response
|
| 557 |
+
for answer_tokens in [chosen_tokens, rejected_tokens]:
|
| 558 |
+
if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
|
| 559 |
+
for k in ["input_ids", "attention_mask"]:
|
| 560 |
+
answer_tokens[k] = answer_tokens[k][: self.max_length - longer_response_length]
|
| 561 |
+
|
| 562 |
+
# Create labels
|
| 563 |
+
chosen_sequence_tokens = {
|
| 564 |
+
k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"]
|
| 565 |
+
}
|
| 566 |
+
rejected_sequence_tokens = {
|
| 567 |
+
k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"]
|
| 568 |
+
}
|
| 569 |
+
chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:]
|
| 570 |
+
chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [-100] * len(
|
| 571 |
+
chosen_tokens["prompt_input_ids"]
|
| 572 |
+
)
|
| 573 |
+
rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:]
|
| 574 |
+
rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [-100] * len(
|
| 575 |
+
rejected_tokens["prompt_input_ids"]
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
for k, toks in {
|
| 579 |
+
"chosen_": chosen_sequence_tokens,
|
| 580 |
+
"rejected_": rejected_sequence_tokens,
|
| 581 |
+
"": prompt_tokens,
|
| 582 |
+
}.items():
|
| 583 |
+
for type_key, tokens in toks.items():
|
| 584 |
+
if type_key == "token_type_ids":
|
| 585 |
+
continue
|
| 586 |
+
batch[f"{k}{type_key}"] = tokens
|
| 587 |
+
|
| 588 |
+
else:
|
| 589 |
+
chosen_tokens = self.processing_class(
|
| 590 |
+
chosen, truncation=True, max_length=self.max_completion_length, add_special_tokens=True
|
| 591 |
+
)
|
| 592 |
+
rejected_tokens = self.processing_class(
|
| 593 |
+
rejected, truncation=True, max_length=self.max_completion_length, add_special_tokens=True
|
| 594 |
+
)
|
| 595 |
+
prompt_tokens = self.processing_class(prompt, add_special_tokens=True)
|
| 596 |
+
|
| 597 |
+
batch["chosen_labels"] = chosen_tokens["input_ids"]
|
| 598 |
+
batch["rejected_labels"] = rejected_tokens["input_ids"]
|
| 599 |
+
batch["prompt_input_ids"] = prompt_tokens["input_ids"]
|
| 600 |
+
batch["prompt_attention_mask"] = prompt_tokens["attention_mask"]
|
| 601 |
+
|
| 602 |
+
if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"):
|
| 603 |
+
batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(
|
| 604 |
+
labels=torch.tensor(batch["rejected_labels"])
|
| 605 |
+
)
|
| 606 |
+
batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(
|
| 607 |
+
labels=torch.tensor(batch["chosen_labels"])
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
return batch
|
| 611 |
+
|
| 612 |
+
@staticmethod
|
| 613 |
+
def concatenated_inputs(
|
| 614 |
+
batch: dict[str, list | torch.LongTensor],
|
| 615 |
+
is_encoder_decoder: bool = False,
|
| 616 |
+
padding_value: int = 0,
|
| 617 |
+
device: torch.device | None = None,
|
| 618 |
+
) -> dict[str, torch.LongTensor]:
|
| 619 |
+
"""Concatenate the chosen and rejected inputs into a single tensor.
|
| 620 |
+
|
| 621 |
+
Args:
|
| 622 |
+
batch:
|
| 623 |
+
A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors
|
| 624 |
+
of shape (batch_size, sequence_length).
|
| 625 |
+
is_encoder_decoder:
|
| 626 |
+
Whether the model is an encoder-decoder model.
|
| 627 |
+
padding_value:
|
| 628 |
+
The padding value to use for the concatenated inputs_ids.
|
| 629 |
+
device:
|
| 630 |
+
The device for the concatenated inputs.
|
| 631 |
+
|
| 632 |
+
Returns:
|
| 633 |
+
A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'.
|
| 634 |
+
"""
|
| 635 |
+
concatenated_batch = {}
|
| 636 |
+
|
| 637 |
+
if is_encoder_decoder:
|
| 638 |
+
max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1])
|
| 639 |
+
else:
|
| 640 |
+
max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1])
|
| 641 |
+
|
| 642 |
+
for k in batch:
|
| 643 |
+
if k.startswith("chosen") and isinstance(batch[k], torch.Tensor):
|
| 644 |
+
if "labels" in k or is_encoder_decoder:
|
| 645 |
+
pad_value = -100
|
| 646 |
+
elif k.endswith("_input_ids"):
|
| 647 |
+
pad_value = padding_value
|
| 648 |
+
elif k.endswith("_attention_mask"):
|
| 649 |
+
pad_value = 0
|
| 650 |
+
concatenated_key = k.replace("chosen", "concatenated")
|
| 651 |
+
concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value)
|
| 652 |
+
for k in batch:
|
| 653 |
+
if k.startswith("rejected") and isinstance(batch[k], torch.Tensor):
|
| 654 |
+
if "labels" in k or is_encoder_decoder:
|
| 655 |
+
pad_value = -100
|
| 656 |
+
elif k.endswith("_input_ids"):
|
| 657 |
+
pad_value = padding_value
|
| 658 |
+
elif k.endswith("_attention_mask"):
|
| 659 |
+
pad_value = 0
|
| 660 |
+
concatenated_key = k.replace("rejected", "concatenated")
|
| 661 |
+
concatenated_batch[concatenated_key] = torch.cat(
|
| 662 |
+
(
|
| 663 |
+
concatenated_batch[concatenated_key],
|
| 664 |
+
pad_to_length(batch[k], max_length, pad_value=pad_value),
|
| 665 |
+
),
|
| 666 |
+
dim=0,
|
| 667 |
+
).to(device=device)
|
| 668 |
+
|
| 669 |
+
if is_encoder_decoder:
|
| 670 |
+
concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device)
|
| 671 |
+
concatenated_batch["concatenated_attention_mask"] = (
|
| 672 |
+
batch["prompt_attention_mask"].repeat(2, 1).to(device=device)
|
| 673 |
+
)
|
| 674 |
+
|
| 675 |
+
return concatenated_batch
|
| 676 |
+
|
| 677 |
+
def cpo_loss(
|
| 678 |
+
self,
|
| 679 |
+
policy_chosen_logps: torch.FloatTensor,
|
| 680 |
+
policy_rejected_logps: torch.FloatTensor,
|
| 681 |
+
) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
|
| 682 |
+
"""Compute the CPO loss for a batch of policy and reference model log probabilities.
|
| 683 |
+
|
| 684 |
+
Args:
|
| 685 |
+
policy_chosen_logps:
|
| 686 |
+
Log probabilities of the policy model for the chosen responses. Shape: (batch_size,)
|
| 687 |
+
policy_rejected_logps:
|
| 688 |
+
Log probabilities of the policy model for the rejected responses. Shape: (batch_size,)
|
| 689 |
+
|
| 690 |
+
Returns:
|
| 691 |
+
A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). The losses tensor contains the CPO
|
| 692 |
+
loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for
|
| 693 |
+
the chosen and rejected responses, respectively.
|
| 694 |
+
"""
|
| 695 |
+
# Apply AlphaPO reward transformation if alpha != 0
|
| 696 |
+
if self.alpha != 0.0:
|
| 697 |
+
# Compute probabilities
|
| 698 |
+
chosen_probs = torch.exp(policy_chosen_logps)
|
| 699 |
+
rejected_probs = torch.exp(policy_rejected_logps)
|
| 700 |
+
|
| 701 |
+
# Apply AlphaPO transformation: r = (1 - p^(-alpha)) / alpha
|
| 702 |
+
policy_chosen_rewards = (1 - chosen_probs.pow(-self.alpha)) / self.alpha
|
| 703 |
+
policy_rejected_rewards = (1 - rejected_probs.pow(-self.alpha)) / self.alpha
|
| 704 |
+
|
| 705 |
+
logits = (policy_chosen_rewards - policy_rejected_rewards).to(self.accelerator.device)
|
| 706 |
+
else:
|
| 707 |
+
# Standard log probability rewards when alpha = 0
|
| 708 |
+
logits = (policy_chosen_logps - policy_rejected_logps).to(self.accelerator.device)
|
| 709 |
+
|
| 710 |
+
# The beta is a temperature parameter for the CPO loss, typically something in the range of 0.1 to 0.5.
|
| 711 |
+
# We ignore the reference model as beta -> 0. The label_smoothing parameter encodes our uncertainty about the labels and
|
| 712 |
+
# calculates a conservative CPO loss.
|
| 713 |
+
|
| 714 |
+
if self.loss_type == "simpo":
|
| 715 |
+
gamma_logratios = self.simpo_gamma / self.beta
|
| 716 |
+
logits = logits - gamma_logratios
|
| 717 |
+
# This reduces to Equation 3 from the CPO paper when label_smoothing -> 0.
|
| 718 |
+
losses = (
|
| 719 |
+
-F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing)
|
| 720 |
+
- F.logsigmoid(-self.beta * logits) * self.label_smoothing
|
| 721 |
+
)
|
| 722 |
+
elif self.loss_type == "sigmoid":
|
| 723 |
+
# This reduces to Equation 3 from the CPO paper when label_smoothing -> 0.
|
| 724 |
+
losses = (
|
| 725 |
+
-F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing)
|
| 726 |
+
- F.logsigmoid(-self.beta * logits) * self.label_smoothing
|
| 727 |
+
)
|
| 728 |
+
elif self.loss_type == "hinge":
|
| 729 |
+
losses = torch.relu(1 - self.beta * logits)
|
| 730 |
+
elif self.loss_type == "ipo":
|
| 731 |
+
# eqn (17) of the paper where beta is the regularization parameter for the IPO loss, denoted by tau in the paper.
|
| 732 |
+
losses = (logits - 1 / (2 * self.beta)) ** 2
|
| 733 |
+
else:
|
| 734 |
+
raise ValueError(
|
| 735 |
+
f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'simpo']"
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
# Calculate rewards for logging
|
| 739 |
+
if self.alpha != 0.0:
|
| 740 |
+
# When using AlphaPO transformation, use the transformed rewards
|
| 741 |
+
chosen_rewards = self.beta * policy_chosen_rewards.to(self.accelerator.device).detach()
|
| 742 |
+
rejected_rewards = self.beta * policy_rejected_rewards.to(self.accelerator.device).detach()
|
| 743 |
+
else:
|
| 744 |
+
# Standard log probability rewards
|
| 745 |
+
chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach()
|
| 746 |
+
rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach()
|
| 747 |
+
|
| 748 |
+
return losses, chosen_rewards, rejected_rewards
|
| 749 |
+
|
| 750 |
+
@staticmethod
|
| 751 |
+
def get_batch_logps(
|
| 752 |
+
logits: torch.FloatTensor,
|
| 753 |
+
labels: torch.LongTensor,
|
| 754 |
+
average_log_prob: bool = False,
|
| 755 |
+
is_encoder_decoder: bool = False,
|
| 756 |
+
) -> torch.FloatTensor:
|
| 757 |
+
"""Compute the log probabilities of the given labels under the given logits.
|
| 758 |
+
|
| 759 |
+
Args:
|
| 760 |
+
logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size)
|
| 761 |
+
labels:
|
| 762 |
+
Labels for which to compute the log probabilities. Label tokens with a value of `-100` are ignored.
|
| 763 |
+
Shape: (batch_size, sequence_length)
|
| 764 |
+
average_log_prob:
|
| 765 |
+
If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the
|
| 766 |
+
log probabilities of the (non-masked) tokens.
|
| 767 |
+
is_encoder_decoder: Whether the model is an encoder-decoder model.
|
| 768 |
+
|
| 769 |
+
Returns:
|
| 770 |
+
A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the
|
| 771 |
+
given logits.
|
| 772 |
+
"""
|
| 773 |
+
if logits.shape[:-1] != labels.shape:
|
| 774 |
+
raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.")
|
| 775 |
+
|
| 776 |
+
if not is_encoder_decoder:
|
| 777 |
+
labels = labels[:, 1:].clone()
|
| 778 |
+
logits = logits[:, :-1, :]
|
| 779 |
+
loss_mask = labels != -100
|
| 780 |
+
|
| 781 |
+
# dummy token; we'll ignore the losses on these tokens later
|
| 782 |
+
labels[labels == -100] = 0
|
| 783 |
+
|
| 784 |
+
per_token_logps = selective_log_softmax(logits, labels)
|
| 785 |
+
|
| 786 |
+
if average_log_prob:
|
| 787 |
+
return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1)
|
| 788 |
+
else:
|
| 789 |
+
return (per_token_logps * loss_mask).sum(-1)
|
| 790 |
+
|
| 791 |
+
def concatenated_forward(
|
| 792 |
+
self, model: nn.Module, batch: dict[str, list | torch.LongTensor]
|
| 793 |
+
) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
|
| 794 |
+
"""Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together.
|
| 795 |
+
|
| 796 |
+
We do this to avoid doing two forward passes, because it's faster for FSDP.
|
| 797 |
+
"""
|
| 798 |
+
concatenated_batch = self.concatenated_inputs(
|
| 799 |
+
batch,
|
| 800 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 801 |
+
padding_value=self.pad_token_id,
|
| 802 |
+
device=self.accelerator.device,
|
| 803 |
+
)
|
| 804 |
+
len_chosen = batch["chosen_labels"].shape[0]
|
| 805 |
+
|
| 806 |
+
model_kwargs = (
|
| 807 |
+
{
|
| 808 |
+
"decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]),
|
| 809 |
+
}
|
| 810 |
+
if self.is_encoder_decoder
|
| 811 |
+
else {}
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
if self.aux_loss_enabled:
|
| 815 |
+
model_kwargs["output_router_logits"] = True
|
| 816 |
+
|
| 817 |
+
outputs = model(
|
| 818 |
+
concatenated_batch["concatenated_input_ids"],
|
| 819 |
+
attention_mask=concatenated_batch["concatenated_attention_mask"],
|
| 820 |
+
use_cache=False,
|
| 821 |
+
**model_kwargs,
|
| 822 |
+
)
|
| 823 |
+
all_logits = outputs.logits
|
| 824 |
+
|
| 825 |
+
def cross_entropy_loss(logits, labels):
|
| 826 |
+
if not self.is_encoder_decoder:
|
| 827 |
+
# Shift so that tokens < n predict n
|
| 828 |
+
logits = logits[..., :-1, :].contiguous()
|
| 829 |
+
labels = labels[..., 1:].contiguous()
|
| 830 |
+
# Flatten the tokens
|
| 831 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 832 |
+
logits = logits.view(-1, logits.shape[-1])
|
| 833 |
+
labels = labels.view(-1)
|
| 834 |
+
# Enable model parallelism
|
| 835 |
+
labels = labels.to(logits.device)
|
| 836 |
+
loss = loss_fct(logits, labels)
|
| 837 |
+
return loss
|
| 838 |
+
|
| 839 |
+
labels = concatenated_batch["concatenated_labels"].clone()
|
| 840 |
+
|
| 841 |
+
if self.cpo_alpha == 0:
|
| 842 |
+
nll_loss = torch.tensor(0.0).to(self.accelerator.device)
|
| 843 |
+
else:
|
| 844 |
+
nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen])
|
| 845 |
+
|
| 846 |
+
all_logps = self.get_batch_logps(
|
| 847 |
+
all_logits,
|
| 848 |
+
concatenated_batch["concatenated_labels"],
|
| 849 |
+
average_log_prob=self.loss_type in ["ipo", "simpo"],
|
| 850 |
+
is_encoder_decoder=self.is_encoder_decoder,
|
| 851 |
+
)
|
| 852 |
+
|
| 853 |
+
chosen_logps = all_logps[:len_chosen]
|
| 854 |
+
rejected_logps = all_logps[len_chosen:]
|
| 855 |
+
|
| 856 |
+
chosen_logits = all_logits[:len_chosen]
|
| 857 |
+
rejected_logits = all_logits[len_chosen:]
|
| 858 |
+
|
| 859 |
+
if self.aux_loss_enabled:
|
| 860 |
+
return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss, outputs.aux_loss)
|
| 861 |
+
|
| 862 |
+
return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss)
|
| 863 |
+
|
| 864 |
+
def get_batch_loss_metrics(
|
| 865 |
+
self,
|
| 866 |
+
model,
|
| 867 |
+
batch: dict[str, list | torch.LongTensor],
|
| 868 |
+
train_eval: Literal["train", "eval"] = "train",
|
| 869 |
+
):
|
| 870 |
+
"""Compute the CPO loss and other metrics for the given batch of inputs for train or test."""
|
| 871 |
+
metrics = {}
|
| 872 |
+
|
| 873 |
+
forward_output = self.concatenated_forward(model, batch)
|
| 874 |
+
(
|
| 875 |
+
policy_chosen_logps,
|
| 876 |
+
policy_rejected_logps,
|
| 877 |
+
policy_chosen_logits,
|
| 878 |
+
policy_rejected_logits,
|
| 879 |
+
policy_nll_loss,
|
| 880 |
+
) = forward_output[:5]
|
| 881 |
+
if self.aux_loss_enabled:
|
| 882 |
+
aux_loss = forward_output[5]
|
| 883 |
+
|
| 884 |
+
losses, chosen_rewards, rejected_rewards = self.cpo_loss(
|
| 885 |
+
policy_chosen_logps,
|
| 886 |
+
policy_rejected_logps,
|
| 887 |
+
)
|
| 888 |
+
|
| 889 |
+
loss = losses.mean() + self.cpo_alpha * policy_nll_loss
|
| 890 |
+
reward_accuracies = (chosen_rewards > rejected_rewards).float()
|
| 891 |
+
|
| 892 |
+
prefix = "eval_" if train_eval == "eval" else ""
|
| 893 |
+
metrics[f"{prefix}rewards/chosen"] = self.accelerator.gather_for_metrics(chosen_rewards).mean().item()
|
| 894 |
+
metrics[f"{prefix}rewards/rejected"] = self.accelerator.gather_for_metrics(rejected_rewards).mean().item()
|
| 895 |
+
metrics[f"{prefix}rewards/accuracies"] = self.accelerator.gather_for_metrics(reward_accuracies).mean().item()
|
| 896 |
+
metrics[f"{prefix}rewards/margins"] = (
|
| 897 |
+
self.accelerator.gather_for_metrics(chosen_rewards - rejected_rewards).mean().item()
|
| 898 |
+
)
|
| 899 |
+
metrics[f"{prefix}logps/rejected"] = (
|
| 900 |
+
self.accelerator.gather_for_metrics(policy_rejected_logps).detach().mean().item()
|
| 901 |
+
)
|
| 902 |
+
metrics[f"{prefix}logps/chosen"] = (
|
| 903 |
+
self.accelerator.gather_for_metrics(policy_chosen_logps).detach().mean().item()
|
| 904 |
+
)
|
| 905 |
+
metrics[f"{prefix}logits/rejected"] = (
|
| 906 |
+
self.accelerator.gather_for_metrics(policy_rejected_logits.detach().mean()).mean().item()
|
| 907 |
+
)
|
| 908 |
+
metrics[f"{prefix}logits/chosen"] = (
|
| 909 |
+
self.accelerator.gather_for_metrics(policy_chosen_logits.detach().mean()).mean().item()
|
| 910 |
+
)
|
| 911 |
+
metrics[f"{prefix}nll_loss"] = self.accelerator.gather_for_metrics(policy_nll_loss).detach().mean().item()
|
| 912 |
+
|
| 913 |
+
if self.aux_loss_enabled:
|
| 914 |
+
loss += self.aux_loss_coef * aux_loss
|
| 915 |
+
|
| 916 |
+
return loss, metrics
|
| 917 |
+
|
| 918 |
+
def compute_loss(
|
| 919 |
+
self,
|
| 920 |
+
model: PreTrainedModel | nn.Module,
|
| 921 |
+
inputs: dict[str, torch.Tensor | Any],
|
| 922 |
+
return_outputs=False,
|
| 923 |
+
num_items_in_batch=None,
|
| 924 |
+
) -> torch.Tensor | tuple[torch.Tensor, dict[str, torch.Tensor]]:
|
| 925 |
+
compute_loss_context_manager = (
|
| 926 |
+
autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
with compute_loss_context_manager:
|
| 930 |
+
loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train")
|
| 931 |
+
|
| 932 |
+
# force log the metrics
|
| 933 |
+
self.store_metrics(metrics, train_eval="train")
|
| 934 |
+
|
| 935 |
+
if return_outputs:
|
| 936 |
+
return (loss, metrics)
|
| 937 |
+
return loss
|
| 938 |
+
|
| 939 |
+
def generate_from_model(self, model, batch: dict[str, torch.LongTensor]) -> str:
|
| 940 |
+
"""Generate samples from the model and reference model for the given batch of inputs."""
|
| 941 |
+
|
| 942 |
+
# If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with
|
| 943 |
+
# the torch amp context manager as some hidden states are silently casted to full precision.
|
| 944 |
+
generate_context_manager = (
|
| 945 |
+
autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
|
| 946 |
+
)
|
| 947 |
+
|
| 948 |
+
with generate_context_manager:
|
| 949 |
+
policy_output = model.generate(
|
| 950 |
+
input_ids=batch["prompt_input_ids"],
|
| 951 |
+
attention_mask=batch["prompt_attention_mask"],
|
| 952 |
+
max_length=self.max_length,
|
| 953 |
+
do_sample=True,
|
| 954 |
+
pad_token_id=self.processing_class.pad_token_id,
|
| 955 |
+
)
|
| 956 |
+
|
| 957 |
+
policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id)
|
| 958 |
+
policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True)
|
| 959 |
+
|
| 960 |
+
return policy_output_decoded
|
| 961 |
+
|
| 962 |
+
def prediction_step(
|
| 963 |
+
self,
|
| 964 |
+
model: PreTrainedModel | nn.Module,
|
| 965 |
+
inputs: dict[str, torch.Tensor | Any],
|
| 966 |
+
prediction_loss_only: bool,
|
| 967 |
+
ignore_keys: list[str] | None = None,
|
| 968 |
+
):
|
| 969 |
+
if ignore_keys is None:
|
| 970 |
+
if hasattr(model, "config"):
|
| 971 |
+
ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", [])
|
| 972 |
+
else:
|
| 973 |
+
ignore_keys = []
|
| 974 |
+
|
| 975 |
+
prediction_context_manager = (
|
| 976 |
+
autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
|
| 977 |
+
)
|
| 978 |
+
|
| 979 |
+
with torch.no_grad(), prediction_context_manager:
|
| 980 |
+
loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval")
|
| 981 |
+
|
| 982 |
+
# force log the metrics
|
| 983 |
+
self.store_metrics(metrics, train_eval="eval")
|
| 984 |
+
|
| 985 |
+
if prediction_loss_only:
|
| 986 |
+
return (loss.detach(), None, None)
|
| 987 |
+
|
| 988 |
+
# logits for the chosen and rejected samples from model
|
| 989 |
+
logits_dict = {
|
| 990 |
+
"eval_logits/chosen": metrics["eval_logits/chosen"],
|
| 991 |
+
"eval_logits/rejected": metrics["eval_logits/rejected"],
|
| 992 |
+
}
|
| 993 |
+
logits = [v for k, v in logits_dict.items() if k not in ignore_keys]
|
| 994 |
+
logits = torch.tensor(logits, device=self.accelerator.device)
|
| 995 |
+
labels = torch.zeros(logits.shape[0], device=self.accelerator.device)
|
| 996 |
+
|
| 997 |
+
return (loss.detach(), logits, labels)
|
| 998 |
+
|
| 999 |
+
def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None:
|
| 1000 |
+
for key, value in metrics.items():
|
| 1001 |
+
self._stored_metrics[train_eval][key].append(value)
|
| 1002 |
+
|
| 1003 |
+
def evaluation_loop(
|
| 1004 |
+
self,
|
| 1005 |
+
dataloader: DataLoader,
|
| 1006 |
+
description: str,
|
| 1007 |
+
prediction_loss_only: bool | None = None,
|
| 1008 |
+
ignore_keys: list[str] | None = None,
|
| 1009 |
+
metric_key_prefix: str = "eval",
|
| 1010 |
+
) -> EvalLoopOutput:
|
| 1011 |
+
"""
|
| 1012 |
+
Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by
|
| 1013 |
+
`Trainer.evaluate()` and `Trainer.predict()`.
|
| 1014 |
+
|
| 1015 |
+
Works both with or without labels.
|
| 1016 |
+
"""
|
| 1017 |
+
|
| 1018 |
+
# Sample and save to game log if requested (for one batch to save time)
|
| 1019 |
+
if self.generate_during_eval:
|
| 1020 |
+
# Generate random indices within the range of the total number of samples
|
| 1021 |
+
num_samples = len(dataloader.dataset)
|
| 1022 |
+
random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size)
|
| 1023 |
+
|
| 1024 |
+
# Use dataloader.dataset.select to get the random batch without iterating over the DataLoader
|
| 1025 |
+
random_batch_dataset = dataloader.dataset.select(random_indices)
|
| 1026 |
+
random_batch = self.data_collator(random_batch_dataset)
|
| 1027 |
+
random_batch = self._prepare_inputs(random_batch)
|
| 1028 |
+
|
| 1029 |
+
policy_output_decoded = self.generate_from_model(self.model, random_batch)
|
| 1030 |
+
|
| 1031 |
+
table = pd.DataFrame(
|
| 1032 |
+
columns=["Prompt", "Policy"],
|
| 1033 |
+
data=[
|
| 1034 |
+
[prompt, pol[len(prompt) :]]
|
| 1035 |
+
for prompt, pol in zip(random_batch["prompt"], policy_output_decoded, strict=True)
|
| 1036 |
+
],
|
| 1037 |
+
)
|
| 1038 |
+
if "wandb" in self.args.report_to:
|
| 1039 |
+
wandb.log({"game_log": wandb.Table(data=table)})
|
| 1040 |
+
|
| 1041 |
+
if "comet_ml" in self.args.report_to:
|
| 1042 |
+
log_table_to_comet_experiment(
|
| 1043 |
+
name="game_log.csv",
|
| 1044 |
+
table=table,
|
| 1045 |
+
)
|
| 1046 |
+
|
| 1047 |
+
# Base evaluation
|
| 1048 |
+
initial_output = super().evaluation_loop(
|
| 1049 |
+
dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix
|
| 1050 |
+
)
|
| 1051 |
+
|
| 1052 |
+
return initial_output
|
| 1053 |
+
|
| 1054 |
+
def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
|
| 1055 |
+
"""
|
| 1056 |
+
Log `logs` on the various objects watching training, including stored metrics.
|
| 1057 |
+
|
| 1058 |
+
Args:
|
| 1059 |
+
logs (`dict[str, float]`):
|
| 1060 |
+
The values to log.
|
| 1061 |
+
start_time (`float`, *optional*):
|
| 1062 |
+
Start time of the training.
|
| 1063 |
+
"""
|
| 1064 |
+
# logs either has 'loss' or 'eval_loss'
|
| 1065 |
+
train_eval = "train" if "loss" in logs else "eval"
|
| 1066 |
+
# Add averaged stored metrics to logs
|
| 1067 |
+
for key, metrics in self._stored_metrics[train_eval].items():
|
| 1068 |
+
logs[key] = torch.tensor(metrics).mean().item()
|
| 1069 |
+
del self._stored_metrics[train_eval]
|
| 1070 |
+
return super().log(logs, start_time)
|
| 1071 |
+
|
| 1072 |
+
def _shift_right(self, input_ids):
|
| 1073 |
+
if self.decoder_start_token_id is None:
|
| 1074 |
+
raise ValueError(
|
| 1075 |
+
"model.config.decoder_start_token_id has to be defined. It is usually set to the pad_token_id."
|
| 1076 |
+
)
|
| 1077 |
+
|
| 1078 |
+
# shift inputs to the right
|
| 1079 |
+
if is_torch_fx_proxy(input_ids):
|
| 1080 |
+
# Item assignment is not supported natively for proxies.
|
| 1081 |
+
shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), self.decoder_start_token_id)
|
| 1082 |
+
shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1)
|
| 1083 |
+
else:
|
| 1084 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 1085 |
+
shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
|
| 1086 |
+
shifted_input_ids[..., 0] = self.decoder_start_token_id
|
| 1087 |
+
|
| 1088 |
+
if self.pad_token_id is None:
|
| 1089 |
+
raise ValueError("model.config.pad_token_id has to be defined.")
|
| 1090 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 1091 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, self.pad_token_id)
|
| 1092 |
+
|
| 1093 |
+
return shifted_input_ids
|
| 1094 |
+
|
| 1095 |
+
# Ensure the model card is saved along with the checkpoint
|
| 1096 |
+
def _save_checkpoint(self, model, trial):
|
| 1097 |
+
if self.args.hub_model_id is None:
|
| 1098 |
+
model_name = Path(self.args.output_dir).name
|
| 1099 |
+
else:
|
| 1100 |
+
model_name = self.args.hub_model_id.split("/")[-1]
|
| 1101 |
+
self.create_model_card(model_name=model_name)
|
| 1102 |
+
super()._save_checkpoint(model, trial)
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/distillation/__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 .distillation_config import DistillationConfig
|
| 16 |
+
from .distillation_trainer import DistillationTrainer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = ["DistillationConfig", "DistillationTrainer"]
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/distillation/distillation_config.py
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 DistillationConfig(_BaseConfig):
|
| 24 |
+
# docstyle-ignore
|
| 25 |
+
r"""
|
| 26 |
+
Configuration class for the [`DistillationTrainer`].
|
| 27 |
+
|
| 28 |
+
Extends [`~transformers.TrainingArguments`] with parameters specific to knowledge distillation. This config is
|
| 29 |
+
independent of [`SFTConfig`] — all necessary fields are declared here.
|
| 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 `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the
|
| 40 |
+
trainer 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.AutoTokenizer.from_pretrained`], for both the student and teacher.
|
| 45 |
+
max_length (`int` or `None`, *optional*, defaults to `1024`):
|
| 46 |
+
Maximum total sequence length (prompt + completion) for tokenization and truncation.
|
| 47 |
+
|
| 48 |
+
> Parameters that control the distillation
|
| 49 |
+
|
| 50 |
+
temperature (`float`, *optional*, defaults to `1.0`):
|
| 51 |
+
Temperature for sampling during generation and for computing the distillation loss. Higher values produce
|
| 52 |
+
softer probability distributions.
|
| 53 |
+
lmbda (`float`, *optional*, defaults to `1.0`):
|
| 54 |
+
Probability of using on-policy (student-generated) data for each gradient accumulation slice. A value of
|
| 55 |
+
`0.0` means fully off-policy (dataset completions only), `1.0` means fully on-policy.
|
| 56 |
+
beta (`float`, *optional*, defaults to `1.0`):
|
| 57 |
+
Interpolation coefficient for the Generalized Jensen-Shannon Divergence loss. When `0.0`, the loss is the
|
| 58 |
+
forward KL divergence. When `1.0`, the loss is the reverse KL divergence. When `0.5`, it is the standard
|
| 59 |
+
JSD.
|
| 60 |
+
reverse_kl_top_1_mode (`str`, *optional*, defaults to `"sampled"`):
|
| 61 |
+
Selection rule for the reverse-KL top-1 token when `beta > 0` and `loss_top_k == 1`. `"sampled"` uses the
|
| 62 |
+
actual completion token in the batch. `"argmax"` uses the student's highest-probability token. This
|
| 63 |
+
setting does not affect the forward-KL support, which always uses the teacher's top-1 token. Ignored when
|
| 64 |
+
`beta == 0` or `loss_top_k != 1`.
|
| 65 |
+
max_completion_length (`int`, *optional*, defaults to `512`):
|
| 66 |
+
Maximum number of tokens to generate per completion during on-policy generation.
|
| 67 |
+
max_prompt_length (`int` or `None`, *optional*):
|
| 68 |
+
Maximum number of tokens for the prompt. If `None`, auto-computed as `max_length - max_completion_length`.
|
| 69 |
+
Prompts are truncated according to the tokenizer's `truncation_side` setting.
|
| 70 |
+
disable_dropout (`bool`, *optional*, defaults to `True`):
|
| 71 |
+
Whether to disable dropout in the student model during training.
|
| 72 |
+
|
| 73 |
+
> Parameters that control the teacher model
|
| 74 |
+
|
| 75 |
+
teacher_model_name_or_path (`str` or `None`, *optional*):
|
| 76 |
+
Model name or path for the teacher model. Used when the teacher is loaded locally.
|
| 77 |
+
teacher_model_revision (`str` or `None`, *optional*):
|
| 78 |
+
Model revision of the teacher model (e.g., branch name, tag, or commit hash).
|
| 79 |
+
teacher_model_init_kwargs (`dict[str, Any]` or `None`, *optional*):
|
| 80 |
+
Keyword arguments passed to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model
|
| 81 |
+
from a string.
|
| 82 |
+
use_teacher_server (`bool`, *optional*, defaults to `False`):
|
| 83 |
+
Whether to use an external vLLM teacher server instead of a local teacher model.
|
| 84 |
+
teacher_model_server_url (`str` or `None`, *optional*):
|
| 85 |
+
Base URL of a vLLM server hosting the teacher model (e.g., `"http://localhost:8000"`). When set, teacher
|
| 86 |
+
logprobs are fetched from the server instead of running a local forward pass when `use_teacher_server=True`.
|
| 87 |
+
loss_top_k (`int`, *optional*, defaults to `1`):
|
| 88 |
+
Number of top tokens to use when computing the JSD/KL loss. Both student and teacher distributions are
|
| 89 |
+
restricted to these K tokens and re-normalized before computing divergence. If 0, the full vocabulary
|
| 90 |
+
is used. For local teachers, the general support rule is teacher top-k for forward KL, student top-k for
|
| 91 |
+
reverse KL, and the union for mixed JSD. When `beta > 0` and `loss_top_k == 1`, the forward support still
|
| 92 |
+
uses the teacher's top-1 token, while the reverse top-1 token is controlled by `reverse_kl_top_1_mode`.
|
| 93 |
+
When `use_teacher_server=True`, the pure forward path (`beta=0`) requires this to be positive and uses the
|
| 94 |
+
teacher's top-k logprobs for the forward term. When `beta > 0`, server-backed distillation requires
|
| 95 |
+
`loss_top_k == 1` and only supports `"sampled"` reverse top-1 tokens.
|
| 96 |
+
loss_add_tail (`bool`, *optional*, defaults to `True`):
|
| 97 |
+
Whether to append a tail bucket that represents the remaining probability mass outside the selected top-k
|
| 98 |
+
support when computing the loss.
|
| 99 |
+
|
| 100 |
+
> Parameters that control on-policy generation
|
| 101 |
+
|
| 102 |
+
num_generations (`int`, *optional*, defaults to `1`):
|
| 103 |
+
Number of completions to generate per prompt during on-policy generation.
|
| 104 |
+
generation_batch_size (`int` or `None`, *optional*):
|
| 105 |
+
Number of unique prompts per worker per optimizer step. If `None`, computed from
|
| 106 |
+
`(per_device_train_batch_size * gradient_accumulation_steps) // num_generations`.
|
| 107 |
+
top_p (`float`, *optional*, defaults to `0.95`):
|
| 108 |
+
Top-p (nucleus) sampling parameter for on-policy generation.
|
| 109 |
+
top_k (`int`, *optional*, defaults to `0`):
|
| 110 |
+
Top-k sampling parameter for on-policy generation. `0` disables top-k filtering.
|
| 111 |
+
|
| 112 |
+
> Parameters that control vLLM for student generation
|
| 113 |
+
|
| 114 |
+
use_vllm (`bool`, *optional*, defaults to `False`):
|
| 115 |
+
Whether to use vLLM for generating on-policy completions from the student model.
|
| 116 |
+
vllm_mode (`str`, *optional*, defaults to `"colocate"`):
|
| 117 |
+
Mode for student vLLM integration. Either `"server"` or `"colocate"`.
|
| 118 |
+
vllm_server_base_url (`str` or `None`, *optional*):
|
| 119 |
+
Base URL for the student vLLM server. If provided, `vllm_server_host` and `vllm_server_port` are ignored.
|
| 120 |
+
vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
|
| 121 |
+
Host of the student vLLM server.
|
| 122 |
+
vllm_server_port (`int`, *optional*, defaults to `8001`):
|
| 123 |
+
Port of the student vLLM server.
|
| 124 |
+
vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
|
| 125 |
+
Timeout for connecting to the student vLLM server.
|
| 126 |
+
vllm_group_port (`int`, *optional*, defaults to `51216`):
|
| 127 |
+
Port for the vLLM weight-update group (NCCL communicator).
|
| 128 |
+
vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`):
|
| 129 |
+
GPU memory utilization for the colocated student vLLM engine.
|
| 130 |
+
vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
|
| 131 |
+
Tensor parallel size for the colocated student vLLM engine.
|
| 132 |
+
vllm_max_model_length (`int` or `None`, *optional*):
|
| 133 |
+
Maximum model sequence length for the colocated vLLM engine.
|
| 134 |
+
vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
|
| 135 |
+
Model implementation backend for vLLM. Use `"vllm"` or `"transformers"`.
|
| 136 |
+
vllm_structured_outputs_regex (`str` or `None`, *optional*):
|
| 137 |
+
Regex pattern for vLLM structured outputs.
|
| 138 |
+
vllm_sync_frequency (`int`, *optional*, defaults to `1`):
|
| 139 |
+
Frequency (in training steps) to synchronize student model weights to the vLLM engine.
|
| 140 |
+
vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
|
| 141 |
+
Enable vLLM sleep mode to offload student weights during the optimizer step.
|
| 142 |
+
|
| 143 |
+
> Parameters that control logging
|
| 144 |
+
|
| 145 |
+
log_completions (`bool`, *optional*, defaults to `False`):
|
| 146 |
+
Whether to log a sample of (prompt, completion) pairs every `log_completions_steps` steps. If `rich` is
|
| 147 |
+
installed, it prints the sample. If `wandb` and/or `trackio` logging is enabled, it logs it to `wandb`
|
| 148 |
+
and/or `trackio`.
|
| 149 |
+
log_completions_steps (`int`, *optional*, defaults to `100`):
|
| 150 |
+
Number of steps between logging completions. Only used if `log_completions` is `True`.
|
| 151 |
+
num_completions_to_print (`int` or `None`, *optional*):
|
| 152 |
+
Number of completions to print. If `None`, all completions are logged.
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
_VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs", "teacher_model_init_kwargs"]
|
| 156 |
+
|
| 157 |
+
# Model
|
| 158 |
+
model_init_kwargs: dict[str, Any] | str | None = field(
|
| 159 |
+
default=None,
|
| 160 |
+
metadata={
|
| 161 |
+
"help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument "
|
| 162 |
+
"of the trainer is provided as a string."
|
| 163 |
+
},
|
| 164 |
+
)
|
| 165 |
+
trust_remote_code: bool = field(
|
| 166 |
+
default=False,
|
| 167 |
+
metadata={
|
| 168 |
+
"help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
|
| 169 |
+
"Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoTokenizer.from_pretrained`, for both the "
|
| 170 |
+
"student and teacher."
|
| 171 |
+
},
|
| 172 |
+
)
|
| 173 |
+
max_length: int | None = field(
|
| 174 |
+
default=1024,
|
| 175 |
+
metadata={"help": "Maximum total sequence length (prompt + completion) for tokenization and truncation."},
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# Overridden defaults
|
| 179 |
+
learning_rate: float = field(
|
| 180 |
+
default=1e-6,
|
| 181 |
+
metadata={"help": "The initial learning rate for AdamW."},
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
# Distillation core
|
| 185 |
+
temperature: float = field(
|
| 186 |
+
default=1.0,
|
| 187 |
+
metadata={
|
| 188 |
+
"help": "Temperature for sampling and loss computation. Higher values produce softer distributions."
|
| 189 |
+
},
|
| 190 |
+
)
|
| 191 |
+
lmbda: float = field(
|
| 192 |
+
default=1.0,
|
| 193 |
+
metadata={
|
| 194 |
+
"help": "Probability of using on-policy (student-generated) data per gradient accumulation slice. "
|
| 195 |
+
"0.0 = fully off-policy, 1.0 = fully on-policy."
|
| 196 |
+
},
|
| 197 |
+
)
|
| 198 |
+
beta: float = field(
|
| 199 |
+
default=1.0,
|
| 200 |
+
metadata={
|
| 201 |
+
"help": "Interpolation coefficient for the Generalized JSD loss. "
|
| 202 |
+
"0.0 = forward KL, 0.5 = JSD, 1.0 = reverse KL."
|
| 203 |
+
},
|
| 204 |
+
)
|
| 205 |
+
reverse_kl_top_1_mode: str = field(
|
| 206 |
+
default="sampled",
|
| 207 |
+
metadata={
|
| 208 |
+
"help": "Reverse-KL top-1 token selection when beta > 0 and loss_top_k == 1. "
|
| 209 |
+
"Use 'sampled' for the actual completion token or 'argmax' for the student's top-1 token. "
|
| 210 |
+
"The forward-KL support always uses the teacher's top-1 token. Ignored when beta == 0 or loss_top_k != 1."
|
| 211 |
+
},
|
| 212 |
+
)
|
| 213 |
+
max_completion_length: int = field(
|
| 214 |
+
default=512,
|
| 215 |
+
metadata={"help": "Maximum number of tokens to generate per completion."},
|
| 216 |
+
)
|
| 217 |
+
max_prompt_length: int | None = field(
|
| 218 |
+
default=None,
|
| 219 |
+
metadata={
|
| 220 |
+
"help": "Maximum number of tokens for the prompt. If None, auto-computed as "
|
| 221 |
+
"max_length - max_completion_length. Prompts are truncated according to the "
|
| 222 |
+
"tokenizer's truncation_side setting."
|
| 223 |
+
},
|
| 224 |
+
)
|
| 225 |
+
disable_dropout: bool = field(
|
| 226 |
+
default=True,
|
| 227 |
+
metadata={"help": "Whether to disable dropout in the student model during training."},
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
# Teacher model (local)
|
| 231 |
+
teacher_model_name_or_path: str | None = field(
|
| 232 |
+
default=None,
|
| 233 |
+
metadata={"help": "Model name or path for the teacher model."},
|
| 234 |
+
)
|
| 235 |
+
teacher_model_revision: str | None = field(
|
| 236 |
+
default=None,
|
| 237 |
+
metadata={"help": "Model revision of the teacher model (e.g., branch name, tag, or commit hash)."},
|
| 238 |
+
)
|
| 239 |
+
teacher_model_init_kwargs: dict[str, Any] | str | None = field(
|
| 240 |
+
default=None,
|
| 241 |
+
metadata={
|
| 242 |
+
"help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained` when instantiating the teacher."
|
| 243 |
+
},
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
# Teacher model (external vLLM server)
|
| 247 |
+
use_teacher_server: bool = field(
|
| 248 |
+
default=False,
|
| 249 |
+
metadata={"help": "Whether to use an external vLLM teacher server instead of a local teacher model."},
|
| 250 |
+
)
|
| 251 |
+
teacher_model_server_url: str | None = field(
|
| 252 |
+
default=None,
|
| 253 |
+
metadata={
|
| 254 |
+
"help": 'Base URL of a vLLM server hosting the teacher model (e.g., "http://localhost:8000"). '
|
| 255 |
+
"Required when use_teacher_server=True."
|
| 256 |
+
},
|
| 257 |
+
)
|
| 258 |
+
loss_top_k: int = field(
|
| 259 |
+
default=1,
|
| 260 |
+
metadata={
|
| 261 |
+
"help": "Number of top tokens to use when computing the JSD/KL loss. "
|
| 262 |
+
"Both student and teacher distributions are restricted to these K tokens "
|
| 263 |
+
"(selected based on beta: teacher's top-k for forward KL, student's top-k for reverse KL, "
|
| 264 |
+
"union of both for JSD) and re-normalized before computing divergence. "
|
| 265 |
+
"If 0, the full vocabulary is used (slower but exact). "
|
| 266 |
+
"When beta > 0 and loss_top_k == 1, the forward support still uses the teacher's top-1 token, "
|
| 267 |
+
"while the reverse top-1 token is controlled by reverse_kl_top_1_mode. "
|
| 268 |
+
"When use_teacher_server=True, beta=0 requires loss_top_k > 0 and uses the teacher's top-k "
|
| 269 |
+
"logprobs for the forward term. When beta > 0, server-backed distillation requires loss_top_k == 1 "
|
| 270 |
+
"and only supports 'sampled' reverse top-1 tokens."
|
| 271 |
+
},
|
| 272 |
+
)
|
| 273 |
+
loss_add_tail: bool = field(
|
| 274 |
+
default=True,
|
| 275 |
+
metadata={
|
| 276 |
+
"help": "Whether to append a tail bucket representing the remaining probability mass outside the selected top-k support."
|
| 277 |
+
},
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
# On-policy generation
|
| 281 |
+
num_generations: int = field(
|
| 282 |
+
default=1,
|
| 283 |
+
metadata={"help": "Number of completions to generate per prompt during on-policy generation."},
|
| 284 |
+
)
|
| 285 |
+
generation_batch_size: int | None = field(
|
| 286 |
+
default=None,
|
| 287 |
+
metadata={
|
| 288 |
+
"help": "Number of unique prompts per worker per optimizer step. "
|
| 289 |
+
"If None, computed from (per_device_train_batch_size * gradient_accumulation_steps) // num_generations."
|
| 290 |
+
},
|
| 291 |
+
)
|
| 292 |
+
top_p: float = field(
|
| 293 |
+
default=0.95,
|
| 294 |
+
metadata={"help": "Top-p (nucleus) sampling parameter for on-policy generation."},
|
| 295 |
+
)
|
| 296 |
+
top_k: int = field(
|
| 297 |
+
default=0,
|
| 298 |
+
metadata={"help": "Top-k sampling parameter for on-policy generation. 0 disables top-k filtering."},
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
# vLLM for student generation
|
| 302 |
+
use_vllm: bool = field(
|
| 303 |
+
default=False,
|
| 304 |
+
metadata={"help": "Whether to use vLLM for generating on-policy completions from the student model."},
|
| 305 |
+
)
|
| 306 |
+
vllm_mode: str = field(
|
| 307 |
+
default="colocate",
|
| 308 |
+
metadata={"help": 'Mode for student vLLM integration. Either "server" or "colocate".'},
|
| 309 |
+
)
|
| 310 |
+
vllm_server_base_url: str | None = field(
|
| 311 |
+
default=None,
|
| 312 |
+
metadata={"help": "Base URL for the student vLLM server."},
|
| 313 |
+
)
|
| 314 |
+
vllm_server_host: str = field(
|
| 315 |
+
default="0.0.0.0",
|
| 316 |
+
metadata={"help": "Host of the student vLLM server."},
|
| 317 |
+
)
|
| 318 |
+
vllm_server_port: int = field(
|
| 319 |
+
default=8001,
|
| 320 |
+
metadata={"help": "Port of the student vLLM server."},
|
| 321 |
+
)
|
| 322 |
+
vllm_server_timeout: float = field(
|
| 323 |
+
default=240.0,
|
| 324 |
+
metadata={"help": "Timeout for connecting to the student vLLM server."},
|
| 325 |
+
)
|
| 326 |
+
vllm_group_port: int = field(
|
| 327 |
+
default=51216,
|
| 328 |
+
metadata={"help": "Port for the vLLM weight-update group (NCCL communicator)."},
|
| 329 |
+
)
|
| 330 |
+
vllm_gpu_memory_utilization: float = field(
|
| 331 |
+
default=0.3,
|
| 332 |
+
metadata={"help": "GPU memory utilization for the colocated student vLLM engine."},
|
| 333 |
+
)
|
| 334 |
+
vllm_tensor_parallel_size: int = field(
|
| 335 |
+
default=1,
|
| 336 |
+
metadata={"help": "Tensor parallel size for the colocated student vLLM engine."},
|
| 337 |
+
)
|
| 338 |
+
vllm_max_model_length: int | None = field(
|
| 339 |
+
default=None,
|
| 340 |
+
metadata={"help": "Maximum model sequence length for the colocated vLLM engine."},
|
| 341 |
+
)
|
| 342 |
+
vllm_model_impl: str = field(
|
| 343 |
+
default="vllm",
|
| 344 |
+
metadata={"help": 'Model implementation backend for vLLM. Use "vllm" or "transformers".'},
|
| 345 |
+
)
|
| 346 |
+
vllm_structured_outputs_regex: str | None = field(
|
| 347 |
+
default=None,
|
| 348 |
+
metadata={"help": "Regex pattern for vLLM structured outputs."},
|
| 349 |
+
)
|
| 350 |
+
vllm_sync_frequency: int = field(
|
| 351 |
+
default=1,
|
| 352 |
+
metadata={"help": "Frequency (in training steps) to synchronize student weights to the vLLM engine."},
|
| 353 |
+
)
|
| 354 |
+
vllm_enable_sleep_mode: bool = field(
|
| 355 |
+
default=False,
|
| 356 |
+
metadata={"help": "Enable vLLM sleep mode to offload student weights during the optimizer step."},
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
# W&B
|
| 360 |
+
|
| 361 |
+
# Logging
|
| 362 |
+
log_completions: bool = field(
|
| 363 |
+
default=False,
|
| 364 |
+
metadata={
|
| 365 |
+
"help": "Whether to log a sample of (prompt, completion) pairs every `log_completions_steps` steps. If `rich` is "
|
| 366 |
+
"installed, it prints the sample. If `wandb` and/or `trackio` logging is enabled, it logs it to `wandb` "
|
| 367 |
+
"and/or `trackio`."
|
| 368 |
+
},
|
| 369 |
+
)
|
| 370 |
+
log_completions_steps: int = field(
|
| 371 |
+
default=100,
|
| 372 |
+
metadata={"help": "Number of steps between logging completions."},
|
| 373 |
+
)
|
| 374 |
+
num_completions_to_print: int | None = field(
|
| 375 |
+
default=None,
|
| 376 |
+
metadata={"help": "Number of completions to print. If None, all completions are logged."},
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
def __post_init__(self):
|
| 380 |
+
super().__post_init__()
|
| 381 |
+
|
| 382 |
+
if self.lmbda < 0.0 or self.lmbda > 1.0:
|
| 383 |
+
raise ValueError(f"lmbda must be in [0.0, 1.0], got {self.lmbda}.")
|
| 384 |
+
if self.beta < 0.0 or self.beta > 1.0:
|
| 385 |
+
raise ValueError(f"beta must be in [0.0, 1.0], got {self.beta}.")
|
| 386 |
+
if self.reverse_kl_top_1_mode not in {"sampled", "argmax"}:
|
| 387 |
+
raise ValueError("reverse_kl_top_1_mode must be one of: 'sampled', 'argmax'")
|
| 388 |
+
|
| 389 |
+
if self.max_length is not None and self.max_completion_length >= self.max_length:
|
| 390 |
+
raise ValueError(
|
| 391 |
+
f"max_completion_length ({self.max_completion_length}) must be smaller than "
|
| 392 |
+
f"max_length ({self.max_length}) to leave room for the prompt."
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
if self.max_prompt_length is None and self.max_length is not None:
|
| 396 |
+
self.max_prompt_length = self.max_length - self.max_completion_length
|
| 397 |
+
|
| 398 |
+
if self.num_generations < 1:
|
| 399 |
+
raise ValueError(f"num_generations must be at least 1, got {self.num_generations}.")
|
| 400 |
+
|
| 401 |
+
local_sequence_batch_size = self.per_device_train_batch_size * self.gradient_accumulation_steps
|
| 402 |
+
if self.generation_batch_size is None:
|
| 403 |
+
self.generation_batch_size = local_sequence_batch_size // self.num_generations
|
| 404 |
+
if self.generation_batch_size < 1:
|
| 405 |
+
raise ValueError(f"generation_batch_size must be at least 1, got {self.generation_batch_size}.")
|
| 406 |
+
if self.generation_batch_size * self.num_generations != local_sequence_batch_size:
|
| 407 |
+
raise ValueError(
|
| 408 |
+
"generation_batch_size * num_generations must equal per_device_train_batch_size * "
|
| 409 |
+
f"gradient_accumulation_steps. Got {self.generation_batch_size} * {self.num_generations} != "
|
| 410 |
+
f"{self.per_device_train_batch_size} * {self.gradient_accumulation_steps}."
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
if self.use_teacher_server and self.use_liger_kernel:
|
| 414 |
+
raise ValueError(
|
| 415 |
+
"use_liger_kernel=True is not supported with use_teacher_server=True because the Liger loss path "
|
| 416 |
+
"requires a local teacher model."
|
| 417 |
+
)
|
| 418 |
+
if self.use_teacher_server and (
|
| 419 |
+
self.teacher_model_server_url is None or not self.teacher_model_server_url.strip()
|
| 420 |
+
):
|
| 421 |
+
raise ValueError("teacher_model_server_url must be set when use_teacher_server=True.")
|
| 422 |
+
|
| 423 |
+
if self.use_teacher_server and self.beta == 0 and self.loss_top_k < 1:
|
| 424 |
+
raise ValueError(
|
| 425 |
+
f"loss_top_k must be positive when using use_teacher_server=True with beta=0 "
|
| 426 |
+
f"(got loss_top_k={self.loss_top_k}). The pure forward server path only has access to the "
|
| 427 |
+
f"teacher's top-k logprobs, so it cannot compute the exact full-vocabulary loss when loss_top_k=0."
|
| 428 |
+
)
|
| 429 |
+
if self.use_teacher_server and self.reverse_kl_top_1_mode == "argmax":
|
| 430 |
+
raise ValueError(
|
| 431 |
+
"reverse_kl_top_1_mode='argmax' is not supported with use_teacher_server=True because the server "
|
| 432 |
+
"cannot provide teacher logprobs for arbitrary student-selected tokens."
|
| 433 |
+
)
|
| 434 |
+
if self.use_teacher_server and self.beta > 0 and self.loss_top_k != 1:
|
| 435 |
+
raise ValueError(
|
| 436 |
+
f"loss_top_k must be 1 when using use_teacher_server=True with beta>0 "
|
| 437 |
+
f"(got loss_top_k={self.loss_top_k}). Mixed forward/reverse distillation with an external teacher "
|
| 438 |
+
"is only implemented for top-1 support."
|
| 439 |
+
)
|
| 440 |
+
if self.reverse_kl_top_1_mode != "sampled" and (self.beta == 0 or self.loss_top_k != 1):
|
| 441 |
+
warnings.warn(
|
| 442 |
+
f"reverse_kl_top_1_mode='{self.reverse_kl_top_1_mode}' has no effect when beta={self.beta} "
|
| 443 |
+
f"and loss_top_k={self.loss_top_k}. It only applies when beta > 0 and loss_top_k == 1.",
|
| 444 |
+
UserWarning,
|
| 445 |
+
stacklevel=2,
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
if self.num_generations > 1 and self.lmbda < 1.0:
|
| 449 |
+
warnings.warn(
|
| 450 |
+
f"num_generations={self.num_generations} with lmbda={self.lmbda} means off-policy batches include "
|
| 451 |
+
f"{self.num_generations} copies of each sample. Consider lmbda=1.0 when num_generations > 1.",
|
| 452 |
+
UserWarning,
|
| 453 |
+
stacklevel=2,
|
| 454 |
+
)
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/distillation/distillation_trainer.py
ADDED
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import warnings
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
from collections.abc import Callable
|
| 20 |
+
from contextlib import nullcontext
|
| 21 |
+
from functools import partial
|
| 22 |
+
from typing import Any, Optional
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.distributed as dist
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
from accelerate.utils import DistributedType, broadcast_object_list, gather_object
|
| 29 |
+
from datasets import Dataset
|
| 30 |
+
from packaging.version import Version
|
| 31 |
+
from torch.utils.data import DataLoader
|
| 32 |
+
from transformers import AutoTokenizer, TrainerCallback, is_trackio_available, is_wandb_available
|
| 33 |
+
from transformers.data.data_collator import DataCollator
|
| 34 |
+
from transformers.feature_extraction_utils import FeatureExtractionMixin
|
| 35 |
+
from transformers.generation.configuration_utils import GenerationConfig
|
| 36 |
+
from transformers.image_processing_utils import BaseImageProcessor
|
| 37 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 38 |
+
from transformers.processing_utils import ProcessorMixin
|
| 39 |
+
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
|
| 40 |
+
from transformers.trainer_utils import EvalPrediction, seed_worker
|
| 41 |
+
from transformers.utils import is_liger_kernel_available, is_peft_available, is_rich_available
|
| 42 |
+
|
| 43 |
+
from ...extras.profiling import profiling_decorator
|
| 44 |
+
from ...generation.vllm_generation import VLLMGeneration
|
| 45 |
+
from ...import_utils import is_vllm_available
|
| 46 |
+
from ...models import prepare_deepspeed
|
| 47 |
+
from ...models.utils import _ForwardRedirection, unwrap_model_for_generation
|
| 48 |
+
from ...trainer.base_trainer import _BaseTrainer
|
| 49 |
+
from ...trainer.utils import RepeatSampler, create_model_from_path, disable_dropout_in_model, pad, split_tensor_dict
|
| 50 |
+
from .distillation_config import DistillationConfig
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if is_liger_kernel_available():
|
| 54 |
+
from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
if is_peft_available():
|
| 58 |
+
import peft
|
| 59 |
+
from peft import PeftConfig, get_peft_model
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
if is_rich_available():
|
| 63 |
+
from rich.console import Console
|
| 64 |
+
from rich.panel import Panel
|
| 65 |
+
from rich.table import Table
|
| 66 |
+
from rich.text import Text
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
if is_trackio_available():
|
| 70 |
+
import trackio
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
if is_wandb_available():
|
| 74 |
+
import wandb
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _print_completions_sample(prompts: list[str], completions: list[str], step: int, num_samples: int = None) -> None:
|
| 78 |
+
"""Print a sample of prompt-completion pairs using rich."""
|
| 79 |
+
if not is_rich_available():
|
| 80 |
+
return
|
| 81 |
+
|
| 82 |
+
console = Console()
|
| 83 |
+
table = Table(show_header=True, header_style="bold white", expand=True)
|
| 84 |
+
table.add_column("Prompt", style="bright_yellow")
|
| 85 |
+
table.add_column("Completion", style="bright_green")
|
| 86 |
+
|
| 87 |
+
if num_samples is not None:
|
| 88 |
+
if num_samples >= len(prompts):
|
| 89 |
+
num_samples = None
|
| 90 |
+
elif num_samples <= 0:
|
| 91 |
+
return
|
| 92 |
+
|
| 93 |
+
if num_samples is not None:
|
| 94 |
+
indices = random.sample(range(len(prompts)), num_samples)
|
| 95 |
+
prompts = [prompts[i] for i in indices]
|
| 96 |
+
completions = [completions[i] for i in indices]
|
| 97 |
+
|
| 98 |
+
for prompt, completion in zip(prompts, completions, strict=True):
|
| 99 |
+
table.add_row(Text(prompt), Text(completion))
|
| 100 |
+
table.add_section()
|
| 101 |
+
|
| 102 |
+
panel = Panel(table, expand=False, title=f"Step {step}", border_style="bold white")
|
| 103 |
+
console.print(panel)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _add_tail_bucket(log_probs, valid_mask):
|
| 107 |
+
"""Append a (K+1)-th tail element: log(1 - sum(exp(top_k_logps))).
|
| 108 |
+
|
| 109 |
+
This creates a proper probability distribution over K+1 elements, preventing trivial zero loss when top_k is small
|
| 110 |
+
(especially top_k=1).
|
| 111 |
+
"""
|
| 112 |
+
log_sum = torch.logsumexp(log_probs, dim=-1, keepdim=True)
|
| 113 |
+
log_sum = torch.clamp(log_sum, max=-1e-7) # ensure sum < 1
|
| 114 |
+
tail = torch.log(-torch.expm1(log_sum)) # log(1 - exp(log_sum))
|
| 115 |
+
tail_mask = torch.ones_like(valid_mask[..., :1], dtype=torch.bool)
|
| 116 |
+
return torch.cat([log_probs, tail], dim=-1), torch.cat([valid_mask, tail_mask], dim=-1)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _jsd_divergence(student_log_probs, teacher_log_probs, beta, support_mask=None):
|
| 120 |
+
"""Compute JSD (or forward/reverse KL) from log-probability tensors.
|
| 121 |
+
|
| 122 |
+
When *support_mask* is not None, uses manual computation with masked positions zeroed. When None, uses
|
| 123 |
+
``F.kl_div``.
|
| 124 |
+
"""
|
| 125 |
+
if support_mask is not None:
|
| 126 |
+
safe_student = torch.where(support_mask, student_log_probs, torch.zeros_like(student_log_probs))
|
| 127 |
+
safe_teacher = torch.where(support_mask, teacher_log_probs, torch.zeros_like(teacher_log_probs))
|
| 128 |
+
student_probs = torch.where(support_mask, student_log_probs.exp(), torch.zeros_like(student_log_probs))
|
| 129 |
+
teacher_probs = torch.where(support_mask, teacher_log_probs.exp(), torch.zeros_like(teacher_log_probs))
|
| 130 |
+
|
| 131 |
+
if beta == 0:
|
| 132 |
+
return torch.nan_to_num(teacher_probs * (safe_teacher - safe_student), nan=0.0)
|
| 133 |
+
elif beta == 1:
|
| 134 |
+
return torch.nan_to_num(student_probs * (safe_student - safe_teacher), nan=0.0)
|
| 135 |
+
else:
|
| 136 |
+
beta_t = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device)
|
| 137 |
+
tiny = torch.finfo(student_probs.dtype).tiny
|
| 138 |
+
mixture_probs = (1 - beta_t) * student_probs + beta_t * teacher_probs
|
| 139 |
+
safe_mixture = torch.where(
|
| 140 |
+
support_mask,
|
| 141 |
+
torch.log(mixture_probs.clamp_min(tiny)),
|
| 142 |
+
torch.zeros_like(student_log_probs),
|
| 143 |
+
)
|
| 144 |
+
kl_teacher = torch.nan_to_num(teacher_probs * (safe_teacher - safe_mixture), nan=0.0)
|
| 145 |
+
kl_student = torch.nan_to_num(student_probs * (safe_student - safe_mixture), nan=0.0)
|
| 146 |
+
return beta_t * kl_teacher + (1 - beta_t) * kl_student
|
| 147 |
+
else:
|
| 148 |
+
if beta == 0:
|
| 149 |
+
return F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True)
|
| 150 |
+
elif beta == 1:
|
| 151 |
+
return F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True)
|
| 152 |
+
else:
|
| 153 |
+
beta_t = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device)
|
| 154 |
+
mixture_log_probs = torch.logsumexp(
|
| 155 |
+
torch.stack([student_log_probs + torch.log1p(-beta_t), teacher_log_probs + torch.log(beta_t)]),
|
| 156 |
+
dim=0,
|
| 157 |
+
)
|
| 158 |
+
kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True)
|
| 159 |
+
kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True)
|
| 160 |
+
return beta_t * kl_teacher + (1 - beta_t) * kl_student
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def build_teacher_request_inputs(
|
| 164 |
+
input_ids: torch.Tensor,
|
| 165 |
+
attention_mask: torch.Tensor,
|
| 166 |
+
prompt_attention_mask: torch.Tensor | None = None,
|
| 167 |
+
labels: torch.Tensor | None = None,
|
| 168 |
+
) -> tuple[list[list[int]], list[int], list[int]]:
|
| 169 |
+
"""Trim padded batch tensors into per-sample sequences for teacher-server requests."""
|
| 170 |
+
|
| 171 |
+
if input_ids.shape != attention_mask.shape:
|
| 172 |
+
raise ValueError(
|
| 173 |
+
f"input_ids and attention_mask must have the same shape, got {input_ids.shape} and {attention_mask.shape}."
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
input_ids_cpu = input_ids.detach().cpu()
|
| 177 |
+
attention_mask_cpu = attention_mask.detach().cpu().bool()
|
| 178 |
+
|
| 179 |
+
if prompt_attention_mask is not None:
|
| 180 |
+
prompt_lengths = prompt_attention_mask.detach().cpu().sum(dim=1).to(torch.long)
|
| 181 |
+
else:
|
| 182 |
+
if labels is None:
|
| 183 |
+
raise ValueError("labels are required when prompt_attention_mask is not provided.")
|
| 184 |
+
if labels.shape != input_ids.shape:
|
| 185 |
+
raise ValueError(f"labels must match input_ids shape, got {labels.shape} and {input_ids.shape}.")
|
| 186 |
+
full_lengths = attention_mask_cpu.sum(dim=1).to(torch.long)
|
| 187 |
+
completion_lengths = (labels.detach().cpu() != -100).sum(dim=1).to(torch.long)
|
| 188 |
+
prompt_lengths = full_lengths - completion_lengths
|
| 189 |
+
|
| 190 |
+
trimmed_input_ids: list[list[int]] = []
|
| 191 |
+
prompt_lengths_list: list[int] = []
|
| 192 |
+
completion_lengths_list: list[int] = []
|
| 193 |
+
|
| 194 |
+
for row, mask, prompt_length in zip(input_ids_cpu, attention_mask_cpu, prompt_lengths, strict=True):
|
| 195 |
+
trimmed_row = row[mask]
|
| 196 |
+
prompt_len = int(prompt_length.item())
|
| 197 |
+
if prompt_len < 0 or prompt_len > trimmed_row.numel():
|
| 198 |
+
raise ValueError(
|
| 199 |
+
f"Invalid prompt length {prompt_len} for trimmed sequence of length {trimmed_row.numel()}."
|
| 200 |
+
)
|
| 201 |
+
trimmed_input_ids.append(trimmed_row.tolist())
|
| 202 |
+
prompt_lengths_list.append(prompt_len)
|
| 203 |
+
completion_lengths_list.append(int(trimmed_row.numel()) - prompt_len)
|
| 204 |
+
|
| 205 |
+
return trimmed_input_ids, prompt_lengths_list, completion_lengths_list
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class _DistillationCollator:
|
| 209 |
+
"""Data collator for the distillation trainer with independent prompt/completion budgets.
|
| 210 |
+
|
| 211 |
+
Unlike ``DataCollatorForChatML``, this collator tokenizes prompts and completions separately so that long
|
| 212 |
+
completions can never truncate the prompt to empty. It also handles prompt-only data (no assistant completions) for
|
| 213 |
+
pure on-policy distillation (``lmbda=1``).
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
def __init__(
|
| 217 |
+
self,
|
| 218 |
+
tokenizer: "PreTrainedTokenizerBase",
|
| 219 |
+
max_length: int,
|
| 220 |
+
max_prompt_length: int,
|
| 221 |
+
messages_key: str = "messages",
|
| 222 |
+
ignore_index: int = -100,
|
| 223 |
+
):
|
| 224 |
+
self.tokenizer = tokenizer
|
| 225 |
+
self.max_length = max_length
|
| 226 |
+
self.max_prompt_length = max_prompt_length
|
| 227 |
+
self.messages_key = messages_key
|
| 228 |
+
self.ignore_index = ignore_index
|
| 229 |
+
|
| 230 |
+
if tokenizer.pad_token_id is None:
|
| 231 |
+
raise ValueError("The tokenizer does not have a pad token. Please set `pad_token_id` in the tokenizer.")
|
| 232 |
+
|
| 233 |
+
def __call__(self, examples: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
|
| 234 |
+
all_input_ids: list[list[int]] = []
|
| 235 |
+
all_labels: list[list[int]] = []
|
| 236 |
+
all_prompt_ids: list[list[int]] = []
|
| 237 |
+
|
| 238 |
+
for example in examples:
|
| 239 |
+
messages = example[self.messages_key]
|
| 240 |
+
|
| 241 |
+
# Split: prompt = everything before the last assistant turn, completion = last assistant turn
|
| 242 |
+
has_completion = len(messages) > 1 and messages[-1].get("role") == "assistant"
|
| 243 |
+
prompt_messages = messages[:-1] if has_completion else messages
|
| 244 |
+
|
| 245 |
+
# Tokenize prompt with its own budget using the tokenizer's truncation side
|
| 246 |
+
formatted_prompt = self.tokenizer.apply_chat_template(
|
| 247 |
+
prompt_messages, tokenize=False, add_generation_prompt=True
|
| 248 |
+
)
|
| 249 |
+
prompt_ids = self.tokenizer(
|
| 250 |
+
formatted_prompt,
|
| 251 |
+
truncation=True,
|
| 252 |
+
max_length=self.max_prompt_length,
|
| 253 |
+
padding=False,
|
| 254 |
+
add_special_tokens=False,
|
| 255 |
+
)["input_ids"]
|
| 256 |
+
|
| 257 |
+
if has_completion:
|
| 258 |
+
# Tokenize the full message (prompt + completion) without truncation first
|
| 259 |
+
formatted_full = self.tokenizer.apply_chat_template(
|
| 260 |
+
messages, tokenize=False, add_generation_prompt=False
|
| 261 |
+
)
|
| 262 |
+
full_ids = self.tokenizer(formatted_full, truncation=False, padding=False, add_special_tokens=False)[
|
| 263 |
+
"input_ids"
|
| 264 |
+
]
|
| 265 |
+
|
| 266 |
+
# Identify completion tokens: everything after the prompt in the full sequence.
|
| 267 |
+
# Use the un-truncated prompt length as the split point.
|
| 268 |
+
formatted_prompt_ids = self.tokenizer(
|
| 269 |
+
formatted_prompt, truncation=False, padding=False, add_special_tokens=False
|
| 270 |
+
)["input_ids"]
|
| 271 |
+
completion_ids = full_ids[len(formatted_prompt_ids) :]
|
| 272 |
+
|
| 273 |
+
# Trim completion so prompt + completion <= max_length
|
| 274 |
+
max_comp = self.max_length - len(prompt_ids)
|
| 275 |
+
if max_comp > 0 and len(completion_ids) > max_comp:
|
| 276 |
+
completion_ids = completion_ids[:max_comp]
|
| 277 |
+
elif max_comp <= 0:
|
| 278 |
+
completion_ids = []
|
| 279 |
+
|
| 280 |
+
input_ids = prompt_ids + completion_ids
|
| 281 |
+
labels = [self.ignore_index] * len(prompt_ids) + list(completion_ids)
|
| 282 |
+
else:
|
| 283 |
+
# Prompt-only: no completion to train on (on-policy will generate one)
|
| 284 |
+
input_ids = list(prompt_ids)
|
| 285 |
+
labels = [self.ignore_index] * len(prompt_ids)
|
| 286 |
+
|
| 287 |
+
all_input_ids.append(input_ids)
|
| 288 |
+
all_labels.append(labels)
|
| 289 |
+
all_prompt_ids.append(list(prompt_ids))
|
| 290 |
+
|
| 291 |
+
# Convert to tensors and left-pad
|
| 292 |
+
pad_id = self.tokenizer.pad_token_id
|
| 293 |
+
input_ids_t = pad(
|
| 294 |
+
[torch.tensor(ids, dtype=torch.long) for ids in all_input_ids],
|
| 295 |
+
padding_side="left",
|
| 296 |
+
padding_value=pad_id,
|
| 297 |
+
)
|
| 298 |
+
attention_mask_t = pad(
|
| 299 |
+
[torch.ones(len(ids), dtype=torch.long) for ids in all_input_ids],
|
| 300 |
+
padding_side="left",
|
| 301 |
+
padding_value=0,
|
| 302 |
+
)
|
| 303 |
+
labels_t = pad(
|
| 304 |
+
[torch.tensor(lab, dtype=torch.long) for lab in all_labels],
|
| 305 |
+
padding_side="left",
|
| 306 |
+
padding_value=self.ignore_index,
|
| 307 |
+
)
|
| 308 |
+
prompts_t = pad(
|
| 309 |
+
[torch.tensor(ids, dtype=torch.long) for ids in all_prompt_ids],
|
| 310 |
+
padding_side="left",
|
| 311 |
+
padding_value=pad_id,
|
| 312 |
+
)
|
| 313 |
+
prompt_mask_t = pad(
|
| 314 |
+
[torch.ones(len(ids), dtype=torch.long) for ids in all_prompt_ids],
|
| 315 |
+
padding_side="left",
|
| 316 |
+
padding_value=0,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
return {
|
| 320 |
+
"input_ids": input_ids_t,
|
| 321 |
+
"attention_mask": attention_mask_t,
|
| 322 |
+
"labels": labels_t,
|
| 323 |
+
"prompts": prompts_t,
|
| 324 |
+
"prompt_attention_mask": prompt_mask_t,
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
class _RepeatBatchDataLoader:
|
| 329 |
+
"""Repeats each collated batch ``repeat_count`` times without re-collation.
|
| 330 |
+
|
| 331 |
+
``RepeatSampler`` with ``repeat_count > 1`` causes the DataLoader to re-collate (re-tokenize) the same examples on
|
| 332 |
+
every repeat, which is wasteful. This wrapper instead keeps ``repeat_count=1`` in the sampler and repeats the
|
| 333 |
+
already-collated tensor dict, avoiding redundant tokenization.
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
def __init__(self, dataloader, repeat_count: int):
|
| 337 |
+
self.dataloader = dataloader
|
| 338 |
+
self.repeat_count = repeat_count
|
| 339 |
+
|
| 340 |
+
def __iter__(self):
|
| 341 |
+
for batch in self.dataloader:
|
| 342 |
+
for _ in range(self.repeat_count):
|
| 343 |
+
yield batch
|
| 344 |
+
|
| 345 |
+
def __len__(self):
|
| 346 |
+
return len(self.dataloader) * self.repeat_count
|
| 347 |
+
|
| 348 |
+
def set_epoch(self, epoch: int):
|
| 349 |
+
if hasattr(self.dataloader, "set_epoch"):
|
| 350 |
+
self.dataloader.set_epoch(epoch)
|
| 351 |
+
|
| 352 |
+
def __getattr__(self, attr):
|
| 353 |
+
return getattr(self.dataloader, attr)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class DistillationTrainer(_BaseTrainer):
|
| 357 |
+
"""
|
| 358 |
+
Trainer for knowledge distillation from a teacher model to a student model.
|
| 359 |
+
|
| 360 |
+
Supports:
|
| 361 |
+
- Generalized JSD loss (forward KL, reverse KL, or interpolated JSD via `beta`)
|
| 362 |
+
- On-policy / off-policy mixing via `lmbda` (buffered across gradient accumulation)
|
| 363 |
+
- Local teacher model or external teacher via vLLM server
|
| 364 |
+
- Student on-policy generation via vLLM or model.generate()
|
| 365 |
+
- Liger kernel for memory-efficient fused JSD loss
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
+
_tag_names = ["trl", "distillation"]
|
| 369 |
+
_name = "Distillation"
|
| 370 |
+
_paper = {
|
| 371 |
+
"title": "On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes",
|
| 372 |
+
"id": "2306.13649",
|
| 373 |
+
# docstyle-ignore
|
| 374 |
+
"citation": textwrap.dedent("""\
|
| 375 |
+
@inproceedings{agarwal2024on-policy,
|
| 376 |
+
title = {{On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes}},
|
| 377 |
+
author = {Rishabh Agarwal and Nino Vieillard and Yongchao Zhou and Piotr Stanczyk and Sabela Ramos Garea and Matthieu Geist and Olivier Bachem},
|
| 378 |
+
year = 2024,
|
| 379 |
+
booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024},
|
| 380 |
+
publisher = {OpenReview.net},
|
| 381 |
+
url = {https://openreview.net/forum?id=3zKtaqxLhW},
|
| 382 |
+
}"""),
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
def __init__(
|
| 386 |
+
self,
|
| 387 |
+
model: PreTrainedModel | nn.Module | str | None = None,
|
| 388 |
+
teacher_model: PreTrainedModel | nn.Module | str = None,
|
| 389 |
+
args: DistillationConfig | None = None,
|
| 390 |
+
data_collator: DataCollator | None = None, # type: ignore
|
| 391 |
+
train_dataset: Dataset | None = None,
|
| 392 |
+
eval_dataset: Dataset | dict[str, Dataset] | None = None,
|
| 393 |
+
processing_class: PreTrainedTokenizerBase
|
| 394 |
+
| BaseImageProcessor
|
| 395 |
+
| FeatureExtractionMixin
|
| 396 |
+
| ProcessorMixin
|
| 397 |
+
| None = None,
|
| 398 |
+
compute_metrics: Callable[[EvalPrediction], dict] | None = None,
|
| 399 |
+
callbacks: list[TrainerCallback] | None = None,
|
| 400 |
+
optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
|
| 401 |
+
preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
|
| 402 |
+
peft_config: Optional["PeftConfig"] = None,
|
| 403 |
+
):
|
| 404 |
+
if args is None:
|
| 405 |
+
args = DistillationConfig(output_dir="tmp_distillation")
|
| 406 |
+
|
| 407 |
+
# ── Student model loading ──
|
| 408 |
+
model_init_kwargs = args.model_init_kwargs or {}
|
| 409 |
+
if isinstance(model_init_kwargs, str):
|
| 410 |
+
import json
|
| 411 |
+
|
| 412 |
+
model_init_kwargs = json.loads(model_init_kwargs)
|
| 413 |
+
teacher_model_init_kwargs = args.teacher_model_init_kwargs or {}
|
| 414 |
+
if isinstance(teacher_model_init_kwargs, str):
|
| 415 |
+
import json
|
| 416 |
+
|
| 417 |
+
teacher_model_init_kwargs = json.loads(teacher_model_init_kwargs)
|
| 418 |
+
if isinstance(model, str):
|
| 419 |
+
model_name_or_path = model
|
| 420 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 421 |
+
model = create_model_from_path(model, **model_init_kwargs)
|
| 422 |
+
else:
|
| 423 |
+
model_name_or_path = model.config._name_or_path if model is not None else None
|
| 424 |
+
|
| 425 |
+
# ── Processing class (tokenizer) ──
|
| 426 |
+
if processing_class is None and model_name_or_path is not None:
|
| 427 |
+
processing_class = AutoTokenizer.from_pretrained(
|
| 428 |
+
model_name_or_path, trust_remote_code=args.trust_remote_code
|
| 429 |
+
)
|
| 430 |
+
if processing_class is not None:
|
| 431 |
+
if getattr(processing_class, "pad_token", None) is None:
|
| 432 |
+
processing_class.pad_token = processing_class.eos_token
|
| 433 |
+
|
| 434 |
+
# ── PEFT ──
|
| 435 |
+
if peft_config is not None:
|
| 436 |
+
if not is_peft_available():
|
| 437 |
+
raise ImportError(
|
| 438 |
+
"You passed `peft_config` but the `peft` library is not installed. "
|
| 439 |
+
"Install it with `pip install trl[peft]`."
|
| 440 |
+
)
|
| 441 |
+
if not isinstance(peft_config, PeftConfig):
|
| 442 |
+
raise TypeError(
|
| 443 |
+
f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
|
| 444 |
+
f"got {type(peft_config).__name__}."
|
| 445 |
+
)
|
| 446 |
+
# ZeRO-3 + PEFT for non-quantized models:
|
| 447 |
+
# - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16.
|
| 448 |
+
# - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter,
|
| 449 |
+
# so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step.
|
| 450 |
+
# - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch.
|
| 451 |
+
# - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for
|
| 452 |
+
# non-quantized bf16 training.
|
| 453 |
+
# - See:
|
| 454 |
+
# - TRL issue: https://github.com/huggingface/trl/issues/6089
|
| 455 |
+
# - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072
|
| 456 |
+
# - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg
|
| 457 |
+
_is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(
|
| 458 |
+
model, "is_loaded_in_8bit", False
|
| 459 |
+
)
|
| 460 |
+
get_peft_model_kwargs = {}
|
| 461 |
+
if (
|
| 462 |
+
args.deepspeed_plugin is not None
|
| 463 |
+
and args.deepspeed_plugin.zero_stage == 3
|
| 464 |
+
and not _is_quantized_model
|
| 465 |
+
and Version(peft.__version__) >= Version("0.12.0")
|
| 466 |
+
):
|
| 467 |
+
get_peft_model_kwargs["autocast_adapter_dtype"] = False
|
| 468 |
+
model = get_peft_model(model, peft_config, **get_peft_model_kwargs)
|
| 469 |
+
|
| 470 |
+
# ── Data collator ──
|
| 471 |
+
if data_collator is None:
|
| 472 |
+
data_collator = _DistillationCollator(
|
| 473 |
+
tokenizer=processing_class,
|
| 474 |
+
max_length=args.max_length,
|
| 475 |
+
max_prompt_length=args.max_prompt_length,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
# ── Liger fused JSD loss ──
|
| 479 |
+
self.use_liger_loss = False
|
| 480 |
+
if args.use_liger_kernel:
|
| 481 |
+
self.liger_jsd_loss = LigerFusedLinearJSDLoss(
|
| 482 |
+
beta=args.beta,
|
| 483 |
+
ignore_index=-100,
|
| 484 |
+
temperature=args.temperature,
|
| 485 |
+
compiled=False,
|
| 486 |
+
weight_hard_loss=0.0,
|
| 487 |
+
weight_soft_loss=1.0,
|
| 488 |
+
)
|
| 489 |
+
self.use_liger_loss = True
|
| 490 |
+
self._forward_redirection = _ForwardRedirection()
|
| 491 |
+
|
| 492 |
+
# ── Teacher model setup ──
|
| 493 |
+
self.teacher_client = None
|
| 494 |
+
self.use_teacher_server = args.use_teacher_server
|
| 495 |
+
self.teacher_model_server_url = args.teacher_model_server_url
|
| 496 |
+
self._local_teacher_tokenizer_matches_student = True
|
| 497 |
+
if self.use_teacher_server:
|
| 498 |
+
from ...generation.vllm_client import VLLMClient
|
| 499 |
+
|
| 500 |
+
self.teacher_client = VLLMClient(base_url=self.teacher_model_server_url, connection_timeout=60.0)
|
| 501 |
+
teacher_model = None
|
| 502 |
+
elif teacher_model is not None:
|
| 503 |
+
if args.teacher_model_init_kwargs is not None and not isinstance(teacher_model, str):
|
| 504 |
+
raise ValueError(
|
| 505 |
+
"You passed teacher_model_init_kwargs to the config, but your teacher_model is already "
|
| 506 |
+
"instantiated."
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
teacher_model_name_or_path = (
|
| 510 |
+
teacher_model
|
| 511 |
+
if isinstance(teacher_model, str)
|
| 512 |
+
else getattr(getattr(teacher_model, "config", None), "_name_or_path", None)
|
| 513 |
+
)
|
| 514 |
+
if teacher_model_name_or_path is None:
|
| 515 |
+
raise ValueError(
|
| 516 |
+
"DistillationTrainer requires a local teacher model with `config._name_or_path` set so its "
|
| 517 |
+
"tokenizer can be validated against the student tokenizer."
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
teacher_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 521 |
+
teacher_tokenizer_kwargs = {}
|
| 522 |
+
teacher_revision = teacher_model_init_kwargs.get("revision", args.teacher_model_revision)
|
| 523 |
+
if teacher_revision is not None:
|
| 524 |
+
teacher_tokenizer_kwargs["revision"] = teacher_revision
|
| 525 |
+
teacher_tokenizer_kwargs["trust_remote_code"] = teacher_model_init_kwargs["trust_remote_code"]
|
| 526 |
+
teacher_processing_class = AutoTokenizer.from_pretrained(
|
| 527 |
+
teacher_model_name_or_path, **teacher_tokenizer_kwargs
|
| 528 |
+
)
|
| 529 |
+
if getattr(teacher_processing_class, "pad_token", None) is None:
|
| 530 |
+
teacher_processing_class.pad_token = teacher_processing_class.eos_token
|
| 531 |
+
self._local_teacher_tokenizer_matches_student = self._local_teacher_tokenizers_match(
|
| 532 |
+
processing_class, teacher_processing_class
|
| 533 |
+
)
|
| 534 |
+
if not self._local_teacher_tokenizer_matches_student:
|
| 535 |
+
warnings.warn(
|
| 536 |
+
"DistillationTrainer's built-in local-teacher loss assumes the student and teacher share the "
|
| 537 |
+
"same tokenizer. The loaded local teacher tokenizer does not match the student tokenizer, so "
|
| 538 |
+
"the teacher weights will be left unchanged for subclass overrides. Direct use of the base "
|
| 539 |
+
"DistillationTrainer with this local teacher remains unsupported.",
|
| 540 |
+
UserWarning,
|
| 541 |
+
stacklevel=2,
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
if isinstance(teacher_model, str):
|
| 545 |
+
dtype = teacher_model_init_kwargs.get("dtype")
|
| 546 |
+
teacher_model_init_kwargs["dtype"] = dtype if dtype in ["auto", None] else getattr(torch, dtype)
|
| 547 |
+
|
| 548 |
+
if isinstance(teacher_model, str):
|
| 549 |
+
init_kwargs = dict(teacher_model_init_kwargs)
|
| 550 |
+
if args.teacher_model_revision is not None:
|
| 551 |
+
init_kwargs.setdefault("revision", args.teacher_model_revision)
|
| 552 |
+
teacher_model = create_model_from_path(teacher_model, **init_kwargs)
|
| 553 |
+
|
| 554 |
+
# Trainer does not need to remove unused columns — the collator handles raw data
|
| 555 |
+
args.remove_unused_columns = False
|
| 556 |
+
|
| 557 |
+
super().__init__(
|
| 558 |
+
model=model,
|
| 559 |
+
args=args,
|
| 560 |
+
data_collator=data_collator,
|
| 561 |
+
train_dataset=train_dataset,
|
| 562 |
+
eval_dataset=eval_dataset,
|
| 563 |
+
processing_class=processing_class,
|
| 564 |
+
compute_metrics=compute_metrics,
|
| 565 |
+
callbacks=callbacks,
|
| 566 |
+
optimizers=optimizers,
|
| 567 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
# ── Prepare teacher model (after super().__init__ so accelerator is ready) ──
|
| 571 |
+
if teacher_model is not None:
|
| 572 |
+
if self._local_teacher_tokenizer_matches_student:
|
| 573 |
+
teacher_model.resize_token_embeddings(self.model.config.get_text_config().vocab_size)
|
| 574 |
+
if self.is_deepspeed_enabled:
|
| 575 |
+
self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator)
|
| 576 |
+
else:
|
| 577 |
+
self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True)
|
| 578 |
+
else:
|
| 579 |
+
self.teacher_model = None
|
| 580 |
+
|
| 581 |
+
if args.disable_dropout:
|
| 582 |
+
disable_dropout_in_model(self.model)
|
| 583 |
+
|
| 584 |
+
# ── Store config values ──
|
| 585 |
+
self.lmbda = args.lmbda
|
| 586 |
+
self.beta = args.beta
|
| 587 |
+
self.temperature = args.temperature
|
| 588 |
+
self.top_p = args.top_p
|
| 589 |
+
self.num_generations = args.num_generations
|
| 590 |
+
self.reverse_kl_top_1_mode = args.reverse_kl_top_1_mode
|
| 591 |
+
self.loss_top_k = args.loss_top_k
|
| 592 |
+
self.loss_add_tail = args.loss_add_tail
|
| 593 |
+
|
| 594 |
+
# ── Buffer state ──
|
| 595 |
+
self._buffered_inputs = None
|
| 596 |
+
self._buffered_on_policy_flags = None
|
| 597 |
+
self._buffered_text_logs = None
|
| 598 |
+
self._buffer_step = 0
|
| 599 |
+
|
| 600 |
+
# ── Loss tracking ──
|
| 601 |
+
self._on_policy_loss_total = 0.0
|
| 602 |
+
self._off_policy_loss_total = 0.0
|
| 603 |
+
self._on_policy_step_equiv = 0.0
|
| 604 |
+
self._off_policy_step_equiv = 0.0
|
| 605 |
+
|
| 606 |
+
# ── Generation config ──
|
| 607 |
+
generation_kwargs = {
|
| 608 |
+
"max_new_tokens": args.max_completion_length,
|
| 609 |
+
"temperature": args.temperature,
|
| 610 |
+
"top_p": args.top_p,
|
| 611 |
+
"do_sample": True,
|
| 612 |
+
"top_k": args.top_k,
|
| 613 |
+
"pad_token_id": self.processing_class.pad_token_id,
|
| 614 |
+
}
|
| 615 |
+
self.generation_config = GenerationConfig(**generation_kwargs)
|
| 616 |
+
self.generation_kwargs = generation_kwargs
|
| 617 |
+
if (
|
| 618 |
+
hasattr(self.model.generation_config, "eos_token_id")
|
| 619 |
+
and self.model.generation_config.eos_token_id is not None
|
| 620 |
+
):
|
| 621 |
+
self.generation_config.eos_token_id = self.model.generation_config.eos_token_id
|
| 622 |
+
|
| 623 |
+
# ── Metrics & Logging ──
|
| 624 |
+
self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
|
| 625 |
+
self._total_train_tokens = 0
|
| 626 |
+
self.log_completions = args.log_completions
|
| 627 |
+
self.log_completions_steps = args.log_completions_steps
|
| 628 |
+
self.num_completions_to_print = args.num_completions_to_print
|
| 629 |
+
|
| 630 |
+
self._textual_logs = {
|
| 631 |
+
"prompt": [],
|
| 632 |
+
"completion": [],
|
| 633 |
+
}
|
| 634 |
+
|
| 635 |
+
# ── vLLM for student generation ──
|
| 636 |
+
self.use_vllm = args.use_vllm
|
| 637 |
+
if self.use_vllm:
|
| 638 |
+
if not is_vllm_available():
|
| 639 |
+
raise ImportError(
|
| 640 |
+
"vLLM is not available and use_vllm is set to True. Please install vLLM with "
|
| 641 |
+
"`pip install vllm` to use it."
|
| 642 |
+
)
|
| 643 |
+
self.vllm_generation = VLLMGeneration(
|
| 644 |
+
model=self.model,
|
| 645 |
+
accelerator=self.accelerator,
|
| 646 |
+
processing_class=self.processing_class,
|
| 647 |
+
mode=args.vllm_mode,
|
| 648 |
+
structured_outputs_regex=args.vllm_structured_outputs_regex,
|
| 649 |
+
server_base_url=args.vllm_server_base_url,
|
| 650 |
+
server_host=args.vllm_server_host,
|
| 651 |
+
server_port=args.vllm_server_port,
|
| 652 |
+
group_port=args.vllm_group_port,
|
| 653 |
+
server_timeout=args.vllm_server_timeout,
|
| 654 |
+
tensor_parallel_size=args.vllm_tensor_parallel_size,
|
| 655 |
+
gpu_memory_utilization=args.vllm_gpu_memory_utilization,
|
| 656 |
+
max_model_length=args.vllm_max_model_length,
|
| 657 |
+
max_num_seqs=args.per_device_train_batch_size * args.gradient_accumulation_steps,
|
| 658 |
+
enable_sleep_mode=args.vllm_enable_sleep_mode,
|
| 659 |
+
model_impl=args.vllm_model_impl,
|
| 660 |
+
temperature=args.temperature,
|
| 661 |
+
top_p=args.top_p,
|
| 662 |
+
top_k=args.top_k,
|
| 663 |
+
max_completion_length=args.max_completion_length,
|
| 664 |
+
logprobs=None,
|
| 665 |
+
)
|
| 666 |
+
self.vllm_sync_frequency = args.vllm_sync_frequency
|
| 667 |
+
self._last_vllm_sync_step = -1
|
| 668 |
+
|
| 669 |
+
@staticmethod
|
| 670 |
+
def _local_teacher_tokenizers_match(
|
| 671 |
+
student_processing_class: PreTrainedTokenizerBase,
|
| 672 |
+
teacher_processing_class: PreTrainedTokenizerBase,
|
| 673 |
+
) -> bool:
|
| 674 |
+
"""Check whether the student and local teacher tokenizers share the same vocabulary."""
|
| 675 |
+
return student_processing_class.get_vocab() == teacher_processing_class.get_vocab()
|
| 676 |
+
|
| 677 |
+
def _raise_if_local_teacher_tokenizer_mismatch(self) -> None:
|
| 678 |
+
"""Guard the base local-teacher JSD path, while still allowing subclass overrides."""
|
| 679 |
+
if self.teacher_model is not None and not self._local_teacher_tokenizer_matches_student:
|
| 680 |
+
raise ValueError(
|
| 681 |
+
"DistillationTrainer's built-in local-teacher loss only supports student/teacher pairs that use "
|
| 682 |
+
"the same tokenizer. Use a same-tokenizer local teacher, set `use_teacher_server=True`, or "
|
| 683 |
+
"override the local teacher loss path in a subclass."
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
def _compute_prompt_length(self, inputs: dict[str, torch.Tensor | Any]) -> int:
|
| 687 |
+
"""Compute the earliest prompt boundary that still includes every completion token in the batch."""
|
| 688 |
+
if inputs.get("labels") is not None:
|
| 689 |
+
attention_mask = inputs["attention_mask"]
|
| 690 |
+
labels = inputs["labels"]
|
| 691 |
+
full_lengths = attention_mask.sum(dim=1)
|
| 692 |
+
completion_lengths = (labels != -100).sum(dim=1)
|
| 693 |
+
return int((full_lengths - completion_lengths).min().item())
|
| 694 |
+
return inputs["prompts"].shape[1]
|
| 695 |
+
|
| 696 |
+
def _get_completion_lengths(self, generated_tokens: torch.Tensor, prompt_width: int) -> torch.Tensor:
|
| 697 |
+
"""Infer per-sample completion lengths from generated tokens."""
|
| 698 |
+
completion_tokens = generated_tokens[:, prompt_width:]
|
| 699 |
+
pad_token_id = self.processing_class.pad_token_id
|
| 700 |
+
eos_token_id = self.generation_config.eos_token_id
|
| 701 |
+
if eos_token_id is None:
|
| 702 |
+
eos_token_ids = set()
|
| 703 |
+
elif isinstance(eos_token_id, int):
|
| 704 |
+
eos_token_ids = {eos_token_id}
|
| 705 |
+
else:
|
| 706 |
+
eos_token_ids = set(eos_token_id)
|
| 707 |
+
pad_equals_eos = pad_token_id is not None and pad_token_id in eos_token_ids
|
| 708 |
+
|
| 709 |
+
completion_lengths = []
|
| 710 |
+
for row in completion_tokens.tolist():
|
| 711 |
+
if pad_equals_eos and eos_token_ids:
|
| 712 |
+
completion_length = len(row)
|
| 713 |
+
for idx, token_id in enumerate(row):
|
| 714 |
+
if token_id in eos_token_ids:
|
| 715 |
+
completion_length = idx + 1
|
| 716 |
+
break
|
| 717 |
+
elif pad_token_id is not None:
|
| 718 |
+
completion_length = len(row)
|
| 719 |
+
while completion_length > 0 and row[completion_length - 1] == pad_token_id:
|
| 720 |
+
completion_length -= 1
|
| 721 |
+
else:
|
| 722 |
+
completion_length = len(row)
|
| 723 |
+
completion_lengths.append(completion_length)
|
| 724 |
+
|
| 725 |
+
return torch.tensor(completion_lengths, device=generated_tokens.device, dtype=torch.long)
|
| 726 |
+
|
| 727 |
+
# ──────────────────────────────────────────────────────────────────────
|
| 728 |
+
# Dataset / Dataloader
|
| 729 |
+
# ──────────────────────────────────────────────────────────────────────
|
| 730 |
+
|
| 731 |
+
def _set_signature_columns_if_needed(self):
|
| 732 |
+
super()._set_signature_columns_if_needed()
|
| 733 |
+
extra_columns = ["prompts", "prompt_attention_mask", "messages", "chat_template_kwargs", "tools"]
|
| 734 |
+
if self._signature_columns is None:
|
| 735 |
+
self._signature_columns = extra_columns
|
| 736 |
+
else:
|
| 737 |
+
for col in extra_columns:
|
| 738 |
+
if col not in self._signature_columns:
|
| 739 |
+
self._signature_columns.append(col)
|
| 740 |
+
|
| 741 |
+
def _get_train_sampler(self, dataset=None):
|
| 742 |
+
if dataset is None:
|
| 743 |
+
dataset = self.train_dataset
|
| 744 |
+
return RepeatSampler(
|
| 745 |
+
data_source=dataset,
|
| 746 |
+
mini_repeat_count=self.num_generations,
|
| 747 |
+
batch_size=self.args.generation_batch_size * self.accelerator.num_processes,
|
| 748 |
+
repeat_count=1,
|
| 749 |
+
shuffle=True,
|
| 750 |
+
seed=self.args.seed,
|
| 751 |
+
)
|
| 752 |
+
|
| 753 |
+
def get_train_dataloader(self):
|
| 754 |
+
"""
|
| 755 |
+
Override to load one generation batch per optimizer window.
|
| 756 |
+
|
| 757 |
+
The dataloader yields batches of size `per_device_train_batch_size * gradient_accumulation_steps`.
|
| 758 |
+
RepeatSampler ensures each generation batch is repeated `gradient_accumulation_steps` times so the Trainer's
|
| 759 |
+
loop iterates the correct number of times.
|
| 760 |
+
"""
|
| 761 |
+
if self.train_dataset is None:
|
| 762 |
+
raise ValueError("Trainer: training requires a train_dataset.")
|
| 763 |
+
|
| 764 |
+
train_dataset = self.train_dataset
|
| 765 |
+
data_collator = self.data_collator
|
| 766 |
+
|
| 767 |
+
dataloader_params = {
|
| 768 |
+
"batch_size": self._train_batch_size * self.args.gradient_accumulation_steps,
|
| 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 |
+
|
| 775 |
+
if not isinstance(train_dataset, torch.utils.data.IterableDataset):
|
| 776 |
+
dataloader_params["sampler"] = self._get_train_sampler()
|
| 777 |
+
dataloader_params["drop_last"] = self.args.dataloader_drop_last
|
| 778 |
+
dataloader_params["worker_init_fn"] = partial(
|
| 779 |
+
seed_worker,
|
| 780 |
+
num_workers=self.args.dataloader_num_workers,
|
| 781 |
+
rank=self.args.process_index,
|
| 782 |
+
)
|
| 783 |
+
if self.args.dataloader_num_workers > 0:
|
| 784 |
+
dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor
|
| 785 |
+
|
| 786 |
+
base_dataloader = self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params))
|
| 787 |
+
return _RepeatBatchDataLoader(base_dataloader, repeat_count=self.args.gradient_accumulation_steps)
|
| 788 |
+
|
| 789 |
+
# ──────────────────────────────────────────────────────────────────────
|
| 790 |
+
# Buffering: on/off-policy mixing across gradient accumulation steps
|
| 791 |
+
# ──────────────────────────────────────────────────────────────────────
|
| 792 |
+
|
| 793 |
+
@profiling_decorator
|
| 794 |
+
def _prepare_inputs(self, generation_batch: dict[str, torch.Tensor | Any]) -> dict[str, torch.Tensor | Any]:
|
| 795 |
+
if not self.model.training:
|
| 796 |
+
return generation_batch
|
| 797 |
+
|
| 798 |
+
buffer_steps = self.args.gradient_accumulation_steps
|
| 799 |
+
if self._buffer_step % buffer_steps == 0 or self._buffered_inputs is None:
|
| 800 |
+
self._fill_buffer(generation_batch, buffer_steps)
|
| 801 |
+
|
| 802 |
+
slice_idx = self._buffer_step % buffer_steps
|
| 803 |
+
inputs = self._buffered_inputs[slice_idx]
|
| 804 |
+
self._buffer_step += 1
|
| 805 |
+
return inputs
|
| 806 |
+
|
| 807 |
+
@profiling_decorator
|
| 808 |
+
def _fill_buffer(self, generation_batch: dict[str, torch.Tensor | Any], buffer_steps: int):
|
| 809 |
+
"""Split batch into slices and decide which are on-policy (student-generated) vs off-policy."""
|
| 810 |
+
slices = split_tensor_dict(generation_batch, buffer_steps)
|
| 811 |
+
|
| 812 |
+
# Decide on-policy flags (synchronized across processes)
|
| 813 |
+
if self.accelerator.is_main_process:
|
| 814 |
+
on_policy_flags = [random.random() <= self.lmbda for _ in range(buffer_steps)]
|
| 815 |
+
else:
|
| 816 |
+
on_policy_flags = [False] * buffer_steps
|
| 817 |
+
on_policy_flags = broadcast_object_list(on_policy_flags, from_process=0)
|
| 818 |
+
|
| 819 |
+
self._buffered_inputs = [None] * buffer_steps
|
| 820 |
+
self._buffered_on_policy_flags = on_policy_flags
|
| 821 |
+
self._buffered_text_logs = [None] * buffer_steps
|
| 822 |
+
|
| 823 |
+
# Store off-policy slices directly
|
| 824 |
+
on_policy_indices = []
|
| 825 |
+
for i, is_on_policy in enumerate(on_policy_flags):
|
| 826 |
+
if is_on_policy:
|
| 827 |
+
on_policy_indices.append(i)
|
| 828 |
+
else:
|
| 829 |
+
self._buffered_inputs[i] = slices[i]
|
| 830 |
+
|
| 831 |
+
# Generate student completions for on-policy slices
|
| 832 |
+
if on_policy_indices:
|
| 833 |
+
self._generate_student_completions(slices, on_policy_indices)
|
| 834 |
+
|
| 835 |
+
# Gather on-policy text logs once per optimizer step (all processes must participate)
|
| 836 |
+
if self.log_completions:
|
| 837 |
+
on_policy_prompts = []
|
| 838 |
+
on_policy_completions = []
|
| 839 |
+
for i in on_policy_indices:
|
| 840 |
+
if self._buffered_text_logs[i] is not None:
|
| 841 |
+
prompts, completions = self._buffered_text_logs[i]
|
| 842 |
+
on_policy_prompts.extend(prompts)
|
| 843 |
+
on_policy_completions.extend(completions)
|
| 844 |
+
self._textual_logs["prompt"].extend(gather_object(on_policy_prompts))
|
| 845 |
+
self._textual_logs["completion"].extend(gather_object(on_policy_completions))
|
| 846 |
+
|
| 847 |
+
@profiling_decorator
|
| 848 |
+
def _generate_student_completions(self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int]):
|
| 849 |
+
"""Generate completions from the student model for on-policy training."""
|
| 850 |
+
if not self.use_vllm:
|
| 851 |
+
self._generate_with_model(slices, on_policy_indices)
|
| 852 |
+
return
|
| 853 |
+
|
| 854 |
+
# Collect all prompts across on-policy slices, stripping left-padding so vLLM
|
| 855 |
+
# receives only real prompt token IDs (like GRPO trainer).
|
| 856 |
+
local_prompts = []
|
| 857 |
+
local_slice_indices = []
|
| 858 |
+
pad_token_id = self.processing_class.pad_token_id
|
| 859 |
+
for slice_idx in on_policy_indices:
|
| 860 |
+
prompt_mask = slices[slice_idx].get("prompt_attention_mask")
|
| 861 |
+
for i, prompt in enumerate(slices[slice_idx]["prompts"]):
|
| 862 |
+
if prompt_mask is not None:
|
| 863 |
+
prompt = prompt[prompt_mask[i].bool()]
|
| 864 |
+
elif pad_token_id is not None:
|
| 865 |
+
first_non_pad = (prompt != pad_token_id).nonzero(as_tuple=True)[0]
|
| 866 |
+
if len(first_non_pad) > 0:
|
| 867 |
+
prompt = prompt[first_non_pad[0] :]
|
| 868 |
+
local_prompts.append(prompt)
|
| 869 |
+
local_slice_indices.append(slice_idx)
|
| 870 |
+
|
| 871 |
+
# Sync student weights to vLLM if needed
|
| 872 |
+
if (
|
| 873 |
+
self.state.global_step != self._last_vllm_sync_step
|
| 874 |
+
and self.state.global_step % self.vllm_sync_frequency == 0
|
| 875 |
+
):
|
| 876 |
+
self.vllm_generation.sync_weights()
|
| 877 |
+
self._last_vllm_sync_step = self.state.global_step
|
| 878 |
+
|
| 879 |
+
# Generate completions — pass token IDs directly, no text decoding
|
| 880 |
+
prompt_ids_list = [p.tolist() for p in local_prompts]
|
| 881 |
+
_, completion_ids, _, _ = self.vllm_generation.generate(
|
| 882 |
+
prompts=prompt_ids_list, images=None, num_generations=self.num_generations
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
# Process completions into the buffer
|
| 886 |
+
self._store_completions_in_buffer(
|
| 887 |
+
slices, on_policy_indices, local_slice_indices, local_prompts, completion_ids
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
def _generate_with_model(self, slices: list[dict[str, torch.Tensor | Any]], on_policy_indices: list[int]):
|
| 891 |
+
"""Fallback generation using model.generate() (no vLLM)."""
|
| 892 |
+
with unwrap_model_for_generation(
|
| 893 |
+
self.model, self.accelerator, generation_kwargs=self.generation_kwargs
|
| 894 |
+
) as unwrapped_model:
|
| 895 |
+
for slice_idx in on_policy_indices:
|
| 896 |
+
slice_inputs = slices[slice_idx]
|
| 897 |
+
generated_outputs = unwrapped_model.generate(
|
| 898 |
+
input_ids=slice_inputs["prompts"],
|
| 899 |
+
attention_mask=slice_inputs.get("prompt_attention_mask", None),
|
| 900 |
+
generation_config=self.generation_config,
|
| 901 |
+
return_dict_in_generate=True,
|
| 902 |
+
)
|
| 903 |
+
generated_tokens = generated_outputs.sequences
|
| 904 |
+
batch_size = generated_tokens.size(0)
|
| 905 |
+
device = generated_tokens.device
|
| 906 |
+
pad_token_id = self.processing_class.pad_token_id
|
| 907 |
+
prompt_width = slice_inputs["prompts"].shape[1]
|
| 908 |
+
prompt_mask = slice_inputs.get("prompt_attention_mask")
|
| 909 |
+
if prompt_mask is not None:
|
| 910 |
+
prompt_token_lengths = prompt_mask.sum(dim=1)
|
| 911 |
+
else:
|
| 912 |
+
prompt_token_lengths = torch.full((batch_size,), prompt_width, dtype=torch.long, device=device)
|
| 913 |
+
completion_lengths = self._get_completion_lengths(generated_tokens, prompt_width)
|
| 914 |
+
new_attention_mask, new_labels = self._build_sequence_batch(
|
| 915 |
+
generated_tokens, prompt_width, prompt_token_lengths, completion_lengths
|
| 916 |
+
)
|
| 917 |
+
|
| 918 |
+
# Decode for logging
|
| 919 |
+
prompt_texts = []
|
| 920 |
+
completion_texts = []
|
| 921 |
+
for idx in range(batch_size):
|
| 922 |
+
prompt_tokens = slice_inputs["prompts"][idx]
|
| 923 |
+
if prompt_mask is not None:
|
| 924 |
+
prompt_tokens = prompt_tokens[prompt_mask[idx].bool()]
|
| 925 |
+
elif pad_token_id is not None:
|
| 926 |
+
prompt_tokens = prompt_tokens[prompt_tokens != pad_token_id]
|
| 927 |
+
prompt_texts.append(
|
| 928 |
+
self.processing_class.decode(prompt_tokens.tolist(), skip_special_tokens=False)
|
| 929 |
+
)
|
| 930 |
+
length = prompt_width
|
| 931 |
+
completion_length = int(completion_lengths[idx].item())
|
| 932 |
+
completion_texts.append(
|
| 933 |
+
self.processing_class.decode(
|
| 934 |
+
generated_tokens[idx, length : length + completion_length].tolist(),
|
| 935 |
+
skip_special_tokens=False,
|
| 936 |
+
)
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
updated = dict(slice_inputs)
|
| 940 |
+
updated["input_ids"] = generated_tokens
|
| 941 |
+
updated["attention_mask"] = new_attention_mask
|
| 942 |
+
updated["labels"] = new_labels
|
| 943 |
+
|
| 944 |
+
self._buffered_inputs[slice_idx] = updated
|
| 945 |
+
self._buffered_text_logs[slice_idx] = (prompt_texts, completion_texts)
|
| 946 |
+
|
| 947 |
+
def _store_completions_in_buffer(
|
| 948 |
+
self,
|
| 949 |
+
slices: list[dict[str, torch.Tensor | Any]],
|
| 950 |
+
on_policy_indices: list[int],
|
| 951 |
+
local_slice_indices: list[int],
|
| 952 |
+
local_prompts: list[torch.Tensor],
|
| 953 |
+
completion_ids: list,
|
| 954 |
+
):
|
| 955 |
+
"""Process vLLM completions and store them in the buffer.
|
| 956 |
+
|
| 957 |
+
Uses original prompt token IDs directly (no decode/re-encode roundtrip), following the same approach as
|
| 958 |
+
GRPOTrainer.
|
| 959 |
+
"""
|
| 960 |
+
device = self.accelerator.device
|
| 961 |
+
pad_token_id = self.processing_class.pad_token_id if self.processing_class.pad_token_id is not None else 0
|
| 962 |
+
max_completion_length = self.generation_config.max_new_tokens
|
| 963 |
+
|
| 964 |
+
# Group completions and prompt token IDs by slice
|
| 965 |
+
slice_completions = {idx: [] for idx in on_policy_indices}
|
| 966 |
+
slice_prompt_ids = {idx: [] for idx in on_policy_indices}
|
| 967 |
+
for i, slice_idx in enumerate(local_slice_indices):
|
| 968 |
+
slice_completions[slice_idx].append(completion_ids[i])
|
| 969 |
+
slice_prompt_ids[slice_idx].append(local_prompts[i])
|
| 970 |
+
|
| 971 |
+
for slice_idx in on_policy_indices:
|
| 972 |
+
slice_inputs = slices[slice_idx]
|
| 973 |
+
prompt_id_tensors = slice_prompt_ids[slice_idx]
|
| 974 |
+
prompt_width = max(len(p) for p in prompt_id_tensors)
|
| 975 |
+
prompt_token_lengths = torch.tensor([len(p) for p in prompt_id_tensors], device=device, dtype=torch.long)
|
| 976 |
+
prompt_attention_mask = (
|
| 977 |
+
torch.arange(prompt_width, device=device).unsqueeze(0)
|
| 978 |
+
>= (prompt_width - prompt_token_lengths).unsqueeze(1)
|
| 979 |
+
).long()
|
| 980 |
+
|
| 981 |
+
# Left-pad prompt token IDs to the longest prompt in this slice
|
| 982 |
+
prompt_ids = torch.stack(
|
| 983 |
+
[F.pad(p, (prompt_width - len(p), 0), value=pad_token_id) for p in prompt_id_tensors]
|
| 984 |
+
).to(device)
|
| 985 |
+
|
| 986 |
+
# Pad/truncate completions (right-pad to max_completion_length)
|
| 987 |
+
completion_tensors = []
|
| 988 |
+
completion_ids_for_text = []
|
| 989 |
+
completion_lengths = []
|
| 990 |
+
for comp_ids in slice_completions[slice_idx]:
|
| 991 |
+
t = torch.tensor(comp_ids, device=device)
|
| 992 |
+
if len(t) > max_completion_length:
|
| 993 |
+
t = t[:max_completion_length]
|
| 994 |
+
completion_ids_for_text.append(t.tolist())
|
| 995 |
+
completion_lengths.append(len(t))
|
| 996 |
+
if len(t) < max_completion_length:
|
| 997 |
+
padding = torch.full((max_completion_length - len(t),), pad_token_id, device=device, dtype=t.dtype)
|
| 998 |
+
t = torch.cat([t, padding])
|
| 999 |
+
completion_tensors.append(t)
|
| 1000 |
+
|
| 1001 |
+
completion_ids_padded = torch.stack(completion_tensors)
|
| 1002 |
+
new_input_ids = torch.cat([prompt_ids, completion_ids_padded], dim=1)
|
| 1003 |
+
completion_lengths = torch.tensor(completion_lengths, device=device, dtype=torch.long)
|
| 1004 |
+
new_attention_mask, new_labels = self._build_sequence_batch(
|
| 1005 |
+
new_input_ids, prompt_width, prompt_token_lengths, completion_lengths
|
| 1006 |
+
)
|
| 1007 |
+
|
| 1008 |
+
# Decode for logging only
|
| 1009 |
+
prompt_texts = self.processing_class.batch_decode(
|
| 1010 |
+
prompt_id_tensors, skip_special_tokens=False, clean_up_tokenization_spaces=False
|
| 1011 |
+
)
|
| 1012 |
+
completion_texts = self.processing_class.batch_decode(
|
| 1013 |
+
completion_ids_for_text, skip_special_tokens=False, clean_up_tokenization_spaces=False
|
| 1014 |
+
)
|
| 1015 |
+
|
| 1016 |
+
updated = dict(slice_inputs)
|
| 1017 |
+
updated["input_ids"] = new_input_ids
|
| 1018 |
+
updated["attention_mask"] = new_attention_mask
|
| 1019 |
+
updated["labels"] = new_labels
|
| 1020 |
+
# Update prompts to match the new padding width so prompt_length is consistent
|
| 1021 |
+
updated["prompts"] = prompt_ids
|
| 1022 |
+
updated["prompt_attention_mask"] = prompt_attention_mask
|
| 1023 |
+
|
| 1024 |
+
self._buffered_inputs[slice_idx] = updated
|
| 1025 |
+
self._buffered_text_logs[slice_idx] = (prompt_texts, completion_texts)
|
| 1026 |
+
|
| 1027 |
+
@staticmethod
|
| 1028 |
+
def _build_sequence_batch(
|
| 1029 |
+
new_input_ids: torch.Tensor,
|
| 1030 |
+
prompt_width: int,
|
| 1031 |
+
prompt_token_lengths: torch.Tensor,
|
| 1032 |
+
completion_lengths: torch.Tensor,
|
| 1033 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1034 |
+
"""Build attention mask and labels from prompt/completion lengths."""
|
| 1035 |
+
prompt_token_lengths = prompt_token_lengths.to(device=new_input_ids.device, dtype=torch.long)
|
| 1036 |
+
completion_lengths = completion_lengths.to(device=new_input_ids.device, dtype=torch.long)
|
| 1037 |
+
positions = torch.arange(new_input_ids.shape[1], device=new_input_ids.device).unsqueeze(0)
|
| 1038 |
+
prompt_mask = (positions < prompt_width) & (positions >= (prompt_width - prompt_token_lengths).unsqueeze(1))
|
| 1039 |
+
completion_mask = (positions >= prompt_width) & (positions < (prompt_width + completion_lengths).unsqueeze(1))
|
| 1040 |
+
new_attention_mask = (prompt_mask | completion_mask).long()
|
| 1041 |
+
|
| 1042 |
+
new_labels = torch.full_like(new_input_ids, -100)
|
| 1043 |
+
new_labels[completion_mask] = new_input_ids[completion_mask]
|
| 1044 |
+
|
| 1045 |
+
return new_attention_mask, new_labels
|
| 1046 |
+
|
| 1047 |
+
# ──────────────────────────────────────────────────────────────────────
|
| 1048 |
+
# Loss computation
|
| 1049 |
+
# ──────────────────────────────────────────────────────────────────────
|
| 1050 |
+
|
| 1051 |
+
@staticmethod
|
| 1052 |
+
def _reduce_divergence_loss(jsd, labels=None, reduction="batchmean", num_items_in_batch=None):
|
| 1053 |
+
"""Reduce a per-token divergence tensor using the trainer's label mask semantics.
|
| 1054 |
+
|
| 1055 |
+
When `num_items_in_batch` is provided (as under gradient accumulation), the divergence is reduced as `sum /
|
| 1056 |
+
num_items_in_batch`, matching the gradient-accumulation-correct behavior of HF's default cross-entropy.
|
| 1057 |
+
Otherwise it falls back to the local `reduction` (default `batchmean`). See issue #4719.
|
| 1058 |
+
"""
|
| 1059 |
+
mask = None
|
| 1060 |
+
if labels is not None:
|
| 1061 |
+
mask = labels != -100
|
| 1062 |
+
jsd = jsd[mask]
|
| 1063 |
+
|
| 1064 |
+
if num_items_in_batch is not None:
|
| 1065 |
+
# Normalize by the global number of valid tokens for gradient-accumulation-correct loss.
|
| 1066 |
+
jsd_sum = jsd.sum()
|
| 1067 |
+
if isinstance(num_items_in_batch, torch.Tensor):
|
| 1068 |
+
num_items_in_batch = num_items_in_batch.to(jsd_sum.device)
|
| 1069 |
+
return jsd_sum / num_items_in_batch
|
| 1070 |
+
if reduction == "batchmean":
|
| 1071 |
+
# clamp_min(1) avoids 0/0 -> nan when a sample has no unmasked positions
|
| 1072 |
+
# (e.g. completion fully truncated). jsd[mask] is empty -> jsd.sum() == 0,
|
| 1073 |
+
# so 0/1 == 0 with a valid grad path.
|
| 1074 |
+
denom = mask.sum().clamp_min(1) if labels is not None else max(jsd.size(0), 1)
|
| 1075 |
+
return jsd.sum() / denom
|
| 1076 |
+
elif reduction == "sum":
|
| 1077 |
+
return jsd.sum()
|
| 1078 |
+
elif reduction == "mean":
|
| 1079 |
+
return jsd.mean()
|
| 1080 |
+
else:
|
| 1081 |
+
return jsd
|
| 1082 |
+
|
| 1083 |
+
@staticmethod
|
| 1084 |
+
def generalized_jsd_loss(
|
| 1085 |
+
student_logits,
|
| 1086 |
+
teacher_logits,
|
| 1087 |
+
labels=None,
|
| 1088 |
+
beta=0.5,
|
| 1089 |
+
temperature=1.0,
|
| 1090 |
+
reduction="batchmean",
|
| 1091 |
+
top_k=0,
|
| 1092 |
+
add_tail=True,
|
| 1093 |
+
num_items_in_batch=None,
|
| 1094 |
+
):
|
| 1095 |
+
"""
|
| 1096 |
+
Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation.
|
| 1097 |
+
|
| 1098 |
+
Args:
|
| 1099 |
+
student_logits: Tensor of shape (batch_size, sequence_length, vocab_size).
|
| 1100 |
+
teacher_logits: Tensor of shape (batch_size, sequence_length, vocab_size).
|
| 1101 |
+
labels: Tensor of shape (batch_size, sequence_length) with -100 for positions to ignore.
|
| 1102 |
+
beta: Interpolation coefficient. 0.0 = forward KL, 1.0 = reverse KL.
|
| 1103 |
+
temperature: Softmax temperature.
|
| 1104 |
+
reduction: 'batchmean', 'sum', 'mean', or 'none'.
|
| 1105 |
+
top_k: Number of top tokens to restrict the loss to. The support set depends on beta:
|
| 1106 |
+
beta=0 (forward KL) uses teacher's top-k, beta=1 (reverse KL) uses student's top-k, 0<beta<1 (JSD) uses
|
| 1107 |
+
the union of both. Distributions are re-normalized over the selected support. If 0, the full vocabulary
|
| 1108 |
+
is used.
|
| 1109 |
+
add_tail: Whether to append a tail bucket representing the remaining probability mass
|
| 1110 |
+
outside the selected top-k support.
|
| 1111 |
+
|
| 1112 |
+
Returns:
|
| 1113 |
+
Scalar loss tensor.
|
| 1114 |
+
"""
|
| 1115 |
+
student_logits = student_logits / temperature
|
| 1116 |
+
teacher_logits = teacher_logits / temperature
|
| 1117 |
+
|
| 1118 |
+
support_mask = None
|
| 1119 |
+
|
| 1120 |
+
if top_k > 0 and student_logits.size(-1) > top_k:
|
| 1121 |
+
neg_inf = torch.full((), float("-inf"), dtype=student_logits.dtype, device=student_logits.device)
|
| 1122 |
+
student_log_probs_full = F.log_softmax(student_logits, dim=-1)
|
| 1123 |
+
teacher_log_probs_full = F.log_softmax(teacher_logits, dim=-1)
|
| 1124 |
+
|
| 1125 |
+
if beta == 0:
|
| 1126 |
+
# Forward KL: teacher-selected support
|
| 1127 |
+
_, support = teacher_logits.topk(top_k, dim=-1)
|
| 1128 |
+
support_mask = torch.ones_like(support, dtype=torch.bool)
|
| 1129 |
+
elif beta == 1:
|
| 1130 |
+
# Reverse KL: student-selected support
|
| 1131 |
+
_, support = student_logits.topk(top_k, dim=-1)
|
| 1132 |
+
support_mask = torch.ones_like(support, dtype=torch.bool)
|
| 1133 |
+
else:
|
| 1134 |
+
# JSD: union of both supports (concatenate + deduplicate)
|
| 1135 |
+
_, student_top = student_logits.topk(top_k, dim=-1)
|
| 1136 |
+
_, teacher_top = teacher_logits.topk(top_k, dim=-1)
|
| 1137 |
+
support = torch.cat([teacher_top, student_top], dim=-1)
|
| 1138 |
+
support_mask = torch.ones(support.shape, dtype=torch.bool, device=support.device)
|
| 1139 |
+
for i in range(1, support.shape[-1]):
|
| 1140 |
+
prev_matches = support[..., i : i + 1] == support[..., :i]
|
| 1141 |
+
prev_valid = support_mask[..., :i]
|
| 1142 |
+
support_mask[..., i] &= ~(prev_matches & prev_valid).any(dim=-1)
|
| 1143 |
+
support = torch.where(support_mask, support, torch.zeros_like(support))
|
| 1144 |
+
|
| 1145 |
+
student_support_logps = student_log_probs_full.gather(-1, support)
|
| 1146 |
+
teacher_support_logps = teacher_log_probs_full.gather(-1, support)
|
| 1147 |
+
|
| 1148 |
+
# Mask invalid (duplicate) positions with -inf
|
| 1149 |
+
student_topk_logps = torch.where(support_mask, student_support_logps, neg_inf)
|
| 1150 |
+
teacher_topk_logps = torch.where(support_mask, teacher_support_logps, neg_inf)
|
| 1151 |
+
|
| 1152 |
+
if add_tail:
|
| 1153 |
+
# Add tail bucket: append log(1 - sum(exp(top_k_logps))) to preserve
|
| 1154 |
+
# the remaining probability mass outside the top-k. This prevents trivial
|
| 1155 |
+
# zero loss when top_k is small (especially top_k=1).
|
| 1156 |
+
base_support_mask = support_mask
|
| 1157 |
+
student_log_probs, support_mask = _add_tail_bucket(student_topk_logps, base_support_mask)
|
| 1158 |
+
teacher_log_probs, _ = _add_tail_bucket(teacher_topk_logps, base_support_mask)
|
| 1159 |
+
else:
|
| 1160 |
+
student_log_probs = student_topk_logps - torch.logsumexp(student_topk_logps, dim=-1, keepdim=True)
|
| 1161 |
+
teacher_log_probs = teacher_topk_logps - torch.logsumexp(teacher_topk_logps, dim=-1, keepdim=True)
|
| 1162 |
+
else:
|
| 1163 |
+
student_log_probs = F.log_softmax(student_logits, dim=-1)
|
| 1164 |
+
teacher_log_probs = F.log_softmax(teacher_logits, dim=-1)
|
| 1165 |
+
|
| 1166 |
+
jsd = _jsd_divergence(student_log_probs, teacher_log_probs, beta, support_mask)
|
| 1167 |
+
return DistillationTrainer._reduce_divergence_loss(
|
| 1168 |
+
jsd, labels=labels, reduction=reduction, num_items_in_batch=num_items_in_batch
|
| 1169 |
+
)
|
| 1170 |
+
|
| 1171 |
+
def _get_reverse_kl_top_1_tokens(
|
| 1172 |
+
self, student_scores: torch.Tensor, completion_tokens: torch.Tensor
|
| 1173 |
+
) -> torch.Tensor:
|
| 1174 |
+
"""Return the reverse-KL top-1 token IDs for the mixed top-1 loss path.
|
| 1175 |
+
|
| 1176 |
+
Args:
|
| 1177 |
+
student_scores: Any (B, T, V) tensor whose argmax selects the student's top token
|
| 1178 |
+
(logits or log-probs — both are order-preserving).
|
| 1179 |
+
completion_tokens: (B, T) actual token IDs in the completion.
|
| 1180 |
+
"""
|
| 1181 |
+
if self.reverse_kl_top_1_mode == "argmax":
|
| 1182 |
+
return student_scores.argmax(dim=-1)
|
| 1183 |
+
return completion_tokens
|
| 1184 |
+
|
| 1185 |
+
def _compute_sparse_top_1_divergence_loss(
|
| 1186 |
+
self,
|
| 1187 |
+
student_log_probs: torch.Tensor,
|
| 1188 |
+
teacher_top1_token_ids: torch.Tensor,
|
| 1189 |
+
teacher_top1_logprobs: torch.Tensor,
|
| 1190 |
+
reverse_token_ids: torch.Tensor,
|
| 1191 |
+
reverse_teacher_logprobs: torch.Tensor,
|
| 1192 |
+
labels: torch.Tensor,
|
| 1193 |
+
num_items_in_batch=None,
|
| 1194 |
+
) -> torch.Tensor:
|
| 1195 |
+
"""Compute exact generalized JSD/KL on top-1 support for the mixed beta>0 path."""
|
| 1196 |
+
neg_inf = torch.full((), float("-inf"), dtype=student_log_probs.dtype, device=student_log_probs.device)
|
| 1197 |
+
|
| 1198 |
+
if self.beta == 1:
|
| 1199 |
+
support = reverse_token_ids.unsqueeze(-1)
|
| 1200 |
+
support_mask = torch.ones_like(support, dtype=torch.bool)
|
| 1201 |
+
teacher_support_logprobs = reverse_teacher_logprobs.unsqueeze(-1)
|
| 1202 |
+
else:
|
| 1203 |
+
teacher_support = teacher_top1_token_ids.unsqueeze(-1)
|
| 1204 |
+
reverse_support = reverse_token_ids.unsqueeze(-1)
|
| 1205 |
+
support = torch.cat([teacher_support, reverse_support], dim=-1)
|
| 1206 |
+
support_mask = torch.ones_like(support, dtype=torch.bool)
|
| 1207 |
+
support_mask[..., 1] = support[..., 1] != support[..., 0]
|
| 1208 |
+
teacher_support_logprobs = torch.stack([teacher_top1_logprobs, reverse_teacher_logprobs], dim=-1)
|
| 1209 |
+
support = torch.where(support_mask, support, torch.zeros_like(support))
|
| 1210 |
+
|
| 1211 |
+
student_support_logprobs = student_log_probs.gather(-1, support)
|
| 1212 |
+
student_support_logprobs = torch.where(support_mask, student_support_logprobs, neg_inf)
|
| 1213 |
+
teacher_support_logprobs = torch.where(support_mask, teacher_support_logprobs, neg_inf)
|
| 1214 |
+
|
| 1215 |
+
if self.loss_add_tail:
|
| 1216 |
+
base_support_mask = support_mask
|
| 1217 |
+
student_sparse_log_probs, support_mask = _add_tail_bucket(student_support_logprobs, base_support_mask)
|
| 1218 |
+
teacher_sparse_log_probs, _ = _add_tail_bucket(teacher_support_logprobs, base_support_mask)
|
| 1219 |
+
else:
|
| 1220 |
+
student_sparse_log_probs = student_support_logprobs - torch.logsumexp(
|
| 1221 |
+
student_support_logprobs, dim=-1, keepdim=True
|
| 1222 |
+
)
|
| 1223 |
+
teacher_sparse_log_probs = teacher_support_logprobs - torch.logsumexp(
|
| 1224 |
+
teacher_support_logprobs, dim=-1, keepdim=True
|
| 1225 |
+
)
|
| 1226 |
+
|
| 1227 |
+
jsd = _jsd_divergence(student_sparse_log_probs, teacher_sparse_log_probs, self.beta, support_mask)
|
| 1228 |
+
return self._reduce_divergence_loss(
|
| 1229 |
+
jsd, labels=labels, reduction="batchmean", num_items_in_batch=num_items_in_batch
|
| 1230 |
+
)
|
| 1231 |
+
|
| 1232 |
+
def _compute_local_sparse_top_1_divergence_loss(
|
| 1233 |
+
self,
|
| 1234 |
+
student_logits: torch.Tensor,
|
| 1235 |
+
teacher_logits: torch.Tensor,
|
| 1236 |
+
completion_tokens: torch.Tensor,
|
| 1237 |
+
labels: torch.Tensor,
|
| 1238 |
+
num_items_in_batch=None,
|
| 1239 |
+
) -> torch.Tensor:
|
| 1240 |
+
"""Compute the mixed top-1 loss for a local teacher using gathered full-logit probabilities."""
|
| 1241 |
+
student_log_probs = F.log_softmax(student_logits / self.temperature, dim=-1)
|
| 1242 |
+
teacher_log_probs = F.log_softmax(teacher_logits / self.temperature, dim=-1)
|
| 1243 |
+
|
| 1244 |
+
teacher_top1_token_ids = teacher_logits.argmax(dim=-1)
|
| 1245 |
+
teacher_top1_logprobs = teacher_log_probs.gather(dim=-1, index=teacher_top1_token_ids.unsqueeze(-1)).squeeze(
|
| 1246 |
+
-1
|
| 1247 |
+
)
|
| 1248 |
+
reverse_token_ids = self._get_reverse_kl_top_1_tokens(student_logits, completion_tokens)
|
| 1249 |
+
reverse_teacher_logprobs = teacher_log_probs.gather(dim=-1, index=reverse_token_ids.unsqueeze(-1)).squeeze(-1)
|
| 1250 |
+
|
| 1251 |
+
return self._compute_sparse_top_1_divergence_loss(
|
| 1252 |
+
student_log_probs=student_log_probs,
|
| 1253 |
+
teacher_top1_token_ids=teacher_top1_token_ids,
|
| 1254 |
+
teacher_top1_logprobs=teacher_top1_logprobs,
|
| 1255 |
+
reverse_token_ids=reverse_token_ids,
|
| 1256 |
+
reverse_teacher_logprobs=reverse_teacher_logprobs,
|
| 1257 |
+
labels=labels,
|
| 1258 |
+
num_items_in_batch=num_items_in_batch,
|
| 1259 |
+
)
|
| 1260 |
+
|
| 1261 |
+
def _get_teacher_logits(self, inputs: dict[str, torch.Tensor | Any]) -> torch.Tensor:
|
| 1262 |
+
"""Get teacher logits — dispatches between local model and external server."""
|
| 1263 |
+
if self.teacher_model is not None:
|
| 1264 |
+
self.teacher_model.eval()
|
| 1265 |
+
with torch.no_grad():
|
| 1266 |
+
return self.teacher_model(
|
| 1267 |
+
input_ids=inputs["input_ids"],
|
| 1268 |
+
attention_mask=inputs["attention_mask"],
|
| 1269 |
+
).logits
|
| 1270 |
+
elif self.use_teacher_server:
|
| 1271 |
+
raise NotImplementedError(
|
| 1272 |
+
"Fetching full teacher logits with use_teacher_server=True is not supported. "
|
| 1273 |
+
"Server-backed distillation only supports per-token logprobs via "
|
| 1274 |
+
"`_get_teacher_token_logprobs_from_server`."
|
| 1275 |
+
)
|
| 1276 |
+
else:
|
| 1277 |
+
raise ValueError("No teacher model or teacher server configured.")
|
| 1278 |
+
|
| 1279 |
+
def _get_teacher_token_logprobs_from_server(
|
| 1280 |
+
self,
|
| 1281 |
+
inputs: dict[str, torch.Tensor | Any],
|
| 1282 |
+
aligned_prompt_length: int,
|
| 1283 |
+
) -> dict[str, torch.Tensor]:
|
| 1284 |
+
"""Fetch per-token teacher logprobs from an external vLLM server.
|
| 1285 |
+
|
| 1286 |
+
Returns a dict with:
|
| 1287 |
+
``actual_logprobs`` – (batch, completion_length) teacher log-prob for the actual
|
| 1288 |
+
token at each position (for reverse KL).
|
| 1289 |
+
``topk_logprobs`` – (batch, completion_length, K) teacher top-k sorted logprobs
|
| 1290 |
+
(for forward KL).
|
| 1291 |
+
``topk_token_ids`` – (batch, completion_length, K) corresponding token IDs.
|
| 1292 |
+
"""
|
| 1293 |
+
import numpy as np
|
| 1294 |
+
|
| 1295 |
+
input_ids = inputs["input_ids"]
|
| 1296 |
+
batch_size = input_ids.shape[0]
|
| 1297 |
+
sequences, prompt_lengths, completion_lengths = build_teacher_request_inputs(
|
| 1298 |
+
input_ids,
|
| 1299 |
+
inputs["attention_mask"],
|
| 1300 |
+
prompt_attention_mask=inputs.get("prompt_attention_mask"),
|
| 1301 |
+
labels=inputs.get("labels"),
|
| 1302 |
+
)
|
| 1303 |
+
|
| 1304 |
+
# The pure forward server path can use the requested teacher top-k support.
|
| 1305 |
+
# When beta > 0, config validation restricts the server-backed path to top-1.
|
| 1306 |
+
requested_top_k = self.loss_top_k
|
| 1307 |
+
result = self.teacher_client.get_sequence_logprobs(
|
| 1308 |
+
sequences=sequences,
|
| 1309 |
+
prompt_lengths=prompt_lengths,
|
| 1310 |
+
top_logprobs=requested_top_k,
|
| 1311 |
+
temperature=self.temperature,
|
| 1312 |
+
)
|
| 1313 |
+
K = requested_top_k
|
| 1314 |
+
|
| 1315 |
+
device = input_ids.device
|
| 1316 |
+
labels = inputs.get("labels")
|
| 1317 |
+
if labels is None:
|
| 1318 |
+
raise ValueError("labels are required to align teacher-server logprobs with the student loss tensors.")
|
| 1319 |
+
|
| 1320 |
+
# The student loss slices tensors in padded-sequence coordinates starting at `aligned_prompt_length`.
|
| 1321 |
+
# Place each teacher completion into that same coordinate system by locating the first non-masked completion
|
| 1322 |
+
# token in `labels`. This works for both left-padded off-policy batches and on-policy batches where
|
| 1323 |
+
# completions are right-padded after a fixed-width prompt block.
|
| 1324 |
+
completion_offsets = []
|
| 1325 |
+
label_mask = labels != -100
|
| 1326 |
+
for sample_mask, comp_len in zip(label_mask, completion_lengths, strict=True):
|
| 1327 |
+
if comp_len == 0:
|
| 1328 |
+
completion_offsets.append(0)
|
| 1329 |
+
continue
|
| 1330 |
+
completion_start = int(torch.nonzero(sample_mask, as_tuple=False)[0].item())
|
| 1331 |
+
completion_offsets.append(completion_start - aligned_prompt_length)
|
| 1332 |
+
|
| 1333 |
+
# Size the output tensors to tightly fit the teacher logprobs. Using the full padded
|
| 1334 |
+
# sequence length would include padding positions with -inf teacher logprobs, producing
|
| 1335 |
+
# +inf in the forward pass and NaN gradients in the backward pass (0 * inf = NaN).
|
| 1336 |
+
# Shorter samples in variable-length batches still need the -inf sentinel at the tail;
|
| 1337 |
+
# downstream loss consumers (_compute_server_sparse_top_1_divergence_loss,
|
| 1338 |
+
# _compute_server_forward_kl_loss) neutralise those positions before the divergence
|
| 1339 |
+
# math runs.
|
| 1340 |
+
completion_length = max(
|
| 1341 |
+
(offset + len(lps) for offset, lps in zip(completion_offsets, result["logprobs"], strict=True)),
|
| 1342 |
+
default=0,
|
| 1343 |
+
)
|
| 1344 |
+
|
| 1345 |
+
# actual_logprobs: (B, T) — teacher logprob for the actual token
|
| 1346 |
+
def _actual_to_tensor(key):
|
| 1347 |
+
arr = np.full((batch_size, completion_length), float("-inf"), dtype=np.float32)
|
| 1348 |
+
for i, (offset, seq_lps) in enumerate(zip(completion_offsets, result[key], strict=True)):
|
| 1349 |
+
if seq_lps:
|
| 1350 |
+
vals = np.array(seq_lps, dtype=np.float32) # (comp_len_i, 1)
|
| 1351 |
+
arr[i, offset : offset + vals.shape[0]] = vals[:, 0]
|
| 1352 |
+
return torch.from_numpy(arr).to(device)
|
| 1353 |
+
|
| 1354 |
+
# topk: (B, T, K)
|
| 1355 |
+
def _topk_to_tensor(key, k, np_dtype, fill):
|
| 1356 |
+
arr = np.full((batch_size, completion_length, k), fill, dtype=np_dtype)
|
| 1357 |
+
for i, (offset, seq_vals) in enumerate(zip(completion_offsets, result[key], strict=True)):
|
| 1358 |
+
if seq_vals:
|
| 1359 |
+
vals = np.array(seq_vals, dtype=np_dtype) # (comp_len_i, k)
|
| 1360 |
+
arr[i, offset : offset + vals.shape[0], :] = vals
|
| 1361 |
+
return torch.from_numpy(arr).to(device)
|
| 1362 |
+
|
| 1363 |
+
return {
|
| 1364 |
+
"actual_logprobs": _actual_to_tensor("actual_logprobs"),
|
| 1365 |
+
"topk_logprobs": _topk_to_tensor("logprobs", K, np.float32, float("-inf")),
|
| 1366 |
+
"topk_token_ids": _topk_to_tensor("logprob_token_ids", K, np.int64, 0),
|
| 1367 |
+
}
|
| 1368 |
+
|
| 1369 |
+
def _compute_server_sparse_top_1_divergence_loss(
|
| 1370 |
+
self,
|
| 1371 |
+
teacher_result: dict[str, torch.Tensor],
|
| 1372 |
+
student_log_probs: torch.Tensor,
|
| 1373 |
+
completion_tokens: torch.Tensor,
|
| 1374 |
+
labels: torch.Tensor,
|
| 1375 |
+
) -> torch.Tensor:
|
| 1376 |
+
"""Compute exact sparse top-1 generalized JSD/KL from server-provided teacher logprobs.
|
| 1377 |
+
|
| 1378 |
+
Args:
|
| 1379 |
+
teacher_result: dict with ``actual_logprobs`` (B, T), ``topk_logprobs`` (B, T, K),
|
| 1380 |
+
``topk_token_ids`` (B, T, K).
|
| 1381 |
+
student_log_probs: (B, T, V) student log-softmax over vocabulary.
|
| 1382 |
+
completion_tokens: (B, T) actual token IDs in the completion.
|
| 1383 |
+
labels: (B, T) with -100 for positions to ignore.
|
| 1384 |
+
"""
|
| 1385 |
+
topk_teacher_lps = teacher_result["topk_logprobs"] # (B, T, 1)
|
| 1386 |
+
topk_token_ids = teacher_result["topk_token_ids"] # (B, T, 1)
|
| 1387 |
+
actual_teacher_lps = teacher_result["actual_logprobs"] # (B, T)
|
| 1388 |
+
required = labels != -100
|
| 1389 |
+
|
| 1390 |
+
missing_actual = required & ~torch.isfinite(actual_teacher_lps)
|
| 1391 |
+
if missing_actual.any():
|
| 1392 |
+
missing_count = int(missing_actual.sum().item())
|
| 1393 |
+
total_required = int(required.sum().item())
|
| 1394 |
+
raise ValueError(
|
| 1395 |
+
"Teacher server is missing actual-token logprobs for required reverse-KL positions: "
|
| 1396 |
+
f"{missing_count}/{total_required}."
|
| 1397 |
+
)
|
| 1398 |
+
if self.beta < 1:
|
| 1399 |
+
teacher_top1_logprobs = topk_teacher_lps.squeeze(-1)
|
| 1400 |
+
missing_top1 = required & ~torch.isfinite(teacher_top1_logprobs)
|
| 1401 |
+
if missing_top1.any():
|
| 1402 |
+
missing_count = int(missing_top1.sum().item())
|
| 1403 |
+
total_required = int(required.sum().item())
|
| 1404 |
+
raise ValueError(
|
| 1405 |
+
"Teacher server is missing top-1 logprobs for required forward-KL positions: "
|
| 1406 |
+
f"{missing_count}/{total_required}."
|
| 1407 |
+
)
|
| 1408 |
+
|
| 1409 |
+
# Replace -inf teacher logprobs at intra-batch padding (labels == -100) with 0 so
|
| 1410 |
+
# reverse-KL's student_probs·(log_s - log_t) does not leak +inf into the backward pass.
|
| 1411 |
+
pad_mask_2d = ~required
|
| 1412 |
+
pad_mask_3d = pad_mask_2d.unsqueeze(-1)
|
| 1413 |
+
topk_teacher_lps = torch.where(pad_mask_3d, 0.0, topk_teacher_lps)
|
| 1414 |
+
actual_teacher_lps = torch.where(pad_mask_2d, 0.0, actual_teacher_lps)
|
| 1415 |
+
|
| 1416 |
+
# Server path only supports "sampled" mode — config validation enforces this, but we guard
|
| 1417 |
+
# explicitly so future relaxations of the config check don't silently change behaviour.
|
| 1418 |
+
reverse_token_ids = self._get_reverse_kl_top_1_tokens(student_log_probs, completion_tokens)
|
| 1419 |
+
# The server path normalizes locally (batchmean), not by num_items_in_batch: teacher logprobs may not cover
|
| 1420 |
+
# every student completion token (the loss is summed over the trimmed teacher window), so the global token
|
| 1421 |
+
# count would be the wrong denominator. Gradient-accumulation normalization for the server path is left as a
|
| 1422 |
+
# follow-up.
|
| 1423 |
+
return self._compute_sparse_top_1_divergence_loss(
|
| 1424 |
+
student_log_probs=student_log_probs,
|
| 1425 |
+
teacher_top1_token_ids=topk_token_ids.squeeze(-1),
|
| 1426 |
+
teacher_top1_logprobs=topk_teacher_lps.squeeze(-1),
|
| 1427 |
+
reverse_token_ids=reverse_token_ids,
|
| 1428 |
+
reverse_teacher_logprobs=actual_teacher_lps,
|
| 1429 |
+
labels=labels,
|
| 1430 |
+
)
|
| 1431 |
+
|
| 1432 |
+
def _compute_server_forward_kl_loss(
|
| 1433 |
+
self,
|
| 1434 |
+
teacher_result: dict[str, torch.Tensor],
|
| 1435 |
+
student_log_probs: torch.Tensor,
|
| 1436 |
+
labels: torch.Tensor,
|
| 1437 |
+
) -> torch.Tensor:
|
| 1438 |
+
"""Compute sparse forward KL from server-provided teacher top-k logprobs (beta==0 path).
|
| 1439 |
+
|
| 1440 |
+
Args:
|
| 1441 |
+
teacher_result: dict with ``topk_logprobs`` (B, T, K) and ``topk_token_ids`` (B, T, K).
|
| 1442 |
+
student_log_probs: (B, T, V) student log-softmax over vocabulary.
|
| 1443 |
+
labels: (B, T) with -100 for positions to ignore.
|
| 1444 |
+
"""
|
| 1445 |
+
teacher_topk_logprobs = teacher_result["topk_logprobs"]
|
| 1446 |
+
teacher_topk_token_ids = teacher_result["topk_token_ids"]
|
| 1447 |
+
valid = teacher_topk_logprobs > float("-inf")
|
| 1448 |
+
neg_inf = torch.full((), float("-inf"), dtype=student_log_probs.dtype, device=student_log_probs.device)
|
| 1449 |
+
student_topk_logprobs = student_log_probs.gather(dim=-1, index=teacher_topk_token_ids)
|
| 1450 |
+
student_topk_logprobs = torch.where(valid, student_topk_logprobs, neg_inf)
|
| 1451 |
+
teacher_topk_logprobs = torch.where(valid, teacher_topk_logprobs, neg_inf)
|
| 1452 |
+
|
| 1453 |
+
if self.loss_add_tail:
|
| 1454 |
+
base_support_mask = valid
|
| 1455 |
+
student_sparse_log_probs, support_mask = _add_tail_bucket(student_topk_logprobs, base_support_mask)
|
| 1456 |
+
teacher_sparse_log_probs, _ = _add_tail_bucket(teacher_topk_logprobs, base_support_mask)
|
| 1457 |
+
else:
|
| 1458 |
+
support_mask = valid
|
| 1459 |
+
student_sparse_log_probs = student_topk_logprobs - torch.logsumexp(
|
| 1460 |
+
student_topk_logprobs, dim=-1, keepdim=True
|
| 1461 |
+
)
|
| 1462 |
+
teacher_sparse_log_probs = teacher_topk_logprobs - torch.logsumexp(
|
| 1463 |
+
teacher_topk_logprobs, dim=-1, keepdim=True
|
| 1464 |
+
)
|
| 1465 |
+
|
| 1466 |
+
jsd = _jsd_divergence(
|
| 1467 |
+
student_sparse_log_probs,
|
| 1468 |
+
teacher_sparse_log_probs,
|
| 1469 |
+
beta=0.0,
|
| 1470 |
+
support_mask=support_mask,
|
| 1471 |
+
)
|
| 1472 |
+
# See `_compute_server_sparse_top_1_divergence_loss`: the server path normalizes locally, not by
|
| 1473 |
+
# num_items_in_batch, because the teacher window may not cover every student completion token.
|
| 1474 |
+
return self._reduce_divergence_loss(jsd, labels=labels, reduction="batchmean")
|
| 1475 |
+
|
| 1476 |
+
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 1477 |
+
self._raise_if_local_teacher_tokenizer_mismatch()
|
| 1478 |
+
|
| 1479 |
+
if self.use_liger_loss:
|
| 1480 |
+
loss = self._compute_liger_loss(model, inputs, num_items_in_batch=num_items_in_batch)
|
| 1481 |
+
return (loss, None) if return_outputs else loss
|
| 1482 |
+
|
| 1483 |
+
# Student forward pass
|
| 1484 |
+
student_outputs = model(
|
| 1485 |
+
input_ids=inputs["input_ids"],
|
| 1486 |
+
attention_mask=inputs["attention_mask"],
|
| 1487 |
+
)
|
| 1488 |
+
prompt_length = self._compute_prompt_length(inputs)
|
| 1489 |
+
labels = inputs["labels"][:, prompt_length:]
|
| 1490 |
+
completion_tokens = inputs["input_ids"][:, prompt_length:]
|
| 1491 |
+
|
| 1492 |
+
if self.use_teacher_server:
|
| 1493 |
+
# Server path: token-level divergence using teacher logprobs.
|
| 1494 |
+
# The server returns:
|
| 1495 |
+
# actual_logprobs – (B, T) teacher log p(x_actual) (for reverse KL)
|
| 1496 |
+
# topk_logprobs – (B, T, K) teacher top-k sorted logprobs (for forward KL)
|
| 1497 |
+
# topk_token_ids – (B, T, K) corresponding token IDs
|
| 1498 |
+
teacher_result = self._get_teacher_token_logprobs_from_server(inputs, prompt_length)
|
| 1499 |
+
|
| 1500 |
+
student_logits = student_outputs.logits[:, prompt_length - 1 : -1, :]
|
| 1501 |
+
student_log_probs = F.log_softmax(student_logits / self.temperature, dim=-1)
|
| 1502 |
+
|
| 1503 |
+
comp_len = teacher_result["actual_logprobs"].shape[1]
|
| 1504 |
+
completion_tokens = completion_tokens[:, :comp_len]
|
| 1505 |
+
trimmed_labels = labels[:, :comp_len]
|
| 1506 |
+
|
| 1507 |
+
if self.beta > 0:
|
| 1508 |
+
loss = self._compute_server_sparse_top_1_divergence_loss(
|
| 1509 |
+
teacher_result=teacher_result,
|
| 1510 |
+
student_log_probs=student_log_probs[:, :comp_len, :],
|
| 1511 |
+
completion_tokens=completion_tokens,
|
| 1512 |
+
labels=trimmed_labels,
|
| 1513 |
+
)
|
| 1514 |
+
else:
|
| 1515 |
+
loss = self._compute_server_forward_kl_loss(
|
| 1516 |
+
teacher_result=teacher_result,
|
| 1517 |
+
student_log_probs=student_log_probs[:, :comp_len, :],
|
| 1518 |
+
labels=trimmed_labels,
|
| 1519 |
+
)
|
| 1520 |
+
else:
|
| 1521 |
+
# Local teacher: exact full-vocabulary loss except for the shared mixed top-1 path.
|
| 1522 |
+
teacher_logits = self._get_teacher_logits(inputs)
|
| 1523 |
+
student_logits = student_outputs.logits[:, prompt_length - 1 : -1, :]
|
| 1524 |
+
teacher_logits = teacher_logits[:, prompt_length - 1 : -1, :]
|
| 1525 |
+
if self.beta > 0 and self.loss_top_k == 1:
|
| 1526 |
+
loss = self._compute_local_sparse_top_1_divergence_loss(
|
| 1527 |
+
student_logits=student_logits,
|
| 1528 |
+
teacher_logits=teacher_logits,
|
| 1529 |
+
completion_tokens=completion_tokens,
|
| 1530 |
+
labels=labels,
|
| 1531 |
+
num_items_in_batch=num_items_in_batch,
|
| 1532 |
+
)
|
| 1533 |
+
else:
|
| 1534 |
+
loss = self.generalized_jsd_loss(
|
| 1535 |
+
student_logits=student_logits,
|
| 1536 |
+
teacher_logits=teacher_logits,
|
| 1537 |
+
labels=labels,
|
| 1538 |
+
beta=self.beta,
|
| 1539 |
+
temperature=self.temperature,
|
| 1540 |
+
top_k=self.loss_top_k,
|
| 1541 |
+
add_tail=self.loss_add_tail,
|
| 1542 |
+
num_items_in_batch=num_items_in_batch,
|
| 1543 |
+
)
|
| 1544 |
+
|
| 1545 |
+
return (loss, student_outputs) if return_outputs else loss
|
| 1546 |
+
|
| 1547 |
+
def _liger_student_forward(self, student, inputs):
|
| 1548 |
+
"""Decoder-only forward used by the Liger JSD path (skips lm_head to save memory)."""
|
| 1549 |
+
if hasattr(student, "get_decoder") and student.get_decoder() is not None:
|
| 1550 |
+
decoder = student.get_decoder()
|
| 1551 |
+
else:
|
| 1552 |
+
decoder = getattr(student, getattr(student, "base_model_prefix", "model"), student)
|
| 1553 |
+
return decoder(
|
| 1554 |
+
input_ids=inputs["input_ids"],
|
| 1555 |
+
attention_mask=inputs["attention_mask"],
|
| 1556 |
+
use_cache=False,
|
| 1557 |
+
)
|
| 1558 |
+
|
| 1559 |
+
def _compute_liger_loss(self, model, inputs, num_items_in_batch=None):
|
| 1560 |
+
"""Memory-efficient JSD using Liger kernel (operates on hidden states, not full logits)."""
|
| 1561 |
+
# Route through the DDP/FSDP wrapper via _forward_redirection so that
|
| 1562 |
+
# DDP.forward() is called and prepare_for_backward() fires correctly.
|
| 1563 |
+
unwrapped_student = self.accelerator.unwrap_model(model)
|
| 1564 |
+
student_outputs = self._forward_redirection(
|
| 1565 |
+
model, unwrapped_student, self._liger_student_forward, unwrapped_student, inputs
|
| 1566 |
+
)
|
| 1567 |
+
|
| 1568 |
+
self.teacher_model.eval()
|
| 1569 |
+
unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model)
|
| 1570 |
+
if hasattr(unwrapped_teacher, "get_decoder") and unwrapped_teacher.get_decoder() is not None:
|
| 1571 |
+
base_teacher = unwrapped_teacher.get_decoder()
|
| 1572 |
+
else:
|
| 1573 |
+
base_teacher = getattr(
|
| 1574 |
+
unwrapped_teacher, getattr(unwrapped_teacher, "base_model_prefix", "model"), unwrapped_teacher
|
| 1575 |
+
)
|
| 1576 |
+
with torch.no_grad():
|
| 1577 |
+
teacher_outputs = base_teacher(
|
| 1578 |
+
input_ids=inputs["input_ids"],
|
| 1579 |
+
attention_mask=inputs["attention_mask"],
|
| 1580 |
+
use_cache=False,
|
| 1581 |
+
)
|
| 1582 |
+
|
| 1583 |
+
student_hidden = student_outputs.last_hidden_state[:, :-1]
|
| 1584 |
+
teacher_hidden = teacher_outputs.last_hidden_state[:, :-1]
|
| 1585 |
+
del student_outputs, teacher_outputs
|
| 1586 |
+
|
| 1587 |
+
student_hidden = student_hidden.reshape(-1, student_hidden.shape[-1])
|
| 1588 |
+
teacher_hidden = teacher_hidden.reshape(-1, teacher_hidden.shape[-1])
|
| 1589 |
+
|
| 1590 |
+
labels_mask = inputs["labels"] != -100
|
| 1591 |
+
masked_input_ids = torch.where(labels_mask, inputs["input_ids"], torch.full_like(inputs["input_ids"], -100))
|
| 1592 |
+
true_labels = masked_input_ids[:, 1:].reshape(-1)
|
| 1593 |
+
|
| 1594 |
+
student_head = unwrapped_student.get_output_embeddings()
|
| 1595 |
+
teacher_head = unwrapped_teacher.get_output_embeddings()
|
| 1596 |
+
|
| 1597 |
+
loss = self.liger_jsd_loss(
|
| 1598 |
+
student_input=student_hidden,
|
| 1599 |
+
student_weight=student_head.weight,
|
| 1600 |
+
teacher_input=teacher_hidden,
|
| 1601 |
+
teacher_weight=teacher_head.weight,
|
| 1602 |
+
true_labels=true_labels,
|
| 1603 |
+
student_bias=getattr(student_head, "bias", None),
|
| 1604 |
+
teacher_bias=getattr(teacher_head, "bias", None),
|
| 1605 |
+
)
|
| 1606 |
+
|
| 1607 |
+
# The Liger JSD loss normalizes by the local number of valid tokens. Under gradient accumulation we want
|
| 1608 |
+
# the global normalization, so rescale by `num_valid_local / num_items_in_batch`.
|
| 1609 |
+
if num_items_in_batch is not None:
|
| 1610 |
+
num_valid_local = (true_labels != -100).sum().clamp_min(1)
|
| 1611 |
+
if isinstance(num_items_in_batch, torch.Tensor):
|
| 1612 |
+
num_items_in_batch = num_items_in_batch.to(loss.device)
|
| 1613 |
+
loss = loss * num_valid_local / num_items_in_batch
|
| 1614 |
+
|
| 1615 |
+
del student_hidden, teacher_hidden, true_labels
|
| 1616 |
+
return loss
|
| 1617 |
+
|
| 1618 |
+
def _get_liger_zero3_lm_head_gather_ctx(self, model: nn.Module):
|
| 1619 |
+
"""Context manager for gathering lm_head parameters under Liger + ZeRO-3."""
|
| 1620 |
+
if not self.use_liger_loss:
|
| 1621 |
+
return nullcontext()
|
| 1622 |
+
|
| 1623 |
+
deepspeed_plugin = self.accelerator.state.deepspeed_plugin
|
| 1624 |
+
if deepspeed_plugin is None or deepspeed_plugin.zero_stage != 3:
|
| 1625 |
+
return nullcontext()
|
| 1626 |
+
|
| 1627 |
+
import deepspeed
|
| 1628 |
+
|
| 1629 |
+
unwrapped_student = self.accelerator.unwrap_model(model)
|
| 1630 |
+
unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model)
|
| 1631 |
+
student_head = unwrapped_student.get_output_embeddings()
|
| 1632 |
+
teacher_head = unwrapped_teacher.get_output_embeddings()
|
| 1633 |
+
params = [student_head.weight, teacher_head.weight]
|
| 1634 |
+
if student_head.bias is not None:
|
| 1635 |
+
params.append(student_head.bias)
|
| 1636 |
+
if teacher_head.bias is not None:
|
| 1637 |
+
params.append(teacher_head.bias)
|
| 1638 |
+
return deepspeed.zero.GatheredParameters(params, modifier_rank=None)
|
| 1639 |
+
|
| 1640 |
+
# ──────────────────────────────────────────────────────────────────────
|
| 1641 |
+
# Training step & Logging
|
| 1642 |
+
# ──────────────────────────────────────────────────────────────────────
|
| 1643 |
+
|
| 1644 |
+
@profiling_decorator
|
| 1645 |
+
def training_step(
|
| 1646 |
+
self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None
|
| 1647 |
+
) -> torch.Tensor:
|
| 1648 |
+
"""Training step with on/off-policy loss tracking and completion stats."""
|
| 1649 |
+
buffer_steps = self.args.gradient_accumulation_steps
|
| 1650 |
+
|
| 1651 |
+
with self._get_liger_zero3_lm_head_gather_ctx(model):
|
| 1652 |
+
loss = super().training_step(model, inputs, num_items_in_batch)
|
| 1653 |
+
|
| 1654 |
+
slice_idx = (self._buffer_step - 1) % buffer_steps
|
| 1655 |
+
|
| 1656 |
+
# Determine if this slice is on-policy
|
| 1657 |
+
is_on_policy = False
|
| 1658 |
+
if self._buffered_on_policy_flags is not None and slice_idx < len(self._buffered_on_policy_flags):
|
| 1659 |
+
is_on_policy = self._buffered_on_policy_flags[slice_idx]
|
| 1660 |
+
|
| 1661 |
+
# Track completion length stats — read from buffered inputs (which reflect on-policy generation)
|
| 1662 |
+
actual_inputs = self._buffered_inputs[slice_idx] if self._buffered_inputs is not None else inputs
|
| 1663 |
+
labels = actual_inputs.get("labels")
|
| 1664 |
+
if labels is not None:
|
| 1665 |
+
completion_lengths = (labels != -100).sum(dim=1).float()
|
| 1666 |
+
gathered_lengths = self.accelerator.gather(completion_lengths)
|
| 1667 |
+
mode = "train"
|
| 1668 |
+
prefix = "on_policy" if is_on_policy else "off_policy"
|
| 1669 |
+
self._metrics[mode][f"completions/{prefix}_mean_length"].append(gathered_lengths.mean().item())
|
| 1670 |
+
self._metrics[mode][f"completions/{prefix}_max_length"].append(gathered_lengths.max().item())
|
| 1671 |
+
self._metrics[mode][f"completions/{prefix}_min_length"].append(gathered_lengths.min().item())
|
| 1672 |
+
|
| 1673 |
+
# Log fraction of completions that hit max_completion_length (truncated)
|
| 1674 |
+
max_comp_len = getattr(self.generation_config, "max_new_tokens", None)
|
| 1675 |
+
if is_on_policy and max_comp_len is not None:
|
| 1676 |
+
truncated_frac = (gathered_lengths >= max_comp_len).float().mean().item()
|
| 1677 |
+
self._metrics[mode]["completions/truncated_fraction"].append(truncated_frac)
|
| 1678 |
+
|
| 1679 |
+
# Track loss per policy type
|
| 1680 |
+
loss_scalar = float(loss.detach())
|
| 1681 |
+
step_equiv = 1.0 / self.args.gradient_accumulation_steps
|
| 1682 |
+
if is_on_policy:
|
| 1683 |
+
self._on_policy_loss_total += loss_scalar
|
| 1684 |
+
self._on_policy_step_equiv += step_equiv
|
| 1685 |
+
else:
|
| 1686 |
+
self._off_policy_loss_total += loss_scalar
|
| 1687 |
+
self._off_policy_step_equiv += step_equiv
|
| 1688 |
+
|
| 1689 |
+
return loss
|
| 1690 |
+
|
| 1691 |
+
def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
|
| 1692 |
+
mode = "train" if self.model.training else "eval"
|
| 1693 |
+
metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()}
|
| 1694 |
+
|
| 1695 |
+
if mode == "train":
|
| 1696 |
+
# Aggregate on/off-policy losses across distributed processes
|
| 1697 |
+
device = self.accelerator.device if hasattr(self.accelerator, "device") else torch.device("cpu")
|
| 1698 |
+
vec = torch.tensor(
|
| 1699 |
+
[
|
| 1700 |
+
self._on_policy_loss_total,
|
| 1701 |
+
self._off_policy_loss_total,
|
| 1702 |
+
self._on_policy_step_equiv,
|
| 1703 |
+
self._off_policy_step_equiv,
|
| 1704 |
+
],
|
| 1705 |
+
dtype=torch.float64,
|
| 1706 |
+
device=device,
|
| 1707 |
+
)
|
| 1708 |
+
|
| 1709 |
+
if (
|
| 1710 |
+
getattr(self.accelerator, "distributed_type", DistributedType.NO) != DistributedType.NO
|
| 1711 |
+
and dist.is_available()
|
| 1712 |
+
and dist.is_initialized()
|
| 1713 |
+
):
|
| 1714 |
+
dist.all_reduce(vec, op=dist.ReduceOp.SUM)
|
| 1715 |
+
|
| 1716 |
+
on_sum, off_sum, on_eq, off_eq = vec.tolist()
|
| 1717 |
+
if on_eq > 0:
|
| 1718 |
+
logs["on_policy_loss"] = round(on_sum / on_eq, 4)
|
| 1719 |
+
if off_eq > 0:
|
| 1720 |
+
logs["off_policy_loss"] = round(off_sum / off_eq, 4)
|
| 1721 |
+
|
| 1722 |
+
self._on_policy_loss_total = self._off_policy_loss_total = 0.0
|
| 1723 |
+
self._on_policy_step_equiv = self._off_policy_step_equiv = 0.0
|
| 1724 |
+
|
| 1725 |
+
if mode == "eval":
|
| 1726 |
+
metrics = {f"eval_{key}": val for key, val in metrics.items()}
|
| 1727 |
+
|
| 1728 |
+
logs.update(metrics)
|
| 1729 |
+
super().log(logs, start_time)
|
| 1730 |
+
self._metrics[mode].clear()
|
| 1731 |
+
|
| 1732 |
+
# Log completions to console, wandb, and trackio
|
| 1733 |
+
should_log_completions = (
|
| 1734 |
+
self.log_completions
|
| 1735 |
+
and self.state.global_step > 0
|
| 1736 |
+
and self.state.global_step % self.log_completions_steps == 0
|
| 1737 |
+
)
|
| 1738 |
+
|
| 1739 |
+
if should_log_completions and self.accelerator.is_main_process:
|
| 1740 |
+
prompts = list(self._textual_logs["prompt"])
|
| 1741 |
+
completions = list(self._textual_logs["completion"])
|
| 1742 |
+
|
| 1743 |
+
if prompts:
|
| 1744 |
+
_print_completions_sample(prompts, completions, self.state.global_step, self.num_completions_to_print)
|
| 1745 |
+
|
| 1746 |
+
logging_backends = []
|
| 1747 |
+
if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None:
|
| 1748 |
+
logging_backends.append(wandb)
|
| 1749 |
+
if self.args.report_to and "trackio" in self.args.report_to:
|
| 1750 |
+
logging_backends.append(trackio)
|
| 1751 |
+
|
| 1752 |
+
if logging_backends:
|
| 1753 |
+
import pandas as pd
|
| 1754 |
+
|
| 1755 |
+
table_data = {
|
| 1756 |
+
"step": [str(self.state.global_step)] * len(prompts),
|
| 1757 |
+
"prompt": prompts,
|
| 1758 |
+
"completion": completions,
|
| 1759 |
+
}
|
| 1760 |
+
df = pd.DataFrame(table_data)
|
| 1761 |
+
if self.num_completions_to_print and len(df) > self.num_completions_to_print:
|
| 1762 |
+
df = df.sample(n=self.num_completions_to_print, random_state=42)
|
| 1763 |
+
|
| 1764 |
+
for logging_backend in logging_backends:
|
| 1765 |
+
logging_backend.log({"completions": logging_backend.Table(dataframe=df)})
|
| 1766 |
+
|
| 1767 |
+
# Clear text logs on all processes after the logging interval
|
| 1768 |
+
if should_log_completions:
|
| 1769 |
+
self._textual_logs["prompt"].clear()
|
| 1770 |
+
self._textual_logs["completion"].clear()
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/dppo/__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 .dppo_config import DPPOConfig
|
| 17 |
+
from .dppo_trainer import DPPOTrainer
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/dppo/dppo_config.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.grpo_config import GRPOConfig
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class DPPOConfig(GRPOConfig):
|
| 23 |
+
"""
|
| 24 |
+
Configuration class for DPPOTrainer.
|
| 25 |
+
|
| 26 |
+
DPPO (Divergence Proximal Policy Optimization) replaces PPO/GRPO's heuristic ratio-clipping with a principled trust
|
| 27 |
+
region based on direct policy divergence estimates.
|
| 28 |
+
|
| 29 |
+
Paper: "Rethinking the Trust Region in LLM Reinforcement Learning" (arXiv:2602.04879)
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
divergence_type (`Literal["binary_tv", "binary_kl", "topk_tv", "topk_kl"]`, *optional*, defaults to `"binary_tv"`):
|
| 33 |
+
Divergence approximation used for the trust-region mask. Binary variants use only per-token log-probs;
|
| 34 |
+
top-K variants require storing top-K token IDs and log-probs during rollout generation plus full logits
|
| 35 |
+
during training.
|
| 36 |
+
|
| 37 |
+
divergence_topk (`int`, *optional*, defaults to `20`):
|
| 38 |
+
K for top-K divergence approximations. Only used when `divergence_type` is `"topk_tv"` or `"topk_kl"`.
|
| 39 |
+
|
| 40 |
+
clip_ratio_c (`float`, *optional*, defaults to `20.0`):
|
| 41 |
+
Upper bound on the importance-sampling ratio for stability. The IS ratio is clamped to [0, clip_ratio_c].
|
| 42 |
+
|
| 43 |
+
epsilon (`float`, inherited from GRPOConfig, default overridden to `0.15`):
|
| 44 |
+
Divergence threshold δ_low. Tokens whose divergence exceeds this when the policy moves in the
|
| 45 |
+
advantage-decreasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL
|
| 46 |
+
divergence.
|
| 47 |
+
|
| 48 |
+
epsilon_high (`float`, inherited from GRPOConfig, default overridden to `0.15`):
|
| 49 |
+
Divergence threshold δ_high. Tokens whose divergence exceeds this when the policy moves in the
|
| 50 |
+
advantage-increasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL
|
| 51 |
+
divergence.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
divergence_type: Literal["binary_tv", "binary_kl", "topk_tv", "topk_kl"] = field(
|
| 55 |
+
default="binary_tv",
|
| 56 |
+
metadata={
|
| 57 |
+
"help": "Divergence approximation used for the trust-region mask. Binary variants use only per-token "
|
| 58 |
+
"log-probs; top-K variants require storing top-K token IDs and log-probs during rollout generation plus "
|
| 59 |
+
"full logits during training."
|
| 60 |
+
},
|
| 61 |
+
)
|
| 62 |
+
divergence_topk: int = field(
|
| 63 |
+
default=20,
|
| 64 |
+
metadata={
|
| 65 |
+
"help": "K for top-K divergence approximations. Only used when `divergence_type` is `'topk_tv'` or "
|
| 66 |
+
"`'topk_kl'`."
|
| 67 |
+
},
|
| 68 |
+
)
|
| 69 |
+
clip_ratio_c: float = field(
|
| 70 |
+
default=20.0,
|
| 71 |
+
metadata={
|
| 72 |
+
"help": "Upper bound on the importance-sampling ratio for stability. The IS ratio is clamped to "
|
| 73 |
+
"[0, clip_ratio_c]."
|
| 74 |
+
},
|
| 75 |
+
)
|
| 76 |
+
epsilon: float = field(
|
| 77 |
+
default=0.15,
|
| 78 |
+
metadata={
|
| 79 |
+
"help": "Divergence threshold δ_low. Tokens whose divergence exceeds this when the policy moves in the "
|
| 80 |
+
"advantage-decreasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL "
|
| 81 |
+
"divergence."
|
| 82 |
+
},
|
| 83 |
+
)
|
| 84 |
+
epsilon_high: float = field(
|
| 85 |
+
default=0.15,
|
| 86 |
+
metadata={
|
| 87 |
+
"help": "Divergence threshold δ_high. Tokens whose divergence exceeds this when the policy moves in the "
|
| 88 |
+
"advantage-increasing direction are masked. The paper recommends 0.15 for TV divergence and 0.05 for KL "
|
| 89 |
+
"divergence."
|
| 90 |
+
},
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def __post_init__(self):
|
| 94 |
+
super().__post_init__()
|
| 95 |
+
|
| 96 |
+
if self.divergence_type not in ("binary_tv", "binary_kl", "topk_tv", "topk_kl"):
|
| 97 |
+
raise ValueError(
|
| 98 |
+
f"divergence_type must be one of 'binary_tv', 'binary_kl', 'topk_tv', 'topk_kl', "
|
| 99 |
+
f"got {self.divergence_type!r}"
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if self.divergence_topk < 1:
|
| 103 |
+
raise ValueError(f"divergence_topk must be >= 1, got {self.divergence_topk}")
|
| 104 |
+
|
| 105 |
+
if self.clip_ratio_c <= 0:
|
| 106 |
+
raise ValueError(f"clip_ratio_c must be > 0, got {self.clip_ratio_c}")
|
| 107 |
+
|
| 108 |
+
if self.loss_type != "dapo":
|
| 109 |
+
raise ValueError(f"loss_type {self.loss_type} is not supported for DPPO")
|
| 110 |
+
|
| 111 |
+
if self.top_entropy_quantile != 1.0:
|
| 112 |
+
raise ValueError("top_entropy_quantile is not supported for DPPO")
|
| 113 |
+
|
| 114 |
+
if self.off_policy_mask_threshold is not None:
|
| 115 |
+
raise ValueError("off_policy_mask_threshold is not supported for DPPO")
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/dppo/dppo_trainer.py
ADDED
|
@@ -0,0 +1,1387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 asyncio
|
| 16 |
+
import copy
|
| 17 |
+
import math
|
| 18 |
+
import textwrap
|
| 19 |
+
from collections.abc import Callable
|
| 20 |
+
from contextlib import nullcontext
|
| 21 |
+
from copy import copy as shallow_copy
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
import transformers
|
| 27 |
+
from accelerate.utils import gather_object
|
| 28 |
+
from datasets import Dataset, IterableDataset
|
| 29 |
+
from packaging.version import Version
|
| 30 |
+
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
|
| 31 |
+
from transformers import (
|
| 32 |
+
PreTrainedModel,
|
| 33 |
+
PreTrainedTokenizerBase,
|
| 34 |
+
ProcessorMixin,
|
| 35 |
+
Trainer,
|
| 36 |
+
TrainerCallback,
|
| 37 |
+
)
|
| 38 |
+
from transformers.utils import is_peft_available
|
| 39 |
+
|
| 40 |
+
from ...chat_template_utils import parse_response
|
| 41 |
+
from ...data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages
|
| 42 |
+
from ...extras.profiling import profiling_context, profiling_decorator
|
| 43 |
+
from ...models import unwrap_model_for_generation
|
| 44 |
+
from ...models.utils import disable_gradient_checkpointing
|
| 45 |
+
from ...trainer.grpo_trainer import EnvironmentFactory, GRPOTrainer, RewardFunc, RolloutFunc
|
| 46 |
+
from ...trainer.utils import entropy_from_logits, nanstd, pad, selective_log_softmax, use_adapter
|
| 47 |
+
from .dppo_config import DPPOConfig
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if is_peft_available():
|
| 51 |
+
from peft import PeftConfig, PeftModel
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
SAFETY_CLAMP_MAX = 20
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _strip_padding(tensor: torch.Tensor, mask: torch.Tensor) -> list[list]:
|
| 58 |
+
"""Remove padding from a batched tensor using a mask, returning a ragged list-of-lists."""
|
| 59 |
+
return [row[m].tolist() for row, m in zip(tensor, mask.bool(), strict=True)]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class DPPOTrainer(GRPOTrainer):
|
| 63 |
+
"""
|
| 64 |
+
Trainer for Divergence Proximal Policy Optimization (DPPO).
|
| 65 |
+
|
| 66 |
+
DPPO replaces PPO/GRPO's heuristic ratio-clipping with a principled trust region based on direct policy divergence
|
| 67 |
+
estimates. PPO-style clipping masks tokens based on probability ratio π/μ, which over-penalizes low-probability
|
| 68 |
+
tokens and under-penalizes high-probability tokens. In contrast, DPPO masks based on direct approximation of policy
|
| 69 |
+
divergence (e.g TV or KL) ensuring updates stay within a theoretically grounded trust region.
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
Four divergence approximations are supported:
|
| 73 |
+
- `binary_tv`: Absolute probability difference |π(a) - μ(a)| (simplest)
|
| 74 |
+
- `binary_kl`: Bernoulli KL divergence between old and new token probabilities
|
| 75 |
+
- `topk_tv`: Total variation over the top-K tokens of the distribution
|
| 76 |
+
- `topk_kl`: KL divergence over the top-K tokens of the distribution
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]):
|
| 80 |
+
Model to be trained. Can be either:
|
| 81 |
+
|
| 82 |
+
- A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
|
| 83 |
+
path to a *directory* containing model weights saved using
|
| 84 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
| 85 |
+
using `<ModelArchitecture>.from_pretrained` (where `<ModelArchitecture>` is derived from the model
|
| 86 |
+
config) with the keyword arguments in `args.model_init_kwargs`.
|
| 87 |
+
- A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
|
| 88 |
+
- A [`~peft.PeftModel`] object. Only causal language models are supported.
|
| 89 |
+
reward_funcs (`RewardFunc | list[RewardFunc]`):
|
| 90 |
+
Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
|
| 91 |
+
functions with the prompts and completions and sum the rewards. Can be either:
|
| 92 |
+
|
| 93 |
+
- A single reward function, such as:
|
| 94 |
+
- A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a
|
| 95 |
+
path to a *directory* containing model weights saved using
|
| 96 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
| 97 |
+
using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the
|
| 98 |
+
keyword arguments in `args.model_init_kwargs`.
|
| 99 |
+
- A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported.
|
| 100 |
+
- A custom reward function: The function is provided with the prompts and the generated completions,
|
| 101 |
+
plus any additional columns in the dataset. It should return a list of rewards. Custom reward
|
| 102 |
+
functions can be either synchronous or asynchronous and can also return `None` when the reward is
|
| 103 |
+
not applicable to those samples. This is useful for multi-task training where different reward
|
| 104 |
+
functions apply to different types of samples. When a reward function returns `None` for a sample,
|
| 105 |
+
that reward function is excluded from the reward calculation for that sample. For more details, see
|
| 106 |
+
[Using a custom reward
|
| 107 |
+
function](#using-a-custom-reward-function).
|
| 108 |
+
|
| 109 |
+
The trainer's state is also passed to the reward function. The trainer's state is an instance of
|
| 110 |
+
[`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the
|
| 111 |
+
reward function's signature.
|
| 112 |
+
- A list of reward functions, where each item can independently be any of the above types. Mixing different
|
| 113 |
+
types within the list (e.g., a string model ID and a custom reward function) is allowed.
|
| 114 |
+
args ([`DPPOConfig`], *optional*):
|
| 115 |
+
Configuration for this trainer. If `None`, a default configuration is used.
|
| 116 |
+
train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
|
| 117 |
+
Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is
|
| 118 |
+
ignored. The format of the samples can be either:
|
| 119 |
+
|
| 120 |
+
- [Standard](dataset_formats#standard): Each sample contains plain text.
|
| 121 |
+
- [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
|
| 122 |
+
and content).
|
| 123 |
+
eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
|
| 124 |
+
Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
|
| 125 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*):
|
| 126 |
+
Processing class used to process the data. The padding side must be set to "left". If `None`, the
|
| 127 |
+
processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A
|
| 128 |
+
padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
|
| 129 |
+
`tokenizer.eos_token` will be used as the default.
|
| 130 |
+
reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*):
|
| 131 |
+
Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
|
| 132 |
+
|
| 133 |
+
- A single processing class: Used when `reward_funcs` contains only one reward function.
|
| 134 |
+
- A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
|
| 135 |
+
If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is
|
| 136 |
+
`None`, the tokenizer for the model is automatically loaded using
|
| 137 |
+
[`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward
|
| 138 |
+
functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes`
|
| 139 |
+
are ignored.
|
| 140 |
+
callbacks (list of [`~transformers.TrainerCallback`], *optional*):
|
| 141 |
+
List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
|
| 142 |
+
in [here](https://huggingface.co/docs/transformers/main_classes/callback).
|
| 143 |
+
|
| 144 |
+
If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
|
| 145 |
+
method.
|
| 146 |
+
optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`):
|
| 147 |
+
A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your
|
| 148 |
+
model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`.
|
| 149 |
+
peft_config ([`~peft.PeftConfig`], *optional*):
|
| 150 |
+
PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
|
| 151 |
+
tools (list of `Callable`, *optional*):
|
| 152 |
+
A list of callable tool functions (sync or async) that the model can invoke during generation. Each tool
|
| 153 |
+
should be a standard Python function with properly type-hinted arguments and return values, and a
|
| 154 |
+
Google-style docstring describing its purpose, arguments, and return value. For more details, see:
|
| 155 |
+
https://huggingface.co/docs/transformers/en/chat_extras#passing-tools. The model uses the function's name,
|
| 156 |
+
type hints, and docstring to determine how to call it. Ensure that the model's chat template supports tool
|
| 157 |
+
use and that it has been fine-tuned for tool calling.
|
| 158 |
+
rollout_func (`RolloutFunc`, *optional*):
|
| 159 |
+
Function to use for generating completions. It receives the list of prompts allocated to the current
|
| 160 |
+
process and the trainer instance. It must return a dict with `"prompt_ids"`, `"completion_ids"`, and
|
| 161 |
+
`"logprobs"` fields. Any other fields are forwarded to the reward functions. This feature is experimental
|
| 162 |
+
and may change or be removed at any time without prior notice.
|
| 163 |
+
environment_factory (`EnvironmentFactory`, *optional*):
|
| 164 |
+
A callable that creates and returns an environment instance. The environment class should define methods
|
| 165 |
+
that can be invoked as tools during generation. Each method should comply with the same requirements as the
|
| 166 |
+
`tools` described above. If `environment_factory` is provided, an instance of the environment is created
|
| 167 |
+
for each generation in the batch, allowing for parallel and independent interactions. The environment must
|
| 168 |
+
also implement a callable `reset` method that can be used to reset state between generations. The `reset`
|
| 169 |
+
method should return either `None` or a string: when it returns a string, that string is appended to the
|
| 170 |
+
last user message before generation. This feature is experimental and may change or be removed at any time
|
| 171 |
+
without prior notice.
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
_tag_names = ["trl", "dppo"]
|
| 175 |
+
_name = "DPPO"
|
| 176 |
+
_paper = {
|
| 177 |
+
"title": "Rethinking the Trust Region in LLM Reinforcement Learning",
|
| 178 |
+
"id": "2602.04879",
|
| 179 |
+
# docstyle-ignore
|
| 180 |
+
"citation": textwrap.dedent("""\
|
| 181 |
+
@article{qi2026rethinking,
|
| 182 |
+
title = {{Rethinking the Trust Region in LLM Reinforcement Learning}},
|
| 183 |
+
author = {Qi, Penghui and Zhou, Xiangxin and Liu, Zichen and Pang, Tianyu and Du, Chao and Lin, Min and Lee, Wee Sun},
|
| 184 |
+
journal = {arXiv preprint arXiv:2602.04879},
|
| 185 |
+
year = {2026}
|
| 186 |
+
}"""),
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
def __init__(
|
| 190 |
+
self,
|
| 191 |
+
model: "str | PreTrainedModel | PeftModel",
|
| 192 |
+
reward_funcs: RewardFunc | list[RewardFunc],
|
| 193 |
+
args: DPPOConfig | None = None,
|
| 194 |
+
train_dataset: Dataset | IterableDataset | None = None,
|
| 195 |
+
eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
|
| 196 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
|
| 197 |
+
reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
|
| 198 |
+
callbacks: list[TrainerCallback] | None = None,
|
| 199 |
+
optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
|
| 200 |
+
peft_config: "PeftConfig | None" = None,
|
| 201 |
+
tools: list[Callable] | None = None,
|
| 202 |
+
rollout_func: RolloutFunc | None = None,
|
| 203 |
+
environment_factory: EnvironmentFactory | None = None,
|
| 204 |
+
):
|
| 205 |
+
if args is None:
|
| 206 |
+
model_name = model if isinstance(model, str) else model.config._name_or_path
|
| 207 |
+
model_name = model_name.split("/")[-1]
|
| 208 |
+
args = DPPOConfig(f"{model_name}-DPPO")
|
| 209 |
+
|
| 210 |
+
self.divergence_type = args.divergence_type
|
| 211 |
+
self.divergence_topk = args.divergence_topk
|
| 212 |
+
self.clip_ratio_c = args.clip_ratio_c
|
| 213 |
+
|
| 214 |
+
super().__init__(
|
| 215 |
+
model=model,
|
| 216 |
+
reward_funcs=reward_funcs,
|
| 217 |
+
args=args,
|
| 218 |
+
train_dataset=train_dataset,
|
| 219 |
+
eval_dataset=eval_dataset,
|
| 220 |
+
processing_class=processing_class,
|
| 221 |
+
reward_processing_classes=reward_processing_classes,
|
| 222 |
+
callbacks=callbacks,
|
| 223 |
+
optimizers=optimizers,
|
| 224 |
+
peft_config=peft_config,
|
| 225 |
+
tools=tools,
|
| 226 |
+
rollout_func=rollout_func,
|
| 227 |
+
environment_factory=environment_factory,
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
if self.divergence_type in ["topk_tv", "topk_kl"] and self.use_vllm:
|
| 231 |
+
self.vllm_generation.logprobs = self.divergence_topk
|
| 232 |
+
|
| 233 |
+
def _tokenize_prompts(self, prompts: list):
|
| 234 |
+
"""Tokenize prompts and extract images/multimodal fields for generation."""
|
| 235 |
+
if is_conversational({"prompt": prompts[0]}):
|
| 236 |
+
images = []
|
| 237 |
+
has_images = False
|
| 238 |
+
for prompt in prompts:
|
| 239 |
+
prompt_images = []
|
| 240 |
+
for message in prompt:
|
| 241 |
+
if isinstance(message["content"], list):
|
| 242 |
+
for part in message["content"]:
|
| 243 |
+
if part["type"] == "image":
|
| 244 |
+
prompt_images.append(part["image"])
|
| 245 |
+
has_images = True
|
| 246 |
+
images.append(prompt_images if prompt_images else None)
|
| 247 |
+
images = images if has_images else None
|
| 248 |
+
|
| 249 |
+
# Workaround for a bug in transformers 5.3.0 where some processors (e.g. Qwen2.5-VL) crash on
|
| 250 |
+
# batched unpadded input (transformers#44514).
|
| 251 |
+
# Fixed in transformers 5.4.0 (transformers#44563).
|
| 252 |
+
needs_padding_workaround = Version("5.3.0") <= Version(transformers.__version__) < Version("5.4.0")
|
| 253 |
+
tokenized = self.processing_class.apply_chat_template(
|
| 254 |
+
conversation=prompts,
|
| 255 |
+
tools=self.tools or None, # `or None`: Llama bug: it renders tool boilerplate for tools=[]
|
| 256 |
+
chat_template=self.chat_template,
|
| 257 |
+
add_generation_prompt=True,
|
| 258 |
+
tokenize=True,
|
| 259 |
+
return_dict=True,
|
| 260 |
+
**({"padding": True} if needs_padding_workaround else {}),
|
| 261 |
+
**self.chat_template_kwargs,
|
| 262 |
+
)
|
| 263 |
+
if needs_padding_workaround:
|
| 264 |
+
# Unpad input_ids: remove padding tokens using attention_mask to get per-sequence lists
|
| 265 |
+
prompt_ids = [
|
| 266 |
+
[tok for tok, m in zip(ids, mask, strict=True) if m]
|
| 267 |
+
for ids, mask in zip(tokenized["input_ids"], tokenized["attention_mask"], strict=True)
|
| 268 |
+
]
|
| 269 |
+
else:
|
| 270 |
+
prompt_ids = tokenized["input_ids"]
|
| 271 |
+
multimodal_fields = {k: v for k, v in tokenized.items() if k not in ("input_ids", "attention_mask")}
|
| 272 |
+
else:
|
| 273 |
+
prompt_ids = self.processing_class(text=prompts)["input_ids"]
|
| 274 |
+
images = None
|
| 275 |
+
multimodal_fields = {}
|
| 276 |
+
return prompt_ids, images, multimodal_fields
|
| 277 |
+
|
| 278 |
+
def _generate_single_turn(self, prompt_ids, images, multimodal_fields):
|
| 279 |
+
"""Generate completions, always extracting sampled token logprobs.
|
| 280 |
+
|
| 281 |
+
Returns:
|
| 282 |
+
5-tuple of (prompt_ids, completion_ids, logprobs, topk_logprobs, topk_token_ids). topk_logprobs and
|
| 283 |
+
topk_token_ids are None when divergence_type is not topk.
|
| 284 |
+
"""
|
| 285 |
+
device = self.accelerator.device
|
| 286 |
+
mode = "train" if self.model.training else "eval"
|
| 287 |
+
needs_topk = self.divergence_type in ["topk_tv", "topk_kl"]
|
| 288 |
+
K = self.divergence_topk
|
| 289 |
+
|
| 290 |
+
if self.use_vllm:
|
| 291 |
+
if self.state.global_step != self._last_loaded_step:
|
| 292 |
+
with profiling_context(self, "sync_weights"):
|
| 293 |
+
self.vllm_generation.sync_weights()
|
| 294 |
+
self._last_loaded_step = self.state.global_step
|
| 295 |
+
|
| 296 |
+
num_generations = self.num_generations if mode == "train" else self.num_generations_eval
|
| 297 |
+
prompt_ids, completion_ids, logprobs, logprob_token_ids = self.vllm_generation.generate(
|
| 298 |
+
prompts=prompt_ids,
|
| 299 |
+
images=images,
|
| 300 |
+
num_generations=num_generations,
|
| 301 |
+
profiler=profiling_context(self, "vLLM.generate"),
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
if needs_topk:
|
| 305 |
+
# vLLM returns up to K+1 entries sorted by rank (most probable first).
|
| 306 |
+
# The sampled token is always included but may be at any position.
|
| 307 |
+
# Per the paper, A'_t = TopK(μ, K) ∪ {a_t}. We keep exactly K slots: if the
|
| 308 |
+
# sampled token a_t is not in the top-K, it replaces the K-th ranked entry.
|
| 309 |
+
topk_logprobs = []
|
| 310 |
+
topk_token_ids = []
|
| 311 |
+
sampled_logprobs = []
|
| 312 |
+
for seq_lps, seq_tids, seq_cids in zip(logprobs, logprob_token_ids, completion_ids, strict=True):
|
| 313 |
+
seq_topk_lps, seq_topk_tids, seq_sampled = [], [], []
|
| 314 |
+
for step_lps, step_tids, sampled_tid in zip(seq_lps, seq_tids, seq_cids, strict=True):
|
| 315 |
+
idx = step_tids.index(sampled_tid)
|
| 316 |
+
seq_sampled.append(step_lps[idx])
|
| 317 |
+
# Take top-K entries, then ensure sampled token is present
|
| 318 |
+
tk_lps = step_lps[:K]
|
| 319 |
+
tk_tids = step_tids[:K]
|
| 320 |
+
if sampled_tid not in tk_tids:
|
| 321 |
+
tk_lps[-1] = step_lps[idx]
|
| 322 |
+
tk_tids[-1] = sampled_tid
|
| 323 |
+
seq_topk_lps.append(tk_lps)
|
| 324 |
+
seq_topk_tids.append(tk_tids)
|
| 325 |
+
topk_logprobs.append(seq_topk_lps)
|
| 326 |
+
topk_token_ids.append(seq_topk_tids)
|
| 327 |
+
sampled_logprobs.append(seq_sampled)
|
| 328 |
+
else:
|
| 329 |
+
sampled_logprobs = [[step_lps[0] for step_lps in seq_lps] for seq_lps in logprobs]
|
| 330 |
+
topk_logprobs = None
|
| 331 |
+
topk_token_ids = None
|
| 332 |
+
|
| 333 |
+
return prompt_ids, completion_ids, sampled_logprobs, topk_logprobs, topk_token_ids
|
| 334 |
+
else:
|
| 335 |
+
prompt_tensors = [torch.tensor(ids) for ids in prompt_ids]
|
| 336 |
+
padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left")
|
| 337 |
+
attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left")
|
| 338 |
+
generate_inputs = {"input_ids": padded_ids, "attention_mask": attention_mask}
|
| 339 |
+
for key, value in multimodal_fields.items():
|
| 340 |
+
if isinstance(value, torch.Tensor):
|
| 341 |
+
generate_inputs[key] = value
|
| 342 |
+
elif isinstance(value, list) and value and isinstance(value[0], list):
|
| 343 |
+
generate_inputs[key] = pad([torch.tensor(x) for x in value], padding_value=0, padding_side="left")
|
| 344 |
+
else:
|
| 345 |
+
generate_inputs[key] = torch.tensor(np.array(value))
|
| 346 |
+
generate_inputs = Trainer._prepare_inputs(self, generate_inputs)
|
| 347 |
+
|
| 348 |
+
gen_config = shallow_copy(self.generation_config)
|
| 349 |
+
gen_config.output_logits = True
|
| 350 |
+
gen_config.return_dict_in_generate = True
|
| 351 |
+
|
| 352 |
+
with (
|
| 353 |
+
profiling_context(self, "transformers.generate"),
|
| 354 |
+
unwrap_model_for_generation(
|
| 355 |
+
self.model_wrapped,
|
| 356 |
+
self.accelerator,
|
| 357 |
+
gather_deepspeed3_params=self.args.ds3_gather_for_generation,
|
| 358 |
+
generation_kwargs=self.generation_kwargs,
|
| 359 |
+
) as unwrapped_model,
|
| 360 |
+
torch.no_grad(),
|
| 361 |
+
FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(),
|
| 362 |
+
):
|
| 363 |
+
gen_output = unwrapped_model.generate(**generate_inputs, generation_config=gen_config)
|
| 364 |
+
|
| 365 |
+
prompt_ids_tensor, prompt_mask = generate_inputs["input_ids"], generate_inputs["attention_mask"]
|
| 366 |
+
prompt_length = prompt_ids_tensor.size(1)
|
| 367 |
+
completion_ids = gen_output.sequences[:, prompt_length:]
|
| 368 |
+
|
| 369 |
+
sampled_chunks = []
|
| 370 |
+
topk_logps_chunks = [] if needs_topk else None
|
| 371 |
+
topk_ids_chunks = [] if needs_topk else None
|
| 372 |
+
|
| 373 |
+
for t, logits_t in enumerate(gen_output.logits):
|
| 374 |
+
# logits_t: (B, V)
|
| 375 |
+
logits_t = logits_t / self.temperature
|
| 376 |
+
|
| 377 |
+
# exact sampled-token logprob without allocating (B, V) log_softmax output
|
| 378 |
+
logZ_t = torch.logsumexp(logits_t, dim=-1, keepdim=True)
|
| 379 |
+
sampled_ids_t = completion_ids[:, t : t + 1]
|
| 380 |
+
sampled_lp_t = logits_t.gather(-1, sampled_ids_t) - logZ_t
|
| 381 |
+
sampled_chunks.append(sampled_lp_t.cpu())
|
| 382 |
+
|
| 383 |
+
if needs_topk:
|
| 384 |
+
topk_logits_t, topk_ids_t = torch.topk(logits_t, k=K, dim=-1) # (B, K), (B, K)
|
| 385 |
+
topk_lp_t = topk_logits_t - logZ_t
|
| 386 |
+
|
| 387 |
+
# Ensure sampled token is included in A'_t = TopK ∪ {a_t}
|
| 388 |
+
missing = ~(topk_ids_t == sampled_ids_t).any(dim=-1)
|
| 389 |
+
if missing.any():
|
| 390 |
+
topk_ids_t = topk_ids_t.clone()
|
| 391 |
+
topk_lp_t = topk_lp_t.clone()
|
| 392 |
+
topk_ids_t[missing, -1] = sampled_ids_t[missing, 0]
|
| 393 |
+
topk_lp_t[missing, -1] = sampled_lp_t[missing, 0]
|
| 394 |
+
|
| 395 |
+
topk_ids_chunks.append(topk_ids_t.cpu())
|
| 396 |
+
topk_logps_chunks.append(topk_lp_t.cpu())
|
| 397 |
+
|
| 398 |
+
# Mask everything after the first EOS token
|
| 399 |
+
is_eos = completion_ids == self._tokenizer.eos_token_id
|
| 400 |
+
has_eos = is_eos.any(dim=1)
|
| 401 |
+
eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device)
|
| 402 |
+
eos_idx[has_eos] = is_eos.int().argmax(dim=1)[has_eos]
|
| 403 |
+
sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1)
|
| 404 |
+
completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int()
|
| 405 |
+
prompt_mask_cpu = prompt_mask.bool().cpu()
|
| 406 |
+
completion_mask_cpu = completion_mask.bool().cpu()
|
| 407 |
+
|
| 408 |
+
prompt_ids_out = _strip_padding(prompt_ids_tensor.cpu(), prompt_mask_cpu)
|
| 409 |
+
completion_ids_out = _strip_padding(completion_ids.cpu(), completion_mask_cpu)
|
| 410 |
+
logprobs_out = _strip_padding(torch.cat(sampled_chunks, dim=1), completion_mask_cpu)
|
| 411 |
+
if needs_topk:
|
| 412 |
+
topk_logprobs = _strip_padding(torch.stack(topk_logps_chunks, dim=1), completion_mask_cpu)
|
| 413 |
+
topk_token_ids = _strip_padding(torch.stack(topk_ids_chunks, dim=1), completion_mask_cpu)
|
| 414 |
+
else:
|
| 415 |
+
topk_logprobs = None
|
| 416 |
+
topk_token_ids = None
|
| 417 |
+
|
| 418 |
+
return prompt_ids_out, completion_ids_out, logprobs_out, topk_logprobs, topk_token_ids
|
| 419 |
+
|
| 420 |
+
def _tool_call_loop(
|
| 421 |
+
self, prompts, prompt_ids, completion_ids, completions, logprobs, topk_logprobs, topk_token_ids
|
| 422 |
+
):
|
| 423 |
+
"""Tool execution loop that also threads top-K logprob data alongside logprobs.
|
| 424 |
+
|
| 425 |
+
Mirrors GRPOTrainer._tool_call_loop but additionally concatenates topk_logprobs and topk_token_ids the same way
|
| 426 |
+
logprobs is concatenated: real data for model-generated tokens, zero-padding for tool-result tokens. When topk
|
| 427 |
+
data is None (binary divergence), behaves identically to the parent.
|
| 428 |
+
"""
|
| 429 |
+
K = self.divergence_topk
|
| 430 |
+
has_topk = topk_logprobs is not None
|
| 431 |
+
|
| 432 |
+
tool_calls = [completion[0].get("tool_calls") for completion in completions]
|
| 433 |
+
idxs_with_tool = [idx for idx, tool_call in enumerate(tool_calls) if tool_call]
|
| 434 |
+
tool_calls = [tool_calls[idx] for idx in idxs_with_tool]
|
| 435 |
+
tool_mask = [[1] * len(ids) for ids in completion_ids]
|
| 436 |
+
tool_call_count = 0
|
| 437 |
+
tool_failure_count = 0
|
| 438 |
+
iteration_num = 0
|
| 439 |
+
while idxs_with_tool and iteration_num < self.max_tool_calling_iterations:
|
| 440 |
+
prompt_completion_tools = [prompts[i] for i in idxs_with_tool]
|
| 441 |
+
|
| 442 |
+
for idx in range(len(idxs_with_tool)):
|
| 443 |
+
idx_with_tool = idxs_with_tool[idx]
|
| 444 |
+
tool_call_list = tool_calls[idx]
|
| 445 |
+
prompt_completion_tool = prompt_completion_tools[idx]
|
| 446 |
+
sync_tool_dict = self._sync_tool_dicts[idx_with_tool]
|
| 447 |
+
async_tool_dict = self._async_tool_dicts[idx_with_tool]
|
| 448 |
+
prompt_completion_tool.append(completions[idx_with_tool][-1])
|
| 449 |
+
async_coros = []
|
| 450 |
+
tool_call_results = []
|
| 451 |
+
for tool_call in tool_call_list:
|
| 452 |
+
tool_call_count += 1
|
| 453 |
+
if tool_call["type"] == "function":
|
| 454 |
+
function = tool_call["function"]
|
| 455 |
+
name = function["name"]
|
| 456 |
+
try:
|
| 457 |
+
if name in sync_tool_dict:
|
| 458 |
+
tool_call_results.append((name, sync_tool_dict[name](**function["arguments"])))
|
| 459 |
+
elif name in async_tool_dict:
|
| 460 |
+
async_coros.append((name, async_tool_dict[name](**function["arguments"])))
|
| 461 |
+
else:
|
| 462 |
+
raise ValueError(f"Tool {name} not found.")
|
| 463 |
+
except Exception as err:
|
| 464 |
+
tool_failure_count += 1
|
| 465 |
+
tool_call_results.append((name, {"error": str(err)}))
|
| 466 |
+
else:
|
| 467 |
+
tool_failure_count += 1
|
| 468 |
+
name = tool_call.get("name", "unknown")
|
| 469 |
+
tool_call_results.append((name, {"error": f"Unsupported tool call type: {tool_call['type']}"}))
|
| 470 |
+
|
| 471 |
+
if async_coros:
|
| 472 |
+
|
| 473 |
+
async def _run_async_tools(async_coros):
|
| 474 |
+
coros = [coro for _, coro in async_coros]
|
| 475 |
+
results = await asyncio.gather(*coros, return_exceptions=True)
|
| 476 |
+
return [(name, result) for (name, _), result in zip(async_coros, results, strict=False)]
|
| 477 |
+
|
| 478 |
+
async_results = asyncio.run_coroutine_threadsafe(
|
| 479 |
+
_run_async_tools(async_coros), self.async_loop
|
| 480 |
+
).result()
|
| 481 |
+
|
| 482 |
+
for name, result in async_results:
|
| 483 |
+
if isinstance(result, Exception):
|
| 484 |
+
tool_failure_count += 1
|
| 485 |
+
tool_call_results.append((name, {"error": str(result)}))
|
| 486 |
+
else:
|
| 487 |
+
tool_call_results.append((name, result))
|
| 488 |
+
|
| 489 |
+
for name, result in tool_call_results:
|
| 490 |
+
tool_message = {"role": "tool", "name": name, "content": str(result)}
|
| 491 |
+
prompt_completion_tool.append(tool_message)
|
| 492 |
+
completions[idx_with_tool].append(tool_message)
|
| 493 |
+
|
| 494 |
+
# Tokenize and filter samples whose length exceeds max allowed length
|
| 495 |
+
pct_ids = self.processing_class.apply_chat_template(
|
| 496 |
+
prompt_completion_tools,
|
| 497 |
+
tools=self.tools or None, # `or None`: Llama bug: it renders tool boilerplate for tools=[]
|
| 498 |
+
chat_template=self.chat_template,
|
| 499 |
+
add_generation_prompt=True,
|
| 500 |
+
tokenize=True,
|
| 501 |
+
return_dict=False,
|
| 502 |
+
**self.chat_template_kwargs,
|
| 503 |
+
)
|
| 504 |
+
if self.use_vllm and self.vllm_mode == "colocate":
|
| 505 |
+
max_model_len = self.vllm_generation.llm.llm_engine.model_config.max_model_len
|
| 506 |
+
elif not self.use_vllm:
|
| 507 |
+
max_model_len = self.model.config.max_position_embeddings
|
| 508 |
+
else:
|
| 509 |
+
raise NotImplementedError(
|
| 510 |
+
f"Unsupported mode detected: use_vllm={self.use_vllm}, vllm_mode={self.vllm_mode}"
|
| 511 |
+
)
|
| 512 |
+
overlong = [len(pct) >= max_model_len for pct in pct_ids]
|
| 513 |
+
for idx in range(len(idxs_with_tool)):
|
| 514 |
+
idx_with_tool = idxs_with_tool[idx]
|
| 515 |
+
if overlong[idx]:
|
| 516 |
+
prompt_length = len(prompt_ids[idx_with_tool])
|
| 517 |
+
ct = pct_ids[idx][prompt_length : prompt_length + self.max_completion_length]
|
| 518 |
+
completion_ids[idx_with_tool] = ct
|
| 519 |
+
tool_mask[idx_with_tool] += [1] * (len(ct) - len(tool_mask[idx_with_tool]))
|
| 520 |
+
if logprobs is not None:
|
| 521 |
+
logprobs[idx_with_tool] += [0.0] * (len(ct) - len(logprobs[idx_with_tool]))
|
| 522 |
+
if has_topk:
|
| 523 |
+
topk_logprobs[idx_with_tool] += [[0.0] * K] * (len(ct) - len(topk_logprobs[idx_with_tool]))
|
| 524 |
+
topk_token_ids[idx_with_tool] += [[0] * K] * (len(ct) - len(topk_token_ids[idx_with_tool]))
|
| 525 |
+
|
| 526 |
+
idxs_with_tool = [idx for idx, o in zip(idxs_with_tool, overlong, strict=True) if not o]
|
| 527 |
+
prompt_completion_tools = [pct for pct, o in zip(prompt_completion_tools, overlong, strict=True) if not o]
|
| 528 |
+
if not idxs_with_tool:
|
| 529 |
+
break
|
| 530 |
+
|
| 531 |
+
# Generate new completions after tool execution
|
| 532 |
+
pct_prompt_ids, pct_images, pct_multimodal_fields = self._tokenize_prompts(prompt_completion_tools)
|
| 533 |
+
(
|
| 534 |
+
prompt_completion_tool_ids,
|
| 535 |
+
post_tool_ids,
|
| 536 |
+
post_tool_logprobs,
|
| 537 |
+
post_tool_topk_logprobs,
|
| 538 |
+
post_tool_topk_token_ids,
|
| 539 |
+
) = self._generate_single_turn(pct_prompt_ids, pct_images, pct_multimodal_fields)
|
| 540 |
+
|
| 541 |
+
# Sanity check: chat template must be prefix-preserving
|
| 542 |
+
for idx in range(len(idxs_with_tool)):
|
| 543 |
+
idx_with_tool = idxs_with_tool[idx]
|
| 544 |
+
pct = prompt_completion_tool_ids[idx]
|
| 545 |
+
if prompt_ids[idx_with_tool] != pct[: len(prompt_ids[idx_with_tool])]:
|
| 546 |
+
raise ValueError(
|
| 547 |
+
"The chat template is not prefix-preserving. Please update it to use a prefix-preserving "
|
| 548 |
+
"format."
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
# Truncate so that pct[len(prompt_ids[idx]):] + post_tool does not exceed max_completion_length
|
| 552 |
+
for idx in range(len(idxs_with_tool)):
|
| 553 |
+
idx_with_tool = idxs_with_tool[idx]
|
| 554 |
+
prompt_len = len(prompt_ids[idx_with_tool])
|
| 555 |
+
completion_tool_ids = prompt_completion_tool_ids[idx][prompt_len:]
|
| 556 |
+
excess_length = len(completion_tool_ids) + len(post_tool_ids[idx]) - self.max_completion_length
|
| 557 |
+
if excess_length > 0:
|
| 558 |
+
post_tool_ids[idx] = post_tool_ids[idx][:-excess_length]
|
| 559 |
+
if logprobs is not None:
|
| 560 |
+
post_tool_logprobs[idx] = post_tool_logprobs[idx][:-excess_length]
|
| 561 |
+
if has_topk and post_tool_topk_logprobs is not None:
|
| 562 |
+
post_tool_topk_logprobs[idx] = post_tool_topk_logprobs[idx][:-excess_length]
|
| 563 |
+
post_tool_topk_token_ids[idx] = post_tool_topk_token_ids[idx][:-excess_length]
|
| 564 |
+
excess_length = len(completion_tool_ids) + len(post_tool_ids[idx]) - self.max_completion_length
|
| 565 |
+
if excess_length > 0:
|
| 566 |
+
prompt_completion_tool_ids[idx] = prompt_completion_tool_ids[idx][:-excess_length]
|
| 567 |
+
|
| 568 |
+
# Update tool_mask and logprobs: tool result tokens get 0/0.0, post-tool model tokens get 1/real values
|
| 569 |
+
for idx in range(len(idxs_with_tool)):
|
| 570 |
+
idx_with_tool = idxs_with_tool[idx]
|
| 571 |
+
prompt_completion_tool_length = len(prompt_completion_tool_ids[idx])
|
| 572 |
+
prompt_length = len(prompt_ids[idx_with_tool])
|
| 573 |
+
completion_length = len(completion_ids[idx_with_tool])
|
| 574 |
+
post_tool_length = len(post_tool_ids[idx])
|
| 575 |
+
tool_length = prompt_completion_tool_length - prompt_length - completion_length
|
| 576 |
+
tool_mask[idx_with_tool] += [0] * tool_length + [1] * post_tool_length
|
| 577 |
+
if logprobs is not None:
|
| 578 |
+
logprobs[idx_with_tool] += [0.0] * tool_length + post_tool_logprobs[idx]
|
| 579 |
+
if has_topk:
|
| 580 |
+
topk_pad = [[0.0] * K] * tool_length
|
| 581 |
+
tid_pad = [[0] * K] * tool_length
|
| 582 |
+
post_topk_lp = post_tool_topk_logprobs[idx] if post_tool_topk_logprobs is not None else []
|
| 583 |
+
post_topk_tid = post_tool_topk_token_ids[idx] if post_tool_topk_token_ids is not None else []
|
| 584 |
+
topk_logprobs[idx_with_tool] += topk_pad + post_topk_lp
|
| 585 |
+
topk_token_ids[idx_with_tool] += tid_pad + post_topk_tid
|
| 586 |
+
|
| 587 |
+
# Update completion_ids with the new completions (after tool execution)
|
| 588 |
+
for idx in range(len(idxs_with_tool)):
|
| 589 |
+
idx_with_tool = idxs_with_tool[idx]
|
| 590 |
+
prompt_length = len(prompt_ids[idx_with_tool])
|
| 591 |
+
pct = prompt_completion_tool_ids[idx]
|
| 592 |
+
completion_ids[idx_with_tool] = pct[prompt_length:] + post_tool_ids[idx]
|
| 593 |
+
|
| 594 |
+
# Decode post-tool completions
|
| 595 |
+
post_tool_completions = [parse_response(self._tokenizer, ids) if ids else {} for ids in post_tool_ids]
|
| 596 |
+
|
| 597 |
+
for idx in range(len(idxs_with_tool)):
|
| 598 |
+
idx_with_tool = idxs_with_tool[idx]
|
| 599 |
+
if post_tool_completions[idx]:
|
| 600 |
+
completions[idx_with_tool].append(post_tool_completions[idx])
|
| 601 |
+
|
| 602 |
+
# Check for further tool calls
|
| 603 |
+
tool_calls = [completion.get("tool_calls") for completion in post_tool_completions]
|
| 604 |
+
idxs_with_tool = [idx for idx, tool_call in zip(idxs_with_tool, tool_calls, strict=True) if tool_call]
|
| 605 |
+
tool_calls = [tool_call for tool_call in tool_calls if tool_call]
|
| 606 |
+
iteration_num += 1
|
| 607 |
+
|
| 608 |
+
return (
|
| 609 |
+
tool_mask,
|
| 610 |
+
completions,
|
| 611 |
+
completion_ids,
|
| 612 |
+
logprobs,
|
| 613 |
+
topk_logprobs,
|
| 614 |
+
topk_token_ids,
|
| 615 |
+
tool_call_count,
|
| 616 |
+
tool_failure_count,
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
def _generate(self, prompts: list):
|
| 620 |
+
"""Generate completions, handling tool calls, and thread top-K logprob data through the full pipeline.
|
| 621 |
+
|
| 622 |
+
Returns:
|
| 623 |
+
9-tuple of (prompt_ids, completion_ids, tool_mask, completions, total_completion_tokens, logprobs,
|
| 624 |
+
topk_logprobs, topk_token_ids, extra_fields).
|
| 625 |
+
"""
|
| 626 |
+
device = self.accelerator.device
|
| 627 |
+
mode = "train" if self.model.training else "eval"
|
| 628 |
+
needs_topk = self.divergence_type in ["topk_tv", "topk_kl"]
|
| 629 |
+
|
| 630 |
+
# Copy the prompts to avoid modifying the original list
|
| 631 |
+
prompts = copy.deepcopy(prompts)
|
| 632 |
+
|
| 633 |
+
if self.rollout_func is not None:
|
| 634 |
+
# Keep vLLM weights in sync for custom rollouts that rely on vLLM utilities.
|
| 635 |
+
if self.use_vllm and self.state.global_step != self._last_loaded_step:
|
| 636 |
+
with profiling_context(self, "sync_weights"):
|
| 637 |
+
self.vllm_generation.sync_weights()
|
| 638 |
+
self._last_loaded_step = self.state.global_step
|
| 639 |
+
|
| 640 |
+
# Pass prompts to rollout_func preserving structured messages.
|
| 641 |
+
# Chat templating must happen inside rollout_func, at the backend boundary, so that
|
| 642 |
+
# multimodal content (images, typed content blocks) is not lost before rollout logic runs.
|
| 643 |
+
output = self.rollout_func(prompts, self)
|
| 644 |
+
required_keys = {"prompt_ids", "completion_ids", "logprobs"}
|
| 645 |
+
missing_keys = required_keys - output.keys()
|
| 646 |
+
if missing_keys:
|
| 647 |
+
missing_keys_list = sorted(missing_keys)
|
| 648 |
+
raise ValueError(f"rollout_func must return keys {missing_keys_list} in its output dict.")
|
| 649 |
+
extra_fields = {k: v for k, v in output.items() if k not in required_keys}
|
| 650 |
+
prompt_ids = output["prompt_ids"]
|
| 651 |
+
completion_ids = output["completion_ids"]
|
| 652 |
+
logprobs = output["logprobs"]
|
| 653 |
+
topk_logprobs = extra_fields.pop("topk_logprobs", None)
|
| 654 |
+
topk_token_ids = extra_fields.pop("topk_token_ids", None)
|
| 655 |
+
if needs_topk and (topk_logprobs is None or topk_token_ids is None):
|
| 656 |
+
raise ValueError(
|
| 657 |
+
"rollout_func must return keys ['topk_logprobs', 'topk_token_ids'] when divergence_type is "
|
| 658 |
+
f"{self.divergence_type!r}."
|
| 659 |
+
)
|
| 660 |
+
else:
|
| 661 |
+
prompt_ids, images, multimodal_fields = self._tokenize_prompts(prompts)
|
| 662 |
+
prompt_ids, completion_ids, logprobs, topk_logprobs, topk_token_ids = self._generate_single_turn(
|
| 663 |
+
prompt_ids, images, multimodal_fields
|
| 664 |
+
)
|
| 665 |
+
extra_fields = {}
|
| 666 |
+
|
| 667 |
+
# Decode completions. It's important to use `parse_response` when possible, because it handles tool calls.
|
| 668 |
+
if is_conversational({"prompt": prompts[0]}):
|
| 669 |
+
if (
|
| 670 |
+
Version(transformers.__version__) >= Version("5.0.0") # parse_response added in v5
|
| 671 |
+
and hasattr(self._tokenizer, "response_schema") # attribute not set by default for now
|
| 672 |
+
and self._tokenizer.response_schema is not None # only works if the tokenizer has a schema
|
| 673 |
+
):
|
| 674 |
+
completions = [[parse_response(self._tokenizer, ids)] for ids in completion_ids]
|
| 675 |
+
else:
|
| 676 |
+
contents = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
|
| 677 |
+
completions = [[{"role": "assistant", "content": content}] for content in contents]
|
| 678 |
+
else:
|
| 679 |
+
completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
|
| 680 |
+
|
| 681 |
+
# Extract tool calls from the completions and (possibly) execute them
|
| 682 |
+
if self.tools:
|
| 683 |
+
(
|
| 684 |
+
tool_mask,
|
| 685 |
+
completions,
|
| 686 |
+
completion_ids,
|
| 687 |
+
logprobs,
|
| 688 |
+
topk_logprobs,
|
| 689 |
+
topk_token_ids,
|
| 690 |
+
tool_call_count,
|
| 691 |
+
tool_failure_count,
|
| 692 |
+
) = self._tool_call_loop(
|
| 693 |
+
prompts, prompt_ids, completion_ids, completions, logprobs, topk_logprobs, topk_token_ids
|
| 694 |
+
)
|
| 695 |
+
else:
|
| 696 |
+
tool_mask = extra_fields.pop("env_mask", None)
|
| 697 |
+
|
| 698 |
+
# Get completion length per sequence, used for logging
|
| 699 |
+
prompt_lengths = torch.tensor([len(ids) for ids in prompt_ids], device=device)
|
| 700 |
+
if tool_mask is not None:
|
| 701 |
+
completion_lengths = torch.tensor([sum(mask) for mask in tool_mask], device=device)
|
| 702 |
+
else:
|
| 703 |
+
completion_lengths = torch.tensor([len(ids) for ids in completion_ids], device=device)
|
| 704 |
+
agg_prompt_lengths = self.accelerator.gather(prompt_lengths)
|
| 705 |
+
agg_completion_lengths = self.accelerator.gather(completion_lengths)
|
| 706 |
+
total_prompt_tokens = agg_prompt_lengths.sum()
|
| 707 |
+
total_completion_tokens = agg_completion_lengths.sum()
|
| 708 |
+
|
| 709 |
+
if mode == "train":
|
| 710 |
+
self.state.num_input_tokens_seen += (total_prompt_tokens + total_completion_tokens).item()
|
| 711 |
+
self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen]
|
| 712 |
+
|
| 713 |
+
self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item())
|
| 714 |
+
self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item())
|
| 715 |
+
self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item())
|
| 716 |
+
|
| 717 |
+
eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id]
|
| 718 |
+
is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids], device=device)
|
| 719 |
+
agg_is_truncated = self.accelerator.gather(is_truncated)
|
| 720 |
+
self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item())
|
| 721 |
+
term_completion_lengths = agg_completion_lengths[~agg_is_truncated]
|
| 722 |
+
if len(term_completion_lengths) == 0:
|
| 723 |
+
term_completion_lengths = torch.zeros(1, device=device)
|
| 724 |
+
self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item())
|
| 725 |
+
self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item())
|
| 726 |
+
self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item())
|
| 727 |
+
|
| 728 |
+
if self.tools:
|
| 729 |
+
agg_tool_call_count = self.accelerator.gather(torch.tensor(tool_call_count, device=device)).sum()
|
| 730 |
+
tool_call_frequency = (agg_tool_call_count / len(agg_prompt_lengths)).item()
|
| 731 |
+
self._metrics[mode]["tools/call_frequency"].append(tool_call_frequency)
|
| 732 |
+
agg_tool_failure_count = self.accelerator.gather(torch.tensor(tool_failure_count, device=device)).sum()
|
| 733 |
+
failure_frequency = (
|
| 734 |
+
(agg_tool_failure_count / agg_tool_call_count).item() if agg_tool_call_count > 0 else 0.0
|
| 735 |
+
)
|
| 736 |
+
self._metrics[mode]["tools/failure_frequency"].append(failure_frequency)
|
| 737 |
+
|
| 738 |
+
return (
|
| 739 |
+
prompt_ids,
|
| 740 |
+
completion_ids,
|
| 741 |
+
tool_mask,
|
| 742 |
+
completions,
|
| 743 |
+
total_completion_tokens,
|
| 744 |
+
logprobs,
|
| 745 |
+
topk_logprobs,
|
| 746 |
+
topk_token_ids,
|
| 747 |
+
extra_fields,
|
| 748 |
+
)
|
| 749 |
+
|
| 750 |
+
@profiling_decorator
|
| 751 |
+
def _get_per_token_logps_with_topk(
|
| 752 |
+
self,
|
| 753 |
+
model,
|
| 754 |
+
input_ids,
|
| 755 |
+
attention_mask,
|
| 756 |
+
logits_to_keep,
|
| 757 |
+
topk_token_ids,
|
| 758 |
+
batch_size=None,
|
| 759 |
+
compute_entropy=False,
|
| 760 |
+
pixel_values=None,
|
| 761 |
+
image_grid_thw=None,
|
| 762 |
+
num_images=None,
|
| 763 |
+
pixel_attention_mask=None,
|
| 764 |
+
image_sizes=None,
|
| 765 |
+
token_type_ids=None,
|
| 766 |
+
mm_token_type_ids=None,
|
| 767 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor]:
|
| 768 |
+
"""Compute per-token log-probs, (optionally) entropies, and top-K log-probs in one forward pass.
|
| 769 |
+
|
| 770 |
+
Evaluates the current policy's log-probs at the rollout's top-K token IDs from the same forward pass used for
|
| 771 |
+
per_token_logps, avoiding an extra model call.
|
| 772 |
+
|
| 773 |
+
Args:
|
| 774 |
+
topk_token_ids: Rollout policy's top-K token IDs, shape (B, T, K). The current policy's
|
| 775 |
+
log-probs are evaluated at these positions.
|
| 776 |
+
|
| 777 |
+
Returns:
|
| 778 |
+
Tuple of (per_token_logps, entropies, current_topk_logps).
|
| 779 |
+
"""
|
| 780 |
+
batch_size = batch_size or input_ids.size(0)
|
| 781 |
+
all_logps = []
|
| 782 |
+
all_entropies = []
|
| 783 |
+
all_topk_logps = []
|
| 784 |
+
|
| 785 |
+
for start in range(0, input_ids.size(0), batch_size):
|
| 786 |
+
end = start + batch_size
|
| 787 |
+
input_ids_batch = input_ids[start:end]
|
| 788 |
+
attention_mask_batch = attention_mask[start:end]
|
| 789 |
+
|
| 790 |
+
model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch}
|
| 791 |
+
if image_grid_thw is not None and pixel_values is not None:
|
| 792 |
+
rows_per_image = image_grid_thw.prod(dim=-1)
|
| 793 |
+
rows_per_sample = torch.split(rows_per_image, num_images)
|
| 794 |
+
rows_per_sample = torch.stack([s.sum() for s in rows_per_sample])
|
| 795 |
+
cum_rows = torch.cat([torch.tensor([0], device=rows_per_sample.device), rows_per_sample.cumsum(0)])
|
| 796 |
+
row_start, row_end = cum_rows[start].item(), cum_rows[end].item()
|
| 797 |
+
model_inputs["pixel_values"] = pixel_values[row_start:row_end]
|
| 798 |
+
cum_imgs = torch.tensor([0] + num_images).cumsum(0)
|
| 799 |
+
img_start, img_end = cum_imgs[start], cum_imgs[end]
|
| 800 |
+
model_inputs["image_grid_thw"] = image_grid_thw[img_start:img_end]
|
| 801 |
+
elif pixel_values is not None:
|
| 802 |
+
model_inputs["pixel_values"] = pixel_values[start:end]
|
| 803 |
+
if pixel_attention_mask is not None:
|
| 804 |
+
model_inputs["pixel_attention_mask"] = pixel_attention_mask[start:end]
|
| 805 |
+
if image_sizes is not None:
|
| 806 |
+
model_inputs["image_sizes"] = image_sizes[start:end]
|
| 807 |
+
if token_type_ids is not None:
|
| 808 |
+
model_inputs["token_type_ids"] = token_type_ids[start:end]
|
| 809 |
+
if mm_token_type_ids is not None:
|
| 810 |
+
model_inputs["mm_token_type_ids"] = mm_token_type_ids[start:end]
|
| 811 |
+
|
| 812 |
+
if "logits_to_keep" in self.model_kwarg_keys:
|
| 813 |
+
model_inputs["logits_to_keep"] = logits_to_keep + 1
|
| 814 |
+
|
| 815 |
+
model_inputs["use_cache"] = False
|
| 816 |
+
|
| 817 |
+
logits = model(**model_inputs).logits
|
| 818 |
+
logits = logits[:, :-1, :]
|
| 819 |
+
logits = logits[:, -logits_to_keep:, :]
|
| 820 |
+
logits = logits / self.temperature
|
| 821 |
+
|
| 822 |
+
completion_ids = input_ids_batch[:, -logits_to_keep:]
|
| 823 |
+
logps = selective_log_softmax(logits, completion_ids)
|
| 824 |
+
all_logps.append(logps)
|
| 825 |
+
|
| 826 |
+
if compute_entropy:
|
| 827 |
+
with torch.no_grad():
|
| 828 |
+
entropies = entropy_from_logits(logits)
|
| 829 |
+
all_entropies.append(entropies)
|
| 830 |
+
|
| 831 |
+
with torch.no_grad():
|
| 832 |
+
topk_logps = selective_log_softmax(logits, topk_token_ids[start:end])
|
| 833 |
+
all_topk_logps.append(topk_logps)
|
| 834 |
+
|
| 835 |
+
logps = torch.cat(all_logps, dim=0)
|
| 836 |
+
entropies = torch.cat(all_entropies, dim=0) if compute_entropy else None
|
| 837 |
+
topk_logps = torch.cat(all_topk_logps, dim=0)
|
| 838 |
+
return logps, entropies, topk_logps
|
| 839 |
+
|
| 840 |
+
def _generate_and_score_completions(
|
| 841 |
+
self, inputs: list[dict[str, torch.Tensor | Any]]
|
| 842 |
+
) -> dict[str, torch.Tensor | Any]:
|
| 843 |
+
device = self.accelerator.device
|
| 844 |
+
mode = "train" if self.model.training else "eval"
|
| 845 |
+
|
| 846 |
+
prompts = [x["prompt"] for x in inputs]
|
| 847 |
+
|
| 848 |
+
if self.environments:
|
| 849 |
+
for prompt, environment, reset_kwargs in zip(prompts, self.environments, inputs, strict=True):
|
| 850 |
+
observation = environment.reset(**reset_kwargs)
|
| 851 |
+
if observation is None:
|
| 852 |
+
continue
|
| 853 |
+
prompt[-1]["content"] += observation
|
| 854 |
+
|
| 855 |
+
if "images" in inputs[0]:
|
| 856 |
+
images = [example.get("images") for example in inputs]
|
| 857 |
+
elif "image" in inputs[0]:
|
| 858 |
+
images = [[example.get("image")] if example.get("image") is not None else None for example in inputs]
|
| 859 |
+
else:
|
| 860 |
+
images = None
|
| 861 |
+
# Transformers requires at least one image in the batch, otherwise it throws an error
|
| 862 |
+
if images is not None and all(img_list == [] for img_list in images):
|
| 863 |
+
images = None
|
| 864 |
+
|
| 865 |
+
# If the prompts are conversational and the inputs contain images, we need to convert the prompts from
|
| 866 |
+
# [{"role": "user", "content": "What color is the sky?"}] to
|
| 867 |
+
# [{"role": "user", "content": [{"type": "image", "image": <Image>}, {"type": "text", "text": "What color is the sky?"}]}]
|
| 868 |
+
if images is not None:
|
| 869 |
+
if not is_conversational(inputs[0]):
|
| 870 |
+
raise ValueError(
|
| 871 |
+
"Multimodal training requires conversational prompts. It looks like the dataset contains "
|
| 872 |
+
"non-conversational inputs, likely because a chat template was applied before passing the dataset "
|
| 873 |
+
"to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat "
|
| 874 |
+
"template internally."
|
| 875 |
+
)
|
| 876 |
+
prompts = [
|
| 877 |
+
prepare_multimodal_messages(prompt, images=image_list)
|
| 878 |
+
for prompt, image_list in zip(prompts, images, strict=True)
|
| 879 |
+
]
|
| 880 |
+
|
| 881 |
+
(
|
| 882 |
+
prompt_ids_list,
|
| 883 |
+
completion_ids_list,
|
| 884 |
+
tool_mask_list,
|
| 885 |
+
completions,
|
| 886 |
+
num_items_in_batch,
|
| 887 |
+
sampling_per_token_logps_list,
|
| 888 |
+
topk_logprobs_list,
|
| 889 |
+
topk_token_ids_list,
|
| 890 |
+
extra_fields,
|
| 891 |
+
) = self._generate(prompts)
|
| 892 |
+
|
| 893 |
+
# Convert lists of token IDs to padded tensors
|
| 894 |
+
prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list]
|
| 895 |
+
prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids]
|
| 896 |
+
prompt_ids = pad(
|
| 897 |
+
prompt_ids,
|
| 898 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 899 |
+
padding_side="left",
|
| 900 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 901 |
+
).to(device=device)
|
| 902 |
+
prompt_mask = pad(
|
| 903 |
+
prompt_mask, padding_value=0, padding_side="left", pad_to_multiple_of=self.pad_to_multiple_of
|
| 904 |
+
).to(device=device)
|
| 905 |
+
completion_ids = [torch.tensor(ids) for ids in completion_ids_list]
|
| 906 |
+
completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids]
|
| 907 |
+
completion_ids = pad(
|
| 908 |
+
completion_ids,
|
| 909 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 910 |
+
padding_side="right",
|
| 911 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 912 |
+
).to(device=device)
|
| 913 |
+
completion_mask = pad(
|
| 914 |
+
completion_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of
|
| 915 |
+
).to(device=device)
|
| 916 |
+
sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list]
|
| 917 |
+
sampling_per_token_logps = pad(
|
| 918 |
+
sampling_per_token_logps,
|
| 919 |
+
padding_value=0.0,
|
| 920 |
+
padding_side="right",
|
| 921 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 922 |
+
).to(device=device)
|
| 923 |
+
if tool_mask_list is not None:
|
| 924 |
+
tool_mask = [torch.tensor(mask) for mask in tool_mask_list]
|
| 925 |
+
tool_mask = pad(
|
| 926 |
+
tool_mask, padding_value=1, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of
|
| 927 |
+
).to(device=device)
|
| 928 |
+
else:
|
| 929 |
+
tool_mask = None
|
| 930 |
+
if topk_logprobs_list is not None:
|
| 931 |
+
sampling_topk_logps = [torch.tensor(lp) for lp in topk_logprobs_list]
|
| 932 |
+
sampling_topk_logps = pad(
|
| 933 |
+
sampling_topk_logps,
|
| 934 |
+
padding_value=0.0,
|
| 935 |
+
padding_side="right",
|
| 936 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 937 |
+
).to(device=device)
|
| 938 |
+
sampling_topk_token_ids = [torch.tensor(tid, dtype=torch.long) for tid in topk_token_ids_list]
|
| 939 |
+
sampling_topk_token_ids = pad(
|
| 940 |
+
sampling_topk_token_ids,
|
| 941 |
+
padding_value=0,
|
| 942 |
+
padding_side="right",
|
| 943 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 944 |
+
).to(device=device)
|
| 945 |
+
else:
|
| 946 |
+
sampling_topk_logps = None
|
| 947 |
+
sampling_topk_token_ids = None
|
| 948 |
+
|
| 949 |
+
# If mask_truncated_completions is enabled, zero out truncated completions for attention and loss masking
|
| 950 |
+
if self.mask_truncated_completions:
|
| 951 |
+
eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id]
|
| 952 |
+
is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device)
|
| 953 |
+
# Mask completion_mask for attention masking
|
| 954 |
+
completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int()
|
| 955 |
+
# Also mask tool_mask for consistency in multi-turn training
|
| 956 |
+
if tool_mask is not None:
|
| 957 |
+
tool_mask = tool_mask * (~is_truncated).unsqueeze(1).int()
|
| 958 |
+
|
| 959 |
+
# Concatenate prompt_mask with completion_mask for logit computation
|
| 960 |
+
prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C)
|
| 961 |
+
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C)
|
| 962 |
+
|
| 963 |
+
logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
|
| 964 |
+
batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size
|
| 965 |
+
|
| 966 |
+
num_images = [len(img_list) for img_list in images] if images is not None else None
|
| 967 |
+
|
| 968 |
+
# Get forward_kwargs for models with multimodal inputs
|
| 969 |
+
if images is not None:
|
| 970 |
+
prompts_text = [
|
| 971 |
+
apply_chat_template(
|
| 972 |
+
{"prompt": prompt}, self.processing_class, tools=self.tools, **self.chat_template_kwargs
|
| 973 |
+
)["prompt"]
|
| 974 |
+
for prompt in prompts
|
| 975 |
+
]
|
| 976 |
+
prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt")
|
| 977 |
+
prompt_inputs = Trainer._prepare_inputs(self, prompt_inputs)
|
| 978 |
+
forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]}
|
| 979 |
+
else:
|
| 980 |
+
forward_kwargs = {}
|
| 981 |
+
|
| 982 |
+
# If token_type_ids are used, extend them with zeros for the completion part
|
| 983 |
+
if "token_type_ids" in forward_kwargs:
|
| 984 |
+
token_type_ids = forward_kwargs["token_type_ids"]
|
| 985 |
+
if self.pad_to_multiple_of is not None:
|
| 986 |
+
padding_size = prompt_ids.size(1) - token_type_ids.size(1)
|
| 987 |
+
if padding_size > 0:
|
| 988 |
+
token_type_ids = torch.cat(
|
| 989 |
+
[token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1
|
| 990 |
+
)
|
| 991 |
+
forward_kwargs["token_type_ids"] = torch.cat(
|
| 992 |
+
[token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1
|
| 993 |
+
)
|
| 994 |
+
# If mm_token_type_ids are used, extend them with zeros for the completion part
|
| 995 |
+
if "mm_token_type_ids" in forward_kwargs:
|
| 996 |
+
mm_token_type_ids = forward_kwargs["mm_token_type_ids"]
|
| 997 |
+
if self.pad_to_multiple_of is not None:
|
| 998 |
+
padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1)
|
| 999 |
+
if padding_size > 0:
|
| 1000 |
+
mm_token_type_ids = torch.cat(
|
| 1001 |
+
[mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids],
|
| 1002 |
+
dim=1,
|
| 1003 |
+
)
|
| 1004 |
+
forward_kwargs["mm_token_type_ids"] = torch.cat(
|
| 1005 |
+
[mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1
|
| 1006 |
+
)
|
| 1007 |
+
|
| 1008 |
+
# When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a
|
| 1009 |
+
# torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True").
|
| 1010 |
+
# Temporarily disable checkpointing to avoid this warning during inference.
|
| 1011 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 1012 |
+
# Compute the per-token log probabilities for the reference model
|
| 1013 |
+
if self.beta != 0.0:
|
| 1014 |
+
if self.ref_model is not None:
|
| 1015 |
+
ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies(
|
| 1016 |
+
self.ref_model,
|
| 1017 |
+
prompt_completion_ids,
|
| 1018 |
+
attention_mask,
|
| 1019 |
+
logits_to_keep,
|
| 1020 |
+
batch_size=batch_size,
|
| 1021 |
+
num_images=num_images,
|
| 1022 |
+
**forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
|
| 1023 |
+
)
|
| 1024 |
+
else:
|
| 1025 |
+
# When training a PEFT adapter, how we obtain the reference depends on the setup:
|
| 1026 |
+
# - New adapter: disabling adapters yields the base model.
|
| 1027 |
+
# - Re-training an existing adapter: an initial copy is loaded under the name "ref".
|
| 1028 |
+
model = self.accelerator.unwrap_model(self.model)
|
| 1029 |
+
with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None):
|
| 1030 |
+
ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies(
|
| 1031 |
+
self.model,
|
| 1032 |
+
prompt_completion_ids,
|
| 1033 |
+
attention_mask,
|
| 1034 |
+
logits_to_keep,
|
| 1035 |
+
batch_size=batch_size,
|
| 1036 |
+
num_images=num_images,
|
| 1037 |
+
**forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
|
| 1038 |
+
)
|
| 1039 |
+
else:
|
| 1040 |
+
ref_per_token_logps = None
|
| 1041 |
+
|
| 1042 |
+
# Decode
|
| 1043 |
+
prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True)
|
| 1044 |
+
completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
|
| 1045 |
+
|
| 1046 |
+
# Merge extra_fields from rollout_func into inputs for reward functions
|
| 1047 |
+
if extra_fields:
|
| 1048 |
+
for i, inp in enumerate(inputs):
|
| 1049 |
+
for key, values in extra_fields.items():
|
| 1050 |
+
if isinstance(values, list) and i < len(values):
|
| 1051 |
+
inp[key] = values[i]
|
| 1052 |
+
elif not isinstance(values, list):
|
| 1053 |
+
inp[key] = values
|
| 1054 |
+
|
| 1055 |
+
# Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is
|
| 1056 |
+
# important because rewards will be normalized per group, and completions are distributed. We will later slice
|
| 1057 |
+
# rewards_per_func to extract each process's subset.
|
| 1058 |
+
rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
|
| 1059 |
+
num_generations = self.num_generations if mode == "train" else self.num_generations_eval
|
| 1060 |
+
|
| 1061 |
+
if self.multi_objective_aggregation == "sum_then_normalize":
|
| 1062 |
+
# Apply weights to each reward function's output and sum
|
| 1063 |
+
rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
|
| 1064 |
+
mean_grouped_rewards = rewards.view(-1, num_generations).mean(dim=1)
|
| 1065 |
+
mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(num_generations, dim=0)
|
| 1066 |
+
if self.scale_rewards in ["group", "none"]:
|
| 1067 |
+
# If self.scale_rewards = "none", we'll only use std_rewards to check for zero std for logging
|
| 1068 |
+
if num_generations > 1:
|
| 1069 |
+
std_rewards = rewards.view(-1, num_generations).std(dim=1)
|
| 1070 |
+
std_rewards = std_rewards.repeat_interleave(num_generations, dim=0)
|
| 1071 |
+
else: # doesn't occur during training, but could occur in eval when num_generations_eval=1
|
| 1072 |
+
std_rewards = torch.zeros_like(rewards)
|
| 1073 |
+
elif self.scale_rewards == "batch":
|
| 1074 |
+
# Compute global std
|
| 1075 |
+
if rewards.numel() > 1:
|
| 1076 |
+
std_rewards = rewards.std().expand_as(rewards)
|
| 1077 |
+
else: # doesn't occur during training, but could occur in eval when num_generations_eval=batch_size=1
|
| 1078 |
+
std_rewards = torch.zeros_like(rewards)
|
| 1079 |
+
else:
|
| 1080 |
+
raise ValueError(
|
| 1081 |
+
f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'."
|
| 1082 |
+
)
|
| 1083 |
+
|
| 1084 |
+
advantages = rewards - mean_grouped_rewards
|
| 1085 |
+
if self.scale_rewards != "none":
|
| 1086 |
+
advantages = advantages / (std_rewards + 1e-4)
|
| 1087 |
+
is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging
|
| 1088 |
+
|
| 1089 |
+
elif self.multi_objective_aggregation == "normalize_then_sum":
|
| 1090 |
+
grouped = rewards_per_func.view(-1, num_generations, len(self.reward_funcs))
|
| 1091 |
+
mean_k = torch.nanmean(grouped, dim=1, keepdim=True)
|
| 1092 |
+
std_k = nanstd(grouped, dim=1, keepdim=True) if num_generations > 1 else torch.zeros_like(mean_k)
|
| 1093 |
+
reward_k = (grouped - mean_k) / (std_k + 1e-4)
|
| 1094 |
+
reward_k = reward_k.view(-1, len(self.reward_funcs))
|
| 1095 |
+
rewards = (reward_k * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
|
| 1096 |
+
std_rewards = rewards.std().expand_as(rewards) if rewards.numel() > 1 else torch.zeros_like(rewards)
|
| 1097 |
+
advantages = (rewards - rewards.mean()) / (std_rewards + 1e-4)
|
| 1098 |
+
is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging
|
| 1099 |
+
|
| 1100 |
+
else:
|
| 1101 |
+
raise ValueError(
|
| 1102 |
+
f"Invalid multi_objective_aggregation: {self.multi_objective_aggregation}. Must be "
|
| 1103 |
+
"'sum_then_normalize' or 'normalize_then_sum'."
|
| 1104 |
+
)
|
| 1105 |
+
|
| 1106 |
+
# Slice to keep only the local part of the data
|
| 1107 |
+
process_slice = slice(
|
| 1108 |
+
self.accelerator.process_index * len(prompts),
|
| 1109 |
+
(self.accelerator.process_index + 1) * len(prompts),
|
| 1110 |
+
)
|
| 1111 |
+
all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
|
| 1112 |
+
advantages = advantages[process_slice]
|
| 1113 |
+
|
| 1114 |
+
# Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
|
| 1115 |
+
for i, reward_func_name in enumerate(self.reward_func_names):
|
| 1116 |
+
mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
|
| 1117 |
+
self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
|
| 1118 |
+
std_func_rewards = nanstd(rewards_per_func[:, i]).item()
|
| 1119 |
+
self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards)
|
| 1120 |
+
rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1)
|
| 1121 |
+
self._metrics[mode]["reward"].append(rewards.mean().item())
|
| 1122 |
+
self._metrics[mode]["reward_std"].append(rewards.std().item())
|
| 1123 |
+
self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
|
| 1124 |
+
|
| 1125 |
+
# Log prompt and completion texts
|
| 1126 |
+
self._logs["prompt"].extend(gather_object(prompts_text))
|
| 1127 |
+
self._logs["completion"].extend(gather_object(completions_text))
|
| 1128 |
+
for i, name in enumerate(self.reward_func_names):
|
| 1129 |
+
self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
|
| 1130 |
+
self._logs["advantages"].extend(all_process_advantages.tolist())
|
| 1131 |
+
|
| 1132 |
+
# Flush user-logged extra columns (from log_extra), gathering across processes.
|
| 1133 |
+
# Keys must be sorted so that all ranks call gather_object in the same order, otherwise values
|
| 1134 |
+
# get mis-attributed across columns (dict insertion order may differ between processes).
|
| 1135 |
+
for column in sorted(self._pending_extra_logs):
|
| 1136 |
+
self._logs["extra"][column].extend(gather_object(self._pending_extra_logs[column]))
|
| 1137 |
+
self._pending_extra_logs.clear()
|
| 1138 |
+
|
| 1139 |
+
# Flush user-logged metrics (from log_metric), averaging across processes.
|
| 1140 |
+
# Keys must be sorted so that all ranks call accelerator.gather in the same order, otherwise values
|
| 1141 |
+
# get mis-attributed across metrics (dict insertion order may differ between processes).
|
| 1142 |
+
for name in sorted(self._pending_metrics):
|
| 1143 |
+
values = self._pending_metrics[name]
|
| 1144 |
+
local_mean = sum(values) / len(values)
|
| 1145 |
+
global_mean = self.accelerator.gather(torch.tensor(local_mean, device=device)).mean().item()
|
| 1146 |
+
self._metrics[mode][name].append(global_mean)
|
| 1147 |
+
self._pending_metrics.clear()
|
| 1148 |
+
|
| 1149 |
+
if images is not None:
|
| 1150 |
+
self._logs["images"].extend(gather_object(images))
|
| 1151 |
+
|
| 1152 |
+
output = {
|
| 1153 |
+
"prompt_ids": prompt_ids,
|
| 1154 |
+
"prompt_mask": prompt_mask,
|
| 1155 |
+
"completion_ids": completion_ids,
|
| 1156 |
+
"completion_mask": completion_mask,
|
| 1157 |
+
"advantages": advantages,
|
| 1158 |
+
"num_items_in_batch": num_items_in_batch,
|
| 1159 |
+
"sampling_per_token_logps": sampling_per_token_logps,
|
| 1160 |
+
}
|
| 1161 |
+
if ref_per_token_logps is not None:
|
| 1162 |
+
output["ref_per_token_logps"] = ref_per_token_logps
|
| 1163 |
+
if "pixel_values" in forward_kwargs:
|
| 1164 |
+
output["pixel_values"] = forward_kwargs["pixel_values"]
|
| 1165 |
+
if "image_grid_thw" in forward_kwargs:
|
| 1166 |
+
output["image_grid_thw"] = forward_kwargs["image_grid_thw"]
|
| 1167 |
+
if "pixel_attention_mask" in forward_kwargs:
|
| 1168 |
+
output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"]
|
| 1169 |
+
if "image_sizes" in forward_kwargs:
|
| 1170 |
+
output["image_sizes"] = forward_kwargs["image_sizes"]
|
| 1171 |
+
if "token_type_ids" in forward_kwargs:
|
| 1172 |
+
output["token_type_ids"] = forward_kwargs["token_type_ids"]
|
| 1173 |
+
if "mm_token_type_ids" in forward_kwargs:
|
| 1174 |
+
output["mm_token_type_ids"] = forward_kwargs["mm_token_type_ids"]
|
| 1175 |
+
if images is not None:
|
| 1176 |
+
output["num_images"] = num_images
|
| 1177 |
+
if tool_mask is not None:
|
| 1178 |
+
output["tool_mask"] = tool_mask
|
| 1179 |
+
if sampling_topk_logps is not None:
|
| 1180 |
+
output["sampling_topk_logps"] = sampling_topk_logps
|
| 1181 |
+
if sampling_topk_token_ids is not None:
|
| 1182 |
+
output["sampling_topk_token_ids"] = sampling_topk_token_ids
|
| 1183 |
+
return output
|
| 1184 |
+
|
| 1185 |
+
@torch.no_grad()
|
| 1186 |
+
def _compute_divergence_mask(
|
| 1187 |
+
self,
|
| 1188 |
+
per_token_logps,
|
| 1189 |
+
sampling_per_token_logps,
|
| 1190 |
+
advantages,
|
| 1191 |
+
completion_mask,
|
| 1192 |
+
current_topk_logps=None,
|
| 1193 |
+
sampling_topk_logps=None,
|
| 1194 |
+
):
|
| 1195 |
+
"""
|
| 1196 |
+
Compute a per-token trust-region mask based on the configured divergence type. Tokens where the policy has
|
| 1197 |
+
diverged too far from the sampling distribution (in a direction that would increase the loss) are masked out.
|
| 1198 |
+
|
| 1199 |
+
Args:
|
| 1200 |
+
per_token_logps (`torch.Tensor`):
|
| 1201 |
+
Log-probabilities of the current policy at the sampled tokens, shape `(B, T)`.
|
| 1202 |
+
sampling_per_token_logps (`torch.Tensor`):
|
| 1203 |
+
Log-probabilities of the sampling (rollout) policy at the sampled tokens, shape `(B, T)`.
|
| 1204 |
+
advantages (`torch.Tensor`):
|
| 1205 |
+
Per-token or per-sequence advantage estimates, broadcastable to `(B, T)`.
|
| 1206 |
+
completion_mask (`torch.Tensor`):
|
| 1207 |
+
Binary mask of shape `(B, T)` where `1` indicates valid completion tokens and `0` padding.
|
| 1208 |
+
current_topk_logps (`torch.Tensor` or `None`):
|
| 1209 |
+
Log-probabilities of the current policy at the rollout's top-K token IDs, shape `(B, T, K)`. Required
|
| 1210 |
+
when `divergence_type` is `"topk_tv"` or `"topk_kl"`.
|
| 1211 |
+
sampling_topk_logps (`torch.Tensor` or `None`):
|
| 1212 |
+
Log-probabilities of the sampling policy at the rollout's top-K token IDs, shape `(B, T, K)`. Required
|
| 1213 |
+
when `divergence_type` is `"topk_tv"` or `"topk_kl"`.
|
| 1214 |
+
|
| 1215 |
+
Returns:
|
| 1216 |
+
`torch.Tensor`:
|
| 1217 |
+
Float mask of shape `(B, T)` where `1.0` indicates tokens to keep and `0.0` tokens to mask out.
|
| 1218 |
+
"""
|
| 1219 |
+
prob = torch.exp(per_token_logps)
|
| 1220 |
+
sampling_prob = torch.exp(sampling_per_token_logps)
|
| 1221 |
+
|
| 1222 |
+
delta_low = self.epsilon_low
|
| 1223 |
+
delta_high = self.epsilon_high
|
| 1224 |
+
|
| 1225 |
+
if self.divergence_type == "binary_tv":
|
| 1226 |
+
# TV = |π - μ|
|
| 1227 |
+
divergence = (prob - sampling_prob).abs()
|
| 1228 |
+
# Mask tokens where divergence > threshold AND policy moves away from trust region
|
| 1229 |
+
invalid_pos = (divergence > delta_high) & (prob > sampling_prob)
|
| 1230 |
+
invalid_neg = (divergence > delta_low) & (prob < sampling_prob)
|
| 1231 |
+
mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg)
|
| 1232 |
+
|
| 1233 |
+
elif self.divergence_type == "binary_kl":
|
| 1234 |
+
# Bernoulli KL: D = μ log(μ/π) + (1-μ) log((1-μ)/(1-π))
|
| 1235 |
+
kl = sampling_prob * (sampling_per_token_logps - per_token_logps) + (1 - sampling_prob) * (
|
| 1236 |
+
torch.log1p(-sampling_prob.clamp(max=1 - 1e-7)) - torch.log1p(-prob.clamp(max=1 - 1e-7))
|
| 1237 |
+
)
|
| 1238 |
+
|
| 1239 |
+
invalid_pos = (kl > delta_high) & (prob > sampling_prob)
|
| 1240 |
+
invalid_neg = (kl > delta_low) & (prob < sampling_prob)
|
| 1241 |
+
mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg)
|
| 1242 |
+
|
| 1243 |
+
elif self.divergence_type in ("topk_tv", "topk_kl"):
|
| 1244 |
+
current_topk_probs = torch.exp(current_topk_logps.float())
|
| 1245 |
+
rollout_topk_probs = torch.exp(sampling_topk_logps.float())
|
| 1246 |
+
|
| 1247 |
+
# Aggregate remaining probability mass outside top-K into a single rest bucket.
|
| 1248 |
+
rollout_rest = (1.0 - rollout_topk_probs.sum(dim=-1)).clamp(min=1e-12)
|
| 1249 |
+
current_rest = (1.0 - current_topk_probs.sum(dim=-1)).clamp(min=1e-12)
|
| 1250 |
+
|
| 1251 |
+
if self.divergence_type == "topk_tv":
|
| 1252 |
+
topk_tv = (current_topk_probs - rollout_topk_probs).abs().sum(dim=-1)
|
| 1253 |
+
rest_tv = (current_rest - rollout_rest).abs()
|
| 1254 |
+
divergence = (topk_tv + rest_tv) / 2.0
|
| 1255 |
+
else:
|
| 1256 |
+
topk_kl = (rollout_topk_probs * (sampling_topk_logps - current_topk_logps)).sum(dim=-1)
|
| 1257 |
+
rest_kl = rollout_rest * (rollout_rest.log() - current_rest.log())
|
| 1258 |
+
divergence = topk_kl + rest_kl
|
| 1259 |
+
|
| 1260 |
+
invalid_pos = (divergence > delta_high) & (prob > sampling_prob)
|
| 1261 |
+
invalid_neg = (divergence > delta_low) & (prob < sampling_prob)
|
| 1262 |
+
mask = torch.where(advantages > 0, ~invalid_pos, ~invalid_neg)
|
| 1263 |
+
|
| 1264 |
+
else:
|
| 1265 |
+
raise ValueError(f"Unknown divergence_type: {self.divergence_type}")
|
| 1266 |
+
|
| 1267 |
+
return mask.float() * completion_mask
|
| 1268 |
+
|
| 1269 |
+
def _compute_loss(self, model, inputs):
|
| 1270 |
+
# Compute per-token log probabilities for the model
|
| 1271 |
+
prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
|
| 1272 |
+
completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
|
| 1273 |
+
input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
|
| 1274 |
+
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
|
| 1275 |
+
logits_to_keep = completion_ids.size(1)
|
| 1276 |
+
mask = completion_mask if "tool_mask" not in inputs else completion_mask * inputs["tool_mask"]
|
| 1277 |
+
|
| 1278 |
+
forward_kwargs = {
|
| 1279 |
+
"pixel_values": inputs.get("pixel_values"),
|
| 1280 |
+
"image_grid_thw": inputs.get("image_grid_thw"),
|
| 1281 |
+
"num_images": inputs.get("num_images"),
|
| 1282 |
+
"pixel_attention_mask": inputs.get("pixel_attention_mask"),
|
| 1283 |
+
"image_sizes": inputs.get("image_sizes"),
|
| 1284 |
+
"token_type_ids": inputs.get("token_type_ids"),
|
| 1285 |
+
"mm_token_type_ids": inputs.get("mm_token_type_ids"),
|
| 1286 |
+
}
|
| 1287 |
+
|
| 1288 |
+
sampling_topk_token_ids = inputs.get("sampling_topk_token_ids")
|
| 1289 |
+
if self.divergence_type.startswith("topk_") and sampling_topk_token_ids is not None:
|
| 1290 |
+
per_token_logps, entropies, current_topk_logps = self._get_per_token_logps_with_topk(
|
| 1291 |
+
model,
|
| 1292 |
+
input_ids,
|
| 1293 |
+
attention_mask,
|
| 1294 |
+
logits_to_keep,
|
| 1295 |
+
topk_token_ids=sampling_topk_token_ids,
|
| 1296 |
+
compute_entropy=True,
|
| 1297 |
+
**forward_kwargs,
|
| 1298 |
+
)
|
| 1299 |
+
else:
|
| 1300 |
+
per_token_logps, entropies, _ = self._get_per_token_logps_and_entropies(
|
| 1301 |
+
model,
|
| 1302 |
+
input_ids,
|
| 1303 |
+
attention_mask,
|
| 1304 |
+
logits_to_keep,
|
| 1305 |
+
compute_entropy=True,
|
| 1306 |
+
**forward_kwargs,
|
| 1307 |
+
)
|
| 1308 |
+
current_topk_logps = None
|
| 1309 |
+
|
| 1310 |
+
sampling_per_token_logps = inputs["sampling_per_token_logps"]
|
| 1311 |
+
sampling_topk_logps = inputs.get("sampling_topk_logps")
|
| 1312 |
+
|
| 1313 |
+
advantages = inputs["advantages"]
|
| 1314 |
+
if advantages.dim() == 1:
|
| 1315 |
+
advantages = advantages.unsqueeze(1)
|
| 1316 |
+
|
| 1317 |
+
# DPPO: compute IS ratio (clamped, detached) and divergence mask
|
| 1318 |
+
log_ratio = per_token_logps - sampling_per_token_logps
|
| 1319 |
+
ratio = torch.exp(log_ratio.clamp(max=math.log(self.clip_ratio_c))).detach()
|
| 1320 |
+
divergence_mask = self._compute_divergence_mask(
|
| 1321 |
+
per_token_logps,
|
| 1322 |
+
sampling_per_token_logps,
|
| 1323 |
+
advantages,
|
| 1324 |
+
mask,
|
| 1325 |
+
current_topk_logps=current_topk_logps,
|
| 1326 |
+
sampling_topk_logps=sampling_topk_logps,
|
| 1327 |
+
)
|
| 1328 |
+
|
| 1329 |
+
# DPPO loss: -advantages * ratio * mask * log_prob
|
| 1330 |
+
per_token_loss = -advantages * ratio * divergence_mask * per_token_logps
|
| 1331 |
+
|
| 1332 |
+
# KL divergence with reference model
|
| 1333 |
+
if self.beta != 0.0:
|
| 1334 |
+
ref_per_token_logps = inputs["ref_per_token_logps"]
|
| 1335 |
+
per_token_kl = (
|
| 1336 |
+
torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
|
| 1337 |
+
)
|
| 1338 |
+
per_token_loss = per_token_loss + self.beta * per_token_kl
|
| 1339 |
+
|
| 1340 |
+
mode = "train" if self.model.training else "eval"
|
| 1341 |
+
normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes
|
| 1342 |
+
loss = (per_token_loss * mask).sum() / normalizer
|
| 1343 |
+
|
| 1344 |
+
# Log metrics
|
| 1345 |
+
completion_token_count = mask.sum().clamp(min=1.0)
|
| 1346 |
+
|
| 1347 |
+
def masked_batch_mean(x):
|
| 1348 |
+
if x.shape[1] == 1:
|
| 1349 |
+
return x.mean()
|
| 1350 |
+
return (x * mask).sum() / completion_token_count
|
| 1351 |
+
|
| 1352 |
+
if self.beta != 0.0:
|
| 1353 |
+
mean_kl = masked_batch_mean(per_token_kl)
|
| 1354 |
+
self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
|
| 1355 |
+
|
| 1356 |
+
mean_entropy = masked_batch_mean(entropies)
|
| 1357 |
+
self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item())
|
| 1358 |
+
|
| 1359 |
+
prob_diff = (torch.exp(per_token_logps) - torch.exp(sampling_per_token_logps)).abs()
|
| 1360 |
+
self._metrics[mode]["prob_diff/mean"].append(
|
| 1361 |
+
self.accelerator.gather(masked_batch_mean(prob_diff)).nanmean().item()
|
| 1362 |
+
)
|
| 1363 |
+
per_seq_max = prob_diff.masked_fill(mask == 0, float("-inf")).max(dim=1).values
|
| 1364 |
+
per_seq_min = prob_diff.masked_fill(mask == 0, float("inf")).min(dim=1).values
|
| 1365 |
+
self._metrics[mode]["prob_diff/max"].append(self.accelerator.gather(per_seq_max).max().item())
|
| 1366 |
+
self._metrics[mode]["prob_diff/min"].append(self.accelerator.gather(per_seq_min).min().item())
|
| 1367 |
+
|
| 1368 |
+
self._metrics[mode]["advantages/mean"].append(advantages.mean().item())
|
| 1369 |
+
self._metrics[mode]["advantages/std"].append(advantages.std().item())
|
| 1370 |
+
|
| 1371 |
+
# Log divergence mask statistics (analogous to clip_ratio in GRPO)
|
| 1372 |
+
is_masked = (divergence_mask == 0) & (mask > 0)
|
| 1373 |
+
is_masked_pos = is_masked & (advantages > 0)
|
| 1374 |
+
is_masked_neg = is_masked & (advantages < 0)
|
| 1375 |
+
|
| 1376 |
+
mask_ratio_pos = masked_batch_mean(is_masked_pos.float())
|
| 1377 |
+
mask_ratio_neg = masked_batch_mean(is_masked_neg.float())
|
| 1378 |
+
mask_ratio = masked_batch_mean(is_masked.float())
|
| 1379 |
+
|
| 1380 |
+
gathered_mask_ratio_neg = self.accelerator.gather(mask_ratio_neg)
|
| 1381 |
+
self._metrics[mode]["mask_ratio/negative_adv_mean"].append(gathered_mask_ratio_neg.nanmean().item())
|
| 1382 |
+
gathered_mask_ratio_pos = self.accelerator.gather(mask_ratio_pos)
|
| 1383 |
+
self._metrics[mode]["mask_ratio/positive_adv_mean"].append(gathered_mask_ratio_pos.nanmean().item())
|
| 1384 |
+
gathered_mask_ratio = self.accelerator.gather(mask_ratio)
|
| 1385 |
+
self._metrics[mode]["mask_ratio/overall_mean"].append(gathered_mask_ratio.nanmean().item())
|
| 1386 |
+
|
| 1387 |
+
return loss
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gfpo/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 .gfpo_config import GFPOConfig
|
| 16 |
+
from .gfpo_trainer import GFPOTrainer
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gfpo/gfpo_config.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.grpo_config import GRPOConfig as _GRPOConfig
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class GFPOConfig(_GRPOConfig):
|
| 22 |
+
num_remains_in_group: int | None = field(
|
| 23 |
+
default=None,
|
| 24 |
+
metadata={
|
| 25 |
+
"help": "number inputs remains after group filter function, `'num_remains_in_group'` must be >=2 if given."
|
| 26 |
+
},
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def __post_init__(self):
|
| 30 |
+
super().__post_init__()
|
| 31 |
+
|
| 32 |
+
if self.num_remains_in_group is not None and self.num_remains_in_group >= self.num_generations:
|
| 33 |
+
raise ValueError(
|
| 34 |
+
f"Number remains in Group {self.num_remains_in_group} must be less than num_generations : {self.num_generations}."
|
| 35 |
+
)
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gfpo/gfpo_trainer.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from collections.abc import Callable
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from accelerate.utils import gather_object
|
| 21 |
+
|
| 22 |
+
from ...data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages
|
| 23 |
+
from ...models.utils import disable_gradient_checkpointing
|
| 24 |
+
from ...trainer.grpo_trainer import GRPOTrainer as _GRPOTrainer
|
| 25 |
+
from ...trainer.utils import nanmax, nanmin, nanstd, pad
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
logger = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
GroupFilterFunc = Callable[[list[list[Any]], list[list[Any]]], list[list[float]]]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class GFPOTrainer(_GRPOTrainer):
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
model,
|
| 37 |
+
reward_funcs,
|
| 38 |
+
args=None,
|
| 39 |
+
train_dataset=None,
|
| 40 |
+
eval_dataset=None,
|
| 41 |
+
processing_class=None,
|
| 42 |
+
reward_processing_classes=None,
|
| 43 |
+
group_filter_func=None,
|
| 44 |
+
callbacks=None,
|
| 45 |
+
optimizers=(None, None),
|
| 46 |
+
peft_config=None,
|
| 47 |
+
):
|
| 48 |
+
super().__init__(
|
| 49 |
+
model=model,
|
| 50 |
+
reward_funcs=reward_funcs,
|
| 51 |
+
args=args,
|
| 52 |
+
train_dataset=train_dataset,
|
| 53 |
+
eval_dataset=eval_dataset,
|
| 54 |
+
processing_class=processing_class,
|
| 55 |
+
reward_processing_classes=reward_processing_classes,
|
| 56 |
+
callbacks=callbacks,
|
| 57 |
+
optimizers=optimizers,
|
| 58 |
+
peft_config=peft_config,
|
| 59 |
+
)
|
| 60 |
+
self.group_filter_func = group_filter_func
|
| 61 |
+
self.num_remains_in_group = args.num_remains_in_group
|
| 62 |
+
if self.group_filter_func is None and self.num_remains_in_group is not None:
|
| 63 |
+
raise ValueError(
|
| 64 |
+
f"Group filter function must not be None when num_remains_in_group ({self.num_remains_in_group}) is given."
|
| 65 |
+
)
|
| 66 |
+
if self.group_filter_func is not None and self.num_remains_in_group is None:
|
| 67 |
+
logger.warning("Group filter function is not activated since num_remains_in_group is not set")
|
| 68 |
+
|
| 69 |
+
def _generate_and_score_completions(self, inputs):
|
| 70 |
+
device = self.accelerator.device
|
| 71 |
+
mode = "train" if self.model.training else "eval"
|
| 72 |
+
|
| 73 |
+
prompts = [x["prompt"] for x in inputs]
|
| 74 |
+
|
| 75 |
+
if "images" in inputs[0]:
|
| 76 |
+
images = [example.get("images") for example in inputs]
|
| 77 |
+
elif "image" in inputs[0]:
|
| 78 |
+
images = [[example.get("image")] if example.get("image") is not None else None for example in inputs]
|
| 79 |
+
else:
|
| 80 |
+
images = None
|
| 81 |
+
# Transformers requires at least one image in the batch, otherwise it throws an error
|
| 82 |
+
if images is not None and all(img_list == [] for img_list in images):
|
| 83 |
+
images = None
|
| 84 |
+
|
| 85 |
+
# If the prompts are conversational and the inputs contain images, we need to convert the prompts from
|
| 86 |
+
# [{"role": "user", "content": "What color is the sky?"}] to
|
| 87 |
+
# [{"role": "user", "content": [{"type": "image", "image": <Image>}, {"type": "text", "text": "What color is the sky?"}]}]
|
| 88 |
+
if images is not None:
|
| 89 |
+
if not is_conversational(inputs[0]):
|
| 90 |
+
raise ValueError(
|
| 91 |
+
"Multimodal training requires conversational prompts. It looks like the dataset contains "
|
| 92 |
+
"non-conversational inputs, likely because a chat template was applied before passing the dataset "
|
| 93 |
+
"to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat "
|
| 94 |
+
"template internally."
|
| 95 |
+
)
|
| 96 |
+
prompts = [
|
| 97 |
+
prepare_multimodal_messages(prompt, images=image_list)
|
| 98 |
+
for prompt, image_list in zip(prompts, images, strict=True)
|
| 99 |
+
]
|
| 100 |
+
|
| 101 |
+
dataset_images = images # preserve dataset images before _generate may overwrite
|
| 102 |
+
(
|
| 103 |
+
prompt_ids_list,
|
| 104 |
+
completion_ids_list,
|
| 105 |
+
tool_mask_list,
|
| 106 |
+
completions,
|
| 107 |
+
num_items_in_batch,
|
| 108 |
+
sampling_per_token_logps_list,
|
| 109 |
+
extra_fields,
|
| 110 |
+
images,
|
| 111 |
+
tool_images,
|
| 112 |
+
) = self._generate(prompts)
|
| 113 |
+
if images is None:
|
| 114 |
+
images = dataset_images # restore dataset images (rollout_func path returns None)
|
| 115 |
+
|
| 116 |
+
# Convert lists of token IDs to padded tensors
|
| 117 |
+
prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list]
|
| 118 |
+
prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids]
|
| 119 |
+
prompt_ids = pad(
|
| 120 |
+
prompt_ids,
|
| 121 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 122 |
+
padding_side="left",
|
| 123 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 124 |
+
).to(device=device)
|
| 125 |
+
prompt_mask = pad(
|
| 126 |
+
prompt_mask,
|
| 127 |
+
padding_value=0,
|
| 128 |
+
padding_side="left",
|
| 129 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 130 |
+
).to(device=device)
|
| 131 |
+
completion_ids = [torch.tensor(ids) for ids in completion_ids_list]
|
| 132 |
+
completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids]
|
| 133 |
+
completion_ids = pad(
|
| 134 |
+
completion_ids,
|
| 135 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 136 |
+
padding_side="right",
|
| 137 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 138 |
+
).to(device=device)
|
| 139 |
+
completion_mask = pad(
|
| 140 |
+
completion_mask,
|
| 141 |
+
padding_value=0,
|
| 142 |
+
padding_side="right",
|
| 143 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 144 |
+
).to(device=device)
|
| 145 |
+
if sampling_per_token_logps_list is not None:
|
| 146 |
+
sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list]
|
| 147 |
+
sampling_per_token_logps = pad(
|
| 148 |
+
sampling_per_token_logps,
|
| 149 |
+
padding_value=0.0,
|
| 150 |
+
padding_side="right",
|
| 151 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 152 |
+
).to(device=device)
|
| 153 |
+
else:
|
| 154 |
+
sampling_per_token_logps = None
|
| 155 |
+
|
| 156 |
+
# If mask_truncated_completions is enabled, zero out truncated completions in completion_mask
|
| 157 |
+
if self.mask_truncated_completions:
|
| 158 |
+
eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id]
|
| 159 |
+
is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device)
|
| 160 |
+
completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int()
|
| 161 |
+
|
| 162 |
+
# Concatenate prompt_mask with completion_mask for logit computation
|
| 163 |
+
prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C)
|
| 164 |
+
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C)
|
| 165 |
+
|
| 166 |
+
logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
|
| 167 |
+
batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size
|
| 168 |
+
|
| 169 |
+
num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None
|
| 170 |
+
|
| 171 |
+
# Get forward_kwargs for models with multimodal inputs
|
| 172 |
+
if images is not None:
|
| 173 |
+
prompts_text = [
|
| 174 |
+
apply_chat_template({"prompt": prompt}, self.processing_class)["prompt"] for prompt in prompts
|
| 175 |
+
]
|
| 176 |
+
prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt")
|
| 177 |
+
prompt_inputs = super()._prepare_inputs(prompt_inputs)
|
| 178 |
+
forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]}
|
| 179 |
+
else:
|
| 180 |
+
forward_kwargs = {}
|
| 181 |
+
|
| 182 |
+
# If token_type_ids are used, extend them with zeros for the completion part
|
| 183 |
+
if "token_type_ids" in forward_kwargs:
|
| 184 |
+
token_type_ids = forward_kwargs["token_type_ids"]
|
| 185 |
+
if self.pad_to_multiple_of is not None:
|
| 186 |
+
# Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len
|
| 187 |
+
padding_size = prompt_ids.size(1) - token_type_ids.size(1)
|
| 188 |
+
if padding_size > 0:
|
| 189 |
+
token_type_ids = torch.cat(
|
| 190 |
+
[token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1
|
| 191 |
+
)
|
| 192 |
+
forward_kwargs["token_type_ids"] = torch.cat(
|
| 193 |
+
[token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1
|
| 194 |
+
)
|
| 195 |
+
# If mm_token_type_ids are used, extend them with zeros for the completion part
|
| 196 |
+
if "mm_token_type_ids" in forward_kwargs:
|
| 197 |
+
mm_token_type_ids = forward_kwargs["mm_token_type_ids"]
|
| 198 |
+
if self.pad_to_multiple_of is not None:
|
| 199 |
+
# Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len
|
| 200 |
+
padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1)
|
| 201 |
+
if padding_size > 0:
|
| 202 |
+
mm_token_type_ids = torch.cat(
|
| 203 |
+
[mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids],
|
| 204 |
+
dim=1,
|
| 205 |
+
)
|
| 206 |
+
forward_kwargs["mm_token_type_ids"] = torch.cat(
|
| 207 |
+
[mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a
|
| 211 |
+
# torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True").
|
| 212 |
+
# Temporarily disable checkpointing to avoid this warning during inference.
|
| 213 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 214 |
+
# If the generation and optimization steps are misaligned—i.e., if generation does not occur at the end of
|
| 215 |
+
# a full optimizer step (when gradient_accumulation_steps is not a multiple of generate_every)—then the
|
| 216 |
+
# samples may come from an earlier version of the model. In that case, we need to track old_per_token_logps
|
| 217 |
+
# for importance sampling. If the steps are aligned, importance sampling isn't necessary and we set
|
| 218 |
+
# old_per_token_logps to None.
|
| 219 |
+
# When using vLLM, we always compute old_per_token_logps for importance sampling, it was shown that the
|
| 220 |
+
# distribution mismatch between vLLM and the training model can be large and harm the training.
|
| 221 |
+
generate_every = self.args.steps_per_generation * self.num_iterations # generation frequency
|
| 222 |
+
if self.args.gradient_accumulation_steps % generate_every != 0 or (
|
| 223 |
+
self.use_vllm and self.vllm_importance_sampling_correction
|
| 224 |
+
):
|
| 225 |
+
old_per_token_logps, _, _ = self._get_per_token_logps_and_entropies(
|
| 226 |
+
self.model,
|
| 227 |
+
prompt_completion_ids,
|
| 228 |
+
attention_mask,
|
| 229 |
+
logits_to_keep,
|
| 230 |
+
batch_size,
|
| 231 |
+
num_images=num_images,
|
| 232 |
+
**forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
|
| 233 |
+
)
|
| 234 |
+
else:
|
| 235 |
+
old_per_token_logps = None
|
| 236 |
+
|
| 237 |
+
# Compute the importance sampling ratio when using vLLM, to correct for potential distribution mismatch
|
| 238 |
+
if self.use_vllm and self.vllm_importance_sampling_correction:
|
| 239 |
+
importance_sampling_ratio = torch.exp(old_per_token_logps - sampling_per_token_logps)
|
| 240 |
+
importance_sampling_ratio = torch.clamp(
|
| 241 |
+
importance_sampling_ratio,
|
| 242 |
+
min=self.vllm_importance_sampling_clip_min,
|
| 243 |
+
max=self.vllm_importance_sampling_clip_max,
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
# Compute the per-token log probabilities for the reference model
|
| 247 |
+
if self.beta != 0.0:
|
| 248 |
+
if self.ref_model is not None:
|
| 249 |
+
ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies(
|
| 250 |
+
self.ref_model,
|
| 251 |
+
prompt_completion_ids,
|
| 252 |
+
attention_mask,
|
| 253 |
+
logits_to_keep,
|
| 254 |
+
batch_size=batch_size,
|
| 255 |
+
num_images=num_images,
|
| 256 |
+
**forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
|
| 257 |
+
)
|
| 258 |
+
else:
|
| 259 |
+
with self.accelerator.unwrap_model(self.model).disable_adapter():
|
| 260 |
+
ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies(
|
| 261 |
+
self.model,
|
| 262 |
+
prompt_completion_ids,
|
| 263 |
+
attention_mask,
|
| 264 |
+
logits_to_keep,
|
| 265 |
+
batch_size=batch_size,
|
| 266 |
+
num_images=num_images,
|
| 267 |
+
**forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
|
| 268 |
+
)
|
| 269 |
+
else:
|
| 270 |
+
ref_per_token_logps = None
|
| 271 |
+
|
| 272 |
+
# Decode
|
| 273 |
+
prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True)
|
| 274 |
+
completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
|
| 275 |
+
if is_conversational(inputs[0]):
|
| 276 |
+
completions = []
|
| 277 |
+
for prompt, completion in zip(prompts, completions_text, strict=True):
|
| 278 |
+
bootstrap = prompt.pop()["content"] if prompt[-1]["role"] == "assistant" else ""
|
| 279 |
+
if isinstance(bootstrap, list): # for VLM, the format might be [{"type": "text", "text": "..."}]
|
| 280 |
+
assert len(bootstrap) == 1 and bootstrap[0]["type"] == "text"
|
| 281 |
+
bootstrap = bootstrap[0]["text"]
|
| 282 |
+
completions.append([{"role": "assistant", "content": bootstrap + completion}])
|
| 283 |
+
else:
|
| 284 |
+
completions = completions_text
|
| 285 |
+
|
| 286 |
+
# Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is
|
| 287 |
+
# important because rewards will be normalized per group, and completions are distributed. We will later slice
|
| 288 |
+
# rewards_per_func to extract each process's subset.
|
| 289 |
+
rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
|
| 290 |
+
|
| 291 |
+
# Apply weights to each reward function's output and sum
|
| 292 |
+
rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
|
| 293 |
+
|
| 294 |
+
num_in_group = self.num_generations
|
| 295 |
+
num_inputs_in_device = len(prompts)
|
| 296 |
+
|
| 297 |
+
if self.num_remains_in_group is not None and mode == "train":
|
| 298 |
+
num_in_group = self.num_remains_in_group
|
| 299 |
+
|
| 300 |
+
all_completions = gather_object(completions)
|
| 301 |
+
|
| 302 |
+
group_filter_scores = self.group_filter_func(
|
| 303 |
+
group_completions=[
|
| 304 |
+
all_completions[i : i + 1 * self.num_generations]
|
| 305 |
+
for i in range(len(all_completions) // self.num_generations)
|
| 306 |
+
],
|
| 307 |
+
group_rewards=rewards.view(-1, self.num_generations).tolist(),
|
| 308 |
+
)
|
| 309 |
+
group_filter_scores = torch.tensor(group_filter_scores, device=device)
|
| 310 |
+
|
| 311 |
+
_, group_local_indices = torch.topk(group_filter_scores, self.num_remains_in_group, dim=-1)
|
| 312 |
+
group_row_offsets = torch.arange(0, len(all_completions), self.num_generations, device=device).unsqueeze(1)
|
| 313 |
+
group_global_indices = group_row_offsets + group_local_indices
|
| 314 |
+
group_global_indices = group_global_indices.flatten()
|
| 315 |
+
|
| 316 |
+
rewards = rewards[group_global_indices]
|
| 317 |
+
rewards_per_func = rewards_per_func[group_global_indices, :]
|
| 318 |
+
|
| 319 |
+
num_inputs_in_device = int(len(prompts) / self.num_generations * self.num_remains_in_group)
|
| 320 |
+
|
| 321 |
+
# Compute grouped-wise rewards
|
| 322 |
+
mean_grouped_rewards = rewards.view(-1, num_in_group).mean(dim=1)
|
| 323 |
+
|
| 324 |
+
# Normalize the rewards to compute the advantages
|
| 325 |
+
mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(num_in_group, dim=0)
|
| 326 |
+
advantages = rewards - mean_grouped_rewards
|
| 327 |
+
|
| 328 |
+
if self.scale_rewards in ["group", "none"]:
|
| 329 |
+
# If self.scale_rewards = "none", we'll still log group level std
|
| 330 |
+
std_rewards = rewards.view(-1, num_in_group).std(dim=1)
|
| 331 |
+
std_rewards = std_rewards.repeat_interleave(num_in_group, dim=0)
|
| 332 |
+
elif self.scale_rewards == "batch":
|
| 333 |
+
# Compute global std
|
| 334 |
+
std_rewards = rewards.std().expand_as(rewards)
|
| 335 |
+
else:
|
| 336 |
+
raise ValueError(
|
| 337 |
+
f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'."
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards))
|
| 341 |
+
if self.scale_rewards != "none":
|
| 342 |
+
advantages = advantages / (std_rewards + 1e-4)
|
| 343 |
+
|
| 344 |
+
# Slice to keep only the local part of the data
|
| 345 |
+
process_slice = slice(
|
| 346 |
+
self.accelerator.process_index * num_inputs_in_device,
|
| 347 |
+
(self.accelerator.process_index + 1) * num_inputs_in_device,
|
| 348 |
+
)
|
| 349 |
+
all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
|
| 350 |
+
advantages = advantages[process_slice]
|
| 351 |
+
|
| 352 |
+
if self.num_remains_in_group is not None and mode == "train":
|
| 353 |
+
local_input_indices_to_keep = group_global_indices[process_slice] - self.accelerator.process_index * len(
|
| 354 |
+
prompts
|
| 355 |
+
) # step is length of prompts
|
| 356 |
+
|
| 357 |
+
prompt_ids = prompt_ids[local_input_indices_to_keep]
|
| 358 |
+
prompt_mask = prompt_mask[local_input_indices_to_keep]
|
| 359 |
+
completion_ids = completion_ids[local_input_indices_to_keep]
|
| 360 |
+
completion_mask = completion_mask[local_input_indices_to_keep]
|
| 361 |
+
attention_mask = attention_mask[local_input_indices_to_keep]
|
| 362 |
+
completion_lengths = completion_mask.sum(1)
|
| 363 |
+
agg_completion_lengths = self.accelerator.gather(completion_lengths)
|
| 364 |
+
num_items_in_batch = agg_completion_lengths.sum()
|
| 365 |
+
|
| 366 |
+
if sampling_per_token_logps is not None:
|
| 367 |
+
sampling_per_token_logps = sampling_per_token_logps[local_input_indices_to_keep]
|
| 368 |
+
if old_per_token_logps is not None:
|
| 369 |
+
old_per_token_logps = old_per_token_logps[local_input_indices_to_keep]
|
| 370 |
+
if ref_per_token_logps is not None:
|
| 371 |
+
ref_per_token_logps = ref_per_token_logps[local_input_indices_to_keep]
|
| 372 |
+
if self.use_vllm and self.vllm_importance_sampling_correction:
|
| 373 |
+
importance_sampling_ratio = importance_sampling_ratio[local_input_indices_to_keep]
|
| 374 |
+
|
| 375 |
+
# Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
|
| 376 |
+
for i, reward_func_name in enumerate(self.reward_func_names):
|
| 377 |
+
mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
|
| 378 |
+
self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
|
| 379 |
+
std_func_rewards = nanstd(rewards_per_func[:, i]).item()
|
| 380 |
+
self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards)
|
| 381 |
+
rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1)
|
| 382 |
+
self._metrics[mode]["reward"].append(rewards.mean().item())
|
| 383 |
+
self._metrics[mode]["reward_std"].append(rewards.std().item())
|
| 384 |
+
self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
|
| 385 |
+
|
| 386 |
+
# Log prompt and completion texts
|
| 387 |
+
all_prompts_text = gather_object(prompts_text)
|
| 388 |
+
all_completions_text = gather_object(completions_text)
|
| 389 |
+
all_images = gather_object(images) if images is not None else None
|
| 390 |
+
if self.num_remains_in_group is not None and mode == "train":
|
| 391 |
+
group_global_indices_list = group_global_indices.tolist()
|
| 392 |
+
all_prompts_text = [all_prompts_text[i] for i in group_global_indices_list]
|
| 393 |
+
all_completions_text = [all_completions_text[i] for i in group_global_indices_list]
|
| 394 |
+
if images is not None:
|
| 395 |
+
all_images = [all_images[i] for i in group_global_indices_list]
|
| 396 |
+
|
| 397 |
+
self._logs["prompt"].extend(all_prompts_text)
|
| 398 |
+
self._logs["completion"].extend(all_completions_text)
|
| 399 |
+
for i, name in enumerate(self.reward_func_names):
|
| 400 |
+
self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
|
| 401 |
+
self._logs["advantages"].extend(all_process_advantages.tolist())
|
| 402 |
+
|
| 403 |
+
if images is not None:
|
| 404 |
+
self._logs["images"].extend(all_images)
|
| 405 |
+
|
| 406 |
+
if self.use_vllm and self.vllm_importance_sampling_correction:
|
| 407 |
+
delta = torch.abs(old_per_token_logps - sampling_per_token_logps)
|
| 408 |
+
delta = delta[completion_mask.bool()]
|
| 409 |
+
mean_delta = torch.mean(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device)
|
| 410 |
+
max_delta = torch.max(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device)
|
| 411 |
+
self._metrics[mode]["sampling/sampling_logp_difference/mean"].append(
|
| 412 |
+
self.accelerator.gather(mean_delta).mean().item()
|
| 413 |
+
)
|
| 414 |
+
self._metrics[mode]["sampling/sampling_logp_difference/max"].append(
|
| 415 |
+
self.accelerator.gather(max_delta).max().item()
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
flat_is_ratio = importance_sampling_ratio[completion_mask.bool()]
|
| 419 |
+
min_importance_sampling_ratio = (
|
| 420 |
+
torch.min(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
|
| 421 |
+
)
|
| 422 |
+
mean_importance_sampling_ratio = (
|
| 423 |
+
torch.mean(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
|
| 424 |
+
)
|
| 425 |
+
max_importance_sampling_ratio = (
|
| 426 |
+
torch.max(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
|
| 427 |
+
)
|
| 428 |
+
self._metrics[mode]["sampling/importance_sampling_ratio/min"].append(
|
| 429 |
+
nanmin(self.accelerator.gather(min_importance_sampling_ratio)).item()
|
| 430 |
+
)
|
| 431 |
+
self._metrics[mode]["sampling/importance_sampling_ratio/mean"].append(
|
| 432 |
+
self.accelerator.gather(mean_importance_sampling_ratio).nanmean().item()
|
| 433 |
+
)
|
| 434 |
+
self._metrics[mode]["sampling/importance_sampling_ratio/max"].append(
|
| 435 |
+
nanmax(self.accelerator.gather(max_importance_sampling_ratio)).item()
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
output = {
|
| 439 |
+
"prompt_ids": prompt_ids,
|
| 440 |
+
"prompt_mask": prompt_mask,
|
| 441 |
+
"completion_ids": completion_ids,
|
| 442 |
+
"completion_mask": completion_mask,
|
| 443 |
+
"advantages": advantages,
|
| 444 |
+
"num_items_in_batch": num_items_in_batch,
|
| 445 |
+
}
|
| 446 |
+
if old_per_token_logps is not None:
|
| 447 |
+
output["old_per_token_logps"] = old_per_token_logps
|
| 448 |
+
if self.use_vllm and self.vllm_importance_sampling_correction:
|
| 449 |
+
output["importance_sampling_ratio"] = importance_sampling_ratio
|
| 450 |
+
if ref_per_token_logps is not None:
|
| 451 |
+
output["ref_per_token_logps"] = ref_per_token_logps
|
| 452 |
+
if "pixel_values" in forward_kwargs:
|
| 453 |
+
output["pixel_values"] = forward_kwargs["pixel_values"]
|
| 454 |
+
if "image_grid_thw" in forward_kwargs:
|
| 455 |
+
output["image_grid_thw"] = forward_kwargs["image_grid_thw"]
|
| 456 |
+
if "pixel_attention_mask" in forward_kwargs:
|
| 457 |
+
output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"]
|
| 458 |
+
if "image_sizes" in forward_kwargs:
|
| 459 |
+
output["image_sizes"] = forward_kwargs["image_sizes"]
|
| 460 |
+
if "token_type_ids" in forward_kwargs:
|
| 461 |
+
output["token_type_ids"] = forward_kwargs["token_type_ids"]
|
| 462 |
+
if images is not None:
|
| 463 |
+
output["num_images"] = num_images
|
| 464 |
+
return output
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gkd/__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 .gkd_config import GKDConfig
|
| 16 |
+
from .gkd_trainer import GKDTrainer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = ["GKDConfig", "GKDTrainer"]
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gkd/gkd_config.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.sft_config import SFTConfig
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class GKDConfig(SFTConfig):
|
| 23 |
+
"""
|
| 24 |
+
Configuration class for [`experimental.gkd.GKDTrainer`].
|
| 25 |
+
|
| 26 |
+
This class includes only the parameters that are specific to GKD training. For a full list of training arguments,
|
| 27 |
+
please refer to the [`~transformers.TrainingArguments`] and [`SFTConfig`] documentation.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
temperature (`float`, *optional*, defaults to `0.9`):
|
| 31 |
+
Temperature for sampling. The higher the temperature, the more random the completions.
|
| 32 |
+
lmbda (`float`, *optional*, defaults to `0.5`):
|
| 33 |
+
Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy
|
| 34 |
+
student-generated outputs).
|
| 35 |
+
beta (`float`, *optional*, defaults to `0.5`):
|
| 36 |
+
Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence loss. When
|
| 37 |
+
beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL Divergence.
|
| 38 |
+
max_new_tokens (`int`, *optional*, defaults to `128`):
|
| 39 |
+
Maximum number of tokens to generate per completion.
|
| 40 |
+
teacher_model_name_or_path (`str`, *optional*):
|
| 41 |
+
Model name or path of the teacher model. If `None`, the teacher model will be the same as the model being
|
| 42 |
+
trained.
|
| 43 |
+
teacher_model_init_kwargs (`dict[str, Any]`, *optional*):
|
| 44 |
+
Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model
|
| 45 |
+
from a string.
|
| 46 |
+
disable_dropout (`bool`, *optional*, defaults to `True`):
|
| 47 |
+
Whether to disable dropout in the model.
|
| 48 |
+
seq_kd (`bool`, *optional*, defaults to `False`):
|
| 49 |
+
Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised FT on
|
| 50 |
+
teacher-generated output).
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
_VALID_DICT_FIELDS = SFTConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"]
|
| 54 |
+
|
| 55 |
+
temperature: float = field(
|
| 56 |
+
default=0.9,
|
| 57 |
+
metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."},
|
| 58 |
+
)
|
| 59 |
+
lmbda: float = field(
|
| 60 |
+
default=0.5,
|
| 61 |
+
metadata={
|
| 62 |
+
"help": "Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy "
|
| 63 |
+
"student-generated outputs)."
|
| 64 |
+
},
|
| 65 |
+
)
|
| 66 |
+
beta: float = field(
|
| 67 |
+
default=0.5,
|
| 68 |
+
metadata={
|
| 69 |
+
"help": "Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence "
|
| 70 |
+
"loss. When beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL "
|
| 71 |
+
"Divergence."
|
| 72 |
+
},
|
| 73 |
+
)
|
| 74 |
+
max_new_tokens: int = field(
|
| 75 |
+
default=128,
|
| 76 |
+
metadata={"help": "Maximum number of tokens to generate per completion."},
|
| 77 |
+
)
|
| 78 |
+
teacher_model_name_or_path: str | None = field(
|
| 79 |
+
default=None,
|
| 80 |
+
metadata={
|
| 81 |
+
"help": "Model name or path of the teacher model. If `None`, the teacher model will be the same as the "
|
| 82 |
+
"model being trained."
|
| 83 |
+
},
|
| 84 |
+
)
|
| 85 |
+
teacher_model_init_kwargs: dict[str, Any] | str | None = field(
|
| 86 |
+
default=None,
|
| 87 |
+
metadata={
|
| 88 |
+
"help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the "
|
| 89 |
+
"teacher model from a string."
|
| 90 |
+
},
|
| 91 |
+
)
|
| 92 |
+
disable_dropout: bool = field(
|
| 93 |
+
default=True,
|
| 94 |
+
metadata={"help": "Whether to disable dropouts in `model`."},
|
| 95 |
+
)
|
| 96 |
+
seq_kd: bool = field(
|
| 97 |
+
default=False,
|
| 98 |
+
metadata={
|
| 99 |
+
"help": "Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised "
|
| 100 |
+
"FT on teacher-generated output)."
|
| 101 |
+
},
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
def __post_init__(self):
|
| 105 |
+
super().__post_init__()
|
| 106 |
+
# check lmbda and beta are in the range [0, 1]
|
| 107 |
+
if self.lmbda < 0.0 or self.lmbda > 1.0:
|
| 108 |
+
raise ValueError("lmbda must be in the range [0.0, 1.0].")
|
| 109 |
+
if self.beta < 0.0 or self.beta > 1.0:
|
| 110 |
+
raise ValueError("beta must be in the range [0.0, 1.0].")
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gkd/gkd_trainer.py
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from collections.abc import Callable
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
from datasets import Dataset
|
| 24 |
+
from transformers import (
|
| 25 |
+
AutoModelForCausalLM,
|
| 26 |
+
BaseImageProcessor,
|
| 27 |
+
DataCollator,
|
| 28 |
+
FeatureExtractionMixin,
|
| 29 |
+
GenerationConfig,
|
| 30 |
+
PreTrainedModel,
|
| 31 |
+
PreTrainedTokenizerBase,
|
| 32 |
+
ProcessorMixin,
|
| 33 |
+
TrainerCallback,
|
| 34 |
+
)
|
| 35 |
+
from transformers.trainer_utils import EvalPrediction
|
| 36 |
+
from transformers.utils import ModelOutput, is_liger_kernel_available, is_peft_available
|
| 37 |
+
|
| 38 |
+
from ...models import prepare_deepspeed
|
| 39 |
+
from ...models.utils import _ForwardRedirection, unwrap_model_for_generation
|
| 40 |
+
from ...trainer.sft_trainer import SFTTrainer
|
| 41 |
+
from ...trainer.utils import disable_dropout_in_model
|
| 42 |
+
from ..utils import DataCollatorForChatML, empty_cache
|
| 43 |
+
from .gkd_config import GKDConfig
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if is_liger_kernel_available():
|
| 47 |
+
from liger_kernel.chunked_loss import LigerFusedLinearJSDLoss
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if is_peft_available():
|
| 51 |
+
from peft import PeftConfig
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class GKDTrainer(SFTTrainer):
|
| 55 |
+
"""Trainer for Generalized Knowledge Distillation (GKD) of language models.
|
| 56 |
+
|
| 57 |
+
For details on GKD, see the paper: [On-Policy Distillation of Language Models: Learning from Self-Generated
|
| 58 |
+
Mistakes](https://huggingface.co/papers/2306.13649).
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `str`, *optional*):
|
| 62 |
+
Model to be trained, or the string identifier of the model to be instantiated from a pretrained model.
|
| 63 |
+
teacher_model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `str`, *optional*):
|
| 64 |
+
Teacher model for knowledge distillation, or the string identifier of the model to be instantiated from a
|
| 65 |
+
pretrained model.
|
| 66 |
+
args ([`experimental.gkd.GKDConfig`], *optional*):
|
| 67 |
+
Training arguments.
|
| 68 |
+
data_collator ([`~transformers.DataCollator`], *optional*):
|
| 69 |
+
Data collator to batch samples from the dataset. It defaults to a
|
| 70 |
+
[`experimental.utils.DataCollatorForChatML`] using the `processing_class`.
|
| 71 |
+
train_dataset ([`~datasets.Dataset`], *optional*):
|
| 72 |
+
Dataset for training.
|
| 73 |
+
eval_dataset ([`~datasets.Dataset`] or `dict` of [`~datasets.Dataset`], *optional*):
|
| 74 |
+
Dataset for evaluation.
|
| 75 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
|
| 76 |
+
Class to process the data.
|
| 77 |
+
compute_metrics (`Callable`, *optional*):
|
| 78 |
+
Function to compute metrics at evaluation. Must take in an [`~transformers.EvalPrediction`] and return a
|
| 79 |
+
dictionary string to float.
|
| 80 |
+
callbacks (`list` of [`~transformers.TrainerCallback`], *optional*):
|
| 81 |
+
Callbacks to use during training.
|
| 82 |
+
optimizers (`tuple` of `torch.optim.Optimizer` and `torch.optim.lr_scheduler.LambdaLR`, *optional*, defaults to `(None, None)`):
|
| 83 |
+
Tuple containing the optimizer and the learning rate scheduler to use for training.
|
| 84 |
+
preprocess_logits_for_metrics (`Callable`, *optional*):
|
| 85 |
+
Function to preprocess the logits before computing the metrics. Must take in the `logits` and `labels` and
|
| 86 |
+
return the logits to be used for metrics computation.
|
| 87 |
+
peft_config ([`~peft.PeftConfig`], *optional*):
|
| 88 |
+
PEFT configuration to use PEFT for training. If `None`, PEFT is not used. If provided, the `model` will be
|
| 89 |
+
wrapped with the specified PEFT adapter.
|
| 90 |
+
formatting_func (`Callable`, *optional*):
|
| 91 |
+
Function to format the dataset. Must take in an example and return an example.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
_tag_names = ["trl", "gkd"]
|
| 95 |
+
_name = "GKD"
|
| 96 |
+
_paper = {
|
| 97 |
+
"title": "On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes",
|
| 98 |
+
"id": "2306.13649",
|
| 99 |
+
# docstyle-ignore
|
| 100 |
+
"citation": textwrap.dedent("""\
|
| 101 |
+
@inproceedings{agarwal2024on-policy,
|
| 102 |
+
title = {{On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes}},
|
| 103 |
+
author = {Rishabh Agarwal and Nino Vieillard and Yongchao Zhou and Piotr Stanczyk and Sabela Ramos Garea and Matthieu Geist and Olivier Bachem},
|
| 104 |
+
year = 2024,
|
| 105 |
+
booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024},
|
| 106 |
+
publisher = {OpenReview.net},
|
| 107 |
+
url = {https://openreview.net/forum?id=3zKtaqxLhW},
|
| 108 |
+
}"""),
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
def __init__(
|
| 112 |
+
self,
|
| 113 |
+
model: PreTrainedModel | nn.Module | str | None = None,
|
| 114 |
+
teacher_model: PreTrainedModel | nn.Module | str = None,
|
| 115 |
+
args: GKDConfig | None = None,
|
| 116 |
+
data_collator: DataCollator | None = None, # type: ignore
|
| 117 |
+
train_dataset: Dataset | None = None,
|
| 118 |
+
eval_dataset: Dataset | dict[str, Dataset] | None = None,
|
| 119 |
+
processing_class: PreTrainedTokenizerBase
|
| 120 |
+
| BaseImageProcessor
|
| 121 |
+
| FeatureExtractionMixin
|
| 122 |
+
| ProcessorMixin
|
| 123 |
+
| None = None,
|
| 124 |
+
compute_metrics: Callable[[EvalPrediction], dict] | None = None,
|
| 125 |
+
callbacks: list[TrainerCallback] | None = None,
|
| 126 |
+
optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
|
| 127 |
+
preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
|
| 128 |
+
peft_config: "PeftConfig | None" = None,
|
| 129 |
+
formatting_func: Callable | None = None,
|
| 130 |
+
):
|
| 131 |
+
# Ensure Trainer does not drop non-signature columns used by the collator (e.g., "prompts")
|
| 132 |
+
args.remove_unused_columns = False
|
| 133 |
+
# Respect a user-provided data_collator; otherwise, provide a ChatML collator that
|
| 134 |
+
if data_collator is None:
|
| 135 |
+
data_collator = DataCollatorForChatML(tokenizer=processing_class, max_length=args.max_length)
|
| 136 |
+
|
| 137 |
+
# Ensure SFTTrainer does not pre-process the dataset when using a ChatML collator,
|
| 138 |
+
# so that raw conversational fields (e.g., "messages") remain available to the collator.
|
| 139 |
+
if args.dataset_kwargs is None:
|
| 140 |
+
args.dataset_kwargs = {"skip_prepare_dataset": True}
|
| 141 |
+
else:
|
| 142 |
+
args.dataset_kwargs["skip_prepare_dataset"] = True
|
| 143 |
+
|
| 144 |
+
# Liger fused GKD loss (JSD)
|
| 145 |
+
self.use_liger_gkd_loss = False
|
| 146 |
+
if args.use_liger_kernel:
|
| 147 |
+
# Match the non-Liger path: pure JSD (no hard CE component) and no temperature
|
| 148 |
+
# scaling, since `generalized_jsd_loss` is called without a `temperature` argument.
|
| 149 |
+
self.liger_jsd_loss = LigerFusedLinearJSDLoss(
|
| 150 |
+
beta=args.beta,
|
| 151 |
+
ignore_index=-100,
|
| 152 |
+
compiled=False,
|
| 153 |
+
weight_hard_loss=0.0,
|
| 154 |
+
weight_soft_loss=1.0,
|
| 155 |
+
)
|
| 156 |
+
self.use_liger_gkd_loss = True
|
| 157 |
+
self._forward_redirection = _ForwardRedirection()
|
| 158 |
+
|
| 159 |
+
super().__init__(
|
| 160 |
+
model,
|
| 161 |
+
args=args,
|
| 162 |
+
data_collator=data_collator,
|
| 163 |
+
train_dataset=train_dataset,
|
| 164 |
+
eval_dataset=eval_dataset,
|
| 165 |
+
processing_class=processing_class,
|
| 166 |
+
compute_metrics=compute_metrics,
|
| 167 |
+
callbacks=callbacks,
|
| 168 |
+
optimizers=optimizers,
|
| 169 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
| 170 |
+
peft_config=peft_config,
|
| 171 |
+
formatting_func=formatting_func,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
if args.teacher_model_init_kwargs is None:
|
| 175 |
+
teacher_model_init_kwargs = {}
|
| 176 |
+
elif not isinstance(teacher_model, str):
|
| 177 |
+
raise ValueError(
|
| 178 |
+
"You passed teacher_model_init_kwargs to the GKDConfig, but your teacher_model is already instantiated."
|
| 179 |
+
)
|
| 180 |
+
else:
|
| 181 |
+
teacher_model_init_kwargs = args.teacher_model_init_kwargs
|
| 182 |
+
teacher_model_init_kwargs["dtype"] = (
|
| 183 |
+
teacher_model_init_kwargs["dtype"]
|
| 184 |
+
if teacher_model_init_kwargs["dtype"] in ["auto", None]
|
| 185 |
+
else getattr(torch, teacher_model_init_kwargs["dtype"])
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
if isinstance(teacher_model, str):
|
| 189 |
+
teacher_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 190 |
+
teacher_model = AutoModelForCausalLM.from_pretrained(teacher_model, **teacher_model_init_kwargs)
|
| 191 |
+
|
| 192 |
+
# Disable dropout in the model
|
| 193 |
+
if args.disable_dropout:
|
| 194 |
+
disable_dropout_in_model(self.model)
|
| 195 |
+
|
| 196 |
+
if self.is_deepspeed_enabled:
|
| 197 |
+
self.teacher_model = prepare_deepspeed(teacher_model, self.accelerator)
|
| 198 |
+
else:
|
| 199 |
+
self.teacher_model = self.accelerator.prepare_model(teacher_model, evaluation_mode=True)
|
| 200 |
+
|
| 201 |
+
self.lmbda = args.lmbda
|
| 202 |
+
self.beta = args.beta
|
| 203 |
+
self.temperature = args.temperature
|
| 204 |
+
self.seq_kd = args.seq_kd
|
| 205 |
+
|
| 206 |
+
generation_kwargs = {
|
| 207 |
+
"max_new_tokens": args.max_new_tokens,
|
| 208 |
+
"temperature": args.temperature,
|
| 209 |
+
"do_sample": True,
|
| 210 |
+
"top_k": 0,
|
| 211 |
+
"use_cache": False if args.gradient_checkpointing else True,
|
| 212 |
+
"pad_token_id": self.processing_class.pad_token_id,
|
| 213 |
+
}
|
| 214 |
+
self.generation_config = GenerationConfig(**generation_kwargs)
|
| 215 |
+
# Keep training-specific generation kwargs to overwrite model's original generation config
|
| 216 |
+
self.generation_kwargs = generation_kwargs
|
| 217 |
+
# Set custom EOS tokens if they are specified by the model's generation
|
| 218 |
+
# config. This is important for models with the Llama 3 chat template,
|
| 219 |
+
# which use special tokens <|eot_id|> and <|eom_id|> to mark the end of
|
| 220 |
+
# turns or messages.
|
| 221 |
+
if (
|
| 222 |
+
hasattr(self.model.generation_config, "eos_token_id")
|
| 223 |
+
and self.model.generation_config.eos_token_id is not None
|
| 224 |
+
):
|
| 225 |
+
self.generation_config.eos_token_id = self.model.generation_config.eos_token_id
|
| 226 |
+
|
| 227 |
+
@staticmethod
|
| 228 |
+
def generalized_jsd_loss(
|
| 229 |
+
student_logits,
|
| 230 |
+
teacher_logits,
|
| 231 |
+
labels=None,
|
| 232 |
+
beta=0.5,
|
| 233 |
+
temperature=1.0,
|
| 234 |
+
reduction="batchmean",
|
| 235 |
+
num_items_in_batch=None,
|
| 236 |
+
):
|
| 237 |
+
"""
|
| 238 |
+
Compute the generalized Jensen-Shannon Divergence loss for knowledge distillation using F.kl_div. See Eq. (1)
|
| 239 |
+
of https://huggingface.co/papers/2306.13649 for the definition.
|
| 240 |
+
|
| 241 |
+
Args:
|
| 242 |
+
student_logits:
|
| 243 |
+
Tensor of shape (batch_size, sequence_length, vocab_size)
|
| 244 |
+
teacher_logits:
|
| 245 |
+
Tensor of shape (batch_size, sequence_length, vocab_size)
|
| 246 |
+
labels:
|
| 247 |
+
Tensor of shape (batch_size, sequence_length) with -100 for padding tokens to ignore when computing
|
| 248 |
+
loss
|
| 249 |
+
beta:
|
| 250 |
+
Interpolation coefficient between 0 and 1 (default: 0.5)
|
| 251 |
+
temperature:
|
| 252 |
+
Softmax temperature (default: 1.0)
|
| 253 |
+
reduction:
|
| 254 |
+
Specifies the reduction to apply to the output (default: 'batchmean')
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
loss: Scalar tensor with the generalized JSD loss
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
# Apply temperature scaling
|
| 261 |
+
student_logits = student_logits / temperature
|
| 262 |
+
teacher_logits = teacher_logits / temperature
|
| 263 |
+
|
| 264 |
+
# Compute log probabilities for student and probabilities for teacher
|
| 265 |
+
student_log_probs = F.log_softmax(student_logits, dim=-1)
|
| 266 |
+
teacher_log_probs = F.log_softmax(teacher_logits, dim=-1)
|
| 267 |
+
|
| 268 |
+
if beta == 0:
|
| 269 |
+
jsd = F.kl_div(student_log_probs, teacher_log_probs, reduction="none", log_target=True)
|
| 270 |
+
elif beta == 1:
|
| 271 |
+
jsd = F.kl_div(teacher_log_probs, student_log_probs, reduction="none", log_target=True)
|
| 272 |
+
else:
|
| 273 |
+
# Compute the log of the mixture distribution
|
| 274 |
+
# log(a + b) = log(exp(log(a)) + exp(log(b))) -> for mixture
|
| 275 |
+
beta = torch.tensor(beta, dtype=student_log_probs.dtype, device=student_log_probs.device)
|
| 276 |
+
mixture_log_probs = torch.logsumexp(
|
| 277 |
+
torch.stack([student_log_probs + torch.log1p(-beta), teacher_log_probs + torch.log(beta)]),
|
| 278 |
+
dim=0,
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
# Compute KL divergences using F.kl_div
|
| 282 |
+
# PyTorch differs from the standard mathematical definition, so the order of the probability distributions is swapped compared to that defined in the paper.
|
| 283 |
+
kl_teacher = F.kl_div(mixture_log_probs, teacher_log_probs, reduction="none", log_target=True)
|
| 284 |
+
kl_student = F.kl_div(mixture_log_probs, student_log_probs, reduction="none", log_target=True)
|
| 285 |
+
|
| 286 |
+
# Compute the Generalized Jensen-Shannon Divergence
|
| 287 |
+
jsd = beta * kl_teacher + (1 - beta) * kl_student
|
| 288 |
+
|
| 289 |
+
# Masking
|
| 290 |
+
if labels is not None:
|
| 291 |
+
mask = labels != -100
|
| 292 |
+
jsd = jsd[mask]
|
| 293 |
+
|
| 294 |
+
# Apply reduction
|
| 295 |
+
if num_items_in_batch is not None:
|
| 296 |
+
# Normalize by the global number of valid tokens for gradient-accumulation-correct loss (see issue #4719).
|
| 297 |
+
jsd_sum = jsd.sum()
|
| 298 |
+
if isinstance(num_items_in_batch, torch.Tensor):
|
| 299 |
+
num_items_in_batch = num_items_in_batch.to(jsd_sum.device)
|
| 300 |
+
return jsd_sum / num_items_in_batch
|
| 301 |
+
if reduction == "batchmean":
|
| 302 |
+
# clamp_min(1) avoids 0/0 -> nan when a sample has no unmasked positions
|
| 303 |
+
# (e.g. completion fully truncated). jsd[mask] is empty -> jsd.sum() == 0,
|
| 304 |
+
# so 0/1 == 0 with a valid grad path.
|
| 305 |
+
denom = mask.sum().clamp_min(1) if labels is not None else max(jsd.size(0), 1)
|
| 306 |
+
return jsd.sum() / denom
|
| 307 |
+
elif reduction == "sum":
|
| 308 |
+
return jsd.sum()
|
| 309 |
+
elif reduction == "mean":
|
| 310 |
+
return jsd.mean()
|
| 311 |
+
else:
|
| 312 |
+
return jsd
|
| 313 |
+
|
| 314 |
+
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 315 |
+
if self.use_liger_gkd_loss:
|
| 316 |
+
# Forward only through the base models (avoid lm_head to save memory).
|
| 317 |
+
# Route through the DDP/FSDP wrapper via _forward_redirection so that
|
| 318 |
+
# DDP.forward() is called and prepare_for_backward() fires correctly.
|
| 319 |
+
unwrapped_student = self.accelerator.unwrap_model(model)
|
| 320 |
+
student_outputs = self._forward_redirection(
|
| 321 |
+
model, unwrapped_student, self._liger_student_forward, unwrapped_student, inputs
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
self.teacher_model.eval()
|
| 325 |
+
unwrapped_teacher = self.accelerator.unwrap_model(self.teacher_model)
|
| 326 |
+
if hasattr(unwrapped_teacher, "get_decoder") and unwrapped_teacher.get_decoder() is not None:
|
| 327 |
+
base_teacher = unwrapped_teacher.get_decoder()
|
| 328 |
+
else:
|
| 329 |
+
base_teacher = getattr(
|
| 330 |
+
unwrapped_teacher, getattr(unwrapped_teacher, "base_model_prefix", "model"), unwrapped_teacher
|
| 331 |
+
)
|
| 332 |
+
with torch.no_grad():
|
| 333 |
+
teacher_outputs = base_teacher(
|
| 334 |
+
input_ids=inputs["input_ids"],
|
| 335 |
+
attention_mask=inputs["attention_mask"],
|
| 336 |
+
use_cache=False,
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
# hidden states (shifted)
|
| 340 |
+
student_hidden = student_outputs.last_hidden_state[:, :-1]
|
| 341 |
+
teacher_hidden = teacher_outputs.last_hidden_state[:, :-1]
|
| 342 |
+
|
| 343 |
+
# Release teacher outputs; keep student_outputs for return_outputs
|
| 344 |
+
del teacher_outputs
|
| 345 |
+
|
| 346 |
+
# labels mask and labels (shifted)
|
| 347 |
+
labels_mask = inputs["labels"] != -100
|
| 348 |
+
masked_input_ids = torch.where(
|
| 349 |
+
labels_mask, inputs["input_ids"], torch.full_like(inputs["input_ids"], -100)
|
| 350 |
+
)
|
| 351 |
+
true_labels = masked_input_ids[:, 1:].contiguous()
|
| 352 |
+
|
| 353 |
+
# Release intermediate tensors
|
| 354 |
+
del labels_mask, masked_input_ids
|
| 355 |
+
|
| 356 |
+
# heads
|
| 357 |
+
student_head = unwrapped_student.get_output_embeddings()
|
| 358 |
+
teacher_head = unwrapped_teacher.get_output_embeddings()
|
| 359 |
+
|
| 360 |
+
# liger fused jsd loss
|
| 361 |
+
loss = self.liger_jsd_loss(
|
| 362 |
+
student_input=student_hidden,
|
| 363 |
+
student_weight=student_head.weight,
|
| 364 |
+
teacher_input=teacher_hidden,
|
| 365 |
+
teacher_weight=teacher_head.weight,
|
| 366 |
+
true_labels=true_labels,
|
| 367 |
+
student_bias=getattr(student_head, "bias", None),
|
| 368 |
+
teacher_bias=getattr(teacher_head, "bias", None),
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
# The Liger JSD loss normalizes by the local number of valid tokens. Under gradient accumulation we want
|
| 372 |
+
# the global normalization, so rescale by `num_valid_local / num_items_in_batch`.
|
| 373 |
+
if num_items_in_batch is not None:
|
| 374 |
+
num_valid_local = (true_labels != -100).sum().clamp_min(1)
|
| 375 |
+
if isinstance(num_items_in_batch, torch.Tensor):
|
| 376 |
+
num_items_in_batch = num_items_in_batch.to(loss.device)
|
| 377 |
+
loss = loss * num_valid_local / num_items_in_batch
|
| 378 |
+
|
| 379 |
+
# Release hidden states after loss computation
|
| 380 |
+
del student_hidden, teacher_hidden, true_labels
|
| 381 |
+
empty_cache()
|
| 382 |
+
if return_outputs:
|
| 383 |
+
return (loss, ModelOutput(logits=None, last_hidden_state=student_outputs.last_hidden_state))
|
| 384 |
+
else:
|
| 385 |
+
return loss
|
| 386 |
+
else:
|
| 387 |
+
# compute student output
|
| 388 |
+
student_outputs = model(
|
| 389 |
+
input_ids=inputs["input_ids"],
|
| 390 |
+
attention_mask=inputs["attention_mask"],
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
# compute teacher output in eval mode
|
| 394 |
+
self.teacher_model.eval()
|
| 395 |
+
with torch.no_grad():
|
| 396 |
+
teacher_outputs = self.teacher_model(
|
| 397 |
+
input_ids=inputs["input_ids"],
|
| 398 |
+
attention_mask=inputs["attention_mask"],
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
# Standard causal shift: logits at position i predict the token at i + 1. The `labels != -100` mask
|
| 402 |
+
# inside `generalized_jsd_loss` already excludes prompt (and padding) positions, so we do not slice by
|
| 403 |
+
# prompt length. Slicing by `inputs["prompts"].shape[1]` (the batch-max prompt width) would drop real
|
| 404 |
+
# completion tokens for samples whose prompt is shorter than the batch maximum, since `labels` is padded
|
| 405 |
+
# to the full-sequence width independently of `prompts`.
|
| 406 |
+
shifted_student_logits = student_outputs.logits[:, :-1, :]
|
| 407 |
+
shifted_teacher_logits = teacher_outputs.logits[:, :-1, :]
|
| 408 |
+
shifted_labels = inputs["labels"][:, 1:]
|
| 409 |
+
|
| 410 |
+
# compute loss
|
| 411 |
+
loss = self.generalized_jsd_loss(
|
| 412 |
+
student_logits=shifted_student_logits,
|
| 413 |
+
teacher_logits=shifted_teacher_logits,
|
| 414 |
+
labels=shifted_labels,
|
| 415 |
+
beta=self.beta,
|
| 416 |
+
num_items_in_batch=num_items_in_batch,
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
# empty cache
|
| 420 |
+
empty_cache()
|
| 421 |
+
|
| 422 |
+
# Return loss
|
| 423 |
+
return (loss, student_outputs) if return_outputs else loss
|
| 424 |
+
|
| 425 |
+
def _liger_student_forward(self, student, inputs):
|
| 426 |
+
"""Decoder-only forward used by the Liger JSD path (skips lm_head to save memory)."""
|
| 427 |
+
if hasattr(student, "get_decoder") and student.get_decoder() is not None:
|
| 428 |
+
decoder = student.get_decoder()
|
| 429 |
+
else:
|
| 430 |
+
decoder = getattr(student, getattr(student, "base_model_prefix", "model"), student)
|
| 431 |
+
return decoder(
|
| 432 |
+
input_ids=inputs["input_ids"],
|
| 433 |
+
attention_mask=inputs["attention_mask"],
|
| 434 |
+
use_cache=False,
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
@staticmethod
|
| 438 |
+
def generate_on_policy_outputs(model, inputs, generation_config, pad_token_id=None):
|
| 439 |
+
# Generate output with respect to the prompt-only
|
| 440 |
+
generated_outputs = model.generate(
|
| 441 |
+
input_ids=inputs["prompts"],
|
| 442 |
+
attention_mask=inputs.get("prompt_attention_mask", None),
|
| 443 |
+
generation_config=generation_config,
|
| 444 |
+
return_dict_in_generate=True,
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
# Get the generated token IDs
|
| 448 |
+
generated_tokens = generated_outputs.sequences
|
| 449 |
+
# Calculate new attention mask
|
| 450 |
+
new_attention_mask = torch.ones_like(generated_tokens)
|
| 451 |
+
new_labels = generated_tokens.clone()
|
| 452 |
+
|
| 453 |
+
# If there's pad_token_id, set attention mask to 0 for padding tokens
|
| 454 |
+
if pad_token_id is not None:
|
| 455 |
+
new_labels[new_labels == pad_token_id] = -100
|
| 456 |
+
new_attention_mask[generated_tokens == pad_token_id] = 0
|
| 457 |
+
|
| 458 |
+
# Mask the prompt so only the generated completion contributes to the loss. `generate` echoes
|
| 459 |
+
# the prompt back as the first `prompt_length` columns, so masking them with -100 matches the
|
| 460 |
+
# collator convention (`labels[:len(prompt)] = -100`) that `compute_loss` relies on.
|
| 461 |
+
prompt_length = inputs["prompts"].shape[1]
|
| 462 |
+
new_labels[:, :prompt_length] = -100
|
| 463 |
+
|
| 464 |
+
return generated_tokens, new_attention_mask, new_labels
|
| 465 |
+
|
| 466 |
+
def training_step(
|
| 467 |
+
self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None
|
| 468 |
+
) -> torch.Tensor:
|
| 469 |
+
"""
|
| 470 |
+
Perform a training step for the Generalized Knowledge Distillation (GKD) model.
|
| 471 |
+
|
| 472 |
+
This method implements the on-policy learning approach described in the GKD paper. With probability
|
| 473 |
+
`self.lmbda`, it generates new responses using the student model, which are then used for training instead of
|
| 474 |
+
the original inputs.
|
| 475 |
+
"""
|
| 476 |
+
if random.random() <= self.lmbda:
|
| 477 |
+
with (
|
| 478 |
+
unwrap_model_for_generation(
|
| 479 |
+
model,
|
| 480 |
+
self.accelerator,
|
| 481 |
+
generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
|
| 482 |
+
) as unwrapped_model
|
| 483 |
+
):
|
| 484 |
+
new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs(
|
| 485 |
+
unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id
|
| 486 |
+
)
|
| 487 |
+
inputs["input_ids"] = new_input_ids
|
| 488 |
+
inputs["attention_mask"] = new_attention_mask
|
| 489 |
+
inputs["labels"] = new_labels
|
| 490 |
+
elif self.seq_kd:
|
| 491 |
+
with (
|
| 492 |
+
unwrap_model_for_generation(
|
| 493 |
+
self.teacher_model,
|
| 494 |
+
self.accelerator,
|
| 495 |
+
generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
|
| 496 |
+
) as unwrapped_model
|
| 497 |
+
):
|
| 498 |
+
new_input_ids, new_attention_mask, new_labels = self.generate_on_policy_outputs(
|
| 499 |
+
unwrapped_model, inputs, self.generation_config, self.processing_class.pad_token_id
|
| 500 |
+
)
|
| 501 |
+
inputs["input_ids"] = new_input_ids
|
| 502 |
+
inputs["attention_mask"] = new_attention_mask
|
| 503 |
+
inputs["labels"] = new_labels
|
| 504 |
+
|
| 505 |
+
loss = super().training_step(model, inputs, num_items_in_batch)
|
| 506 |
+
return loss
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gmpo/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 .gmpo_config import GMPOConfig
|
| 16 |
+
from .gmpo_trainer import GMPOTrainer
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gmpo/gmpo_config.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.grpo_config import GRPOConfig
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class GMPOConfig(GRPOConfig):
|
| 22 |
+
# docstyle-ignore
|
| 23 |
+
r"""
|
| 24 |
+
Configuration class for the [`GMPOTrainer`].
|
| 25 |
+
|
| 26 |
+
[`GMPOConfig`] inherits every parameter from [`GRPOConfig`]; it only changes the meaning and default of the
|
| 27 |
+
clipping range. In GMPO, clipping is applied to the per-token *log*-importance ratios (i.e. in log space) before
|
| 28 |
+
the geometric mean is taken, so `epsilon` and `epsilon_high` are expressed in log space: the effective ratio
|
| 29 |
+
clipping range is `(exp(-epsilon), exp(epsilon_high))`. The [GMPO paper](https://huggingface.co/papers/2507.20673)
|
| 30 |
+
recommends a markedly wider range than GRPO/DAPO, `(exp(-0.4), exp(0.4))`, to encourage exploration.
|
| 31 |
+
|
| 32 |
+
Parameters:
|
| 33 |
+
epsilon (`float`, *optional*, defaults to `0.4`):
|
| 34 |
+
Lower-bound clipping value, expressed in log space. The lower bound of the per-token importance ratio is
|
| 35 |
+
`exp(-epsilon)`.
|
| 36 |
+
epsilon_high (`float`, *optional*):
|
| 37 |
+
Upper-bound clipping value, expressed in log space. If `None`, it defaults to the value of `epsilon`. The
|
| 38 |
+
upper bound of the per-token importance ratio is `exp(epsilon_high)`.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
epsilon: float = field(
|
| 42 |
+
default=0.4,
|
| 43 |
+
metadata={
|
| 44 |
+
"help": "Lower-bound clipping value, expressed in log space. The lower bound of the per-token importance "
|
| 45 |
+
"ratio is exp(-epsilon). GMPO recommends 0.4."
|
| 46 |
+
},
|
| 47 |
+
)
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gmpo/gmpo_trainer.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 torch
|
| 16 |
+
|
| 17 |
+
from ...trainer.grpo_trainer import GRPOTrainer
|
| 18 |
+
from ...trainer.utils import get_config_model_id, nanmax, nanmin
|
| 19 |
+
from .gmpo_config import GMPOConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class GMPOTrainer(GRPOTrainer):
|
| 23 |
+
"""
|
| 24 |
+
Trainer for Geometric-Mean Policy Optimization (GMPO).
|
| 25 |
+
|
| 26 |
+
GMPO (https://huggingface.co/papers/2507.20673) is a GRPO variant that maximizes the *geometric* mean of the
|
| 27 |
+
token-level importance ratios instead of the arithmetic mean. Because the geometric mean is far less sensitive to
|
| 28 |
+
outlier ratios, the policy update is more stable and a much wider clipping range can be used.
|
| 29 |
+
|
| 30 |
+
The only change w.r.t. [`GRPOTrainer`] is `_compute_loss`. Everything else (generation, reward computation, weight
|
| 31 |
+
syncing, metric logging) is inherited unchanged
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
_tag_names = ["trl", "gmpo"]
|
| 35 |
+
|
| 36 |
+
def __init__(self, model, reward_funcs, args=None, **kwargs):
|
| 37 |
+
if args is None:
|
| 38 |
+
model_name = model if isinstance(model, str) else get_config_model_id(model.config)
|
| 39 |
+
args = GMPOConfig(f"{model_name.split('/')[-1]}-GMPO")
|
| 40 |
+
|
| 41 |
+
super().__init__(model, reward_funcs, args=args, **kwargs)
|
| 42 |
+
|
| 43 |
+
def _compute_loss(self, model, inputs):
|
| 44 |
+
# Compute the per-token log probabilities for the model
|
| 45 |
+
prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
|
| 46 |
+
completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
|
| 47 |
+
input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
|
| 48 |
+
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
|
| 49 |
+
logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
|
| 50 |
+
mask = completion_mask if "tool_mask" not in inputs else completion_mask * inputs["tool_mask"]
|
| 51 |
+
|
| 52 |
+
# Compute the per_token_logps and the entropy at each position in the completion
|
| 53 |
+
per_token_logps, entropies, _ = self._get_per_token_logps_and_entropies(
|
| 54 |
+
model,
|
| 55 |
+
input_ids,
|
| 56 |
+
attention_mask,
|
| 57 |
+
logits_to_keep,
|
| 58 |
+
compute_entropy=True,
|
| 59 |
+
pixel_values=inputs.get("pixel_values"),
|
| 60 |
+
image_grid_thw=inputs.get("image_grid_thw"),
|
| 61 |
+
num_images=inputs.get("num_images"),
|
| 62 |
+
pixel_attention_mask=inputs.get("pixel_attention_mask"),
|
| 63 |
+
image_sizes=inputs.get("image_sizes"),
|
| 64 |
+
token_type_ids=inputs.get("token_type_ids"),
|
| 65 |
+
mm_token_type_ids=inputs.get("mm_token_type_ids"),
|
| 66 |
+
image_position_ids=inputs.get("image_position_ids"),
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
if self.top_entropy_quantile < 1.0:
|
| 70 |
+
entropy_mask = self.get_high_entropy_mask(entropies, mask, 1 - self.top_entropy_quantile)
|
| 71 |
+
else:
|
| 72 |
+
entropy_mask = None
|
| 73 |
+
|
| 74 |
+
advantages = inputs["advantages"]
|
| 75 |
+
# When num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps,
|
| 76 |
+
# old_per_token_logps == per_token_logps, so we skip its computation and use per_token_logps.detach() instead.
|
| 77 |
+
old_per_token_logps = inputs.get("old_per_token_logps")
|
| 78 |
+
old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps
|
| 79 |
+
|
| 80 |
+
# GMPO Objective
|
| 81 |
+
# Per-token log importance ratio
|
| 82 |
+
log_ratio = per_token_logps - old_per_token_logps
|
| 83 |
+
|
| 84 |
+
# Token-level clipping, performed in *log space* for numerical stability. The clip range in
|
| 85 |
+
# ratio space is (exp(-epsilon_low), exp(epsilon_high)); the paper recommends exp(±0.4), markedly wider than
|
| 86 |
+
# GRPO/DAPO, to encourage exploration.
|
| 87 |
+
clamped_log_ratio = torch.clamp(log_ratio, min=-self.epsilon_low, max=self.epsilon_high)
|
| 88 |
+
|
| 89 |
+
# sign-aware, one-sided clipping = PPO's trust-region "min" trick written in log-spaces:
|
| 90 |
+
advantages_col = advantages.unsqueeze(1)
|
| 91 |
+
clipped_log_ratio = torch.where(
|
| 92 |
+
advantages_col > 0,
|
| 93 |
+
torch.minimum(log_ratio, clamped_log_ratio),
|
| 94 |
+
torch.maximum(log_ratio, clamped_log_ratio),
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# Optionally drop low-entropy tokens from the geometric mean
|
| 98 |
+
seq_mask = mask * entropy_mask if entropy_mask is not None else mask
|
| 99 |
+
|
| 100 |
+
# Geometric mean of the clipped token ratios = exp(mean of clipped log-ratios over valid tokens). The 1/|o_i|
|
| 101 |
+
# exponent is the geometric-mean normalization; the paper's ablation shows it is essential.
|
| 102 |
+
log_importance_weights = (clipped_log_ratio * seq_mask).sum(-1) / seq_mask.sum(-1).clamp(min=1.0) # (B,)
|
| 103 |
+
coef = torch.exp(log_importance_weights) # (B,) sequence-level (geometric-mean) importance weight
|
| 104 |
+
|
| 105 |
+
per_sequence_loss = -coef * advantages # (B,)
|
| 106 |
+
|
| 107 |
+
# KL regularization toward the reference model (optional; sequence-averaged to match GMPO's sequence-level
|
| 108 |
+
# objective). Disabled by default (beta == 0)
|
| 109 |
+
if self.beta != 0.0:
|
| 110 |
+
ref_per_token_logps = inputs["ref_per_token_logps"]
|
| 111 |
+
per_token_kl = (
|
| 112 |
+
torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
|
| 113 |
+
)
|
| 114 |
+
seq_kl = (per_token_kl * mask).sum(-1) / mask.sum(-1).clamp(min=1.0) # (B,)
|
| 115 |
+
per_sequence_loss = per_sequence_loss + self.beta * seq_kl
|
| 116 |
+
|
| 117 |
+
# GMPO aggregates with a plain mean over sequences, per token-norm
|
| 118 |
+
# already lives inside the geometric mean.
|
| 119 |
+
mode = "train" if self.model.training else "eval"
|
| 120 |
+
loss = per_sequence_loss.mean()
|
| 121 |
+
normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval
|
| 122 |
+
loss = loss / normalizer
|
| 123 |
+
|
| 124 |
+
# logging
|
| 125 |
+
completion_token_count = mask.sum().clamp(min=1.0)
|
| 126 |
+
|
| 127 |
+
if self.beta != 0.0:
|
| 128 |
+
mean_kl = (per_token_kl * mask).sum() / completion_token_count
|
| 129 |
+
self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
|
| 130 |
+
|
| 131 |
+
mean_entropy = (entropies * mask).sum() / completion_token_count
|
| 132 |
+
self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item())
|
| 133 |
+
|
| 134 |
+
# Fraction of the tokens pushed into the clipped region, in log-space.
|
| 135 |
+
is_high_clipped = (log_ratio > self.epsilon_high) & (advantages_col > 0)
|
| 136 |
+
is_low_clipped = (log_ratio < -self.epsilon_low) & (advantages_col < 0)
|
| 137 |
+
is_region_clipped = is_high_clipped | is_low_clipped
|
| 138 |
+
|
| 139 |
+
low_clip = (is_low_clipped.float() * mask).sum() / completion_token_count
|
| 140 |
+
high_clip = (is_high_clipped.float() * mask).sum() / completion_token_count
|
| 141 |
+
clip_ratio = (is_region_clipped.float() * mask).sum() / completion_token_count
|
| 142 |
+
|
| 143 |
+
gathered_low_clip = self.accelerator.gather(low_clip)
|
| 144 |
+
self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item())
|
| 145 |
+
self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item())
|
| 146 |
+
gathered_high_clip = self.accelerator.gather(high_clip)
|
| 147 |
+
self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item())
|
| 148 |
+
self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item())
|
| 149 |
+
gathered_clip_ratio = self.accelerator.gather(clip_ratio)
|
| 150 |
+
self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item())
|
| 151 |
+
|
| 152 |
+
return loss
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gold/__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 .gold_config import GOLDConfig
|
| 16 |
+
from .gold_trainer import GOLDTrainer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = ["GOLDConfig", "GOLDTrainer"]
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gold/gold_config.py
ADDED
|
@@ -0,0 +1,531 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.sft_config import SFTConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class GOLDConfig(SFTConfig):
|
| 24 |
+
# docstyle-ignore
|
| 25 |
+
r"""
|
| 26 |
+
Configuration class for [`GOLDTrainer`].
|
| 27 |
+
|
| 28 |
+
This class includes only the parameters that are specific to GOLD training. For a full list of training arguments,
|
| 29 |
+
please refer to the [`~transformers.TrainingArguments`] and [`SFTConfig`] documentation.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
> Parameters that control generation and the training loop
|
| 33 |
+
|
| 34 |
+
temperature (`float`, *optional*, defaults to `0.9`):
|
| 35 |
+
Temperature for sampling. The higher the temperature, the more random the completions.
|
| 36 |
+
top_p (`float`, *optional*, defaults to `0.95`):
|
| 37 |
+
If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to
|
| 38 |
+
`top_p` or higher are kept for generation.
|
| 39 |
+
top_k (`int`, *optional*, defaults to `0`):
|
| 40 |
+
Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is
|
| 41 |
+
disabled and all tokens are considered.
|
| 42 |
+
lmbda (`float`, *optional*, defaults to `0.5`):
|
| 43 |
+
Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy
|
| 44 |
+
student-generated outputs).
|
| 45 |
+
beta (`float`, *optional*, defaults to `0.5`):
|
| 46 |
+
Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence loss. When
|
| 47 |
+
beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL Divergence.
|
| 48 |
+
max_completion_length (`int`, *optional*, defaults to `128`):
|
| 49 |
+
Maximum number of tokens to generate per completion.
|
| 50 |
+
teacher_model_name_or_path (`str`, *optional*):
|
| 51 |
+
Model name or path of the teacher model. If `None`, the teacher model will be the same as the model being
|
| 52 |
+
trained.
|
| 53 |
+
teacher_model_revision (`str` or `None`, *optional*, defaults to `None`):
|
| 54 |
+
Model revision of the teacher model (e.g., branch name, tag, or commit hash). If `None`, the default
|
| 55 |
+
revision is used.
|
| 56 |
+
teacher_model_init_kwargs (`dict[str, Any]`, *optional*):
|
| 57 |
+
Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model
|
| 58 |
+
from a string.
|
| 59 |
+
teacher_tokenizer_name_or_path (`str`, *optional*):
|
| 60 |
+
Tokenizer name or path for the teacher model. If None when using ULD loss, will use the same tokenizer as
|
| 61 |
+
the student model (not recommended for cross-tokenizer distillation).
|
| 62 |
+
disable_dropout (`bool`, *optional*, defaults to `True`):
|
| 63 |
+
Whether to disable dropout in the model.
|
| 64 |
+
seq_kd (`bool`, *optional*, defaults to `False`):
|
| 65 |
+
Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised FT on
|
| 66 |
+
teacher-generated output).
|
| 67 |
+
num_generations (`int`, *optional*, defaults to `1`):
|
| 68 |
+
Number of generations per prompt. Each prompt is repeated this many times in the generation batch.
|
| 69 |
+
generation_batch_size (`int` or `None`, *optional*, defaults to `None`):
|
| 70 |
+
Number of unique prompts per worker per optimizer step. If `None`, it is computed from
|
| 71 |
+
`(per_device_train_batch_size * gradient_accumulation_steps) // num_generations`.
|
| 72 |
+
> Parameters that control the ULD loss
|
| 73 |
+
|
| 74 |
+
use_uld_loss (`bool`, *optional*, defaults to `False`):
|
| 75 |
+
Whether to use Universal Logit Distillation (ULD) loss instead of Generalized Jensen-Shannon Divergence
|
| 76 |
+
loss.
|
| 77 |
+
use_extended_uld (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Whether to enable extended ULD alignment that uses tokenizers to align and merge token probabilities
|
| 79 |
+
across student and teacher tokenizations. When `True`, the trainer will compute token mappings and merge
|
| 80 |
+
probabilities for split tokens; when `False`, ULD will use simple positional truncation like in the
|
| 81 |
+
original ULD paper.
|
| 82 |
+
uld_token_merge_strategy (`str`, *optional*, defaults to `"observed"`):
|
| 83 |
+
Strategy used to align answer logits and merge token probabilities in the ULD loss. With `"observed"`, the
|
| 84 |
+
answer logits are sliced at the answer positions and split tokens (when `use_extended_uld=True`) are merged
|
| 85 |
+
by multiplying the marginal distribution at the first position by the scalar conditional probabilities of
|
| 86 |
+
the actual later tokens. With `"bayesian"`, the answer-logit slice is shifted one position earlier so that
|
| 87 |
+
`probs[k]` predicts `token_ids[k]` (chain rule), and split tokens are merged using the last position's full
|
| 88 |
+
distribution, conditioned on the actual prefix tokens, multiplied by the scalar probabilities of the
|
| 89 |
+
earlier tokens. The logit-alignment shift applies whether or not `use_extended_uld` is enabled.
|
| 90 |
+
uld_use_hybrid_loss (`bool`, *optional*, defaults to `False`):
|
| 91 |
+
Whether to use a hybrid loss that combines ULD loss and JSD loss. When `True`, the final loss is a
|
| 92 |
+
combination of JSD for known token mappings and ULD for unknown token mappings.
|
| 93 |
+
uld_hybrid_matched_weight (`float` or `None`, *optional*):
|
| 94 |
+
Weight for the matched token loss component when using hybrid ULD + JSD loss. This weight scales the JSD
|
| 95 |
+
loss computed over tokens that have a direct mapping between student and teacher tokenizations. If `None`,
|
| 96 |
+
uses adaptive weighting based on vocabulary overlap. Must be set together with
|
| 97 |
+
`uld_hybrid_unmatched_weight` (both `None` or both `float`).
|
| 98 |
+
uld_hybrid_unmatched_weight (`float` or `None`, *optional*):
|
| 99 |
+
Weight for the unmatched token loss component when using hybrid ULD + JSD loss. This weight scales the ULD
|
| 100 |
+
loss computed over tokens that do not have a direct mapping between student and teacher tokenizations. If
|
| 101 |
+
`None`, uses adaptive weighting based on vocabulary overlap. Must be set together with
|
| 102 |
+
`uld_hybrid_matched_weight` (both `None` or both `float`).
|
| 103 |
+
uld_crossentropy_weight (`float`, *optional*, defaults to `0.0`):
|
| 104 |
+
Weight for the cross-entropy loss component in ULD loss. If 0, only ULD distillation loss is used.
|
| 105 |
+
uld_distillation_weight (`float`, *optional*, defaults to `1.0`):
|
| 106 |
+
Weight for the distillation loss component in ULD loss.
|
| 107 |
+
uld_student_temperature (`float`, *optional*, defaults to `1.0`):
|
| 108 |
+
Temperature for student logits in ULD loss computation.
|
| 109 |
+
uld_teacher_temperature (`float`, *optional*, defaults to `1.0`):
|
| 110 |
+
Temperature for teacher logits in ULD loss computation.
|
| 111 |
+
uld_skip_student_eos (`bool`, *optional*, defaults to `True`):
|
| 112 |
+
Whether to skip EOS token for student in ULD loss computation.
|
| 113 |
+
uld_skip_teacher_eos (`bool`, *optional*, defaults to `True`):
|
| 114 |
+
Whether to skip EOS token for teacher in ULD loss computation.
|
| 115 |
+
> Parameters that control vLLM integration
|
| 116 |
+
|
| 117 |
+
use_vllm (`bool`, *optional*, defaults to `False`):
|
| 118 |
+
Whether to use vLLM for generating completions from the student model. Requires `vllm` to be installed.
|
| 119 |
+
vllm_mode (`str`, *optional*, defaults to `"colocate"`):
|
| 120 |
+
Mode for student vLLM integration. Either `"server"` (connect to a running TRL vLLM server) or `"colocate"`
|
| 121 |
+
(run vLLM in the same process).
|
| 122 |
+
vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
|
| 123 |
+
Host of the vLLM server for the student model (if `vllm_mode="server"`).
|
| 124 |
+
vllm_server_port (`int`, *optional*, defaults to `8001`):
|
| 125 |
+
Port of the vLLM server for the student model (if `vllm_mode="server"`).
|
| 126 |
+
vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
|
| 127 |
+
Timeout for connecting to the student vLLM server (if `vllm_mode="server"`).
|
| 128 |
+
vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.9`):
|
| 129 |
+
GPU memory utilization for the colocated student vLLM engine (if `vllm_mode="colocate"`). It is recommended
|
| 130 |
+
to set this to a low value if the student and teacher models share the same GPU.
|
| 131 |
+
vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
|
| 132 |
+
Tensor parallel size for the colocated student vLLM engine (if `vllm_mode="colocate"`).
|
| 133 |
+
vllm_structured_outputs_regex (`str`, *optional*):
|
| 134 |
+
Regex for vLLM structured outputs for the student model.
|
| 135 |
+
vllm_server_base_url (`str`, *optional*):
|
| 136 |
+
Base URL for the vLLM server (e.g., `"http://localhost:8001"`). If provided, `vllm_server_host` and
|
| 137 |
+
`vllm_server_port` are ignored.
|
| 138 |
+
vllm_group_port (`int`, *optional*, defaults to `51216`):
|
| 139 |
+
Port for the vLLM weight-update group (NCCL communicator). Unless the port is occupied, there is no need to
|
| 140 |
+
change it.
|
| 141 |
+
vllm_max_model_length (`int`, *optional*):
|
| 142 |
+
Maximum model sequence length for the colocated vLLM engine when `vllm_mode="colocate"`. Defaults to the
|
| 143 |
+
model's maximum context length.
|
| 144 |
+
vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
|
| 145 |
+
Model implementation backend to use in vLLM. Use `"vllm"` (default) or `"transformers"`.
|
| 146 |
+
vllm_sync_frequency (`int`, *optional*, defaults to `1`):
|
| 147 |
+
Frequency (in training steps) to synchronize student model weights to vLLM engine. Set to 1 to sync after
|
| 148 |
+
every step.
|
| 149 |
+
vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
|
| 150 |
+
Enable vLLM sleep mode to offload student weights/cache during the optimizer step. Keeps GPU memory usage
|
| 151 |
+
low, but waking the engine adds host–device transfer latency.
|
| 152 |
+
|
| 153 |
+
> Parameters that control logging
|
| 154 |
+
|
| 155 |
+
log_completions (`bool`, *optional*, defaults to `False`):
|
| 156 |
+
Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is installed,
|
| 157 |
+
it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`.
|
| 158 |
+
log_completions_steps (`int`, *optional*, defaults to `100`):
|
| 159 |
+
Number of steps between logging (prompt, completion) pairs. Only used if `log_completions` is set to
|
| 160 |
+
`True`.
|
| 161 |
+
num_completions_to_print (`int` or `None`, *optional*):
|
| 162 |
+
Number of completions to print with `rich`. If `None`, all completions are logged.
|
| 163 |
+
wandb_log_unique_prompts (`bool`, *optional*, defaults to `True`):
|
| 164 |
+
Whether to log the unique prompts to wandb. This will create a new run for each unique prompt.
|
| 165 |
+
callbacks (`list[str]`, *optional*, defaults to `[]`):
|
| 166 |
+
The callbacks to run during training.
|
| 167 |
+
|
| 168 |
+
> [!NOTE]
|
| 169 |
+
> These parameters have default values different from [`~transformers.TrainingArguments`]:
|
| 170 |
+
> - `learning_rate`: Defaults to `1e-7` instead of `5e-5`.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
_VALID_DICT_FIELDS = SFTConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"]
|
| 174 |
+
|
| 175 |
+
# Parameters whose default values are overridden from TrainingArguments
|
| 176 |
+
learning_rate: float = field(
|
| 177 |
+
default=1e-7,
|
| 178 |
+
metadata={"help": "The initial learning rate for AdamW."},
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
# GOLD-specific parameters
|
| 182 |
+
temperature: float = field(
|
| 183 |
+
default=0.9,
|
| 184 |
+
metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."},
|
| 185 |
+
)
|
| 186 |
+
top_p: float = field(
|
| 187 |
+
default=0.95,
|
| 188 |
+
metadata={
|
| 189 |
+
"help": "If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to "
|
| 190 |
+
"`top_p` or higher are kept for generation."
|
| 191 |
+
},
|
| 192 |
+
)
|
| 193 |
+
top_k: int = field(
|
| 194 |
+
default=0,
|
| 195 |
+
metadata={
|
| 196 |
+
"help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, "
|
| 197 |
+
"top-k-filtering is disabled and all tokens are considered."
|
| 198 |
+
},
|
| 199 |
+
)
|
| 200 |
+
lmbda: float = field(
|
| 201 |
+
default=0.5,
|
| 202 |
+
metadata={
|
| 203 |
+
"help": "Lambda parameter that controls the student data fraction (i.e., the proportion of on-policy "
|
| 204 |
+
"student-generated outputs)."
|
| 205 |
+
},
|
| 206 |
+
)
|
| 207 |
+
beta: float = field(
|
| 208 |
+
default=0.5,
|
| 209 |
+
metadata={
|
| 210 |
+
"help": "Interpolation coefficient between `0.0` and `1.0` of the Generalized Jensen-Shannon Divergence "
|
| 211 |
+
"loss. When beta is `0.0`, the loss is the KL divergence. When beta is `1.0`, the loss is the Inverse KL "
|
| 212 |
+
"Divergence."
|
| 213 |
+
},
|
| 214 |
+
)
|
| 215 |
+
max_completion_length: int = field(
|
| 216 |
+
default=128,
|
| 217 |
+
metadata={"help": "Maximum number of tokens to generate per completion."},
|
| 218 |
+
)
|
| 219 |
+
teacher_model_name_or_path: str | None = field(
|
| 220 |
+
default=None,
|
| 221 |
+
metadata={
|
| 222 |
+
"help": "Model name or path of the teacher model. If `None`, the teacher model will be the same as the "
|
| 223 |
+
"model being trained."
|
| 224 |
+
},
|
| 225 |
+
)
|
| 226 |
+
teacher_model_revision: str | None = field(
|
| 227 |
+
default=None,
|
| 228 |
+
metadata={
|
| 229 |
+
"help": "Model revision of the teacher model (e.g., branch name, tag, or commit hash). If `None`, the "
|
| 230 |
+
"default revision is used."
|
| 231 |
+
},
|
| 232 |
+
)
|
| 233 |
+
teacher_model_init_kwargs: dict[str, Any] | str | None = field(
|
| 234 |
+
default=None,
|
| 235 |
+
metadata={
|
| 236 |
+
"help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the "
|
| 237 |
+
"teacher model from a string."
|
| 238 |
+
},
|
| 239 |
+
)
|
| 240 |
+
teacher_tokenizer_name_or_path: str | None = field(
|
| 241 |
+
default=None,
|
| 242 |
+
metadata={
|
| 243 |
+
"help": "Tokenizer name or path for the teacher model. If None when using ULD loss, will use the same "
|
| 244 |
+
"tokenizer as the student model (not recommended for cross-tokenizer distillation)."
|
| 245 |
+
},
|
| 246 |
+
)
|
| 247 |
+
disable_dropout: bool = field(
|
| 248 |
+
default=True,
|
| 249 |
+
metadata={"help": "Whether to disable dropouts in `model`."},
|
| 250 |
+
)
|
| 251 |
+
seq_kd: bool = field(
|
| 252 |
+
default=False,
|
| 253 |
+
metadata={
|
| 254 |
+
"help": "Seq_kd parameter that controls whether to perform Sequence-Level KD (can be viewed as supervised "
|
| 255 |
+
"FT on teacher-generated output)."
|
| 256 |
+
},
|
| 257 |
+
)
|
| 258 |
+
num_generations: int = field(
|
| 259 |
+
default=1,
|
| 260 |
+
metadata={
|
| 261 |
+
"help": "Number of generations per prompt. Increasing this will decrease the number of unique prompts per optimization step."
|
| 262 |
+
},
|
| 263 |
+
)
|
| 264 |
+
generation_batch_size: int | None = field(
|
| 265 |
+
default=None,
|
| 266 |
+
metadata={
|
| 267 |
+
"help": "Number of unique prompts per worker per optimizer step. "
|
| 268 |
+
"If None, computed from (per_device_train_batch_size * gradient_accumulation_steps) // num_generations."
|
| 269 |
+
},
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
# ULD Loss parameters
|
| 273 |
+
use_uld_loss: bool = field(
|
| 274 |
+
default=False,
|
| 275 |
+
metadata={
|
| 276 |
+
"help": "Whether to use Universal Logit Distillation (ULD) loss instead of Generalized Jensen-Shannon Divergence loss."
|
| 277 |
+
},
|
| 278 |
+
)
|
| 279 |
+
uld_token_merge_strategy: str = field(
|
| 280 |
+
default="observed",
|
| 281 |
+
metadata={
|
| 282 |
+
"help": (
|
| 283 |
+
'Strategy used to align answer logits and merge token probabilities in the ULD loss. With "observed", '
|
| 284 |
+
"the answer logits are sliced at the answer positions and split tokens (when use_extended_uld=True) "
|
| 285 |
+
"are merged by multiplying the marginal distribution at the first position by the scalar conditional "
|
| 286 |
+
'probabilities of the actual later tokens. With "bayesian", the answer-logit slice is shifted one '
|
| 287 |
+
"position earlier so probs[k] predicts token_ids[k] (chain rule), and split tokens are merged using "
|
| 288 |
+
"the last position's full distribution, conditioned on the actual prefix tokens, multiplied by the "
|
| 289 |
+
"scalar probabilities of the earlier tokens. The logit-alignment shift applies whether or not "
|
| 290 |
+
"use_extended_uld is enabled."
|
| 291 |
+
)
|
| 292 |
+
},
|
| 293 |
+
)
|
| 294 |
+
use_extended_uld: bool = field(
|
| 295 |
+
default=True,
|
| 296 |
+
metadata={
|
| 297 |
+
"help": (
|
| 298 |
+
"Whether to enable extended ULD alignment that uses tokenizers to align and merge token "
|
| 299 |
+
"probabilities across student and teacher tokenizations. When True, the trainer will compute "
|
| 300 |
+
"token mappings and merge probabilities for split tokens; when False, ULD will use simple "
|
| 301 |
+
"positional truncation like in the original ULD paper."
|
| 302 |
+
)
|
| 303 |
+
},
|
| 304 |
+
)
|
| 305 |
+
uld_use_hybrid_loss: bool = field(
|
| 306 |
+
default=False,
|
| 307 |
+
metadata={
|
| 308 |
+
"help": (
|
| 309 |
+
"Whether to use a hybrid loss that combines ULD loss and JSD loss. When True, the final loss is a "
|
| 310 |
+
"a combination of JSD for known token mappings and ULD for unknown token mappings."
|
| 311 |
+
)
|
| 312 |
+
},
|
| 313 |
+
)
|
| 314 |
+
uld_hybrid_matched_weight: float | None = field(
|
| 315 |
+
default=None,
|
| 316 |
+
metadata={
|
| 317 |
+
"help": (
|
| 318 |
+
"Weight for the matched token loss component when using hybrid ULD + JSD loss. This weight scales "
|
| 319 |
+
"the JSD loss computed over tokens that have a direct mapping between student and teacher "
|
| 320 |
+
"tokenizations. If None, uses adaptive weighting based on vocabulary overlap. Must be set together "
|
| 321 |
+
"with uld_hybrid_unmatched_weight (both None or both float)."
|
| 322 |
+
)
|
| 323 |
+
},
|
| 324 |
+
)
|
| 325 |
+
uld_hybrid_unmatched_weight: float | None = field(
|
| 326 |
+
default=None,
|
| 327 |
+
metadata={
|
| 328 |
+
"help": (
|
| 329 |
+
"Weight for the unmatched token loss component when using hybrid ULD + JSD loss. This weight scales "
|
| 330 |
+
"the ULD loss computed over tokens that do not have a direct mapping between student and teacher "
|
| 331 |
+
"tokenizations. If None, uses adaptive weighting based on vocabulary overlap. Must be set together "
|
| 332 |
+
"with uld_hybrid_matched_weight (both None or both float)."
|
| 333 |
+
)
|
| 334 |
+
},
|
| 335 |
+
)
|
| 336 |
+
uld_crossentropy_weight: float = field(
|
| 337 |
+
default=0.0,
|
| 338 |
+
metadata={"help": "Weight for the cross-entropy loss component in ULD loss."},
|
| 339 |
+
)
|
| 340 |
+
uld_distillation_weight: float = field(
|
| 341 |
+
default=1.0,
|
| 342 |
+
metadata={"help": "Weight for the distillation loss component in ULD loss."},
|
| 343 |
+
)
|
| 344 |
+
uld_student_temperature: float = field(
|
| 345 |
+
default=1.0,
|
| 346 |
+
metadata={"help": "Temperature for student logits in ULD loss computation."},
|
| 347 |
+
)
|
| 348 |
+
uld_teacher_temperature: float = field(
|
| 349 |
+
default=1.0,
|
| 350 |
+
metadata={"help": "Temperature for teacher logits in ULD loss computation."},
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
uld_skip_student_eos: bool = field(
|
| 354 |
+
default=True,
|
| 355 |
+
metadata={"help": "Whether to skip EOS token for student in ULD loss computation."},
|
| 356 |
+
)
|
| 357 |
+
uld_skip_teacher_eos: bool = field(
|
| 358 |
+
default=True,
|
| 359 |
+
metadata={"help": "Whether to skip EOS token for teacher in ULD loss computation."},
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
# vLLM parameters
|
| 363 |
+
use_vllm: bool = field(
|
| 364 |
+
default=False,
|
| 365 |
+
metadata={"help": "Whether to use vLLM for generating completions. Requires `vllm` to be installed."},
|
| 366 |
+
)
|
| 367 |
+
vllm_mode: str = field(
|
| 368 |
+
default="colocate",
|
| 369 |
+
metadata={
|
| 370 |
+
"help": 'Mode for vLLM integration. Either "server" (connect to a running TRL vLLM server) or "colocate" (run vLLM in the same process).'
|
| 371 |
+
},
|
| 372 |
+
)
|
| 373 |
+
vllm_server_base_url: str | None = field(
|
| 374 |
+
default=None,
|
| 375 |
+
metadata={
|
| 376 |
+
"help": 'Base URL for the vLLM server (e.g., "http://localhost:8001"). If provided, vllm_server_host and vllm_server_port are ignored.'
|
| 377 |
+
},
|
| 378 |
+
)
|
| 379 |
+
vllm_server_host: str = field(
|
| 380 |
+
default="0.0.0.0",
|
| 381 |
+
metadata={"help": 'Host of the vLLM server when `vllm_mode="server"`.'},
|
| 382 |
+
)
|
| 383 |
+
vllm_server_port: int = field(
|
| 384 |
+
default=8001,
|
| 385 |
+
metadata={"help": 'Port of the vLLM server when `vllm_mode="server"`.'},
|
| 386 |
+
)
|
| 387 |
+
vllm_server_timeout: float = field(
|
| 388 |
+
default=240.0,
|
| 389 |
+
metadata={"help": 'Timeout (in seconds) for connecting to the vLLM server when `vllm_mode="server"`.'},
|
| 390 |
+
)
|
| 391 |
+
vllm_group_port: int = field(
|
| 392 |
+
default=51216,
|
| 393 |
+
metadata={"help": "Port for the vLLM weight-update group (NCCL communicator)."},
|
| 394 |
+
)
|
| 395 |
+
vllm_gpu_memory_utilization: float = field(
|
| 396 |
+
default=0.9,
|
| 397 |
+
metadata={
|
| 398 |
+
"help": 'GPU memory utilization for the colocated vLLM engine when `vllm_mode="colocate"`. Lower values reduce contention when sharing a device with the student/teacher models.'
|
| 399 |
+
},
|
| 400 |
+
)
|
| 401 |
+
vllm_tensor_parallel_size: int = field(
|
| 402 |
+
default=1,
|
| 403 |
+
metadata={"help": 'Tensor parallel size for the colocated vLLM engine when `vllm_mode="colocate"`.'},
|
| 404 |
+
)
|
| 405 |
+
vllm_max_model_length: int | None = field(
|
| 406 |
+
default=None,
|
| 407 |
+
metadata={
|
| 408 |
+
"help": 'Maximum model sequence length for the colocated vLLM engine when `vllm_mode="colocate"`. Defaults to the model\'s maximum context length.'
|
| 409 |
+
},
|
| 410 |
+
)
|
| 411 |
+
vllm_model_impl: str = field(
|
| 412 |
+
default="vllm",
|
| 413 |
+
metadata={"help": 'Model implementation backend to use in vLLM. Use "vllm" (default) or "transformers".'},
|
| 414 |
+
)
|
| 415 |
+
vllm_structured_outputs_regex: str | None = field(
|
| 416 |
+
default=None,
|
| 417 |
+
metadata={"help": "Regex pattern used for vLLM structured outputs (optional)."},
|
| 418 |
+
)
|
| 419 |
+
vllm_sync_frequency: int = field(
|
| 420 |
+
default=1,
|
| 421 |
+
metadata={
|
| 422 |
+
"help": "Frequency (in training steps) to synchronize model weights to the vLLM engine. Set to 1 to sync after every step."
|
| 423 |
+
},
|
| 424 |
+
)
|
| 425 |
+
vllm_enable_sleep_mode: bool = field(
|
| 426 |
+
default=False,
|
| 427 |
+
metadata={
|
| 428 |
+
"help": "Enable vLLM sleep mode to offload student weights/cache during the optimizer step. Keeps GPU "
|
| 429 |
+
"memory usage low, but waking the engine adds host–device transfer latency."
|
| 430 |
+
},
|
| 431 |
+
)
|
| 432 |
+
# Parameters that control the logging
|
| 433 |
+
log_completions: bool = field(
|
| 434 |
+
default=False,
|
| 435 |
+
metadata={
|
| 436 |
+
"help": "Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is "
|
| 437 |
+
"installed, it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`."
|
| 438 |
+
},
|
| 439 |
+
)
|
| 440 |
+
log_completions_steps: int = field(
|
| 441 |
+
default=100,
|
| 442 |
+
metadata={
|
| 443 |
+
"help": "Number of steps between logging (prompt, completion) pairs. Only used if `log_completions` is "
|
| 444 |
+
"set to `True`."
|
| 445 |
+
},
|
| 446 |
+
)
|
| 447 |
+
num_completions_to_print: int | None = field(
|
| 448 |
+
default=None,
|
| 449 |
+
metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."},
|
| 450 |
+
)
|
| 451 |
+
wandb_log_unique_prompts: bool = field(
|
| 452 |
+
default=True,
|
| 453 |
+
metadata={
|
| 454 |
+
"help": ("Whether to log the unique prompts to wandb. This will create a new run for each unique prompt.")
|
| 455 |
+
},
|
| 456 |
+
)
|
| 457 |
+
callbacks: list[str] = field(
|
| 458 |
+
default_factory=lambda: [],
|
| 459 |
+
metadata={"help": "The callbacks to run during training."},
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
def __post_init__(self):
|
| 463 |
+
super().__post_init__()
|
| 464 |
+
|
| 465 |
+
# check lmbda and beta are in the range [0, 1]
|
| 466 |
+
if self.lmbda < 0.0 or self.lmbda > 1.0:
|
| 467 |
+
raise ValueError("lmbda must be in the range [0.0, 1.0].")
|
| 468 |
+
if self.beta < 0.0 or self.beta > 1.0:
|
| 469 |
+
raise ValueError("beta must be in the range [0.0, 1.0].")
|
| 470 |
+
|
| 471 |
+
# Validate that max_length is sufficient for max_completion_length
|
| 472 |
+
if self.max_length is not None and self.max_completion_length >= self.max_length:
|
| 473 |
+
raise ValueError(
|
| 474 |
+
f"max_completion_length ({self.max_completion_length}) must be smaller than max_length ({self.max_length}) "
|
| 475 |
+
f"to leave room for the prompt. Consider increasing max_length or reducing max_completion_length."
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
if self.num_generations < 1:
|
| 479 |
+
raise ValueError(f"num_generations must be at least 1, got {self.num_generations}.")
|
| 480 |
+
local_sequence_batch_size = self.per_device_train_batch_size * self.gradient_accumulation_steps
|
| 481 |
+
if self.generation_batch_size is None:
|
| 482 |
+
self.generation_batch_size = local_sequence_batch_size // self.num_generations
|
| 483 |
+
if self.generation_batch_size < 1:
|
| 484 |
+
raise ValueError(
|
| 485 |
+
f"generation_batch_size must be at least 1. Got generation_batch_size={self.generation_batch_size}."
|
| 486 |
+
)
|
| 487 |
+
if self.generation_batch_size * self.num_generations != local_sequence_batch_size:
|
| 488 |
+
raise ValueError(
|
| 489 |
+
"generation_batch_size and num_generations must exactly partition the local optimizer-step batch. "
|
| 490 |
+
"Expected generation_batch_size * num_generations == per_device_train_batch_size * "
|
| 491 |
+
f"gradient_accumulation_steps, got {self.generation_batch_size} * {self.num_generations} != "
|
| 492 |
+
f"{self.per_device_train_batch_size} * {self.gradient_accumulation_steps}."
|
| 493 |
+
)
|
| 494 |
+
if self.num_generations > 1 and self.lmbda < 1.0:
|
| 495 |
+
warnings.warn(
|
| 496 |
+
f"num_generations={self.num_generations} with lmbda={self.lmbda} means off-policy batches include "
|
| 497 |
+
f"{self.num_generations} copies of each sample; consider lmbda=1.0 when num_generations > 1.",
|
| 498 |
+
UserWarning,
|
| 499 |
+
stacklevel=2,
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
# Validate ULD parameters
|
| 503 |
+
if self.use_uld_loss:
|
| 504 |
+
if self.uld_crossentropy_weight < 0.0:
|
| 505 |
+
raise ValueError("uld_crossentropy_weight must be non-negative.")
|
| 506 |
+
if self.uld_distillation_weight < 0.0:
|
| 507 |
+
raise ValueError("uld_distillation_weight must be non-negative.")
|
| 508 |
+
if self.uld_student_temperature <= 0.0:
|
| 509 |
+
raise ValueError("uld_student_temperature must be positive.")
|
| 510 |
+
if self.uld_teacher_temperature <= 0.0:
|
| 511 |
+
raise ValueError("uld_teacher_temperature must be positive.")
|
| 512 |
+
if self.uld_token_merge_strategy not in ("observed", "bayesian"):
|
| 513 |
+
raise ValueError(
|
| 514 |
+
'uld_token_merge_strategy must be either "observed" or "bayesian", got '
|
| 515 |
+
f'"{self.uld_token_merge_strategy}".'
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
# Validate hybrid loss weights - both must be None or both must be set
|
| 519 |
+
if self.uld_use_hybrid_loss:
|
| 520 |
+
if (self.uld_hybrid_matched_weight is None) != (self.uld_hybrid_unmatched_weight is None):
|
| 521 |
+
raise ValueError(
|
| 522 |
+
"uld_hybrid_matched_weight and uld_hybrid_unmatched_weight must both be None (for adaptive "
|
| 523 |
+
"weighting) or both be set to numeric values. Got uld_hybrid_matched_weight="
|
| 524 |
+
f"{self.uld_hybrid_matched_weight} and uld_hybrid_unmatched_weight="
|
| 525 |
+
f"{self.uld_hybrid_unmatched_weight}."
|
| 526 |
+
)
|
| 527 |
+
if self.uld_hybrid_matched_weight is not None:
|
| 528 |
+
if self.uld_hybrid_matched_weight < 0.0:
|
| 529 |
+
raise ValueError("uld_hybrid_matched_weight must be non-negative.")
|
| 530 |
+
if self.uld_hybrid_unmatched_weight < 0.0:
|
| 531 |
+
raise ValueError("uld_hybrid_unmatched_weight must be non-negative.")
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gold/gold_trainer.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/grpo_with_replay_buffer/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 .grpo_with_replay_buffer_config import GRPOWithReplayBufferConfig
|
| 16 |
+
from .grpo_with_replay_buffer_trainer import GRPOWithReplayBufferTrainer, ReplayBuffer
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.grpo_config import GRPOConfig
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class GRPOWithReplayBufferConfig(GRPOConfig):
|
| 22 |
+
"""
|
| 23 |
+
New Parameters:
|
| 24 |
+
replay_buffer_size (`int`, *optional*, defaults to `64`):
|
| 25 |
+
A cache that stores the rollouts with the highest advantage scores and variance per group. If a new
|
| 26 |
+
group has 0 variance, it is replaced with a group sampled from the replay buffer.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
replay_buffer_size: int = field(
|
| 30 |
+
default=64,
|
| 31 |
+
metadata={
|
| 32 |
+
"help": "A cache that stores the rollouts with the highest advantage scores and variance per group. If a new group has 0 variance, it is replaced with a group sampled from the replay buffer."
|
| 33 |
+
},
|
| 34 |
+
)
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py
ADDED
|
@@ -0,0 +1,797 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 heapq
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from accelerate.utils import gather_object
|
| 20 |
+
|
| 21 |
+
from ...data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages
|
| 22 |
+
from ...models.utils import disable_gradient_checkpointing
|
| 23 |
+
from ...trainer.grpo_trainer import GRPOTrainer
|
| 24 |
+
from ...trainer.utils import nanmax, nanmin, nanstd, pad
|
| 25 |
+
from .grpo_with_replay_buffer_config import GRPOWithReplayBufferConfig
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ReplayBuffer:
|
| 29 |
+
"""
|
| 30 |
+
A simple replay buffer to store and sample previously seen rollouts.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, max_size: int):
|
| 34 |
+
self.max_size = max_size
|
| 35 |
+
self.heap = [] # Min-heap of (score, data) tuples
|
| 36 |
+
|
| 37 |
+
def add(self, scores: list[float], data: list[dict]):
|
| 38 |
+
for score, datum in zip(scores, data, strict=True):
|
| 39 |
+
if len(self.heap) < self.max_size:
|
| 40 |
+
heapq.heappush(self.heap, (score, datum))
|
| 41 |
+
else:
|
| 42 |
+
# Only add if score is better than worst (minimum) item
|
| 43 |
+
if score > self.heap[0][0]:
|
| 44 |
+
heapq.heapreplace(self.heap, (score, datum))
|
| 45 |
+
|
| 46 |
+
def sample(self, num_samples: int) -> list[dict[str, torch.Tensor]]:
|
| 47 |
+
if not self.heap:
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
# Sample by normalized scores
|
| 51 |
+
scores = torch.tensor([item[0] for item in self.heap], dtype=torch.float32)
|
| 52 |
+
probabilities = scores / scores.sum()
|
| 53 |
+
replacement = False
|
| 54 |
+
if num_samples > len(self.heap):
|
| 55 |
+
replacement = True
|
| 56 |
+
chosen_indices = torch.multinomial(probabilities, num_samples, replacement=replacement).tolist()
|
| 57 |
+
return [self.heap[i][1] for i in chosen_indices]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class GRPOWithReplayBufferTrainer(GRPOTrainer):
|
| 61 |
+
def __init__(self, args: GRPOWithReplayBufferConfig | None = None, **kwargs):
|
| 62 |
+
super().__init__(args=args, **kwargs)
|
| 63 |
+
self.replay_buffer = ReplayBuffer(args.replay_buffer_size) if args.replay_buffer_size > 0 else None
|
| 64 |
+
|
| 65 |
+
def _generate_and_score_completions(
|
| 66 |
+
self, inputs: list[dict[str, torch.Tensor | Any]]
|
| 67 |
+
) -> dict[str, torch.Tensor | Any]:
|
| 68 |
+
device = self.accelerator.device
|
| 69 |
+
mode = "train" if self.model.training else "eval"
|
| 70 |
+
|
| 71 |
+
prompts = [x["prompt"] for x in inputs]
|
| 72 |
+
|
| 73 |
+
if "images" in inputs[0]:
|
| 74 |
+
images = [example.get("images") for example in inputs]
|
| 75 |
+
elif "image" in inputs[0]:
|
| 76 |
+
images = [[example.get("image")] if example.get("image") is not None else None for example in inputs]
|
| 77 |
+
else:
|
| 78 |
+
images = None
|
| 79 |
+
# Transformers requires at least one image in the batch, otherwise it throws an error
|
| 80 |
+
if images is not None and all(img_list == [] for img_list in images):
|
| 81 |
+
images = None
|
| 82 |
+
|
| 83 |
+
# If the prompts are conversational and the inputs contain images, we need to convert the prompts from
|
| 84 |
+
# [{"role": "user", "content": "What color is the sky?"}] to
|
| 85 |
+
# [{"role": "user", "content": [{"type": "image", "image": <Image>}, {"type": "text", "text": "What color is the sky?"}]}]
|
| 86 |
+
if images is not None:
|
| 87 |
+
if not is_conversational(inputs[0]):
|
| 88 |
+
raise ValueError(
|
| 89 |
+
"Multimodal training requires conversational prompts. It looks like the dataset contains "
|
| 90 |
+
"non-conversational inputs, likely because a chat template was applied before passing the dataset "
|
| 91 |
+
"to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat "
|
| 92 |
+
"template internally."
|
| 93 |
+
)
|
| 94 |
+
prompts = [
|
| 95 |
+
prepare_multimodal_messages(prompt, images=image_list)
|
| 96 |
+
for prompt, image_list in zip(prompts, images, strict=True)
|
| 97 |
+
]
|
| 98 |
+
|
| 99 |
+
dataset_images = images # preserve dataset images before _generate may overwrite
|
| 100 |
+
(
|
| 101 |
+
prompt_ids_list,
|
| 102 |
+
completion_ids_list,
|
| 103 |
+
tool_mask_list,
|
| 104 |
+
completions,
|
| 105 |
+
num_items_in_batch,
|
| 106 |
+
sampling_per_token_logps_list,
|
| 107 |
+
extra_fields,
|
| 108 |
+
images,
|
| 109 |
+
tool_images,
|
| 110 |
+
) = self._generate(prompts)
|
| 111 |
+
if images is None:
|
| 112 |
+
images = dataset_images # restore dataset images (rollout_func path returns None)
|
| 113 |
+
|
| 114 |
+
# Convert lists of token IDs to padded tensors
|
| 115 |
+
prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list]
|
| 116 |
+
prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids]
|
| 117 |
+
prompt_ids = pad(
|
| 118 |
+
prompt_ids,
|
| 119 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 120 |
+
padding_side="left",
|
| 121 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 122 |
+
).to(device=device)
|
| 123 |
+
prompt_mask = pad(
|
| 124 |
+
prompt_mask,
|
| 125 |
+
padding_value=0,
|
| 126 |
+
padding_side="left",
|
| 127 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 128 |
+
).to(device=device)
|
| 129 |
+
completion_ids = [torch.tensor(ids) for ids in completion_ids_list]
|
| 130 |
+
completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids]
|
| 131 |
+
completion_ids = pad(
|
| 132 |
+
completion_ids,
|
| 133 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 134 |
+
padding_side="right",
|
| 135 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 136 |
+
).to(device=device)
|
| 137 |
+
completion_mask = pad(
|
| 138 |
+
completion_mask,
|
| 139 |
+
padding_value=0,
|
| 140 |
+
padding_side="right",
|
| 141 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 142 |
+
).to(device=device)
|
| 143 |
+
if sampling_per_token_logps_list is not None:
|
| 144 |
+
sampling_per_token_logps = [torch.tensor(logps) for logps in sampling_per_token_logps_list]
|
| 145 |
+
sampling_per_token_logps = pad(
|
| 146 |
+
sampling_per_token_logps,
|
| 147 |
+
padding_value=0.0,
|
| 148 |
+
padding_side="right",
|
| 149 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 150 |
+
).to(device=device)
|
| 151 |
+
else:
|
| 152 |
+
sampling_per_token_logps = None
|
| 153 |
+
if self.tools:
|
| 154 |
+
tool_mask = [torch.tensor(mask) for mask in tool_mask_list]
|
| 155 |
+
tool_mask = pad(
|
| 156 |
+
tool_mask,
|
| 157 |
+
padding_value=1,
|
| 158 |
+
padding_side="right",
|
| 159 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 160 |
+
).to(device=device) # 0 for tool result tokens, 1 elsewhere
|
| 161 |
+
|
| 162 |
+
# If mask_truncated_completions is enabled, zero out truncated completions in completion_mask
|
| 163 |
+
if self.mask_truncated_completions:
|
| 164 |
+
eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id]
|
| 165 |
+
is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device)
|
| 166 |
+
completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int()
|
| 167 |
+
|
| 168 |
+
# Concatenate prompt_mask with completion_mask for logit computation
|
| 169 |
+
prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C)
|
| 170 |
+
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C)
|
| 171 |
+
|
| 172 |
+
logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
|
| 173 |
+
batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size
|
| 174 |
+
|
| 175 |
+
num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None
|
| 176 |
+
|
| 177 |
+
# Get forward_kwargs for models with multimodal inputs
|
| 178 |
+
if images is not None:
|
| 179 |
+
prompts_text = [
|
| 180 |
+
apply_chat_template(
|
| 181 |
+
{"prompt": prompt}, self.processing_class, tools=self.tools, **self.chat_template_kwargs
|
| 182 |
+
)["prompt"]
|
| 183 |
+
for prompt in prompts
|
| 184 |
+
]
|
| 185 |
+
prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt")
|
| 186 |
+
prompt_inputs = super()._prepare_inputs(prompt_inputs)
|
| 187 |
+
forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]}
|
| 188 |
+
else:
|
| 189 |
+
forward_kwargs = {}
|
| 190 |
+
|
| 191 |
+
# If token_type_ids are used, extend them with zeros for the completion part
|
| 192 |
+
if "token_type_ids" in forward_kwargs:
|
| 193 |
+
token_type_ids = forward_kwargs["token_type_ids"]
|
| 194 |
+
if self.pad_to_multiple_of is not None:
|
| 195 |
+
# Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len
|
| 196 |
+
padding_size = prompt_ids.size(1) - token_type_ids.size(1)
|
| 197 |
+
if padding_size > 0:
|
| 198 |
+
token_type_ids = torch.cat(
|
| 199 |
+
[token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1
|
| 200 |
+
)
|
| 201 |
+
forward_kwargs["token_type_ids"] = torch.cat(
|
| 202 |
+
[token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1
|
| 203 |
+
)
|
| 204 |
+
# If mm_token_type_ids are used, extend them with zeros for the completion part
|
| 205 |
+
if "mm_token_type_ids" in forward_kwargs:
|
| 206 |
+
mm_token_type_ids = forward_kwargs["mm_token_type_ids"]
|
| 207 |
+
if self.pad_to_multiple_of is not None:
|
| 208 |
+
# Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len
|
| 209 |
+
padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1)
|
| 210 |
+
if padding_size > 0:
|
| 211 |
+
mm_token_type_ids = torch.cat(
|
| 212 |
+
[mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids],
|
| 213 |
+
dim=1,
|
| 214 |
+
)
|
| 215 |
+
forward_kwargs["mm_token_type_ids"] = torch.cat(
|
| 216 |
+
[mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
# When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a
|
| 220 |
+
# torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True").
|
| 221 |
+
# Temporarily disable checkpointing to avoid this warning during inference.
|
| 222 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 223 |
+
# If the generation and optimization steps are misaligned—i.e., if generation does not occur at the end of
|
| 224 |
+
# a full optimizer step (when gradient_accumulation_steps is not a multiple of generate_every)—then the
|
| 225 |
+
# samples may come from an earlier version of the model. In that case, we need to track old_per_token_logps
|
| 226 |
+
# for importance sampling. If the steps are aligned, importance sampling isn't necessary and we set
|
| 227 |
+
# old_per_token_logps to None.
|
| 228 |
+
# When using vLLM, we always compute old_per_token_logps for importance sampling, it was shown that the
|
| 229 |
+
# distribution mismatch between vLLM and the training model can be large and harm the training.
|
| 230 |
+
generate_every = self.args.steps_per_generation * self.num_iterations # generation frequency
|
| 231 |
+
if self.args.gradient_accumulation_steps % generate_every != 0 or (
|
| 232 |
+
self.use_vllm and self.vllm_importance_sampling_correction
|
| 233 |
+
):
|
| 234 |
+
old_per_token_logps, _, _ = self._get_per_token_logps_and_entropies(
|
| 235 |
+
self.model,
|
| 236 |
+
prompt_completion_ids,
|
| 237 |
+
attention_mask,
|
| 238 |
+
logits_to_keep,
|
| 239 |
+
batch_size,
|
| 240 |
+
num_images=num_images,
|
| 241 |
+
**forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
|
| 242 |
+
)
|
| 243 |
+
else:
|
| 244 |
+
old_per_token_logps = None
|
| 245 |
+
|
| 246 |
+
# Compute the importance sampling ratio when using vLLM, to correct for potential distribution mismatch
|
| 247 |
+
if self.use_vllm and self.vllm_importance_sampling_correction:
|
| 248 |
+
importance_sampling_ratio = torch.exp(old_per_token_logps - sampling_per_token_logps)
|
| 249 |
+
importance_sampling_ratio = torch.clamp(
|
| 250 |
+
importance_sampling_ratio,
|
| 251 |
+
min=self.vllm_importance_sampling_clip_min,
|
| 252 |
+
max=self.vllm_importance_sampling_clip_max,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# Compute the per-token log probabilities for the reference model
|
| 256 |
+
if self.beta != 0.0:
|
| 257 |
+
if self.ref_model is not None:
|
| 258 |
+
ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies(
|
| 259 |
+
self.ref_model,
|
| 260 |
+
prompt_completion_ids,
|
| 261 |
+
attention_mask,
|
| 262 |
+
logits_to_keep,
|
| 263 |
+
batch_size=batch_size,
|
| 264 |
+
num_images=num_images,
|
| 265 |
+
**forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
|
| 266 |
+
)
|
| 267 |
+
else:
|
| 268 |
+
with self.accelerator.unwrap_model(self.model).disable_adapter():
|
| 269 |
+
ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies(
|
| 270 |
+
self.model,
|
| 271 |
+
prompt_completion_ids,
|
| 272 |
+
attention_mask,
|
| 273 |
+
logits_to_keep,
|
| 274 |
+
batch_size=batch_size,
|
| 275 |
+
num_images=num_images,
|
| 276 |
+
**forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask and image_sizes
|
| 277 |
+
)
|
| 278 |
+
else:
|
| 279 |
+
ref_per_token_logps = None
|
| 280 |
+
|
| 281 |
+
# Decode
|
| 282 |
+
prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True)
|
| 283 |
+
completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
|
| 284 |
+
|
| 285 |
+
# Merge extra_fields from rollout_func into inputs for reward functions
|
| 286 |
+
if extra_fields:
|
| 287 |
+
for i, inp in enumerate(inputs):
|
| 288 |
+
for key, values in extra_fields.items():
|
| 289 |
+
if isinstance(values, list) and i < len(values):
|
| 290 |
+
inp[key] = values[i]
|
| 291 |
+
elif not isinstance(values, list):
|
| 292 |
+
inp[key] = values
|
| 293 |
+
|
| 294 |
+
# Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is
|
| 295 |
+
# important because rewards will be normalized per group, and completions are distributed. We will later slice
|
| 296 |
+
# rewards_per_func to extract each process's subset.
|
| 297 |
+
rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
|
| 298 |
+
|
| 299 |
+
# Apply weights to each reward function's output and sum
|
| 300 |
+
rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
|
| 301 |
+
|
| 302 |
+
# Compute grouped-wise rewards
|
| 303 |
+
mean_grouped_rewards = rewards.view(-1, self.num_generations).mean(dim=1)
|
| 304 |
+
|
| 305 |
+
# Normalize the rewards to compute the advantages
|
| 306 |
+
mean_grouped_rewards = mean_grouped_rewards.repeat_interleave(self.num_generations, dim=0)
|
| 307 |
+
advantages = rewards - mean_grouped_rewards
|
| 308 |
+
|
| 309 |
+
grouped_std_rewards = rewards.view(-1, self.num_generations).std(dim=1)
|
| 310 |
+
grouped_std_rewards = grouped_std_rewards.repeat_interleave(self.num_generations, dim=0)
|
| 311 |
+
|
| 312 |
+
if self.scale_rewards in ["group", "none"]:
|
| 313 |
+
# If self.scale_rewards = "none", we'll still log group level std
|
| 314 |
+
std_rewards = grouped_std_rewards.clone()
|
| 315 |
+
elif self.scale_rewards == "batch":
|
| 316 |
+
# Compute global std
|
| 317 |
+
std_rewards = rewards.std().expand_as(rewards)
|
| 318 |
+
else:
|
| 319 |
+
raise ValueError(
|
| 320 |
+
f"Invalid value for scale_rewards: {self.scale_rewards}. Must be one of 'batch', 'group', or 'none'."
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards))
|
| 324 |
+
if self.scale_rewards != "none":
|
| 325 |
+
advantages = advantages / (std_rewards + 1e-4)
|
| 326 |
+
|
| 327 |
+
# Slice to keep only the local part of the data
|
| 328 |
+
process_slice = slice(
|
| 329 |
+
self.accelerator.process_index * len(prompts),
|
| 330 |
+
(self.accelerator.process_index + 1) * len(prompts),
|
| 331 |
+
)
|
| 332 |
+
all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
|
| 333 |
+
advantages = advantages[process_slice]
|
| 334 |
+
grouped_std_rewards = grouped_std_rewards[process_slice]
|
| 335 |
+
|
| 336 |
+
# Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
|
| 337 |
+
for i, reward_func_name in enumerate(self.reward_func_names):
|
| 338 |
+
mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
|
| 339 |
+
self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
|
| 340 |
+
std_func_rewards = nanstd(rewards_per_func[:, i]).item()
|
| 341 |
+
self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards)
|
| 342 |
+
rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1)
|
| 343 |
+
self._metrics[mode]["reward"].append(rewards.mean().item())
|
| 344 |
+
self._metrics[mode]["reward_std"].append(rewards.std().item())
|
| 345 |
+
self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
|
| 346 |
+
|
| 347 |
+
# Log prompt and completion texts
|
| 348 |
+
self._logs["prompt"].extend(gather_object(prompts_text))
|
| 349 |
+
self._logs["completion"].extend(gather_object(completions_text))
|
| 350 |
+
for i, name in enumerate(self.reward_func_names):
|
| 351 |
+
self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
|
| 352 |
+
self._logs["advantages"].extend(all_process_advantages.tolist())
|
| 353 |
+
|
| 354 |
+
if images is not None:
|
| 355 |
+
self._logs["images"].extend(gather_object(images))
|
| 356 |
+
|
| 357 |
+
if self.use_vllm and self.vllm_importance_sampling_correction:
|
| 358 |
+
delta = torch.abs(old_per_token_logps - sampling_per_token_logps)
|
| 359 |
+
mask = completion_mask.bool() if not self.tools else (completion_mask * tool_mask).bool()
|
| 360 |
+
delta = delta[mask]
|
| 361 |
+
mean_delta = torch.mean(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device)
|
| 362 |
+
max_delta = torch.max(delta) if delta.numel() > 0 else torch.tensor(0.0, device=device)
|
| 363 |
+
self._metrics[mode]["sampling/sampling_logp_difference/mean"].append(
|
| 364 |
+
self.accelerator.gather(mean_delta).mean().item()
|
| 365 |
+
)
|
| 366 |
+
self._metrics[mode]["sampling/sampling_logp_difference/max"].append(
|
| 367 |
+
self.accelerator.gather(max_delta).max().item()
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
flat_is_ratio = importance_sampling_ratio[mask]
|
| 371 |
+
min_importance_sampling_ratio = (
|
| 372 |
+
torch.min(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
|
| 373 |
+
)
|
| 374 |
+
mean_importance_sampling_ratio = (
|
| 375 |
+
torch.mean(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
|
| 376 |
+
)
|
| 377 |
+
max_importance_sampling_ratio = (
|
| 378 |
+
torch.max(flat_is_ratio) if flat_is_ratio.numel() > 0 else torch.tensor(0.0, device=device)
|
| 379 |
+
)
|
| 380 |
+
self._metrics[mode]["sampling/importance_sampling_ratio/min"].append(
|
| 381 |
+
nanmin(self.accelerator.gather(min_importance_sampling_ratio)).item()
|
| 382 |
+
)
|
| 383 |
+
self._metrics[mode]["sampling/importance_sampling_ratio/mean"].append(
|
| 384 |
+
self.accelerator.gather(mean_importance_sampling_ratio).nanmean().item()
|
| 385 |
+
)
|
| 386 |
+
self._metrics[mode]["sampling/importance_sampling_ratio/max"].append(
|
| 387 |
+
nanmax(self.accelerator.gather(max_importance_sampling_ratio)).item()
|
| 388 |
+
)
|
| 389 |
+
outputs_after_sampling_buffer = self.update_with_replay_buffer(
|
| 390 |
+
advantages,
|
| 391 |
+
grouped_std_rewards,
|
| 392 |
+
prompt_ids,
|
| 393 |
+
prompt_mask,
|
| 394 |
+
completion_ids,
|
| 395 |
+
completion_mask,
|
| 396 |
+
forward_kwargs,
|
| 397 |
+
num_items_in_batch,
|
| 398 |
+
old_per_token_logps,
|
| 399 |
+
ref_per_token_logps,
|
| 400 |
+
importance_sampling_ratio if self.use_vllm and self.vllm_importance_sampling_correction else None,
|
| 401 |
+
)
|
| 402 |
+
if outputs_after_sampling_buffer is not None:
|
| 403 |
+
return outputs_after_sampling_buffer
|
| 404 |
+
else:
|
| 405 |
+
output = {
|
| 406 |
+
"prompt_ids": prompt_ids,
|
| 407 |
+
"prompt_mask": prompt_mask,
|
| 408 |
+
"completion_ids": completion_ids,
|
| 409 |
+
"completion_mask": completion_mask,
|
| 410 |
+
"advantages": advantages,
|
| 411 |
+
"num_items_in_batch": num_items_in_batch,
|
| 412 |
+
}
|
| 413 |
+
if old_per_token_logps is not None:
|
| 414 |
+
output["old_per_token_logps"] = old_per_token_logps
|
| 415 |
+
if self.use_vllm and self.vllm_importance_sampling_correction:
|
| 416 |
+
output["importance_sampling_ratio"] = importance_sampling_ratio
|
| 417 |
+
if ref_per_token_logps is not None:
|
| 418 |
+
output["ref_per_token_logps"] = ref_per_token_logps
|
| 419 |
+
if "pixel_values" in forward_kwargs:
|
| 420 |
+
output["pixel_values"] = forward_kwargs["pixel_values"]
|
| 421 |
+
if "image_grid_thw" in forward_kwargs:
|
| 422 |
+
output["image_grid_thw"] = forward_kwargs["image_grid_thw"]
|
| 423 |
+
if "pixel_attention_mask" in forward_kwargs:
|
| 424 |
+
output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"]
|
| 425 |
+
if "image_sizes" in forward_kwargs:
|
| 426 |
+
output["image_sizes"] = forward_kwargs["image_sizes"]
|
| 427 |
+
if "token_type_ids" in forward_kwargs:
|
| 428 |
+
output["token_type_ids"] = forward_kwargs["token_type_ids"]
|
| 429 |
+
if images is not None:
|
| 430 |
+
output["num_images"] = num_images
|
| 431 |
+
if self.tools:
|
| 432 |
+
output["tool_mask"] = tool_mask
|
| 433 |
+
return output
|
| 434 |
+
|
| 435 |
+
def slice_group_data(
|
| 436 |
+
self, data: torch.Tensor, mask: torch.Tensor, group_idx: int
|
| 437 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 438 |
+
"""
|
| 439 |
+
Slices the input data and mask tensors for a specific group index. Also trims the sequence length to the
|
| 440 |
+
maximum length in the group based on the mask.
|
| 441 |
+
|
| 442 |
+
Args:
|
| 443 |
+
data: Tensor of shape (num_groups * num_generations, seq_length)
|
| 444 |
+
mask: Tensor of shape (num_groups * num_generations, seq_length)
|
| 445 |
+
group_idx: Index of the group to slice
|
| 446 |
+
Returns:
|
| 447 |
+
Tuple of (sliced_data, sliced_mask) for the specified group, with sequence length trimmed to the maximum
|
| 448 |
+
length in the group.
|
| 449 |
+
"""
|
| 450 |
+
start_idx = group_idx * self.num_generations
|
| 451 |
+
end_idx = (group_idx + 1) * self.num_generations
|
| 452 |
+
group_data = data[start_idx:end_idx]
|
| 453 |
+
group_mask = mask[start_idx:end_idx]
|
| 454 |
+
group_max_len = group_mask.sum(dim=1).max().item()
|
| 455 |
+
return group_data[:, :group_max_len], group_mask[:, :group_max_len]
|
| 456 |
+
|
| 457 |
+
def update_replay_buffer(
|
| 458 |
+
self,
|
| 459 |
+
groups_with_variance: torch.Tensor,
|
| 460 |
+
group_advantages: torch.Tensor,
|
| 461 |
+
group_std_rewards: torch.Tensor,
|
| 462 |
+
prompt_ids: torch.Tensor,
|
| 463 |
+
prompt_mask: torch.Tensor,
|
| 464 |
+
completion_ids: torch.Tensor,
|
| 465 |
+
completion_mask: torch.Tensor,
|
| 466 |
+
forward_kwargs: dict,
|
| 467 |
+
optional_vision_fields: list[str] = None,
|
| 468 |
+
old_per_token_logps: torch.Tensor | None = None,
|
| 469 |
+
ref_per_token_logps: torch.Tensor | None = None,
|
| 470 |
+
importance_sampling_ratio: float | None = None,
|
| 471 |
+
) -> None:
|
| 472 |
+
"""
|
| 473 |
+
Update the replay buffer with groups that have reward variance (std > 0).
|
| 474 |
+
|
| 475 |
+
Args:
|
| 476 |
+
groups_with_variance: Boolean tensor indicating which groups have reward variance
|
| 477 |
+
group_advantages: Tensor of shape (num_groups, num_generations) containing advantage values
|
| 478 |
+
group_std_rewards: Tensor of shape (num_groups, num_generations) containing std of rewards per group
|
| 479 |
+
prompt_ids: Tensor containing prompt token IDs
|
| 480 |
+
prompt_mask: Tensor containing prompt attention masks
|
| 481 |
+
completion_ids: Tensor containing completion token IDs
|
| 482 |
+
completion_mask: Tensor containing completion attention masks
|
| 483 |
+
forward_kwargs: Dictionary containing additional prompt inputs (vision data, etc.)
|
| 484 |
+
optional_vision_fields: List of optional vision-related fields to include if present in forward_kwargs
|
| 485 |
+
old_per_token_logps: Optional tensor of old per-token log probabilities
|
| 486 |
+
ref_per_token_logps: Optional tensor of reference per-token log probabilities
|
| 487 |
+
importance_sampling_ratio: Optional importance sampling correction ratio
|
| 488 |
+
"""
|
| 489 |
+
# Prepare buffered outputs for groups with variance
|
| 490 |
+
buffered_outputs = []
|
| 491 |
+
for _, group_idx in enumerate(groups_with_variance.nonzero(as_tuple=True)[0].unique().tolist()):
|
| 492 |
+
group_prompt_ids, group_prompt_mask = self.slice_group_data(prompt_ids, prompt_mask, group_idx)
|
| 493 |
+
group_completion_ids, group_completion_mask = self.slice_group_data(
|
| 494 |
+
completion_ids, completion_mask, group_idx
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
# Store unpadded data in the buffer
|
| 498 |
+
buffered_output = {
|
| 499 |
+
"prompt_ids": group_prompt_ids,
|
| 500 |
+
"completion_ids": group_completion_ids,
|
| 501 |
+
"advantages": group_advantages[group_idx].tolist(),
|
| 502 |
+
"prompt_mask": group_prompt_mask,
|
| 503 |
+
"completion_mask": group_completion_mask,
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
+
# Add optional fields if they exist
|
| 507 |
+
optional_fields = {
|
| 508 |
+
"old_per_token_logps": old_per_token_logps if old_per_token_logps is not None else None,
|
| 509 |
+
"ref_per_token_logps": ref_per_token_logps if ref_per_token_logps is not None else None,
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
for field_name, field_data in optional_fields.items():
|
| 513 |
+
if field_data is not None:
|
| 514 |
+
buffered_output[field_name] = self.slice_group_data(field_data, completion_mask, group_idx)[0]
|
| 515 |
+
|
| 516 |
+
# Add importance sampling if needed
|
| 517 |
+
if self.use_vllm and self.vllm_importance_sampling_correction:
|
| 518 |
+
buffered_output["importance_sampling_ratio"] = importance_sampling_ratio
|
| 519 |
+
|
| 520 |
+
if optional_vision_fields:
|
| 521 |
+
# Add vision-related fields if they exist
|
| 522 |
+
for field_name in optional_vision_fields:
|
| 523 |
+
if field_name in forward_kwargs:
|
| 524 |
+
buffered_output[field_name] = self.slice_group_data(
|
| 525 |
+
forward_kwargs[field_name], prompt_mask, group_idx
|
| 526 |
+
)[0]
|
| 527 |
+
|
| 528 |
+
buffered_outputs.append(buffered_output)
|
| 529 |
+
|
| 530 |
+
if groups_with_variance.any():
|
| 531 |
+
# Calculate replay buffer scores for groups with variance
|
| 532 |
+
replay_buffer_scores = (group_advantages.abs() * group_std_rewards).sum(dim=-1)[groups_with_variance]
|
| 533 |
+
# Add all groups to replay buffer at once (batch operation)
|
| 534 |
+
self.replay_buffer.add(replay_buffer_scores.tolist(), buffered_outputs)
|
| 535 |
+
|
| 536 |
+
def sample_from_replay_buffer(
|
| 537 |
+
self, num_samples: int, optional_vision_fields: list[str] = None, optional_tensor_fields: list[str] = None
|
| 538 |
+
) -> list[dict]:
|
| 539 |
+
"""
|
| 540 |
+
Sample groups from the replay buffer.
|
| 541 |
+
|
| 542 |
+
Args:
|
| 543 |
+
num_samples: Number of samples to draw from the replay buffer
|
| 544 |
+
optional_vision_fields: List of optional vision-related fields to include if present in sampled data
|
| 545 |
+
optional_tensor_fields: List of optional tensor fields to include if present in sampled data
|
| 546 |
+
Returns:
|
| 547 |
+
List of sampled data dictionaries from the replay buffer
|
| 548 |
+
"""
|
| 549 |
+
sampled = self.replay_buffer.sample(num_samples=num_samples)
|
| 550 |
+
|
| 551 |
+
# Extract and concatenate sampled data
|
| 552 |
+
sampled_data = {
|
| 553 |
+
"prompt_ids": [],
|
| 554 |
+
"prompt_mask": [],
|
| 555 |
+
"completion_ids": [],
|
| 556 |
+
"completion_mask": [],
|
| 557 |
+
"advantages": [],
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
all_optional_fields = (optional_tensor_fields or []) + (optional_vision_fields or [])
|
| 561 |
+
# Initialize containers for optional fields if they exist in sampled data
|
| 562 |
+
for field in all_optional_fields:
|
| 563 |
+
if sampled and field in sampled[0]:
|
| 564 |
+
sampled_data[field] = []
|
| 565 |
+
|
| 566 |
+
# Extract data from each sampled item
|
| 567 |
+
for item in sampled:
|
| 568 |
+
# Handle core fields
|
| 569 |
+
for key in ["prompt_ids", "prompt_mask", "completion_ids", "completion_mask"]:
|
| 570 |
+
sampled_data[key].append(item[key])
|
| 571 |
+
|
| 572 |
+
# Handle advantages (list, not tensor)
|
| 573 |
+
sampled_data["advantages"].append(item["advantages"])
|
| 574 |
+
|
| 575 |
+
# Handle optional fields
|
| 576 |
+
for field in all_optional_fields:
|
| 577 |
+
if field in item:
|
| 578 |
+
sampled_data[field].append(item[field])
|
| 579 |
+
|
| 580 |
+
return sampled_data
|
| 581 |
+
|
| 582 |
+
def update_with_replay_buffer(
|
| 583 |
+
self,
|
| 584 |
+
group_advantages: torch.Tensor,
|
| 585 |
+
group_std_rewards: torch.Tensor,
|
| 586 |
+
prompt_ids: torch.Tensor,
|
| 587 |
+
prompt_mask: torch.Tensor,
|
| 588 |
+
completion_ids: torch.Tensor,
|
| 589 |
+
completion_mask: torch.Tensor,
|
| 590 |
+
forward_kwargs: dict,
|
| 591 |
+
num_items_in_batch: int,
|
| 592 |
+
old_per_token_logps: torch.Tensor | None = None,
|
| 593 |
+
ref_per_token_logps: torch.Tensor | None = None,
|
| 594 |
+
importance_sampling_ratio: float | None = None,
|
| 595 |
+
) -> None:
|
| 596 |
+
"""
|
| 597 |
+
Update current batch data with samples from replay buffer.
|
| 598 |
+
|
| 599 |
+
Groups with reward variance (std > 0) are added to the replay buffer and then replaced with samples from the
|
| 600 |
+
buffer to improve training stability.
|
| 601 |
+
|
| 602 |
+
Args:
|
| 603 |
+
group_advantages: Tensor of shape (num_groups, num_generations) containing advantage values
|
| 604 |
+
group_std_rewards: Tensor of shape (num_groups, num_generations) containing std of rewards per group
|
| 605 |
+
prompt_ids: Tensor containing prompt token IDs
|
| 606 |
+
prompt_mask: Tensor containing prompt attention masks
|
| 607 |
+
completion_ids: Tensor containing completion token IDs
|
| 608 |
+
completion_mask: Tensor containing completion attention masks
|
| 609 |
+
forward_kwargs: Dictionary containing additional prompt inputs (vision data, etc.)
|
| 610 |
+
num_items_in_batch: Number of items in the current batch
|
| 611 |
+
old_per_token_logps: Optional tensor of old per-token log probabilities
|
| 612 |
+
ref_per_token_logps: Optional tensor of reference per-token log probabilities
|
| 613 |
+
importance_sampling_ratio: Optional importance sampling correction ratio
|
| 614 |
+
"""
|
| 615 |
+
if self.replay_buffer.max_size <= 0:
|
| 616 |
+
return
|
| 617 |
+
|
| 618 |
+
# Groups to consider for adding to the replay buffer
|
| 619 |
+
groups_with_variance = group_std_rewards.max(dim=0).values > 0
|
| 620 |
+
# Groups to replace from the replay buffer
|
| 621 |
+
groups_without_variance = ~groups_with_variance
|
| 622 |
+
|
| 623 |
+
# Track which optional fields are present in sampled data
|
| 624 |
+
optional_tensor_fields = ["old_per_token_logps", "ref_per_token_logps"]
|
| 625 |
+
vision_fields = ["pixel_values", "image_grid_thw", "pixel_attention_mask", "image_sizes"]
|
| 626 |
+
|
| 627 |
+
self.update_replay_buffer(
|
| 628 |
+
groups_with_variance,
|
| 629 |
+
group_advantages,
|
| 630 |
+
group_std_rewards,
|
| 631 |
+
prompt_ids,
|
| 632 |
+
prompt_mask,
|
| 633 |
+
completion_ids,
|
| 634 |
+
completion_mask,
|
| 635 |
+
forward_kwargs,
|
| 636 |
+
vision_fields,
|
| 637 |
+
old_per_token_logps,
|
| 638 |
+
ref_per_token_logps,
|
| 639 |
+
importance_sampling_ratio,
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
# Sample from replay buffer to replace groups with variance
|
| 643 |
+
num_groups_to_replace = groups_without_variance.sum().item()
|
| 644 |
+
if not num_groups_to_replace:
|
| 645 |
+
return
|
| 646 |
+
|
| 647 |
+
sampled_data = self.sample_from_replay_buffer(
|
| 648 |
+
num_samples=num_groups_to_replace,
|
| 649 |
+
optional_vision_fields=vision_fields,
|
| 650 |
+
optional_tensor_fields=optional_tensor_fields,
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
# Pad sampled data if they are shorter than the current batch sequences
|
| 654 |
+
# Or pad the current batch if sampled are longer
|
| 655 |
+
current_batch_prompt_seq_len = prompt_ids.size(1)
|
| 656 |
+
current_batch_completion_seq_len = completion_ids.size(1)
|
| 657 |
+
|
| 658 |
+
groups_to_replace_idxs = groups_with_variance.logical_not().nonzero(as_tuple=True)[0].unique().tolist()
|
| 659 |
+
|
| 660 |
+
# Determine target (max) sequence lengths once
|
| 661 |
+
sampled_prompt_lengths = [t.size(1) for t in sampled_data["prompt_ids"]]
|
| 662 |
+
sampled_completion_lengths = [t.size(1) for t in sampled_data["completion_ids"]]
|
| 663 |
+
target_prompt_len = max([current_batch_prompt_seq_len] + sampled_prompt_lengths)
|
| 664 |
+
target_completion_len = max([current_batch_completion_seq_len] + sampled_completion_lengths)
|
| 665 |
+
|
| 666 |
+
# If any sampled prompt is longer, pad the whole batch prompt tensors once (left padding)
|
| 667 |
+
if target_prompt_len > current_batch_prompt_seq_len:
|
| 668 |
+
prompt_ids = pad(
|
| 669 |
+
list(prompt_ids.unbind(0)),
|
| 670 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 671 |
+
pad_to_multiple_of=target_prompt_len,
|
| 672 |
+
padding_side="left",
|
| 673 |
+
)
|
| 674 |
+
prompt_mask = pad(
|
| 675 |
+
list(prompt_mask.unbind(0)), padding_value=0, pad_to_multiple_of=target_prompt_len, padding_side="left"
|
| 676 |
+
)
|
| 677 |
+
# If any sampled completion is longer, pad the whole batch completion tensors once (right padding)
|
| 678 |
+
if target_completion_len > current_batch_completion_seq_len:
|
| 679 |
+
completion_ids = pad(
|
| 680 |
+
list(completion_ids.unbind(0)),
|
| 681 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 682 |
+
pad_to_multiple_of=target_completion_len,
|
| 683 |
+
padding_side="right",
|
| 684 |
+
)
|
| 685 |
+
completion_mask = pad(
|
| 686 |
+
list(completion_mask.unbind(0)),
|
| 687 |
+
padding_value=0,
|
| 688 |
+
pad_to_multiple_of=target_completion_len,
|
| 689 |
+
padding_side="right",
|
| 690 |
+
)
|
| 691 |
+
if old_per_token_logps is not None:
|
| 692 |
+
old_per_token_logps = pad(
|
| 693 |
+
list(old_per_token_logps.unbind(0)),
|
| 694 |
+
padding_value=0.0,
|
| 695 |
+
pad_to_multiple_of=target_completion_len,
|
| 696 |
+
padding_side="right",
|
| 697 |
+
)
|
| 698 |
+
if ref_per_token_logps is not None:
|
| 699 |
+
ref_per_token_logps = pad(
|
| 700 |
+
list(ref_per_token_logps.unbind(0)),
|
| 701 |
+
padding_value=0.0,
|
| 702 |
+
pad_to_multiple_of=target_completion_len,
|
| 703 |
+
padding_side="right",
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
# Replace per-group data, padding only sampled groups that are shorter than the target
|
| 707 |
+
for i, group_idx in enumerate(groups_to_replace_idxs):
|
| 708 |
+
start_idx = group_idx * self.num_generations
|
| 709 |
+
end_idx = (group_idx + 1) * self.num_generations
|
| 710 |
+
idx_range = slice(start_idx, end_idx)
|
| 711 |
+
|
| 712 |
+
# Pad sampled prompt to target length if needed
|
| 713 |
+
if sampled_data["prompt_ids"][i].size(1) < target_prompt_len:
|
| 714 |
+
sampled_data["prompt_ids"][i] = pad(
|
| 715 |
+
sampled_data["prompt_ids"][i],
|
| 716 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 717 |
+
pad_to_multiple_of=target_prompt_len,
|
| 718 |
+
padding_side="left",
|
| 719 |
+
)
|
| 720 |
+
sampled_data["prompt_mask"][i] = pad(
|
| 721 |
+
sampled_data["prompt_mask"][i],
|
| 722 |
+
padding_value=0,
|
| 723 |
+
pad_to_multiple_of=target_prompt_len,
|
| 724 |
+
padding_side="left",
|
| 725 |
+
)
|
| 726 |
+
|
| 727 |
+
# Pad sampled completion to target length if needed
|
| 728 |
+
if sampled_data["completion_ids"][i].size(1) < target_completion_len:
|
| 729 |
+
sampled_data["completion_ids"][i] = pad(
|
| 730 |
+
sampled_data["completion_ids"][i],
|
| 731 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 732 |
+
pad_to_multiple_of=target_completion_len,
|
| 733 |
+
padding_side="right",
|
| 734 |
+
)
|
| 735 |
+
sampled_data["completion_mask"][i] = pad(
|
| 736 |
+
sampled_data["completion_mask"][i],
|
| 737 |
+
padding_value=0,
|
| 738 |
+
pad_to_multiple_of=target_completion_len,
|
| 739 |
+
padding_side="right",
|
| 740 |
+
)
|
| 741 |
+
if "old_per_token_logps" in sampled_data:
|
| 742 |
+
sampled_data["old_per_token_logps"][i] = pad(
|
| 743 |
+
sampled_data["old_per_token_logps"][i],
|
| 744 |
+
padding_value=0.0,
|
| 745 |
+
pad_to_multiple_of=target_completion_len,
|
| 746 |
+
padding_side="right",
|
| 747 |
+
)
|
| 748 |
+
if "ref_per_token_logps" in sampled_data:
|
| 749 |
+
sampled_data["ref_per_token_logps"][i] = pad(
|
| 750 |
+
sampled_data["ref_per_token_logps"][i],
|
| 751 |
+
padding_value=0.0,
|
| 752 |
+
pad_to_multiple_of=target_completion_len,
|
| 753 |
+
padding_side="right",
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
# Assign (replace) group slice
|
| 757 |
+
prompt_ids[idx_range] = sampled_data["prompt_ids"][i]
|
| 758 |
+
prompt_mask[idx_range] = sampled_data["prompt_mask"][i]
|
| 759 |
+
completion_ids[idx_range] = sampled_data["completion_ids"][i]
|
| 760 |
+
completion_mask[idx_range] = sampled_data["completion_mask"][i]
|
| 761 |
+
group_advantages[group_idx] = sampled_data["advantages"][i]
|
| 762 |
+
|
| 763 |
+
if "old_per_token_logps" in sampled_data:
|
| 764 |
+
old_per_token_logps[idx_range] = sampled_data["old_per_token_logps"][i]
|
| 765 |
+
if "ref_per_token_logps" in sampled_data:
|
| 766 |
+
ref_per_token_logps[idx_range] = sampled_data["ref_per_token_logps"][i]
|
| 767 |
+
|
| 768 |
+
for field in vision_fields:
|
| 769 |
+
if field in sampled_data and field in forward_kwargs:
|
| 770 |
+
forward_kwargs[field][idx_range] = sampled_data[field][i]
|
| 771 |
+
|
| 772 |
+
# Prepare final outputs after sampling and replacement
|
| 773 |
+
outputs_after_sampling_buffer = {
|
| 774 |
+
"prompt_ids": prompt_ids,
|
| 775 |
+
"prompt_mask": prompt_mask,
|
| 776 |
+
"completion_ids": completion_ids,
|
| 777 |
+
"completion_mask": completion_mask,
|
| 778 |
+
"advantages": group_advantages,
|
| 779 |
+
}
|
| 780 |
+
|
| 781 |
+
# Replace optional tensor fields if they exist
|
| 782 |
+
for field in optional_tensor_fields:
|
| 783 |
+
if field in sampled_data:
|
| 784 |
+
outputs_after_sampling_buffer[field] = (
|
| 785 |
+
old_per_token_logps if field == "old_per_token_logps" else ref_per_token_logps
|
| 786 |
+
)
|
| 787 |
+
|
| 788 |
+
# Replace vision fields if they exist
|
| 789 |
+
for field in vision_fields:
|
| 790 |
+
if field in sampled_data and field in forward_kwargs:
|
| 791 |
+
outputs_after_sampling_buffer[field] = forward_kwargs[field]
|
| 792 |
+
|
| 793 |
+
outputs_after_sampling_buffer["num_items_in_batch"] = num_items_in_batch
|
| 794 |
+
if self.use_vllm and self.vllm_importance_sampling_correction:
|
| 795 |
+
outputs_after_sampling_buffer["importance_sampling_ratio"] = importance_sampling_ratio
|
| 796 |
+
|
| 797 |
+
return outputs_after_sampling_buffer
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gspo_token/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 .grpo_trainer import GRPOTrainer
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/gspo_token/grpo_trainer.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 torch
|
| 16 |
+
|
| 17 |
+
from ...trainer.grpo_trainer import GRPOTrainer as _GRPOTrainer
|
| 18 |
+
from ...trainer.utils import nanmax, nanmin
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class GRPOTrainer(_GRPOTrainer):
|
| 22 |
+
def _compute_loss(self, model, inputs):
|
| 23 |
+
# Compute the per-token log probabilities for the model
|
| 24 |
+
prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
|
| 25 |
+
completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
|
| 26 |
+
input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
|
| 27 |
+
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
|
| 28 |
+
logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
|
| 29 |
+
|
| 30 |
+
# Compute the per_token_logps and the entropy at each position in the completion
|
| 31 |
+
per_token_logps, entropies, _ = self._get_per_token_logps_and_entropies(
|
| 32 |
+
model,
|
| 33 |
+
input_ids,
|
| 34 |
+
attention_mask,
|
| 35 |
+
logits_to_keep,
|
| 36 |
+
compute_entropy=True,
|
| 37 |
+
pixel_values=inputs.get("pixel_values"),
|
| 38 |
+
image_grid_thw=inputs.get("image_grid_thw"),
|
| 39 |
+
num_images=inputs.get("num_images"),
|
| 40 |
+
pixel_attention_mask=inputs.get("pixel_attention_mask"),
|
| 41 |
+
image_sizes=inputs.get("image_sizes"),
|
| 42 |
+
token_type_ids=inputs.get("token_type_ids"),
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
if self.top_entropy_quantile < 1.0:
|
| 46 |
+
entropy_mask = self.get_high_entropy_mask(entropies, completion_mask, 1 - self.top_entropy_quantile)
|
| 47 |
+
else:
|
| 48 |
+
entropy_mask = None
|
| 49 |
+
|
| 50 |
+
# Compute the KL divergence between the model and the reference model
|
| 51 |
+
if self.beta != 0.0:
|
| 52 |
+
ref_per_token_logps = inputs["ref_per_token_logps"]
|
| 53 |
+
per_token_kl = (
|
| 54 |
+
torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# Compute the loss
|
| 58 |
+
advantages = inputs["advantages"]
|
| 59 |
+
# In the base GRPO implementation, advantages are expected to have shape (B,). To support subclasses that
|
| 60 |
+
# provide advantages with shape (B, T) (e.g., MiniLLM), we *conditionally* unsqueeze the tensor.
|
| 61 |
+
if advantages.dim() == 1:
|
| 62 |
+
advantages = advantages.unsqueeze(1)
|
| 63 |
+
# When num_iterations == 1 and steps_per_generation <= gradient_accumulation_steps,
|
| 64 |
+
# old_per_token_logps == per_token_logps. In this case we can skip its computation
|
| 65 |
+
# (see _generate_and_score_completions) and instead use per_token_logps.detach().
|
| 66 |
+
# The exception is when using vLLM, where we always compute old_per_token_logps
|
| 67 |
+
# for importance sampling
|
| 68 |
+
old_per_token_logps = inputs.get("old_per_token_logps")
|
| 69 |
+
old_per_token_logps = per_token_logps.detach() if old_per_token_logps is None else old_per_token_logps
|
| 70 |
+
|
| 71 |
+
log_ratio = per_token_logps - old_per_token_logps
|
| 72 |
+
if self.importance_sampling_level == "token":
|
| 73 |
+
log_importance_weights = log_ratio
|
| 74 |
+
elif self.importance_sampling_level == "sequence":
|
| 75 |
+
log_importance_weights = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)
|
| 76 |
+
log_importance_weights = log_importance_weights.unsqueeze(-1)
|
| 77 |
+
elif self.importance_sampling_level == "sequence_token":
|
| 78 |
+
# GSPO-token: sg[si(θ)] * πθ(yi,t)/sg[πθ(yi,t)]
|
| 79 |
+
seq_level_log_weight = (log_ratio * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)
|
| 80 |
+
seq_level_log_weight = seq_level_log_weight.detach().unsqueeze(-1) # Stop gradient
|
| 81 |
+
log_importance_weights = per_token_logps - per_token_logps.detach() + seq_level_log_weight
|
| 82 |
+
else:
|
| 83 |
+
raise ValueError(
|
| 84 |
+
f"Unknown importance sampling level: {self.importance_sampling_level}. Possible values are 'token' "
|
| 85 |
+
"and 'sequence'."
|
| 86 |
+
)
|
| 87 |
+
# From here, log_importance_weights (and all subsequent tensors, coef_1, coef_2, etc.) shape depends on
|
| 88 |
+
# importance_sampling_level: "token" level: (B, T); "sequence" level: (B, 1)
|
| 89 |
+
|
| 90 |
+
coef_1 = torch.exp(log_importance_weights)
|
| 91 |
+
coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
|
| 92 |
+
|
| 93 |
+
# Two-sided clipping
|
| 94 |
+
if self.args.delta is not None:
|
| 95 |
+
coef_1 = torch.clamp(coef_1, max=self.args.delta)
|
| 96 |
+
|
| 97 |
+
per_token_loss1 = coef_1 * advantages
|
| 98 |
+
per_token_loss2 = coef_2 * advantages
|
| 99 |
+
per_token_loss = -torch.min(per_token_loss1, per_token_loss2)
|
| 100 |
+
if entropy_mask is not None:
|
| 101 |
+
per_token_loss = per_token_loss * entropy_mask
|
| 102 |
+
|
| 103 |
+
if self.use_vllm and self.vllm_importance_sampling_correction:
|
| 104 |
+
per_token_loss = per_token_loss * inputs["importance_sampling_ratio"]
|
| 105 |
+
|
| 106 |
+
if self.beta != 0.0:
|
| 107 |
+
per_token_loss = per_token_loss + self.beta * per_token_kl
|
| 108 |
+
|
| 109 |
+
mode = "train" if self.model.training else "eval"
|
| 110 |
+
if self.loss_type == "grpo":
|
| 111 |
+
loss = ((per_token_loss * completion_mask).sum(-1) / completion_mask.sum(-1).clamp(min=1.0)).mean()
|
| 112 |
+
normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval
|
| 113 |
+
loss = loss / normalizer
|
| 114 |
+
elif self.loss_type == "bnpo":
|
| 115 |
+
loss = (per_token_loss * completion_mask).sum() / completion_mask.sum().clamp(min=1.0)
|
| 116 |
+
normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval
|
| 117 |
+
loss = loss / normalizer
|
| 118 |
+
elif self.loss_type == "dr_grpo":
|
| 119 |
+
loss = (per_token_loss * completion_mask).sum() / (per_token_loss.size(0) * self.max_completion_length)
|
| 120 |
+
normalizer = self.current_gradient_accumulation_steps if mode == "train" else 1.0 # no accum in eval
|
| 121 |
+
loss = loss / normalizer
|
| 122 |
+
elif self.loss_type == "dapo":
|
| 123 |
+
normalizer = inputs["num_items_in_batch"] / self.accelerator.num_processes
|
| 124 |
+
loss = (per_token_loss * completion_mask).sum() / normalizer
|
| 125 |
+
else:
|
| 126 |
+
raise ValueError(f"Unknown loss type: {self.loss_type}")
|
| 127 |
+
|
| 128 |
+
# Log the metrics
|
| 129 |
+
completion_token_count = completion_mask.sum().clamp(min=1.0)
|
| 130 |
+
|
| 131 |
+
def masked_batch_mean(x):
|
| 132 |
+
if x.shape[1] == 1: # when importance_sampling_level == "sequence"
|
| 133 |
+
return x.mean()
|
| 134 |
+
else:
|
| 135 |
+
return (x * completion_mask).sum() / completion_token_count
|
| 136 |
+
|
| 137 |
+
if self.beta != 0.0:
|
| 138 |
+
mean_kl = masked_batch_mean(per_token_kl)
|
| 139 |
+
self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
|
| 140 |
+
|
| 141 |
+
mean_entropy = masked_batch_mean(entropies)
|
| 142 |
+
self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item())
|
| 143 |
+
|
| 144 |
+
# Compute the clipped probability ratios
|
| 145 |
+
is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages < 0)
|
| 146 |
+
is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages > 0)
|
| 147 |
+
is_region_clipped = is_low_clipped | is_high_clipped
|
| 148 |
+
|
| 149 |
+
low_clip = masked_batch_mean(is_low_clipped.float())
|
| 150 |
+
high_clip = masked_batch_mean(is_high_clipped.float())
|
| 151 |
+
clip_ratio = masked_batch_mean(is_region_clipped.float())
|
| 152 |
+
|
| 153 |
+
gathered_low_clip = self.accelerator.gather(low_clip)
|
| 154 |
+
self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item())
|
| 155 |
+
self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item())
|
| 156 |
+
gathered_high_clip = self.accelerator.gather(high_clip)
|
| 157 |
+
self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item())
|
| 158 |
+
self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item())
|
| 159 |
+
gathered_clip_ratio = self.accelerator.gather(clip_ratio)
|
| 160 |
+
self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item())
|
| 161 |
+
return loss
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/harbor/__init__.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 |
+
"""Harbor × TRL integration (experimental).
|
| 16 |
+
|
| 17 |
+
Train on Harbor agentic task suites with `GRPOTrainer` via `environment_factory`, with a pluggable base agent
|
| 18 |
+
(harness). Requires `harbor` installed in the same interpreter (`pip install trl[harbor]`, Python >= 3.12); `harbor` is
|
| 19 |
+
imported lazily so this module imports without it.
|
| 20 |
+
|
| 21 |
+
```python
|
| 22 |
+
>>> from trl.experimental.harbor import HarborSpec
|
| 23 |
+
|
| 24 |
+
>>> spec = HarborSpec("AdithyaSK/data_agent_rl_environment_train", agent="bash", num_tasks=64)
|
| 25 |
+
```
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
from ._env import AGENTS, HarborBashEnv, HarborEnv
|
| 29 |
+
from ._spec import HarborSpec
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
__all__ = ["AGENTS", "HarborBashEnv", "HarborEnv", "HarborSpec"]
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/harbor/_env.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Harbor-backed environments for `GRPOTrainer(environment_factory=...)`.
|
| 16 |
+
|
| 17 |
+
A `HarborEnv` wraps a Harbor sandbox + verifier. TRL drives the rollout loop: it calls the env's tool methods during
|
| 18 |
+
generation and reads `env.reward` afterwards. The pluggable "base agent" is the harness — the set of tool methods the
|
| 19 |
+
env exposes + how it submits. `HarborBashEnv` is the single-`bash`-tool harness (submit by writing
|
| 20 |
+
`/workdir/answer.txt`); subclass `HarborEnv` to add your own.
|
| 21 |
+
|
| 22 |
+
Harbor's API is async and its sandbox client is bound to the event loop it was created on, so each env owns one loop
|
| 23 |
+
and drives start/exec/verify/stop through it synchronously (TRL's tool loop is sync). `harbor` is imported lazily, so
|
| 24 |
+
importing this module does not require it installed (install `trl[harbor]`, which needs Python >= 3.12).
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
import asyncio
|
| 28 |
+
import tempfile
|
| 29 |
+
import threading
|
| 30 |
+
import uuid
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_NO_REWARD = object() # sentinel: reward not computed yet (0.0 is a valid reward)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class HarborEnv:
|
| 38 |
+
"""Base TRL environment backed by a Harbor sandbox + verifier.
|
| 39 |
+
|
| 40 |
+
Subclasses define the tool methods (the harness). The lifecycle TRL drives per rollout: `reset(task_dir)` (start
|
| 41 |
+
the task's sandbox, return its instruction) -> tool methods (exec into the sandbox) -> `reward` (run the verifier
|
| 42 |
+
once, lazily, after the rollout).
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
environment_type (`str`, *optional*, defaults to `"docker"`):
|
| 46 |
+
Harbor sandbox backend, passed through to Harbor (`"docker"`, `"e2b"`, `"daytona"`, ...).
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
#: Extra guidance appended to the task instruction by the harness subclass.
|
| 50 |
+
PROMPT_SUFFIX: str = ""
|
| 51 |
+
|
| 52 |
+
def __init__(self, environment_type: str = "docker"):
|
| 53 |
+
self._environment_type = environment_type
|
| 54 |
+
# Harbor's async sandbox client is bound to the loop it was created on, so we run that loop on a
|
| 55 |
+
# dedicated daemon thread and submit coroutines to it via `run_coroutine_threadsafe`. This works
|
| 56 |
+
# whether the caller is on a plain thread (GRPOTrainer drives tools from the main thread) or
|
| 57 |
+
# already inside a running event loop (AsyncGRPOTrainer's rollout worker calls tool methods from
|
| 58 |
+
# its own loop, where `loop.run_until_complete` would raise "another loop is already running").
|
| 59 |
+
self._loop = asyncio.new_event_loop()
|
| 60 |
+
self._loop_thread = threading.Thread(target=self._loop.run_forever, daemon=True)
|
| 61 |
+
self._loop_thread.start()
|
| 62 |
+
self._env = None # harbor BaseEnvironment for the current task
|
| 63 |
+
self._task = None
|
| 64 |
+
self._paths = None
|
| 65 |
+
self._reward = _NO_REWARD
|
| 66 |
+
|
| 67 |
+
def _run(self, coro):
|
| 68 |
+
"""Run a coroutine on this env's loop (which lives on its own thread) and block for the result."""
|
| 69 |
+
return asyncio.run_coroutine_threadsafe(coro, self._loop).result()
|
| 70 |
+
|
| 71 |
+
def reset(self, task_dir: str | None = None, **kwargs) -> str:
|
| 72 |
+
if task_dir is None:
|
| 73 |
+
raise ValueError("HarborEnv.reset requires `task_dir` (provided by the dataset row).")
|
| 74 |
+
instruction = self._run(self._start(task_dir))
|
| 75 |
+
self._reward = _NO_REWARD
|
| 76 |
+
return instruction + self.PROMPT_SUFFIX
|
| 77 |
+
|
| 78 |
+
def _exec(self, command: str, timeout: int = 180) -> str:
|
| 79 |
+
"""Run a shell command in the sandbox; return combined stdout+stderr (truncated to 8k)."""
|
| 80 |
+
result = self._run(self._env.exec(command, timeout_sec=timeout))
|
| 81 |
+
out = (result.stdout or "") + (result.stderr or "")
|
| 82 |
+
if len(out) > 8000:
|
| 83 |
+
out = out[:8000] + "\n... [truncated]"
|
| 84 |
+
return out or f"(empty output, rc={result.return_code})"
|
| 85 |
+
|
| 86 |
+
@property
|
| 87 |
+
def reward(self) -> float:
|
| 88 |
+
# Submission = the agent wrote /workdir/answer.txt during the rollout; the verifier reads it.
|
| 89 |
+
# Computed once, lazily, on first read (TRL reads this after the rollout via reward_funcs).
|
| 90 |
+
# A fresh env that was never `reset` (e.g. the trainer probing tool methods via
|
| 91 |
+
# `inspect.getmembers`, which evaluates properties) has no sandbox/task to verify — return 0.0
|
| 92 |
+
# without invoking the verifier, which would start the Harbor backend and import `harbor`.
|
| 93 |
+
if self._env is None:
|
| 94 |
+
return 0.0
|
| 95 |
+
if self._reward is _NO_REWARD:
|
| 96 |
+
self._reward = self._run(self._verify())
|
| 97 |
+
return self._reward
|
| 98 |
+
|
| 99 |
+
# ── harbor lifecycle (async, run on this env's loop) ─────────���──────────
|
| 100 |
+
|
| 101 |
+
async def _start(self, task_dir: str) -> str:
|
| 102 |
+
from harbor.environments.factory import EnvironmentFactory
|
| 103 |
+
from harbor.models.task.task import Task
|
| 104 |
+
from harbor.models.trial.config import EnvironmentConfig as TrialEnvironmentConfig
|
| 105 |
+
from harbor.models.trial.paths import TrialPaths
|
| 106 |
+
|
| 107 |
+
await self._stop() # tear down the previous task's sandbox
|
| 108 |
+
self._task = Task(task_dir=Path(task_dir))
|
| 109 |
+
self._paths = TrialPaths(trial_dir=Path(tempfile.mkdtemp(prefix="harbor_trl_")))
|
| 110 |
+
self._env = EnvironmentFactory.create_environment_from_config(
|
| 111 |
+
config=TrialEnvironmentConfig(type=self._environment_type),
|
| 112 |
+
environment_dir=self._task.paths.environment_dir,
|
| 113 |
+
environment_name=self._task.short_name,
|
| 114 |
+
session_id=uuid.uuid4().hex,
|
| 115 |
+
trial_paths=self._paths,
|
| 116 |
+
task_env_config=self._task.config.environment,
|
| 117 |
+
)
|
| 118 |
+
await self._env.start(force_build=False)
|
| 119 |
+
await self._upload_build_files() # some sandbox builds (e.g. E2B from_dockerfile) drop COPY'd files
|
| 120 |
+
await self._env.run_healthcheck() # task pre-agent hook (e.g. pull data into /home/user/input)
|
| 121 |
+
await self._env.exec("mkdir -p /workdir /home/user/input")
|
| 122 |
+
await self._setup() # harness-specific sandbox prep (e.g. start a Jupyter kernel)
|
| 123 |
+
return self._task.instruction
|
| 124 |
+
|
| 125 |
+
async def _upload_build_files(self) -> None:
|
| 126 |
+
"""Replicate the task Dockerfile's `COPY` directives into the sandbox.
|
| 127 |
+
|
| 128 |
+
E2B's remote `from_dockerfile` build honors `RUN` steps but silently drops files `COPY`'d from the build
|
| 129 |
+
context, which breaks healthchecks that run those files (e.g. a data-pull script). We re-create them at
|
| 130 |
+
runtime: `upload_file` writes as the sandbox `user`, so we stage each file in a user-writable tmp path and `mv`
|
| 131 |
+
it into place as root (destinations like `/opt` are root-owned). Idempotent. Handles the common ``COPY <src>
|
| 132 |
+
<dst>`` form; flags / globs / ``--from`` are skipped.
|
| 133 |
+
"""
|
| 134 |
+
dockerfile = self._task.paths.environment_dir / "Dockerfile"
|
| 135 |
+
if not dockerfile.exists():
|
| 136 |
+
return
|
| 137 |
+
for line in dockerfile.read_text().splitlines():
|
| 138 |
+
s = line.strip()
|
| 139 |
+
if not s.upper().startswith("COPY ") or "--from" in s:
|
| 140 |
+
continue
|
| 141 |
+
parts = [p for p in s[len("COPY ") :].split() if not p.startswith("--")]
|
| 142 |
+
if len(parts) < 2:
|
| 143 |
+
continue
|
| 144 |
+
*srcs, dst = parts
|
| 145 |
+
for src in srcs:
|
| 146 |
+
local = self._task.paths.environment_dir / src
|
| 147 |
+
if not local.is_file():
|
| 148 |
+
continue
|
| 149 |
+
remote = dst if (len(srcs) == 1 and not dst.endswith("/")) else dst.rstrip("/") + "/" + Path(src).name
|
| 150 |
+
parent = remote.rsplit("/", 1)[0] or "/"
|
| 151 |
+
tmp = "/tmp/" + uuid.uuid4().hex
|
| 152 |
+
await self._env.upload_file(local, tmp)
|
| 153 |
+
await self._env.exec(f"mkdir -p {parent} && mv {tmp} {remote}", user="root")
|
| 154 |
+
|
| 155 |
+
async def _setup(self) -> None:
|
| 156 |
+
"""Harness-specific sandbox preparation, run once per `reset` after the sandbox is up.
|
| 157 |
+
|
| 158 |
+
Override to upload helper files (`await self._env.upload_file(...)`) or start servers in the sandbox. The
|
| 159 |
+
default is a no-op (the bash harness needs nothing beyond the base setup).
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
async def _verify(self) -> float:
|
| 163 |
+
from harbor.models.trial.config import VerifierConfig
|
| 164 |
+
from harbor.models.trial.paths import EnvironmentPaths
|
| 165 |
+
from harbor.verifier.factory import VerifierFactory
|
| 166 |
+
|
| 167 |
+
# Pre-create the verifier dir (test.sh redirects stdout there; the shell can't mkdir the parent).
|
| 168 |
+
env_paths = EnvironmentPaths.for_os(self._env.os)
|
| 169 |
+
await self._env.empty_dirs([env_paths.verifier_dir], chmod=True)
|
| 170 |
+
# Carry the task's [verifier].env (e.g. expected-answer / judge-model settings) into the verifier,
|
| 171 |
+
# mirroring Harbor's trial runner (`override_env=`). A default trial `VerifierConfig()` is otherwise
|
| 172 |
+
# correct here — the task verifier has no trial-level import_path/kwargs to forward.
|
| 173 |
+
verifier = VerifierFactory.create_verifier_from_config(
|
| 174 |
+
VerifierConfig(),
|
| 175 |
+
task=self._task,
|
| 176 |
+
trial_paths=self._paths,
|
| 177 |
+
environment=self._env,
|
| 178 |
+
override_env=self._task.config.verifier.env or None,
|
| 179 |
+
)
|
| 180 |
+
result = await verifier.verify()
|
| 181 |
+
rewards = result.rewards or {}
|
| 182 |
+
return float(rewards.get("reward", next(iter(rewards.values()), 0.0)))
|
| 183 |
+
|
| 184 |
+
async def _stop(self) -> None:
|
| 185 |
+
if self._env is not None:
|
| 186 |
+
try:
|
| 187 |
+
await self._env.stop(delete=True)
|
| 188 |
+
finally:
|
| 189 |
+
self._env = None
|
| 190 |
+
|
| 191 |
+
def __del__(self):
|
| 192 |
+
try:
|
| 193 |
+
self._run(self._stop())
|
| 194 |
+
except Exception: # noqa: BLE001 — best-effort teardown
|
| 195 |
+
pass
|
| 196 |
+
finally:
|
| 197 |
+
self._loop.call_soon_threadsafe(self._loop.stop)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
_BASH_PROMPT_SUFFIX = (
|
| 201 |
+
"\n\nYou have a single `bash` tool: run a shell command in the sandbox and get its stdout+stderr. "
|
| 202 |
+
"The dataset files are in /home/user/input/. Python 3 + pandas + numpy + scikit-learn are "
|
| 203 |
+
"preinstalled. **Submit your final answer by writing it to /workdir/answer.txt via the `bash` "
|
| 204 |
+
'tool**, e.g. `echo -n "<value>" > /workdir/answer.txt`. Stating the answer in prose does NOT submit '
|
| 205 |
+
"it; only writing the file counts. Keep the answer short, and do not end your turn without submitting."
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class HarborBashEnv(HarborEnv):
|
| 210 |
+
"""Single-`bash`-tool harness; submit by writing `/workdir/answer.txt`."""
|
| 211 |
+
|
| 212 |
+
PROMPT_SUFFIX = _BASH_PROMPT_SUFFIX
|
| 213 |
+
|
| 214 |
+
def bash(self, command: str) -> str:
|
| 215 |
+
"""
|
| 216 |
+
Run a shell command in the sandbox and return its combined stdout+stderr. The shell is non-stateful between
|
| 217 |
+
calls. Use it to explore files (ls, head, cat), run Python (`python3 -c "..."`), and submit the answer (`echo
|
| 218 |
+
-n "<value>" > /workdir/answer.txt`).
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
command: The shell command to run.
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
The command's combined stdout and stderr.
|
| 225 |
+
"""
|
| 226 |
+
return self._exec(command)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
#: Built-in harnesses, selectable by name in `HarborSpec(agent=...)`. Pass a `HarborEnv` subclass (or an
|
| 230 |
+
#: import path / file path resolving to one) for a custom harness.
|
| 231 |
+
AGENTS: dict[str, type[HarborEnv]] = {"bash": HarborBashEnv}
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/harbor/_sp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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 for the Harbor × TRL integration (mirror of ``OpenRewardSpec``).
|
| 16 |
+
|
| 17 |
+
Construct **one** ``HarborSpec`` and read three properties off it — ``.train_dataset``, ``.environment_factory``,
|
| 18 |
+
``.reward_funcs`` — each plugging into the matching ``GRPOTrainer`` kwarg:
|
| 19 |
+
|
| 20 |
+
```python
|
| 21 |
+
>>> from trl import GRPOConfig, GRPOTrainer
|
| 22 |
+
>>> from trl.experimental.harbor import HarborSpec
|
| 23 |
+
|
| 24 |
+
>>> spec = HarborSpec("AdithyaSK/data_agent_rl_environment_train", agent="bash", num_tasks=64)
|
| 25 |
+
|
| 26 |
+
>>> trainer = GRPOTrainer(
|
| 27 |
+
... model="Qwen/Qwen3.5-4B",
|
| 28 |
+
... args=GRPOConfig(num_generations=8, max_steps=50, max_tool_calling_iterations=25),
|
| 29 |
+
... train_dataset=spec.train_dataset,
|
| 30 |
+
... environment_factory=spec.environment_factory,
|
| 31 |
+
... reward_funcs=spec.reward_funcs,
|
| 32 |
+
... )
|
| 33 |
+
>>> trainer.train()
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
A Harbor *task* is a directory (``instruction.md`` + ``task.toml`` + ``environment/`` + ``tests/``); the dataset is a
|
| 37 |
+
tree of them. The ``environment_factory`` env runs Harbor in-process (see ``_env.py``), so ``harbor`` must be installed
|
| 38 |
+
in the same interpreter (``pip install trl[harbor]``, Python >= 3.12). The **base agent** (harness/tool surface) is
|
| 39 |
+
selected by ``agent=`` — ``"bash"`` today, or a custom ``HarborEnv`` subclass.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
from __future__ import annotations
|
| 43 |
+
|
| 44 |
+
import os
|
| 45 |
+
from collections.abc import Callable
|
| 46 |
+
from functools import cached_property, partial
|
| 47 |
+
from pathlib import Path
|
| 48 |
+
from typing import Any
|
| 49 |
+
|
| 50 |
+
from ._env import AGENTS, HarborEnv
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _outcome_reward_func(environments=None, environment_reward=None, **_) -> list[float]:
|
| 54 |
+
"""Default reward: the Harbor verifier's scalar per rollout.
|
| 55 |
+
|
| 56 |
+
`GRPOTrainer` passes the live env instances as `environments=` (read `env.reward`); `AsyncGRPOTrainer` runs envs in
|
| 57 |
+
its rollout worker and passes the already-captured per-rollout rewards as `environment_reward=`. Support both so
|
| 58 |
+
the same spec plugs into either trainer.
|
| 59 |
+
"""
|
| 60 |
+
if environment_reward is not None:
|
| 61 |
+
return [float(r) for r in environment_reward]
|
| 62 |
+
return [float(env.reward) for env in environments]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _resolve_agent(agent: str | type[HarborEnv]) -> type[HarborEnv]:
|
| 66 |
+
"""Resolve the `agent=` selector to a `HarborEnv` subclass.
|
| 67 |
+
|
| 68 |
+
Accepts a `HarborEnv` subclass, a built-in name (`"bash"`), a module import path (`"pkg.module:Class"`), or a file
|
| 69 |
+
path (`"path/to/file.py:Class"`).
|
| 70 |
+
"""
|
| 71 |
+
if isinstance(agent, type):
|
| 72 |
+
cls = agent
|
| 73 |
+
elif agent in AGENTS:
|
| 74 |
+
cls = AGENTS[agent]
|
| 75 |
+
elif ":" in agent:
|
| 76 |
+
import importlib
|
| 77 |
+
import importlib.util
|
| 78 |
+
|
| 79 |
+
target, _, cls_name = agent.rpartition(":") # rpartition: don't split a Windows drive (``D:\...``)
|
| 80 |
+
if target.endswith(".py") or os.path.sep in target: # file path -> load module from file
|
| 81 |
+
spec = importlib.util.spec_from_file_location(Path(target).stem, target)
|
| 82 |
+
module = importlib.util.module_from_spec(spec)
|
| 83 |
+
spec.loader.exec_module(module)
|
| 84 |
+
else: # dotted module path on sys.path
|
| 85 |
+
module = importlib.import_module(target)
|
| 86 |
+
cls = getattr(module, cls_name)
|
| 87 |
+
else:
|
| 88 |
+
raise ValueError(
|
| 89 |
+
f"Unknown agent {agent!r}; use a built-in name ({sorted(AGENTS)}), an import path "
|
| 90 |
+
"'pkg.module:Class', a file path 'path/to/file.py:Class', or a HarborEnv subclass."
|
| 91 |
+
)
|
| 92 |
+
if not (isinstance(cls, type) and issubclass(cls, HarborEnv)):
|
| 93 |
+
raise TypeError(f"agent {agent!r} must resolve to a HarborEnv subclass, got {cls!r}")
|
| 94 |
+
return cls
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _read_task_meta(task_dir: Path) -> dict[str, Any]:
|
| 98 |
+
"""Pull a few useful fields out of ``task.toml`` for the dataset rows / reward funcs."""
|
| 99 |
+
try:
|
| 100 |
+
import tomllib # stdlib on Python 3.11+; lazy so the module imports on 3.10 (e.g. doc build)
|
| 101 |
+
|
| 102 |
+
cfg = tomllib.loads((task_dir / "task.toml").read_text())
|
| 103 |
+
except Exception: # noqa: BLE001
|
| 104 |
+
return {}
|
| 105 |
+
meta = cfg.get("metadata", {})
|
| 106 |
+
return {
|
| 107 |
+
"gold_answer": meta.get("gold_answer"),
|
| 108 |
+
"reward_mode": meta.get("reward_mode_initial"),
|
| 109 |
+
"difficulty_level": meta.get("difficulty_level"),
|
| 110 |
+
"kaggle_dataset": meta.get("kaggle_dataset_name"),
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class HarborSpec:
|
| 115 |
+
"""Single spec object that wires a Harbor task suite into a TRL trainer.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
dataset (`str`):
|
| 119 |
+
A Hugging Face dataset repo id holding a Harbor task tree (e.g.
|
| 120 |
+
`"AdithyaSK/data_agent_rl_environment_train"`), or a local path to a directory containing a `tasks/`
|
| 121 |
+
subtree. Each task is a dir with `instruction.md` / `task.toml` / `environment/` / `tests/`.
|
| 122 |
+
agent (`str` or `type`, *optional*, defaults to `"bash"`):
|
| 123 |
+
The base agent / harness — i.e. the tool surface the env exposes. One of: a built-in name (`"bash"`), an
|
| 124 |
+
import path `"package.module:ClassName"`, a file path `"path/to/file.py:ClassName"`, or a
|
| 125 |
+
[`~trl.experimental.harbor.HarborEnv`] subclass directly.
|
| 126 |
+
environment_type (`str`, *optional*, defaults to `"docker"`):
|
| 127 |
+
Harbor sandbox backend, passed through to Harbor (whatever it supports — `"docker"`, `"e2b"`, `"daytona"`,
|
| 128 |
+
`"gke"`, `"modal"`, `"runloop"`, ...). Not validated here; Harbor validates. `"docker"` is Harbor's own
|
| 129 |
+
default; pick `"e2b"` to offload sandboxing to the cloud.
|
| 130 |
+
num_tasks (`int`, *optional*):
|
| 131 |
+
Cap on the number of tasks pulled into the dataset. `None` uses every task in the tree.
|
| 132 |
+
indices (`list[int]`, *optional*):
|
| 133 |
+
Specific task indices (into the sorted task list). Mutually exclusive with `num_tasks`.
|
| 134 |
+
include_metadata (`bool`, *optional*, defaults to `True`):
|
| 135 |
+
Fold per-task `task.toml` metadata (gold_answer, difficulty, ...) into the dataset rows.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
def __init__(
|
| 139 |
+
self,
|
| 140 |
+
dataset: str,
|
| 141 |
+
*,
|
| 142 |
+
agent: str | type[HarborEnv] = "bash",
|
| 143 |
+
environment_type: str = "docker",
|
| 144 |
+
num_tasks: int | None = None,
|
| 145 |
+
indices: list[int] | None = None,
|
| 146 |
+
include_metadata: bool = True,
|
| 147 |
+
) -> None:
|
| 148 |
+
if num_tasks is not None and indices is not None:
|
| 149 |
+
raise ValueError("Provide num_tasks or indices, not both.")
|
| 150 |
+
self._dataset = dataset
|
| 151 |
+
self._environment_type = environment_type
|
| 152 |
+
self._num_tasks = num_tasks
|
| 153 |
+
self._indices = indices
|
| 154 |
+
self._include_metadata = include_metadata
|
| 155 |
+
self._env_cls = _resolve_agent(agent)
|
| 156 |
+
|
| 157 |
+
# ── public surface ──────────────────────────────────────────────
|
| 158 |
+
|
| 159 |
+
@cached_property
|
| 160 |
+
def _task_dirs(self) -> list[Path]:
|
| 161 |
+
"""Resolve the dataset to a sorted list of local task directories (downloading if needed)."""
|
| 162 |
+
local = Path(self._dataset)
|
| 163 |
+
if (local / "tasks").is_dir():
|
| 164 |
+
root = local / "tasks"
|
| 165 |
+
elif local.is_dir() and any(local.glob("*/task.toml")):
|
| 166 |
+
root = local
|
| 167 |
+
else:
|
| 168 |
+
# Treat as an HF dataset repo id; download the task tree.
|
| 169 |
+
from huggingface_hub import snapshot_download
|
| 170 |
+
|
| 171 |
+
path = Path(snapshot_download(self._dataset, repo_type="dataset", allow_patterns=["tasks/**"]))
|
| 172 |
+
root = path / "tasks"
|
| 173 |
+
dirs = sorted(p.parent for p in root.glob("*/task.toml"))
|
| 174 |
+
if self._indices is not None:
|
| 175 |
+
dirs = [dirs[i] for i in self._indices]
|
| 176 |
+
elif self._num_tasks is not None:
|
| 177 |
+
dirs = dirs[: self._num_tasks]
|
| 178 |
+
if not dirs:
|
| 179 |
+
raise ValueError(f"No tasks (dir with task.toml) found under {root}")
|
| 180 |
+
return dirs
|
| 181 |
+
|
| 182 |
+
@cached_property
|
| 183 |
+
def train_dataset(self):
|
| 184 |
+
"""A `datasets.Dataset` of tasks. Plugs into TRL's `train_dataset=`.
|
| 185 |
+
|
| 186 |
+
Columns: `prompt` (empty user message — TRL appends the env's instruction from `reset`), `task_dir` (passed to
|
| 187 |
+
`reset`), `task_index`, and per-task metadata when `include_metadata`.
|
| 188 |
+
"""
|
| 189 |
+
from datasets import Dataset
|
| 190 |
+
|
| 191 |
+
dirs = self._task_dirs
|
| 192 |
+
rows: dict[str, list[Any]] = {
|
| 193 |
+
"prompt": [[{"role": "user", "content": ""}] for _ in dirs],
|
| 194 |
+
"task_dir": [str(d) for d in dirs],
|
| 195 |
+
# task_index is the position in the sorted suite, so it matches the `indices` selector.
|
| 196 |
+
"task_index": list(self._indices) if self._indices is not None else list(range(len(dirs))),
|
| 197 |
+
}
|
| 198 |
+
if self._include_metadata:
|
| 199 |
+
metas = [_read_task_meta(d) for d in dirs]
|
| 200 |
+
for key in ("gold_answer", "reward_mode", "difficulty_level", "kaggle_dataset"):
|
| 201 |
+
rows[key] = [m.get(key) for m in metas]
|
| 202 |
+
return Dataset.from_dict(rows)
|
| 203 |
+
|
| 204 |
+
@cached_property
|
| 205 |
+
def environment_factory(self) -> Callable[[], HarborEnv]:
|
| 206 |
+
"""Zero-arg callable returning a fresh harness env. Plugs into TRL's `environment_factory=`.
|
| 207 |
+
|
| 208 |
+
Returns a `functools.partial` (not a closure) so it stays picklable — `AsyncGRPOTrainer` runs its rollout
|
| 209 |
+
worker in a separate process and pickles the factory to it (closures/lambdas would fail).
|
| 210 |
+
"""
|
| 211 |
+
return partial(self._env_cls, environment_type=self._environment_type)
|
| 212 |
+
|
| 213 |
+
@property
|
| 214 |
+
def reward_funcs(self) -> Callable[..., list[float]]:
|
| 215 |
+
"""Default outcome reward (Harbor verifier scalar). Plugs into TRL's `reward_funcs=`."""
|
| 216 |
+
return _outcome_reward_func
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/kto/__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 .kto_config import KTOConfig
|
| 16 |
+
from .kto_trainer import KTOTrainer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = ["KTOConfig", "KTOTrainer"]
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/kto/kto_config.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 KTOConfig(_BaseConfig):
|
| 23 |
+
# docstyle-ignore
|
| 24 |
+
r"""
|
| 25 |
+
Configuration class for the [`experimental.kto.KTOTrainer`].
|
| 26 |
+
|
| 27 |
+
This class includes only the parameters that are specific to KTO 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 [`KTOTrainer`] 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 and reference 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.
|
| 54 |
+
If `None`, no truncation is applied.
|
| 55 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 56 |
+
If set, the sequences will be padded to a multiple of this value.
|
| 57 |
+
precompute_ref_log_probs (`bool`, *optional*, defaults to `False`):
|
| 58 |
+
Whether to precompute the reference model log probabilities for the entire training dataset before
|
| 59 |
+
training. This allows to save memory during training, as the reference model does not need to be kept in
|
| 60 |
+
memory.
|
| 61 |
+
precompute_ref_batch_size (`int`, *optional*):
|
| 62 |
+
Batch size to use when precomputing reference model log probabilities. This can be set higher than the
|
| 63 |
+
training batch size to speed up preprocessing. If `None`, defaults to `per_device_train_batch_size` for
|
| 64 |
+
training and `per_device_eval_batch_size` for evaluation.
|
| 65 |
+
|
| 66 |
+
> Parameters that control the training
|
| 67 |
+
|
| 68 |
+
loss_type (`str`, *optional*, defaults to `"kto"`):
|
| 69 |
+
Type of loss to use. Possible values are:
|
| 70 |
+
|
| 71 |
+
- `"kto"`: KTO loss from the [KTO](https://huggingface.co/papers/2402.01306) paper.
|
| 72 |
+
- `"apo_zero_unpaired"`: Unpaired variant of APO-zero loss from the
|
| 73 |
+
[APO](https://huggingface.co/papers/2408.06266) paper.
|
| 74 |
+
|
| 75 |
+
beta (`float`, *optional*, defaults to `0.1`):
|
| 76 |
+
Parameter controlling the deviation from the reference model. Higher β means less deviation from the
|
| 77 |
+
reference model.
|
| 78 |
+
desirable_weight (`float`, *optional*, defaults to `1.0`):
|
| 79 |
+
Desirable losses are weighed by this factor to counter unequal number of desirable and undesirable pairs.
|
| 80 |
+
undesirable_weight (`float`, *optional*, defaults to `1.0`):
|
| 81 |
+
Undesirable losses are weighed by this factor to counter unequal number of desirable and undesirable pairs.
|
| 82 |
+
activation_offloading (`bool`, *optional*, defaults to `False`):
|
| 83 |
+
Whether to offload the activations to the CPU.
|
| 84 |
+
sync_ref_model (`bool`, *optional*, defaults to `False`):
|
| 85 |
+
Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using
|
| 86 |
+
the `ref_model_mixup_alpha` parameter. This synchronization originates from the
|
| 87 |
+
[TR-DPO](https://huggingface.co/papers/2404.09656) paper. `sync_ref_model=True` is not yet compatible with
|
| 88 |
+
PEFT or `precompute_ref_log_probs=True`.
|
| 89 |
+
ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`):
|
| 90 |
+
α parameter from the TR-DPO paper, which controls the mix between the current policy and the previous
|
| 91 |
+
reference policy during updates. The reference policy is updated according to the equation: `π_ref = α *
|
| 92 |
+
π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`.
|
| 93 |
+
ref_model_sync_steps (`int`, *optional*, defaults to `512`):
|
| 94 |
+
τ parameter from the TR-DPO paper, which determines how frequently the current policy is synchronized with
|
| 95 |
+
the reference policy. To use this parameter, you must set `sync_ref_model=True`.
|
| 96 |
+
> [!NOTE]
|
| 97 |
+
> These parameters have default values different from [`~transformers.TrainingArguments`]:
|
| 98 |
+
> - `logging_steps`: Defaults to `10` instead of `500`.
|
| 99 |
+
> - `gradient_checkpointing`: Defaults to `True` instead of `False`.
|
| 100 |
+
> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
|
| 101 |
+
> - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.
|
| 102 |
+
> - `train_sampling_strategy`: Defaults to `"sequential"` instead of `"random"`. Loss types
|
| 103 |
+
> that estimate the KL divergence term (all except `"apo_zero_unpaired"`) require sequential
|
| 104 |
+
> sampling because the KL completion for each example is precomputed against its neighbors in
|
| 105 |
+
> a fixed-order batch; any other strategy breaks that pairing.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
_VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
|
| 109 |
+
|
| 110 |
+
# Parameters whose default values are overridden from TrainingArguments
|
| 111 |
+
learning_rate: float = field(
|
| 112 |
+
default=1e-6,
|
| 113 |
+
metadata={"help": "The initial learning rate for AdamW."},
|
| 114 |
+
)
|
| 115 |
+
train_sampling_strategy: str = field(
|
| 116 |
+
default="sequential",
|
| 117 |
+
metadata={
|
| 118 |
+
"help": "Sampler to use for the training dataloader. Loss types that estimate the KL divergence term "
|
| 119 |
+
"(all except `'apo_zero_unpaired'`) require `'sequential'` because the KL completion for each example is "
|
| 120 |
+
"precomputed against its neighbors in a fixed-order batch; any other strategy breaks that pairing. "
|
| 121 |
+
"Possible values are `'random'`, `'sequential'`, and `'group_by_length'`.",
|
| 122 |
+
"choices": ["random", "sequential", "group_by_length"],
|
| 123 |
+
},
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# Parameters that control the model
|
| 127 |
+
model_init_kwargs: dict[str, Any] | str | None = field(
|
| 128 |
+
default=None,
|
| 129 |
+
metadata={
|
| 130 |
+
"help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of "
|
| 131 |
+
"the `KTOTrainer` is provided as a string."
|
| 132 |
+
},
|
| 133 |
+
)
|
| 134 |
+
trust_remote_code: bool = field(
|
| 135 |
+
default=False,
|
| 136 |
+
metadata={
|
| 137 |
+
"help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
|
| 138 |
+
"Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`."
|
| 139 |
+
},
|
| 140 |
+
)
|
| 141 |
+
disable_dropout: bool = field(
|
| 142 |
+
default=True,
|
| 143 |
+
metadata={"help": "Whether to disable dropout in the model and reference model."},
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
# Parameters that control the data preprocessing
|
| 147 |
+
dataset_num_proc: int | None = field(
|
| 148 |
+
default=None,
|
| 149 |
+
metadata={"help": "Number of processes to use for processing the dataset."},
|
| 150 |
+
)
|
| 151 |
+
max_length: int | None = field(
|
| 152 |
+
default=1024,
|
| 153 |
+
metadata={
|
| 154 |
+
"help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from "
|
| 155 |
+
"the left. If `None`, no truncation is applied."
|
| 156 |
+
},
|
| 157 |
+
)
|
| 158 |
+
pad_to_multiple_of: int | None = field(
|
| 159 |
+
default=None,
|
| 160 |
+
metadata={"help": "If set, the sequences will be padded to a multiple of this value."},
|
| 161 |
+
)
|
| 162 |
+
precompute_ref_log_probs: bool = field(
|
| 163 |
+
default=False,
|
| 164 |
+
metadata={
|
| 165 |
+
"help": "Whether to precompute the reference model log probabilities for the entire training dataset "
|
| 166 |
+
"before training. This allows to save memory during training, as the reference model does not need to be "
|
| 167 |
+
"kept in memory."
|
| 168 |
+
},
|
| 169 |
+
)
|
| 170 |
+
precompute_ref_batch_size: int | None = field(
|
| 171 |
+
default=None,
|
| 172 |
+
metadata={
|
| 173 |
+
"help": "Batch size to use when precomputing reference model log probabilities. This can be set higher "
|
| 174 |
+
"than the training batch size to speed up preprocessing. If `None`, defaults to "
|
| 175 |
+
"`per_device_train_batch_size` for training and `per_device_eval_batch_size` for evaluation."
|
| 176 |
+
},
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# Parameters that control the training
|
| 180 |
+
loss_type: str = field(
|
| 181 |
+
default="kto",
|
| 182 |
+
metadata={
|
| 183 |
+
"help": "Type of loss to use.",
|
| 184 |
+
"choices": ["kto", "apo_zero_unpaired"],
|
| 185 |
+
},
|
| 186 |
+
)
|
| 187 |
+
beta: float = field(
|
| 188 |
+
default=0.1,
|
| 189 |
+
metadata={
|
| 190 |
+
"help": "Parameter controlling the deviation from the reference model. Higher β means less deviation from "
|
| 191 |
+
"the reference model."
|
| 192 |
+
},
|
| 193 |
+
)
|
| 194 |
+
desirable_weight: float = field(
|
| 195 |
+
default=1.0,
|
| 196 |
+
metadata={
|
| 197 |
+
"help": "Desirable losses are weighed by this factor to counter unequal number of desirable and "
|
| 198 |
+
"undesirable pairs.",
|
| 199 |
+
},
|
| 200 |
+
)
|
| 201 |
+
undesirable_weight: float = field(
|
| 202 |
+
default=1.0,
|
| 203 |
+
metadata={
|
| 204 |
+
"help": "Undesirable losses are weighed by this factor to counter unequal number of desirable and "
|
| 205 |
+
"undesirable pairs.",
|
| 206 |
+
},
|
| 207 |
+
)
|
| 208 |
+
activation_offloading: bool = field(
|
| 209 |
+
default=False,
|
| 210 |
+
metadata={"help": "Whether to offload the activations to the CPU."},
|
| 211 |
+
)
|
| 212 |
+
sync_ref_model: bool = field(
|
| 213 |
+
default=False,
|
| 214 |
+
metadata={
|
| 215 |
+
"help": "Whether to synchronize the reference model with the active model every `ref_model_sync_steps` "
|
| 216 |
+
"steps, using the `ref_model_mixup_alpha` parameter. This synchronization originates from the "
|
| 217 |
+
"[TR-DPO](https://huggingface.co/papers/2404.09656) paper. `sync_ref_model=True` is not yet compatible "
|
| 218 |
+
"with PEFT or `precompute_ref_log_probs=True`."
|
| 219 |
+
},
|
| 220 |
+
)
|
| 221 |
+
ref_model_mixup_alpha: float = field(
|
| 222 |
+
default=0.6,
|
| 223 |
+
metadata={
|
| 224 |
+
"help": "α parameter from the TR-DPO paper, which controls the mix between the current policy and the "
|
| 225 |
+
"previous reference policy during updates. The reference policy is updated according to the equation: "
|
| 226 |
+
"`π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`."
|
| 227 |
+
},
|
| 228 |
+
)
|
| 229 |
+
ref_model_sync_steps: int = field(
|
| 230 |
+
default=512,
|
| 231 |
+
metadata={
|
| 232 |
+
"help": "τ parameter from the TR-DPO paper, which determines how frequently the current policy is "
|
| 233 |
+
"synchronized with the reference policy. To use this parameter, you must set `sync_ref_model=True`."
|
| 234 |
+
},
|
| 235 |
+
)
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/kto/kto_trainer.py
ADDED
|
@@ -0,0 +1,1559 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 contextlib
|
| 16 |
+
import os
|
| 17 |
+
import textwrap
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
from collections.abc import Callable
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import transformers
|
| 26 |
+
from accelerate import PartialState
|
| 27 |
+
from accelerate.logging import get_logger
|
| 28 |
+
from accelerate.utils import is_peft_model, tqdm
|
| 29 |
+
from datasets import Dataset, IterableDataset, IterableDatasetDict, concatenate_datasets
|
| 30 |
+
from datasets.fingerprint import Hasher
|
| 31 |
+
from packaging.version import Version
|
| 32 |
+
from torch.nn import functional as F
|
| 33 |
+
from torch.utils.data import DataLoader, Sampler, SequentialSampler
|
| 34 |
+
from transformers import (
|
| 35 |
+
AutoProcessor,
|
| 36 |
+
DataCollator,
|
| 37 |
+
PreTrainedModel,
|
| 38 |
+
PreTrainedTokenizerBase,
|
| 39 |
+
ProcessorMixin,
|
| 40 |
+
TrainerCallback,
|
| 41 |
+
)
|
| 42 |
+
from transformers.data.data_collator import DataCollatorMixin
|
| 43 |
+
from transformers.trainer_utils import EvalLoopOutput, has_length
|
| 44 |
+
from transformers.utils import is_peft_available
|
| 45 |
+
|
| 46 |
+
from ...data_utils import (
|
| 47 |
+
apply_chat_template,
|
| 48 |
+
extract_prompt,
|
| 49 |
+
is_conversational,
|
| 50 |
+
prepare_multimodal_messages,
|
| 51 |
+
unpair_preference_dataset,
|
| 52 |
+
)
|
| 53 |
+
from ...import_utils import is_liger_kernel_available
|
| 54 |
+
from ...models import get_act_offloading_ctx_manager
|
| 55 |
+
from ...models.utils import disable_gradient_checkpointing, prepare_deepspeed, prepare_fsdp
|
| 56 |
+
from ...trainer.base_trainer import _BaseTrainer
|
| 57 |
+
from ...trainer.callbacks import SyncRefModelCallback
|
| 58 |
+
from ...trainer.utils import (
|
| 59 |
+
create_model_from_path,
|
| 60 |
+
disable_dropout_in_model,
|
| 61 |
+
flush_left,
|
| 62 |
+
get_config_model_id,
|
| 63 |
+
hash_module,
|
| 64 |
+
pad,
|
| 65 |
+
selective_log_softmax,
|
| 66 |
+
use_adapter,
|
| 67 |
+
)
|
| 68 |
+
from .kto_config import KTOConfig
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if is_liger_kernel_available():
|
| 72 |
+
from liger_kernel.chunked_loss import LigerFusedLinearKTOLoss
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if is_peft_available():
|
| 76 |
+
import peft
|
| 77 |
+
from peft import LoraConfig, PeftConfig, PeftModel, get_peft_model
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
logger = get_logger(__name__)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]:
|
| 84 |
+
return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@dataclass
|
| 88 |
+
class DataCollatorForUnpairedPreference(DataCollatorMixin):
|
| 89 |
+
"""
|
| 90 |
+
Data collator for unpaired preference data. Assembles completions from raw token IDs and pads sequences to the
|
| 91 |
+
maximum length of the batch.
|
| 92 |
+
|
| 93 |
+
Each example is expected to contain `"prompt_ids"` and `"completion_ids"` keys (and optionally a
|
| 94 |
+
`"KL_completion_ids"` key). The collator returns a dictionary containing:
|
| 95 |
+
- `"input_ids"`: prompt + completion token IDs, padded to the batch maximum length.
|
| 96 |
+
- `"attention_mask"`: attention mask, padded with 0s.
|
| 97 |
+
- `"completion_mask"`: binary mask where 1 marks completion tokens and 0 marks prompt or padding tokens.
|
| 98 |
+
|
| 99 |
+
When `"KL_completion_ids"` is present, the same three tensors are returned for the (mismatched) KL sequence under
|
| 100 |
+
the `"KL_input_ids"`, `"KL_attention_mask"` and `"KL_completion_mask"` keys.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
pad_token_id (`int`):
|
| 104 |
+
Token ID to use for padding `input_ids` sequences.
|
| 105 |
+
max_length (`int`, *optional*):
|
| 106 |
+
Maximum sequence length after assembly. Sequences longer than `max_length` are truncated from the end.
|
| 107 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 108 |
+
If set, the sequences will be padded to a multiple of this value.
|
| 109 |
+
return_tensors (`str`, *optional*, defaults to `"pt"`):
|
| 110 |
+
The tensor type to return. Currently, only `"pt"` (PyTorch tensors) is supported.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
pad_token_id: int
|
| 114 |
+
max_length: int | None = None
|
| 115 |
+
pad_to_multiple_of: int | None = None
|
| 116 |
+
return_tensors: str = "pt"
|
| 117 |
+
|
| 118 |
+
def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
|
| 119 |
+
batch = {}
|
| 120 |
+
for prefix, ids_key in [("", "completion_ids"), ("KL_", "KL_completion_ids")]:
|
| 121 |
+
if ids_key not in examples[0]:
|
| 122 |
+
continue
|
| 123 |
+
|
| 124 |
+
full_ids_list = []
|
| 125 |
+
completion_mask_list = []
|
| 126 |
+
for ex in examples:
|
| 127 |
+
prompt_ids = ex["prompt_ids"]
|
| 128 |
+
answer_ids = ex[ids_key]
|
| 129 |
+
full_ids = prompt_ids + answer_ids
|
| 130 |
+
completion_mask = [0] * len(prompt_ids) + [1] * len(answer_ids)
|
| 131 |
+
if self.max_length is not None:
|
| 132 |
+
full_ids = full_ids[: self.max_length]
|
| 133 |
+
completion_mask = completion_mask[: self.max_length]
|
| 134 |
+
full_ids_list.append(full_ids)
|
| 135 |
+
completion_mask_list.append(completion_mask)
|
| 136 |
+
|
| 137 |
+
batch[f"{prefix}input_ids"] = pad(
|
| 138 |
+
[torch.tensor(ids, dtype=torch.int64) for ids in full_ids_list],
|
| 139 |
+
padding_value=self.pad_token_id,
|
| 140 |
+
padding_side="right",
|
| 141 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 142 |
+
)
|
| 143 |
+
batch[f"{prefix}attention_mask"] = pad(
|
| 144 |
+
[torch.ones(len(ids), dtype=torch.int64) for ids in full_ids_list],
|
| 145 |
+
padding_value=0,
|
| 146 |
+
padding_side="right",
|
| 147 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 148 |
+
)
|
| 149 |
+
batch[f"{prefix}completion_mask"] = pad(
|
| 150 |
+
[torch.tensor(m, dtype=torch.int64) for m in completion_mask_list],
|
| 151 |
+
padding_value=0,
|
| 152 |
+
padding_side="right",
|
| 153 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
if "ref_logps" in examples[0]:
|
| 157 |
+
batch["ref_logps"] = torch.tensor([ex["ref_logps"] for ex in examples])
|
| 158 |
+
if "ref_KL_logps" in examples[0]:
|
| 159 |
+
batch["ref_KL_logps"] = torch.tensor([ex["ref_KL_logps"] for ex in examples])
|
| 160 |
+
batch["label"] = [ex["label"] for ex in examples]
|
| 161 |
+
return batch
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@dataclass
|
| 165 |
+
class DataCollatorForVisionUnpairedPreference(DataCollatorMixin):
|
| 166 |
+
"""
|
| 167 |
+
Data collator for vision unpaired preference data. Performs tokenization and image processing on-the-fly.
|
| 168 |
+
|
| 169 |
+
Unlike the text-only [`DataCollatorForUnpairedPreference`], this collator does not expect pre-tokenized inputs.
|
| 170 |
+
Instead, it takes raw examples with `"prompt"`, `"completion"`, and `"images"` (or `"image"`) keys and processes
|
| 171 |
+
them at collation time. When `calculate_kl` is `True`, the collator also produces KL sequences by cycling
|
| 172 |
+
completions within the batch — the same mismatching strategy as the text-only path, but done here rather than as a
|
| 173 |
+
dataset pre-processing step.
|
| 174 |
+
|
| 175 |
+
Each input example should contain at least:
|
| 176 |
+
- A `"prompt"` key with either a plain text string or a list of message dicts.
|
| 177 |
+
- A `"completion"` key with a plain text string or a list of message dicts.
|
| 178 |
+
- An `"images"` key holding a list of images, or an `"image"` key holding a single image.
|
| 179 |
+
- A `"label"` key (`bool`) indicating whether the completion is desirable.
|
| 180 |
+
|
| 181 |
+
The collator outputs:
|
| 182 |
+
- `"input_ids"`, `"attention_mask"`, `"completion_mask"`: full prompt+completion sequence.
|
| 183 |
+
- `"pixel_values"` and any additional processor outputs (e.g., `"image_grid_thw"`).
|
| 184 |
+
- `"label"`: list of booleans.
|
| 185 |
+
- When `calculate_kl=True`: `"KL_input_ids"`, `"KL_attention_mask"`, `"KL_completion_mask"` for the cycled KL
|
| 186 |
+
sequences.
|
| 187 |
+
|
| 188 |
+
Args:
|
| 189 |
+
processor ([`~transformers.ProcessorMixin`]):
|
| 190 |
+
The processor used to tokenize text and process images.
|
| 191 |
+
max_length (`int`, *optional*):
|
| 192 |
+
Maximum sequence length. Sequences longer than `max_length` are truncated.
|
| 193 |
+
calculate_kl (`bool`, *optional*, defaults to `True`):
|
| 194 |
+
Whether to produce KL sequences by cycling completions within the batch.
|
| 195 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 196 |
+
If set, the sequences will be padded to a multiple of this value.
|
| 197 |
+
return_tensors (`str`, *optional*, defaults to `"pt"`):
|
| 198 |
+
The tensor type to return. Only `"pt"` is supported.
|
| 199 |
+
"""
|
| 200 |
+
|
| 201 |
+
processor: ProcessorMixin
|
| 202 |
+
max_length: int | None = None
|
| 203 |
+
calculate_kl: bool = True
|
| 204 |
+
pad_to_multiple_of: int | None = None
|
| 205 |
+
return_tensors: str = "pt"
|
| 206 |
+
|
| 207 |
+
def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
|
| 208 |
+
if self.pad_to_multiple_of is not None:
|
| 209 |
+
raise NotImplementedError(
|
| 210 |
+
"Padding to a multiple of a value is not yet implemented for vision-language modeling and "
|
| 211 |
+
"prompt-completion data."
|
| 212 |
+
)
|
| 213 |
+
if "image" in examples[0]:
|
| 214 |
+
for example in examples:
|
| 215 |
+
example["images"] = [example.pop("image")]
|
| 216 |
+
images = [example["images"] for example in examples]
|
| 217 |
+
# Transformers requires at least one image in the batch, otherwise it throws an error
|
| 218 |
+
if all(img_list == [] for img_list in images):
|
| 219 |
+
images = None
|
| 220 |
+
if is_conversational(examples[0]): # conversational case
|
| 221 |
+
for example in examples:
|
| 222 |
+
example["prompt"] = prepare_multimodal_messages(example["prompt"], images=example["images"])
|
| 223 |
+
example["completion"] = prepare_multimodal_messages(example["completion"])
|
| 224 |
+
examples = [apply_chat_template(example, self.processor) for example in examples]
|
| 225 |
+
|
| 226 |
+
prompts = [example["prompt"] for example in examples]
|
| 227 |
+
completions = [example["completion"] for example in examples]
|
| 228 |
+
|
| 229 |
+
processed_prompts = self.processor(
|
| 230 |
+
images=images,
|
| 231 |
+
text=prompts,
|
| 232 |
+
padding=True,
|
| 233 |
+
padding_side="left",
|
| 234 |
+
return_tensors=self.return_tensors,
|
| 235 |
+
add_special_tokens=False, # to avoid adding the BOS twice, see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens
|
| 236 |
+
)
|
| 237 |
+
processed_completions = self.processor(
|
| 238 |
+
text=completions,
|
| 239 |
+
padding=True,
|
| 240 |
+
padding_side="right",
|
| 241 |
+
return_tensors=self.return_tensors,
|
| 242 |
+
add_special_tokens=False, # to avoid adding the BOS twice, see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# Concatenate prompts and completions
|
| 246 |
+
prompt_ids, prompt_mask = processed_prompts["input_ids"], processed_prompts["attention_mask"]
|
| 247 |
+
completion_ids, completion_mask = processed_completions["input_ids"], processed_completions["attention_mask"]
|
| 248 |
+
input_ids = torch.cat((prompt_ids, completion_ids), dim=1)
|
| 249 |
+
attention_mask = torch.cat((prompt_mask, completion_mask), dim=1)
|
| 250 |
+
completion_mask = torch.cat((torch.zeros_like(prompt_mask), completion_mask), dim=1)
|
| 251 |
+
|
| 252 |
+
has_tti = "token_type_ids" in processed_prompts
|
| 253 |
+
has_mm_tti = "mm_token_type_ids" in processed_prompts
|
| 254 |
+
|
| 255 |
+
if has_tti: # special case for Gemma
|
| 256 |
+
prompt_token_type_ids = processed_prompts["token_type_ids"]
|
| 257 |
+
completion_token_type_ids = processed_completions["token_type_ids"]
|
| 258 |
+
token_type_ids = torch.cat((prompt_token_type_ids, completion_token_type_ids), dim=1)
|
| 259 |
+
if has_mm_tti: # special case for Qwen2.5-VL
|
| 260 |
+
prompt_mm_token_type_ids = processed_prompts["mm_token_type_ids"]
|
| 261 |
+
completion_mm_token_type_ids = processed_completions.get(
|
| 262 |
+
"mm_token_type_ids", torch.zeros_like(completion_ids)
|
| 263 |
+
)
|
| 264 |
+
mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, completion_mm_token_type_ids), dim=1)
|
| 265 |
+
|
| 266 |
+
# Flush left to reduce padding
|
| 267 |
+
if has_tti and has_mm_tti:
|
| 268 |
+
attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids = flush_left(
|
| 269 |
+
attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids
|
| 270 |
+
)
|
| 271 |
+
elif has_tti:
|
| 272 |
+
attention_mask, input_ids, completion_mask, token_type_ids = flush_left(
|
| 273 |
+
attention_mask, input_ids, completion_mask, token_type_ids
|
| 274 |
+
)
|
| 275 |
+
elif has_mm_tti:
|
| 276 |
+
attention_mask, input_ids, completion_mask, mm_token_type_ids = flush_left(
|
| 277 |
+
attention_mask, input_ids, completion_mask, mm_token_type_ids
|
| 278 |
+
)
|
| 279 |
+
else:
|
| 280 |
+
attention_mask, input_ids, completion_mask = flush_left(attention_mask, input_ids, completion_mask)
|
| 281 |
+
|
| 282 |
+
# Truncate if necessary
|
| 283 |
+
if self.max_length is not None:
|
| 284 |
+
input_ids = input_ids[:, : self.max_length]
|
| 285 |
+
attention_mask = attention_mask[:, : self.max_length]
|
| 286 |
+
completion_mask = completion_mask[:, : self.max_length]
|
| 287 |
+
if has_tti:
|
| 288 |
+
token_type_ids = token_type_ids[:, : self.max_length]
|
| 289 |
+
if has_mm_tti:
|
| 290 |
+
mm_token_type_ids = mm_token_type_ids[:, : self.max_length]
|
| 291 |
+
|
| 292 |
+
# Build the output dictionary
|
| 293 |
+
output = processed_prompts # we take processed_prompts because it contains the images
|
| 294 |
+
output["input_ids"] = input_ids
|
| 295 |
+
output["attention_mask"] = attention_mask
|
| 296 |
+
output["completion_mask"] = completion_mask
|
| 297 |
+
if has_tti:
|
| 298 |
+
output["token_type_ids"] = token_type_ids
|
| 299 |
+
if has_mm_tti:
|
| 300 |
+
output["mm_token_type_ids"] = mm_token_type_ids
|
| 301 |
+
|
| 302 |
+
if self.calculate_kl:
|
| 303 |
+
# Cycle completions by +1 within the batch to create mismatched KL pairs — same strategy as
|
| 304 |
+
# get_kl_completion_ids in the text-only path, but done here to keep the VLM dataset fully raw.
|
| 305 |
+
kl_completions = completions[-1:] + completions[:-1]
|
| 306 |
+
processed_kl = self.processor(
|
| 307 |
+
text=kl_completions,
|
| 308 |
+
padding=True,
|
| 309 |
+
padding_side="right",
|
| 310 |
+
return_tensors=self.return_tensors,
|
| 311 |
+
add_special_tokens=False, # to avoid adding the BOS twice, see https://huggingface.co/blog/qgallouedec/gotchas-in-tokenizer-behavior#7-chat-template-and-tokenization-dont-compose-due-to-special-tokens
|
| 312 |
+
)
|
| 313 |
+
kl_ids = processed_kl["input_ids"]
|
| 314 |
+
kl_mask = processed_kl["attention_mask"]
|
| 315 |
+
|
| 316 |
+
kl_input_ids = torch.cat((prompt_ids, kl_ids), dim=1)
|
| 317 |
+
kl_attention_mask = torch.cat((prompt_mask, kl_mask), dim=1)
|
| 318 |
+
kl_completion_mask = torch.cat((torch.zeros_like(prompt_mask), kl_mask), dim=1)
|
| 319 |
+
|
| 320 |
+
# Build KL token-type tensors using the original (pre-flush) prompt tensors
|
| 321 |
+
if has_tti:
|
| 322 |
+
kl_completion_token_type_ids = processed_kl.get("token_type_ids", torch.zeros_like(kl_ids))
|
| 323 |
+
kl_token_type_ids = torch.cat((prompt_token_type_ids, kl_completion_token_type_ids), dim=1)
|
| 324 |
+
if has_mm_tti:
|
| 325 |
+
kl_completion_mm_token_type_ids = processed_kl.get("mm_token_type_ids", torch.zeros_like(kl_ids))
|
| 326 |
+
kl_mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, kl_completion_mm_token_type_ids), dim=1)
|
| 327 |
+
|
| 328 |
+
if has_tti and has_mm_tti:
|
| 329 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids, kl_mm_token_type_ids = (
|
| 330 |
+
flush_left(
|
| 331 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids, kl_mm_token_type_ids
|
| 332 |
+
)
|
| 333 |
+
)
|
| 334 |
+
elif has_tti:
|
| 335 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids = flush_left(
|
| 336 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids
|
| 337 |
+
)
|
| 338 |
+
elif has_mm_tti:
|
| 339 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_mm_token_type_ids = flush_left(
|
| 340 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_mm_token_type_ids
|
| 341 |
+
)
|
| 342 |
+
else:
|
| 343 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask = flush_left(
|
| 344 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
# Truncate if necessary
|
| 348 |
+
if self.max_length is not None:
|
| 349 |
+
kl_input_ids = kl_input_ids[:, : self.max_length]
|
| 350 |
+
kl_attention_mask = kl_attention_mask[:, : self.max_length]
|
| 351 |
+
kl_completion_mask = kl_completion_mask[:, : self.max_length]
|
| 352 |
+
if has_tti:
|
| 353 |
+
kl_token_type_ids = kl_token_type_ids[:, : self.max_length]
|
| 354 |
+
if has_mm_tti:
|
| 355 |
+
kl_mm_token_type_ids = kl_mm_token_type_ids[:, : self.max_length]
|
| 356 |
+
|
| 357 |
+
output["KL_input_ids"] = kl_input_ids
|
| 358 |
+
output["KL_attention_mask"] = kl_attention_mask
|
| 359 |
+
output["KL_completion_mask"] = kl_completion_mask
|
| 360 |
+
if has_tti:
|
| 361 |
+
output["KL_token_type_ids"] = kl_token_type_ids
|
| 362 |
+
if has_mm_tti:
|
| 363 |
+
output["KL_mm_token_type_ids"] = kl_mm_token_type_ids
|
| 364 |
+
|
| 365 |
+
output["label"] = [ex["label"] for ex in examples]
|
| 366 |
+
return output
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class KTOTrainer(_BaseTrainer):
|
| 370 |
+
"""
|
| 371 |
+
Trainer for Kahneman-Tversky Optimization (KTO) method. This algorithm was initially proposed in the paper [KTO:
|
| 372 |
+
Model Alignment as Prospect Theoretic Optimization](https://huggingface.co/papers/2402.01306). This class is a
|
| 373 |
+
wrapper around the [`~transformers.Trainer`] class and inherits all of its attributes and methods.
|
| 374 |
+
|
| 375 |
+
Example:
|
| 376 |
+
|
| 377 |
+
```python
|
| 378 |
+
>>> from trl.experimental.kto import KTOTrainer
|
| 379 |
+
>>> from datasets import load_dataset
|
| 380 |
+
|
| 381 |
+
>>> dataset = load_dataset("trl-lib/kto-mix-14k", split="train")
|
| 382 |
+
|
| 383 |
+
>>> trainer = KTOTrainer(
|
| 384 |
+
... model="Qwen/Qwen2.5-0.5B-Instruct",
|
| 385 |
+
... train_dataset=dataset,
|
| 386 |
+
... )
|
| 387 |
+
>>> trainer.train()
|
| 388 |
+
```
|
| 389 |
+
|
| 390 |
+
Args:
|
| 391 |
+
model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]):
|
| 392 |
+
Model to be trained. Can be either:
|
| 393 |
+
|
| 394 |
+
- A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
|
| 395 |
+
path to a *directory* containing model weights saved using
|
| 396 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
| 397 |
+
using `<ModelArchitecture>.from_pretrained` (where `<ModelArchitecture>` is derived from the model
|
| 398 |
+
config) with the keyword arguments in `args.model_init_kwargs`.
|
| 399 |
+
- A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
|
| 400 |
+
- A [`~peft.PeftModel`] object. Only causal language models are supported.
|
| 401 |
+
ref_model ([`~transformers.PreTrainedModel`], *optional*):
|
| 402 |
+
Reference model used to compute the reference log probabilities.
|
| 403 |
+
|
| 404 |
+
- If provided, this model is used directly as the reference policy.
|
| 405 |
+
- If `None`, the trainer will automatically use the initial policy corresponding to `model`, i.e. the model
|
| 406 |
+
state before KTO training starts.
|
| 407 |
+
args ([`experimental.kto.KTOConfig`], *optional*):
|
| 408 |
+
Configuration for this trainer. If `None`, a default configuration is used.
|
| 409 |
+
data_collator ([`~transformers.DataCollator`], *optional*):
|
| 410 |
+
Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`.
|
| 411 |
+
Will default to [`~experimental.kto.kto_trainer.DataCollatorForUnpairedPreference`] if the model is a
|
| 412 |
+
language model and [`~experimental.kto.kto_trainer.DataCollatorForVisionUnpairedPreference`] if the model
|
| 413 |
+
is a vision-language model. Custom collators must truncate sequences before padding; the trainer does not
|
| 414 |
+
apply post-collation truncation.
|
| 415 |
+
train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
|
| 416 |
+
Dataset to use for training. This trainer supports [unpaired preference](#unpaired-preference) type. The
|
| 417 |
+
format of the samples can be either:
|
| 418 |
+
|
| 419 |
+
- [Standard](dataset_formats#standard): Each sample contains plain text.
|
| 420 |
+
- [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
|
| 421 |
+
and content).
|
| 422 |
+
eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
|
| 423 |
+
Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
|
| 424 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`], *optional*):
|
| 425 |
+
Processing class used to process the data. The padding side must be set to "left". If `None`, the
|
| 426 |
+
processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A
|
| 427 |
+
padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
|
| 428 |
+
`tokenizer.eos_token` will be used as the default.
|
| 429 |
+
compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
|
| 430 |
+
The function that will be used to compute metrics at evaluation. Must take a
|
| 431 |
+
[`~transformers.EvalPrediction`] and return a dictionary string to metric values. When passing
|
| 432 |
+
[`SFTConfig`] with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a boolean
|
| 433 |
+
`compute_result` argument. This will be triggered after the last eval batch to signal that the function
|
| 434 |
+
needs to calculate and return the global summary statistics rather than accumulating the batch-level
|
| 435 |
+
statistics.
|
| 436 |
+
callbacks (list of [`~transformers.TrainerCallback`], *optional*):
|
| 437 |
+
List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
|
| 438 |
+
in [here](https://huggingface.co/docs/transformers/main_classes/callback).
|
| 439 |
+
|
| 440 |
+
If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
|
| 441 |
+
method.
|
| 442 |
+
optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`):
|
| 443 |
+
A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your
|
| 444 |
+
model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`.
|
| 445 |
+
peft_config ([`~peft.PeftConfig`], *optional*):
|
| 446 |
+
PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
|
| 447 |
+
"""
|
| 448 |
+
|
| 449 |
+
_tag_names = ["trl", "kto"]
|
| 450 |
+
_name = "KTO"
|
| 451 |
+
_paper = {
|
| 452 |
+
"title": "KTO: Model Alignment as Prospect Theoretic Optimization",
|
| 453 |
+
"id": "2402.01306",
|
| 454 |
+
# docstyle-ignore
|
| 455 |
+
"citation": textwrap.dedent("""\
|
| 456 |
+
@article{ethayarajh2024kto,
|
| 457 |
+
title = {{KTO: Model Alignment as Prospect Theoretic Optimization}},
|
| 458 |
+
author = {Kawin Ethayarajh and Winnie Xu and Niklas Muennighoff and Dan Jurafsky and Douwe Kiela},
|
| 459 |
+
year = 2024,
|
| 460 |
+
eprint = {arXiv:2402.01306},
|
| 461 |
+
}"""),
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
def __init__(
|
| 465 |
+
self,
|
| 466 |
+
model: "str | PreTrainedModel | PeftModel",
|
| 467 |
+
ref_model: PreTrainedModel | None = None,
|
| 468 |
+
args: KTOConfig | None = None,
|
| 469 |
+
data_collator: DataCollator | None = None,
|
| 470 |
+
train_dataset: Dataset | IterableDataset | None = None,
|
| 471 |
+
eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
|
| 472 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
|
| 473 |
+
compute_metrics: Callable[[EvalLoopOutput], dict] | None = None,
|
| 474 |
+
callbacks: list[TrainerCallback] | None = None,
|
| 475 |
+
optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
|
| 476 |
+
peft_config: "PeftConfig | None" = None,
|
| 477 |
+
):
|
| 478 |
+
# Args
|
| 479 |
+
if args is None:
|
| 480 |
+
model_name = model if isinstance(model, str) else get_config_model_id(model.config)
|
| 481 |
+
model_name = model_name.split("/")[-1]
|
| 482 |
+
args = KTOConfig(f"{model_name}-KTO")
|
| 483 |
+
|
| 484 |
+
if train_dataset is None:
|
| 485 |
+
raise ValueError("`train_dataset` is required")
|
| 486 |
+
elif isinstance(train_dataset, IterableDataset):
|
| 487 |
+
# IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate
|
| 488 |
+
# batches from multiple processes, leading to mismatch errors.
|
| 489 |
+
if args.accelerator_config.dispatch_batches is True:
|
| 490 |
+
logger.warning(
|
| 491 |
+
"You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` "
|
| 492 |
+
"is forced to `False` when using an `IterableDataset`. To remove this warning, unset "
|
| 493 |
+
"`dispatch_batches` in `KTOConfig` or set it to `False`."
|
| 494 |
+
)
|
| 495 |
+
args.accelerator_config.dispatch_batches = False
|
| 496 |
+
|
| 497 |
+
# Model
|
| 498 |
+
if isinstance(model, str):
|
| 499 |
+
model_init_kwargs = args.model_init_kwargs or {}
|
| 500 |
+
# Distributed training requires device_map=None ("auto" fails)
|
| 501 |
+
if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
|
| 502 |
+
model_init_kwargs["device_map"] = None
|
| 503 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 504 |
+
model = create_model_from_path(model, **model_init_kwargs)
|
| 505 |
+
else:
|
| 506 |
+
if args.model_init_kwargs is not None:
|
| 507 |
+
logger.warning(
|
| 508 |
+
"You passed `model_init_kwargs` to the KTOConfig, but your model is already instantiated. "
|
| 509 |
+
"The `model_init_kwargs` will be ignored."
|
| 510 |
+
)
|
| 511 |
+
# Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do
|
| 512 |
+
_is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False)
|
| 513 |
+
if ref_model is model:
|
| 514 |
+
raise ValueError(
|
| 515 |
+
"`model` and `ref_model` cannot be the same object. In most cases you should omit `ref_model` and "
|
| 516 |
+
"we'll initialize it to a copy of `model` for you."
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
# Processing class
|
| 520 |
+
if processing_class is None:
|
| 521 |
+
processing_class = AutoProcessor.from_pretrained(
|
| 522 |
+
get_config_model_id(model.config), trust_remote_code=args.trust_remote_code
|
| 523 |
+
)
|
| 524 |
+
if isinstance(processing_class, ProcessorMixin):
|
| 525 |
+
self._tokenizer = processing_class.tokenizer
|
| 526 |
+
self._is_vlm = True
|
| 527 |
+
elif isinstance(processing_class, PreTrainedTokenizerBase):
|
| 528 |
+
self._tokenizer = processing_class
|
| 529 |
+
self._is_vlm = False
|
| 530 |
+
else:
|
| 531 |
+
raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
|
| 532 |
+
if self._tokenizer.pad_token is None:
|
| 533 |
+
self._tokenizer.pad_token = self._tokenizer.eos_token
|
| 534 |
+
|
| 535 |
+
# PEFT
|
| 536 |
+
if peft_config is not None:
|
| 537 |
+
if not is_peft_available():
|
| 538 |
+
raise ImportError(
|
| 539 |
+
"You passed `peft_config` but the `peft` library is not installed. "
|
| 540 |
+
"Install it with `pip install trl[peft]`."
|
| 541 |
+
)
|
| 542 |
+
if not isinstance(peft_config, PeftConfig):
|
| 543 |
+
raise TypeError(
|
| 544 |
+
f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
|
| 545 |
+
f"got {type(peft_config).__name__}."
|
| 546 |
+
)
|
| 547 |
+
if is_peft_model(model):
|
| 548 |
+
raise ValueError(
|
| 549 |
+
"You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge "
|
| 550 |
+
"and unload the existing adapter, save the resulting base model, and then pass that base model along "
|
| 551 |
+
"with the new `peft_config` to the trainer."
|
| 552 |
+
)
|
| 553 |
+
# Create PEFT model
|
| 554 |
+
# ZeRO-3 + PEFT for non-quantized models:
|
| 555 |
+
# - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16.
|
| 556 |
+
# - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter,
|
| 557 |
+
# so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step.
|
| 558 |
+
# - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch.
|
| 559 |
+
# - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for
|
| 560 |
+
# non-quantized bf16 training.
|
| 561 |
+
# - See:
|
| 562 |
+
# - TRL issue: https://github.com/huggingface/trl/issues/6089
|
| 563 |
+
# - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072
|
| 564 |
+
# - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg
|
| 565 |
+
get_peft_model_kwargs = {}
|
| 566 |
+
if (
|
| 567 |
+
args.deepspeed_plugin is not None
|
| 568 |
+
and args.deepspeed_plugin.zero_stage == 3
|
| 569 |
+
and not _is_quantized_model
|
| 570 |
+
and Version(peft.__version__) >= Version("0.12.0")
|
| 571 |
+
):
|
| 572 |
+
get_peft_model_kwargs["autocast_adapter_dtype"] = False
|
| 573 |
+
model = get_peft_model(model, peft_config, **get_peft_model_kwargs)
|
| 574 |
+
|
| 575 |
+
elif is_peft_model(model) and ref_model is None:
|
| 576 |
+
# If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy
|
| 577 |
+
# of the "default" adapter, so that we can use it as the reference model during KTO training. PEFT only
|
| 578 |
+
# supports one adapter per model when the LoRA config uses `target_parameters` (see peft#3340), so in that
|
| 579 |
+
# case we skip the "ref" adapter and compute the reference log probs with adapters disabled, i.e. with the
|
| 580 |
+
# base model.
|
| 581 |
+
default_config = model.peft_config["default"]
|
| 582 |
+
if isinstance(default_config, LoraConfig) and default_config.target_parameters:
|
| 583 |
+
logger.warning(
|
| 584 |
+
"PEFT can't add a frozen reference adapter alongside one that uses `target_parameters` "
|
| 585 |
+
"(peft#3340), so the reference log probs are computed from the base model (adapters disabled). "
|
| 586 |
+
"If you wrapped the model only to apply LoRA, pass a `peft_config` to the trainer instead; if you "
|
| 587 |
+
"wrapped it deliberately (pretrained adapter or custom init), note that the base model matches "
|
| 588 |
+
"your adapter only when it's freshly zero-initialized. If it is, this warning is safe to ignore."
|
| 589 |
+
)
|
| 590 |
+
else:
|
| 591 |
+
model.add_adapter("ref", default_config)
|
| 592 |
+
for name, param in model.named_parameters():
|
| 593 |
+
if ".default." in name:
|
| 594 |
+
ref_name = name.replace(".default.", ".ref.")
|
| 595 |
+
ref_param = model.get_parameter(ref_name)
|
| 596 |
+
ref_param.data.copy_(param.data)
|
| 597 |
+
|
| 598 |
+
# When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally
|
| 599 |
+
# handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489
|
| 600 |
+
if is_peft_model(model) and args.gradient_checkpointing:
|
| 601 |
+
model.enable_input_require_grads()
|
| 602 |
+
|
| 603 |
+
# When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the
|
| 604 |
+
# original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by
|
| 605 |
+
# passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for
|
| 606 |
+
# quantized models. See: https://github.com/huggingface/peft/issues/2889
|
| 607 |
+
if _is_quantized_model:
|
| 608 |
+
for param in model.parameters():
|
| 609 |
+
if param.requires_grad:
|
| 610 |
+
param.data = param.data.to(torch.bfloat16)
|
| 611 |
+
|
| 612 |
+
# Vision dataset detection
|
| 613 |
+
dataset_sample = next(iter(train_dataset))
|
| 614 |
+
self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample
|
| 615 |
+
if self._is_vision_dataset and not self._is_vlm:
|
| 616 |
+
raise ValueError(
|
| 617 |
+
"The dataset appears to be vision-related (contains 'image' or 'images' keys), but the provided "
|
| 618 |
+
"model does not seem to be a vision-language model. Please check your model and dataset."
|
| 619 |
+
)
|
| 620 |
+
if self._is_vision_dataset and args.precompute_ref_log_probs:
|
| 621 |
+
raise ValueError(
|
| 622 |
+
"`precompute_ref_log_probs=True` is not supported for vision datasets. For vision-language "
|
| 623 |
+
"models, all data processing is performed on the fly rather than upfront. "
|
| 624 |
+
"Set `precompute_ref_log_probs=False`."
|
| 625 |
+
)
|
| 626 |
+
if self._is_vision_dataset and ("chosen" in dataset_sample or "rejected" in dataset_sample):
|
| 627 |
+
raise ValueError(
|
| 628 |
+
"Vision datasets must be in unpaired format with `completion` and `label` columns. "
|
| 629 |
+
"Paired format (`chosen`/`rejected`) is not supported for vision datasets because "
|
| 630 |
+
"iterating over the full dataset to unpair it would be too expensive for large image "
|
| 631 |
+
"collections. Unpair your dataset first: `dataset = unpair_preference_dataset(dataset)`."
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
# Data collator
|
| 635 |
+
calculate_kl = args.loss_type not in ["apo_zero_unpaired"]
|
| 636 |
+
if data_collator is None and not self._is_vision_dataset:
|
| 637 |
+
data_collator = DataCollatorForUnpairedPreference(
|
| 638 |
+
pad_token_id=self._tokenizer.pad_token_id,
|
| 639 |
+
max_length=args.max_length,
|
| 640 |
+
pad_to_multiple_of=args.pad_to_multiple_of,
|
| 641 |
+
)
|
| 642 |
+
elif data_collator is None and self._is_vision_dataset:
|
| 643 |
+
data_collator = DataCollatorForVisionUnpairedPreference(
|
| 644 |
+
processor=processing_class,
|
| 645 |
+
max_length=args.max_length,
|
| 646 |
+
calculate_kl=calculate_kl,
|
| 647 |
+
pad_to_multiple_of=args.pad_to_multiple_of,
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
# Training arguments
|
| 651 |
+
self.beta = args.beta
|
| 652 |
+
self.precompute_ref_logps = args.precompute_ref_log_probs
|
| 653 |
+
self.loss_type = args.loss_type
|
| 654 |
+
self.desirable_weight = args.desirable_weight
|
| 655 |
+
self.undesirable_weight = args.undesirable_weight
|
| 656 |
+
self.aux_loss_enabled = getattr(model.config, "output_router_logits", False)
|
| 657 |
+
self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0)
|
| 658 |
+
self.calculate_KL = calculate_kl
|
| 659 |
+
if self.calculate_KL and args.train_sampling_strategy != "sequential":
|
| 660 |
+
raise ValueError(
|
| 661 |
+
f"Loss type `'{args.loss_type}'` estimates the KL divergence term and requires "
|
| 662 |
+
f"`train_sampling_strategy='sequential'` because the KL completion for each example is precomputed "
|
| 663 |
+
f"against its neighbors in a fixed-order batch; any other strategy breaks that pairing. "
|
| 664 |
+
f"Got `train_sampling_strategy='{args.train_sampling_strategy}'`."
|
| 665 |
+
)
|
| 666 |
+
if self.calculate_KL and args.per_device_train_batch_size <= 1:
|
| 667 |
+
raise ValueError(
|
| 668 |
+
"Actual (not effective) batch size must be > 1. KTO will not work properly because the KL term will be equivalent to the implied reward."
|
| 669 |
+
)
|
| 670 |
+
if self.aux_loss_enabled and self.aux_loss_coef == 0.0:
|
| 671 |
+
logger.warning(
|
| 672 |
+
"You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to "
|
| 673 |
+
"`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value "
|
| 674 |
+
"greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary "
|
| 675 |
+
"loss.",
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
# Dataset
|
| 679 |
+
# Skip dataset preparation for VLMs: tokenization and image processing happen on-the-fly in the collator.
|
| 680 |
+
if not self._is_vision_dataset:
|
| 681 |
+
train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train")
|
| 682 |
+
if eval_dataset is not None:
|
| 683 |
+
if isinstance(eval_dataset, dict):
|
| 684 |
+
eval_dataset = {
|
| 685 |
+
key: self._prepare_dataset(dataset, processing_class, args, key)
|
| 686 |
+
for key, dataset in eval_dataset.items()
|
| 687 |
+
}
|
| 688 |
+
else:
|
| 689 |
+
eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval")
|
| 690 |
+
|
| 691 |
+
# Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
|
| 692 |
+
# never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
|
| 693 |
+
# (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
|
| 694 |
+
# default to the recommended non-reentrant behavior here, while preserving any user-provided value.
|
| 695 |
+
if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
|
| 696 |
+
args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
|
| 697 |
+
args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
|
| 698 |
+
|
| 699 |
+
super().__init__(
|
| 700 |
+
model=model,
|
| 701 |
+
args=args,
|
| 702 |
+
data_collator=data_collator,
|
| 703 |
+
train_dataset=train_dataset,
|
| 704 |
+
eval_dataset=eval_dataset,
|
| 705 |
+
processing_class=processing_class,
|
| 706 |
+
compute_metrics=compute_metrics,
|
| 707 |
+
callbacks=callbacks,
|
| 708 |
+
optimizers=optimizers,
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
# Initialize activation offloading context
|
| 712 |
+
if self.args.activation_offloading:
|
| 713 |
+
self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model)
|
| 714 |
+
else:
|
| 715 |
+
self.maybe_activation_offload_context = contextlib.nullcontext()
|
| 716 |
+
|
| 717 |
+
# Reference model
|
| 718 |
+
if ref_model is None:
|
| 719 |
+
if is_peft_model(self.model) or args.precompute_ref_log_probs:
|
| 720 |
+
# If PEFT is used, the reference model is not needed since the adapter can be disabled to revert to the
|
| 721 |
+
# initial model. If precompute_ref_log_probs is True, the reference model does not need to be kept in
|
| 722 |
+
# memory during training.
|
| 723 |
+
self.ref_model = None
|
| 724 |
+
else:
|
| 725 |
+
ref_model_init_kwargs = args.model_init_kwargs or {}
|
| 726 |
+
# Distributed training requires device_map=None ("auto" fails)
|
| 727 |
+
if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
|
| 728 |
+
ref_model_init_kwargs["device_map"] = None
|
| 729 |
+
ref_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 730 |
+
ref_model_path = get_config_model_id(self.model.config)
|
| 731 |
+
self.ref_model = create_model_from_path(ref_model_path, **ref_model_init_kwargs)
|
| 732 |
+
else:
|
| 733 |
+
self.ref_model = ref_model
|
| 734 |
+
|
| 735 |
+
# Disable dropout in the model and reference model
|
| 736 |
+
if args.disable_dropout:
|
| 737 |
+
disable_dropout_in_model(model)
|
| 738 |
+
if self.ref_model is not None:
|
| 739 |
+
disable_dropout_in_model(self.ref_model)
|
| 740 |
+
|
| 741 |
+
# Initialize the metrics
|
| 742 |
+
self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
|
| 743 |
+
|
| 744 |
+
# Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
|
| 745 |
+
# model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
|
| 746 |
+
# self.model_accepts_loss_kwargs to False to enable scaling.
|
| 747 |
+
self.model_accepts_loss_kwargs = False
|
| 748 |
+
|
| 749 |
+
# Add tags to the model
|
| 750 |
+
self.model.add_model_tags(self._tag_names)
|
| 751 |
+
|
| 752 |
+
if self.ref_model is not None:
|
| 753 |
+
if self.is_deepspeed_enabled:
|
| 754 |
+
self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
|
| 755 |
+
elif self.is_fsdp_enabled:
|
| 756 |
+
self.ref_model = prepare_fsdp(self.ref_model, self.accelerator)
|
| 757 |
+
else:
|
| 758 |
+
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
|
| 759 |
+
|
| 760 |
+
if args.sync_ref_model:
|
| 761 |
+
if is_peft_model(self.model):
|
| 762 |
+
raise NotImplementedError(
|
| 763 |
+
"You passed `sync_ref_model=True` while using a PEFT model, which is currently not supported. "
|
| 764 |
+
"With PEFT, KTOTrainer does not keep a separate reference model in memory; instead, it recovers "
|
| 765 |
+
"reference behavior by temporarily disabling the adapter. As a result, there is no standalone "
|
| 766 |
+
"`ref_model` instance to synchronize. Use `sync_ref_model=False`, or opt for full fine-tuning if "
|
| 767 |
+
"you need a synced reference model. If you need `sync_ref_model` to work with PEFT, please open a "
|
| 768 |
+
"feature request at https://github.com/huggingface/trl/issues."
|
| 769 |
+
)
|
| 770 |
+
if args.precompute_ref_log_probs:
|
| 771 |
+
raise ValueError(
|
| 772 |
+
"You cannot use `sync_ref_model=True` together with `precompute_ref_log_probs=True`. "
|
| 773 |
+
"`precompute_ref_log_probs=True` assumes a fixed reference model, but with `sync_ref_model=True` "
|
| 774 |
+
"the reference model is periodically updated during training, making any precomputed reference "
|
| 775 |
+
"log-probs stale. Set `precompute_ref_log_probs=False` or disable `sync_ref_model`."
|
| 776 |
+
)
|
| 777 |
+
self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator))
|
| 778 |
+
|
| 779 |
+
self.use_liger_kernel = args.use_liger_kernel
|
| 780 |
+
# Import Liger kernel if enabled
|
| 781 |
+
if self.use_liger_kernel:
|
| 782 |
+
if not is_liger_kernel_available():
|
| 783 |
+
raise ImportError(
|
| 784 |
+
"You set `use_liger_kernel=True` but the liger kernel is not available. "
|
| 785 |
+
"Please install liger-kernel first: `pip install liger-kernel`"
|
| 786 |
+
)
|
| 787 |
+
if self.loss_type in ["apo_zero_unpaired"]:
|
| 788 |
+
raise ValueError(
|
| 789 |
+
"You cannot set `loss_type='apo_zero_unpaired'` with liger-kernel."
|
| 790 |
+
"Only KTO loss is supported with liger-kernel."
|
| 791 |
+
)
|
| 792 |
+
if self.precompute_ref_logps:
|
| 793 |
+
raise ValueError(
|
| 794 |
+
"You cannot use `precompute_ref_log_probs=True` with liger kernel. Please set "
|
| 795 |
+
"`precompute_ref_log_probs=False`."
|
| 796 |
+
)
|
| 797 |
+
if is_peft_model(self.model):
|
| 798 |
+
raise ValueError(
|
| 799 |
+
"You cannot use `use_liger_kernel=True` with Peft models. Please set `use_liger_kernel=False`."
|
| 800 |
+
)
|
| 801 |
+
self.liger_loss_fn = LigerFusedLinearKTOLoss(beta=self.beta, use_ref_model=(self.ref_model is not None))
|
| 802 |
+
|
| 803 |
+
if self.precompute_ref_logps:
|
| 804 |
+
if isinstance(self.train_dataset, IterableDataset) or isinstance(
|
| 805 |
+
self.eval_dataset, (IterableDataset, IterableDatasetDict)
|
| 806 |
+
):
|
| 807 |
+
raise ValueError(
|
| 808 |
+
"`precompute_ref_log_probs=True` is not supported with IterableDataset. Please use a map-style "
|
| 809 |
+
"Dataset or set `precompute_ref_log_probs=False`."
|
| 810 |
+
)
|
| 811 |
+
self.train_dataset = self._precompute_ref_logps(
|
| 812 |
+
self.train_dataset,
|
| 813 |
+
"train",
|
| 814 |
+
self.args.precompute_ref_batch_size or self.args.per_device_train_batch_size,
|
| 815 |
+
)
|
| 816 |
+
if self.eval_dataset is not None:
|
| 817 |
+
if isinstance(self.eval_dataset, dict):
|
| 818 |
+
self.eval_dataset = {
|
| 819 |
+
name: self._precompute_ref_logps(
|
| 820 |
+
dataset, name, self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size
|
| 821 |
+
)
|
| 822 |
+
for name, dataset in self.eval_dataset.items()
|
| 823 |
+
}
|
| 824 |
+
else:
|
| 825 |
+
self.eval_dataset = self._precompute_ref_logps(
|
| 826 |
+
self.eval_dataset,
|
| 827 |
+
"eval",
|
| 828 |
+
self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size,
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
def _tokenize(
|
| 832 |
+
self,
|
| 833 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin,
|
| 834 |
+
input: str | list,
|
| 835 |
+
**kwargs,
|
| 836 |
+
) -> dict[str, list]:
|
| 837 |
+
"""Tokenize a single example for dataset preprocessing.
|
| 838 |
+
|
| 839 |
+
Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for
|
| 840 |
+
non-conversational input (str).
|
| 841 |
+
|
| 842 |
+
Args:
|
| 843 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]):
|
| 844 |
+
The tokenizer or processor to use.
|
| 845 |
+
input (`str` or `list`):
|
| 846 |
+
A string for non-conversational input, or a list of message dicts for conversational input.
|
| 847 |
+
**kwargs:
|
| 848 |
+
Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`, `return_assistant_tokens_mask`).
|
| 849 |
+
|
| 850 |
+
Returns:
|
| 851 |
+
`dict` with at least an `"input_ids"` key mapping to a flat `list[int]`.
|
| 852 |
+
"""
|
| 853 |
+
if isinstance(input, list): # conversational: list of message dicts
|
| 854 |
+
if self._is_vlm:
|
| 855 |
+
input = prepare_multimodal_messages(input)
|
| 856 |
+
result = processing_class.apply_chat_template(input, tokenize=True, return_dict=True, **kwargs)
|
| 857 |
+
else: # non-conversational: plain text string
|
| 858 |
+
result = processing_class(text=input)
|
| 859 |
+
# VLMs emit a batch dimension even for single examples; unwrap it
|
| 860 |
+
if self._is_vlm:
|
| 861 |
+
return {k: v[0] for k, v in result.items()}
|
| 862 |
+
return result
|
| 863 |
+
|
| 864 |
+
def _get_kl_dataset(
|
| 865 |
+
self,
|
| 866 |
+
dataset: Dataset | IterableDataset,
|
| 867 |
+
dataset_name: str,
|
| 868 |
+
args: KTOConfig,
|
| 869 |
+
) -> Dataset | IterableDataset:
|
| 870 |
+
"""
|
| 871 |
+
Creates the KL dataset by creating mismatched (prompt, completion) pairs for KL divergence estimation.
|
| 872 |
+
|
| 873 |
+
Args:
|
| 874 |
+
dataset (`Dataset` or `IterableDataset`):
|
| 875 |
+
Tokenized dataset with `prompt_ids` and `completion_ids` columns.
|
| 876 |
+
dataset_name (`str`):
|
| 877 |
+
Name used in progress bar descriptions.
|
| 878 |
+
args ([`KTOConfig`]):
|
| 879 |
+
Training arguments providing `per_device_train_batch_size` and `dataset_num_proc`.
|
| 880 |
+
|
| 881 |
+
Returns:
|
| 882 |
+
`Dataset` or `IterableDataset` with a single `KL_completion_ids` column.
|
| 883 |
+
"""
|
| 884 |
+
|
| 885 |
+
def get_kl_completion_ids(examples):
|
| 886 |
+
# Create mismatched pairs of prompts and completions for the KL dataset by adding a +1 offset to the order
|
| 887 |
+
# of completions. For best results, the mismatched outputs y' used to estimate the KL term for a batch
|
| 888 |
+
# should be the same set as the matched outputs y used to estimate the rewards in that batch, just paired
|
| 889 |
+
# with different x.
|
| 890 |
+
examples["completion_ids"] = [examples["completion_ids"][-1]] + examples["completion_ids"][:-1]
|
| 891 |
+
return examples
|
| 892 |
+
|
| 893 |
+
map_kwargs = {}
|
| 894 |
+
if isinstance(dataset, Dataset): # IterableDataset does not support num_proc or desc
|
| 895 |
+
map_kwargs["num_proc"] = args.dataset_num_proc
|
| 896 |
+
map_kwargs["desc"] = f"Extracting KL {dataset_name} dataset"
|
| 897 |
+
kl_dataset = dataset.map(
|
| 898 |
+
get_kl_completion_ids, batched=True, batch_size=args.per_device_train_batch_size, **map_kwargs
|
| 899 |
+
)
|
| 900 |
+
|
| 901 |
+
def rename_kl_fn(example):
|
| 902 |
+
return {"KL_completion_ids": example["completion_ids"]}
|
| 903 |
+
|
| 904 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 905 |
+
map_kwargs["desc"] = f"Assembling KL {dataset_name} dataset"
|
| 906 |
+
column_names = get_dataset_column_names(dataset)
|
| 907 |
+
kl_dataset = kl_dataset.map(
|
| 908 |
+
rename_kl_fn,
|
| 909 |
+
remove_columns=[c for c in get_dataset_column_names(kl_dataset) if c in column_names],
|
| 910 |
+
**map_kwargs,
|
| 911 |
+
)
|
| 912 |
+
return kl_dataset
|
| 913 |
+
|
| 914 |
+
def _prepare_dataset(
|
| 915 |
+
self,
|
| 916 |
+
dataset: Dataset | IterableDataset,
|
| 917 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin,
|
| 918 |
+
args: KTOConfig | None,
|
| 919 |
+
dataset_name: str,
|
| 920 |
+
) -> Dataset | IterableDataset:
|
| 921 |
+
# Build the kwargs for the `map` function
|
| 922 |
+
map_kwargs = {}
|
| 923 |
+
if isinstance(dataset, Dataset): # IterableDataset does not support num_proc
|
| 924 |
+
map_kwargs["num_proc"] = args.dataset_num_proc
|
| 925 |
+
|
| 926 |
+
# Compute that only on the main process for faster data processing.
|
| 927 |
+
# see: https://github.com/huggingface/trl/pull/1255
|
| 928 |
+
with PartialState().main_process_first():
|
| 929 |
+
# Extract the prompt if needed
|
| 930 |
+
first_example = next(iter(dataset))
|
| 931 |
+
if "prompt" not in first_example:
|
| 932 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 933 |
+
map_kwargs["desc"] = f"Extracting prompt from {dataset_name} dataset"
|
| 934 |
+
dataset = dataset.map(extract_prompt, **map_kwargs)
|
| 935 |
+
|
| 936 |
+
# Unpair the dataset if needed
|
| 937 |
+
first_example = next(iter(dataset))
|
| 938 |
+
if "chosen" in first_example and "rejected" in first_example:
|
| 939 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 940 |
+
map_kwargs["desc"] = f"Unpairing {dataset_name} dataset"
|
| 941 |
+
dataset = unpair_preference_dataset(dataset, **map_kwargs)
|
| 942 |
+
|
| 943 |
+
# Add EOS token if needed: non-conversational only
|
| 944 |
+
first_example = next(iter(dataset))
|
| 945 |
+
if not is_conversational(first_example):
|
| 946 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 947 |
+
map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset"
|
| 948 |
+
|
| 949 |
+
def add_eos(example, eos_token):
|
| 950 |
+
if not example["completion"].endswith(eos_token):
|
| 951 |
+
example["completion"] = example["completion"] + eos_token
|
| 952 |
+
return example
|
| 953 |
+
|
| 954 |
+
dataset = dataset.map(add_eos, fn_kwargs={"eos_token": self._tokenizer.eos_token}, **map_kwargs)
|
| 955 |
+
|
| 956 |
+
# Tokenize dataset
|
| 957 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 958 |
+
map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset"
|
| 959 |
+
|
| 960 |
+
def tokenize_fn(example, processing_class):
|
| 961 |
+
if is_conversational(example):
|
| 962 |
+
chat_template_kwargs = example.get("chat_template_kwargs", {})
|
| 963 |
+
prompt_ids = self._tokenize(
|
| 964 |
+
processing_class,
|
| 965 |
+
example["prompt"],
|
| 966 |
+
add_generation_prompt=True,
|
| 967 |
+
**chat_template_kwargs,
|
| 968 |
+
)["input_ids"]
|
| 969 |
+
prompt_completion_ids = self._tokenize(
|
| 970 |
+
processing_class,
|
| 971 |
+
example["prompt"] + example["completion"],
|
| 972 |
+
**chat_template_kwargs,
|
| 973 |
+
)["input_ids"]
|
| 974 |
+
else:
|
| 975 |
+
prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"]
|
| 976 |
+
prompt_completion_ids = self._tokenize(
|
| 977 |
+
processing_class, example["prompt"] + example["completion"]
|
| 978 |
+
)["input_ids"]
|
| 979 |
+
|
| 980 |
+
if not prompt_completion_ids[: len(prompt_ids)] == prompt_ids:
|
| 981 |
+
logger.warning(
|
| 982 |
+
"Mismatch between tokenized prompt and the start of tokenized prompt+completion. "
|
| 983 |
+
"This may be due to unexpected tokenizer behavior, whitespace issues, or special "
|
| 984 |
+
"token handling. Verify that the tokenizer is processing text consistently."
|
| 985 |
+
)
|
| 986 |
+
|
| 987 |
+
return {
|
| 988 |
+
"prompt_ids": prompt_ids,
|
| 989 |
+
"completion_ids": prompt_completion_ids[len(prompt_ids) :],
|
| 990 |
+
}
|
| 991 |
+
|
| 992 |
+
dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs)
|
| 993 |
+
|
| 994 |
+
# Get KL datasets if needed
|
| 995 |
+
if self.calculate_KL:
|
| 996 |
+
# create pairs for estimating the KL term by flipping the matched pairs in each batch of size total_batch_size
|
| 997 |
+
# i.e., (x_1, y_1), ..., (x_n, y_n) --> (x_1, y_n), ..., (x_n, y_1) = (x'_1, y'_1), ..., (x'_n, y'_n)
|
| 998 |
+
kl_dataset = self._get_kl_dataset(dataset, dataset_name, args)
|
| 999 |
+
dataset = concatenate_datasets([dataset, kl_dataset], axis=1)
|
| 1000 |
+
|
| 1001 |
+
# Calculate dataset desirability balance
|
| 1002 |
+
if dataset_name == "train" and isinstance(dataset, Dataset): # IterableDataset does not support len
|
| 1003 |
+
num_desirable = max(sum(dataset["label"]), 1)
|
| 1004 |
+
num_undesirable = max(len(dataset["label"]) - num_desirable, 1) # "label" is binary
|
| 1005 |
+
|
| 1006 |
+
if num_desirable != num_undesirable:
|
| 1007 |
+
# The lower and upper bounds come from Eq. (8) of https://huggingface.co/papers/2402.01306
|
| 1008 |
+
des_weight_lower_bound = round((num_undesirable * self.undesirable_weight / num_desirable) * 1, 2)
|
| 1009 |
+
des_weight_upper_bound = round(
|
| 1010 |
+
(num_undesirable * self.undesirable_weight / num_desirable) * 1.33, 2
|
| 1011 |
+
)
|
| 1012 |
+
und_weight_lower_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1.33, 2)
|
| 1013 |
+
und_weight_upper_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1, 2)
|
| 1014 |
+
|
| 1015 |
+
des_weight_in_range = des_weight_lower_bound <= self.desirable_weight <= des_weight_upper_bound
|
| 1016 |
+
und_weight_in_range = und_weight_lower_bound <= self.undesirable_weight <= und_weight_upper_bound
|
| 1017 |
+
|
| 1018 |
+
if not (des_weight_in_range or und_weight_in_range):
|
| 1019 |
+
logger.warning(
|
| 1020 |
+
"You have different amounts of desirable/positive and undesirable/negative examples but the "
|
| 1021 |
+
"weights on the desirable and undesirable losses don't seem to be in an ideal range. Based "
|
| 1022 |
+
f"on your data, we recommend EITHER "
|
| 1023 |
+
f"desirable_weight in [{des_weight_lower_bound}, {des_weight_upper_bound}] or "
|
| 1024 |
+
f"undesirable_weight in [{und_weight_lower_bound}, {und_weight_upper_bound}] (but NOT BOTH). "
|
| 1025 |
+
"See the documentation on how to optimally set these weights.",
|
| 1026 |
+
)
|
| 1027 |
+
return dataset
|
| 1028 |
+
|
| 1029 |
+
def _set_signature_columns_if_needed(self):
|
| 1030 |
+
# If `self.args.remove_unused_columns` is True, non-signature columns are removed.
|
| 1031 |
+
# By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids"
|
| 1032 |
+
# and "attention_mask").
|
| 1033 |
+
if self._signature_columns is None:
|
| 1034 |
+
if self._is_vision_dataset:
|
| 1035 |
+
self._signature_columns = [
|
| 1036 |
+
"prompt",
|
| 1037 |
+
"completion",
|
| 1038 |
+
"image",
|
| 1039 |
+
"images",
|
| 1040 |
+
"label",
|
| 1041 |
+
"chat_template_kwargs",
|
| 1042 |
+
]
|
| 1043 |
+
else:
|
| 1044 |
+
self._signature_columns = [
|
| 1045 |
+
"prompt_ids",
|
| 1046 |
+
"completion_ids",
|
| 1047 |
+
"KL_completion_ids",
|
| 1048 |
+
"label",
|
| 1049 |
+
"ref_logps",
|
| 1050 |
+
"ref_KL_logps",
|
| 1051 |
+
]
|
| 1052 |
+
|
| 1053 |
+
def _get_train_sampler(self, train_dataset: Dataset | None = None) -> Sampler | None:
|
| 1054 |
+
if self.calculate_KL and Version(transformers.__version__) < Version("5.2.0"):
|
| 1055 |
+
if train_dataset is None:
|
| 1056 |
+
train_dataset = self.train_dataset
|
| 1057 |
+
if train_dataset is None or not has_length(train_dataset):
|
| 1058 |
+
return None
|
| 1059 |
+
return SequentialSampler(train_dataset)
|
| 1060 |
+
return super()._get_train_sampler(
|
| 1061 |
+
train_dataset
|
| 1062 |
+
) # Override training step to add activation offloading context.
|
| 1063 |
+
|
| 1064 |
+
def _precompute_ref_logps(self, dataset: Dataset, name: str, batch_size: int) -> Dataset:
|
| 1065 |
+
model_hash = hash_module(self.ref_model or self.model)
|
| 1066 |
+
fingerprint = Hasher.hash((dataset._fingerprint, model_hash, self.calculate_KL))
|
| 1067 |
+
cache_file = dataset._get_cache_file_path(fingerprint)
|
| 1068 |
+
if os.path.exists(cache_file):
|
| 1069 |
+
return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1)
|
| 1070 |
+
|
| 1071 |
+
dataloader = DataLoader(
|
| 1072 |
+
dataset,
|
| 1073 |
+
batch_size=batch_size,
|
| 1074 |
+
collate_fn=self.data_collator,
|
| 1075 |
+
num_workers=self.args.dataloader_num_workers,
|
| 1076 |
+
pin_memory=self.args.dataloader_pin_memory,
|
| 1077 |
+
shuffle=False,
|
| 1078 |
+
)
|
| 1079 |
+
data_loader = self.accelerator.prepare(dataloader)
|
| 1080 |
+
ref_logps = []
|
| 1081 |
+
ref_KL_logps = []
|
| 1082 |
+
for padded_batch in tqdm(iterable=data_loader, desc=f"Computing reference log probs for {name} dataset"):
|
| 1083 |
+
ref_logp, ref_KL_logp = self.compute_ref_log_probs(padded_batch)
|
| 1084 |
+
if self.calculate_KL:
|
| 1085 |
+
ref_logp, ref_KL_logp = self.accelerator.gather_for_metrics((ref_logp, ref_KL_logp))
|
| 1086 |
+
ref_KL_logps.append(ref_KL_logp.cpu())
|
| 1087 |
+
else:
|
| 1088 |
+
ref_logp = self.accelerator.gather_for_metrics(ref_logp)
|
| 1089 |
+
ref_logps.append(ref_logp.cpu())
|
| 1090 |
+
|
| 1091 |
+
ref_logps = torch.cat(ref_logps)
|
| 1092 |
+
if self.calculate_KL:
|
| 1093 |
+
ref_KL_logps = torch.cat(ref_KL_logps)
|
| 1094 |
+
|
| 1095 |
+
if self.accelerator.is_main_process:
|
| 1096 |
+
|
| 1097 |
+
def add_ref_logps(batch, indices):
|
| 1098 |
+
result = {"ref_logps": ref_logps[indices]}
|
| 1099 |
+
if self.calculate_KL:
|
| 1100 |
+
result.update({"ref_KL_logps": ref_KL_logps[indices]})
|
| 1101 |
+
return result
|
| 1102 |
+
|
| 1103 |
+
dataset.map(
|
| 1104 |
+
add_ref_logps,
|
| 1105 |
+
with_indices=True,
|
| 1106 |
+
batched=True,
|
| 1107 |
+
remove_columns=dataset.column_names,
|
| 1108 |
+
new_fingerprint=fingerprint,
|
| 1109 |
+
desc=f"Caching reference log probs for {name} dataset",
|
| 1110 |
+
)
|
| 1111 |
+
self.accelerator.wait_for_everyone()
|
| 1112 |
+
|
| 1113 |
+
return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1)
|
| 1114 |
+
|
| 1115 |
+
def compute_ref_log_probs(self, inputs):
|
| 1116 |
+
"""Computes reference log probabilities for a single padded batch."""
|
| 1117 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 1118 |
+
if self.ref_model is None:
|
| 1119 |
+
if is_peft_model(self.model):
|
| 1120 |
+
model = self.accelerator.unwrap_model(self.model)
|
| 1121 |
+
with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None):
|
| 1122 |
+
completion_logits = self.model(
|
| 1123 |
+
inputs["input_ids"],
|
| 1124 |
+
attention_mask=inputs["attention_mask"],
|
| 1125 |
+
).logits
|
| 1126 |
+
|
| 1127 |
+
if self.calculate_KL:
|
| 1128 |
+
KL_logits = self.model(
|
| 1129 |
+
inputs["KL_input_ids"],
|
| 1130 |
+
attention_mask=inputs["KL_attention_mask"],
|
| 1131 |
+
).logits
|
| 1132 |
+
else:
|
| 1133 |
+
completion_logits = self.model(
|
| 1134 |
+
inputs["input_ids"],
|
| 1135 |
+
attention_mask=inputs["attention_mask"],
|
| 1136 |
+
).logits
|
| 1137 |
+
|
| 1138 |
+
if self.calculate_KL:
|
| 1139 |
+
KL_logits = self.model(
|
| 1140 |
+
inputs["KL_input_ids"],
|
| 1141 |
+
attention_mask=inputs["KL_attention_mask"],
|
| 1142 |
+
).logits
|
| 1143 |
+
else:
|
| 1144 |
+
completion_logits = self.ref_model(inputs["input_ids"], attention_mask=inputs["attention_mask"]).logits
|
| 1145 |
+
|
| 1146 |
+
if self.calculate_KL:
|
| 1147 |
+
KL_logits = self.ref_model(
|
| 1148 |
+
inputs["KL_input_ids"],
|
| 1149 |
+
attention_mask=inputs["KL_attention_mask"],
|
| 1150 |
+
).logits
|
| 1151 |
+
|
| 1152 |
+
shift_logits = completion_logits[:, :-1, :]
|
| 1153 |
+
per_token_logps = selective_log_softmax(shift_logits, inputs["input_ids"][:, 1:])
|
| 1154 |
+
per_token_logps[inputs["completion_mask"][:, 1:] == 0] = 0.0
|
| 1155 |
+
completion_logps = per_token_logps.sum(-1)
|
| 1156 |
+
|
| 1157 |
+
if self.calculate_KL:
|
| 1158 |
+
shift_KL_logits = KL_logits[:, :-1, :]
|
| 1159 |
+
KL_per_token_logps = selective_log_softmax(shift_KL_logits, inputs["KL_input_ids"][:, 1:])
|
| 1160 |
+
KL_per_token_logps[inputs["KL_completion_mask"][:, 1:] == 0] = 0.0
|
| 1161 |
+
KL_logps = KL_per_token_logps.sum(-1)
|
| 1162 |
+
else:
|
| 1163 |
+
KL_logps = None
|
| 1164 |
+
|
| 1165 |
+
return completion_logps, KL_logps
|
| 1166 |
+
|
| 1167 |
+
def _compute_kl_logps(self, model, batch):
|
| 1168 |
+
"""Compute KL log probabilities for a given batch."""
|
| 1169 |
+
KL_logps = None
|
| 1170 |
+
if self.calculate_KL:
|
| 1171 |
+
_non_model_keys = {
|
| 1172 |
+
"input_ids",
|
| 1173 |
+
"attention_mask",
|
| 1174 |
+
"completion_mask",
|
| 1175 |
+
"KL_completion_mask",
|
| 1176 |
+
"KL_token_type_ids",
|
| 1177 |
+
"KL_mm_token_type_ids",
|
| 1178 |
+
"label",
|
| 1179 |
+
"ref_logps",
|
| 1180 |
+
"ref_KL_logps",
|
| 1181 |
+
}
|
| 1182 |
+
KL_model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys}
|
| 1183 |
+
KL_model_kwargs["input_ids"] = KL_model_kwargs.pop("KL_input_ids")
|
| 1184 |
+
KL_model_kwargs["attention_mask"] = KL_model_kwargs.pop("KL_attention_mask")
|
| 1185 |
+
# KL sequences have different widths from the main completion after flush_left; override token-type
|
| 1186 |
+
# tensors with the KL-specific ones the collator built for exactly this purpose.
|
| 1187 |
+
if "KL_token_type_ids" in batch:
|
| 1188 |
+
KL_model_kwargs["token_type_ids"] = batch["KL_token_type_ids"]
|
| 1189 |
+
if "KL_mm_token_type_ids" in batch:
|
| 1190 |
+
KL_model_kwargs["mm_token_type_ids"] = batch["KL_mm_token_type_ids"]
|
| 1191 |
+
|
| 1192 |
+
with torch.no_grad():
|
| 1193 |
+
KL_logits = model(**KL_model_kwargs).logits
|
| 1194 |
+
|
| 1195 |
+
shift_KL_logits = KL_logits[:, :-1, :]
|
| 1196 |
+
KL_per_token_logps = selective_log_softmax(shift_KL_logits, batch["KL_input_ids"][:, 1:])
|
| 1197 |
+
KL_per_token_logps[batch["KL_completion_mask"][:, 1:] == 0] = 0.0
|
| 1198 |
+
KL_logps = KL_per_token_logps.sum(-1)
|
| 1199 |
+
return KL_logps
|
| 1200 |
+
|
| 1201 |
+
def _compute_loss_liger(self, model, inputs, return_outputs):
|
| 1202 |
+
if return_outputs:
|
| 1203 |
+
raise RuntimeError(
|
| 1204 |
+
"return_outputs=True is not supported with the Liger KTO loss. The Liger loss computes the loss "
|
| 1205 |
+
"without materializing logits, so outputs cannot be returned."
|
| 1206 |
+
)
|
| 1207 |
+
mode = "train" if self.model.training else "eval"
|
| 1208 |
+
batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()}
|
| 1209 |
+
|
| 1210 |
+
labels = torch.tensor(batch["label"])
|
| 1211 |
+
num_chosen = labels.sum().to(self.accelerator.device)
|
| 1212 |
+
num_rejected = (len(labels) - num_chosen).to(self.accelerator.device)
|
| 1213 |
+
|
| 1214 |
+
policy_KL_logps = self._compute_kl_logps(model, batch)
|
| 1215 |
+
ref_KL_logps = self._compute_kl_logps(self.ref_model, batch)
|
| 1216 |
+
if self.calculate_KL:
|
| 1217 |
+
kl = (policy_KL_logps - ref_KL_logps).mean().detach()
|
| 1218 |
+
kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0)
|
| 1219 |
+
else:
|
| 1220 |
+
kl = torch.zeros(1).to(self.accelerator.device)
|
| 1221 |
+
|
| 1222 |
+
_non_model_keys = {
|
| 1223 |
+
"completion_mask",
|
| 1224 |
+
"KL_input_ids",
|
| 1225 |
+
"KL_attention_mask",
|
| 1226 |
+
"KL_completion_mask",
|
| 1227 |
+
"KL_token_type_ids",
|
| 1228 |
+
"KL_mm_token_type_ids",
|
| 1229 |
+
"label",
|
| 1230 |
+
"ref_logps",
|
| 1231 |
+
"ref_KL_logps",
|
| 1232 |
+
}
|
| 1233 |
+
model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys}
|
| 1234 |
+
model_kwargs["use_cache"] = False
|
| 1235 |
+
if self.aux_loss_enabled:
|
| 1236 |
+
model_kwargs["output_router_logits"] = True
|
| 1237 |
+
|
| 1238 |
+
# `base_model` gives the inner module (skipping `lm_head`) — text decoder for LMs, multimodal wrapper for
|
| 1239 |
+
# VLMs (so vision-token injection runs before the text decoder). `get_decoder()` won't do: on VLMs it
|
| 1240 |
+
# returns just the text stack and feeds image-placeholder IDs through it.
|
| 1241 |
+
# Pre-5.0 transformers VLMs set `base_model_prefix = ""` so `base_model is self` (re-runs `lm_head`).
|
| 1242 |
+
# Fall back to `.model` there.
|
| 1243 |
+
if self._is_vlm and Version(transformers.__version__) < Version("5.0.0"):
|
| 1244 |
+
backbone, ref_backbone = model.model, self.ref_model.model
|
| 1245 |
+
else:
|
| 1246 |
+
backbone, ref_backbone = model.base_model, self.ref_model.base_model
|
| 1247 |
+
|
| 1248 |
+
outputs = backbone(**model_kwargs)
|
| 1249 |
+
|
| 1250 |
+
# reference model
|
| 1251 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 1252 |
+
ref_outputs = ref_backbone(**{k: v for k, v in model_kwargs.items() if k != "output_router_logits"})
|
| 1253 |
+
lm_head = model.get_output_embeddings()
|
| 1254 |
+
ref_lm_head = self.ref_model.get_output_embeddings()
|
| 1255 |
+
|
| 1256 |
+
shift_completion_mask = batch["completion_mask"][:, 1:]
|
| 1257 |
+
target = batch["input_ids"][:, 1:].clone()
|
| 1258 |
+
target[shift_completion_mask == 0] = -100
|
| 1259 |
+
|
| 1260 |
+
(
|
| 1261 |
+
loss,
|
| 1262 |
+
(
|
| 1263 |
+
chosen_logps_sum,
|
| 1264 |
+
rejected_logps_sum,
|
| 1265 |
+
chosen_logits_sum,
|
| 1266 |
+
rejected_logits_sum,
|
| 1267 |
+
chosen_rewards_sum,
|
| 1268 |
+
rejected_rewards_sum,
|
| 1269 |
+
),
|
| 1270 |
+
) = self.liger_loss_fn(
|
| 1271 |
+
_input=outputs.last_hidden_state[:, :-1],
|
| 1272 |
+
lin_weight=lm_head.weight,
|
| 1273 |
+
target=target,
|
| 1274 |
+
bias=lm_head.bias if hasattr(lm_head, "bias") else None,
|
| 1275 |
+
preference_labels=torch.tensor(batch["label"], dtype=torch.bool).to(self.accelerator.device),
|
| 1276 |
+
ref_input=ref_outputs.last_hidden_state[:, :-1],
|
| 1277 |
+
ref_weight=ref_lm_head.weight,
|
| 1278 |
+
ref_bias=ref_lm_head.bias if hasattr(lm_head, "bias") else None,
|
| 1279 |
+
kl=kl,
|
| 1280 |
+
)
|
| 1281 |
+
if self.aux_loss_enabled:
|
| 1282 |
+
loss += self.aux_loss_coef * outputs.aux_loss
|
| 1283 |
+
|
| 1284 |
+
self._metrics[mode]["kl"].append(kl.item())
|
| 1285 |
+
|
| 1286 |
+
all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item()
|
| 1287 |
+
all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item()
|
| 1288 |
+
|
| 1289 |
+
if all_num_chosen > 0:
|
| 1290 |
+
self._metrics[mode]["rewards/chosen"].append(
|
| 1291 |
+
self.accelerator.gather_for_metrics(chosen_rewards_sum.nansum()).nansum().item() / all_num_chosen
|
| 1292 |
+
)
|
| 1293 |
+
self._metrics[mode]["logps/chosen"].append(
|
| 1294 |
+
self.accelerator.gather_for_metrics(chosen_logps_sum.nansum()).nansum().item() / all_num_chosen
|
| 1295 |
+
)
|
| 1296 |
+
self._metrics[mode]["logits/chosen"].append(
|
| 1297 |
+
self.accelerator.gather_for_metrics(chosen_logits_sum.nansum()).nansum().item() / all_num_chosen
|
| 1298 |
+
)
|
| 1299 |
+
|
| 1300 |
+
if all_num_rejected > 0:
|
| 1301 |
+
self._metrics[mode]["rewards/rejected"].append(
|
| 1302 |
+
self.accelerator.gather_for_metrics(rejected_rewards_sum.nansum()).nansum().item() / all_num_rejected
|
| 1303 |
+
)
|
| 1304 |
+
self._metrics[mode]["logps/rejected"].append(
|
| 1305 |
+
self.accelerator.gather_for_metrics(rejected_logps_sum.nansum()).nansum().item() / all_num_rejected
|
| 1306 |
+
)
|
| 1307 |
+
self._metrics[mode]["logits/rejected"].append(
|
| 1308 |
+
self.accelerator.gather_for_metrics(rejected_logits_sum.nansum()).nansum().item() / all_num_rejected
|
| 1309 |
+
)
|
| 1310 |
+
|
| 1311 |
+
if all_num_chosen > 0 and all_num_rejected > 0:
|
| 1312 |
+
self._metrics[mode]["rewards/margins"].append(
|
| 1313 |
+
self._metrics[mode]["rewards/chosen"][-1] - self._metrics[mode]["rewards/rejected"][-1]
|
| 1314 |
+
)
|
| 1315 |
+
|
| 1316 |
+
return loss
|
| 1317 |
+
|
| 1318 |
+
def _compute_loss(self, model, inputs, return_outputs):
|
| 1319 |
+
"""Compute the KTO loss and other metrics for the given batch of inputs for train or test."""
|
| 1320 |
+
mode = "train" if self.model.training else "eval"
|
| 1321 |
+
batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()}
|
| 1322 |
+
|
| 1323 |
+
labels = torch.tensor(batch["label"])
|
| 1324 |
+
num_chosen = labels.sum().to(self.accelerator.device)
|
| 1325 |
+
num_rejected = (len(labels) - num_chosen).to(self.accelerator.device)
|
| 1326 |
+
|
| 1327 |
+
policy_KL_logps = self._compute_kl_logps(model, batch)
|
| 1328 |
+
|
| 1329 |
+
_non_model_keys = {
|
| 1330 |
+
"completion_mask",
|
| 1331 |
+
"KL_input_ids",
|
| 1332 |
+
"KL_attention_mask",
|
| 1333 |
+
"KL_completion_mask",
|
| 1334 |
+
"KL_token_type_ids",
|
| 1335 |
+
"KL_mm_token_type_ids",
|
| 1336 |
+
"label",
|
| 1337 |
+
"ref_logps",
|
| 1338 |
+
"ref_KL_logps",
|
| 1339 |
+
}
|
| 1340 |
+
model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys}
|
| 1341 |
+
if self.aux_loss_enabled:
|
| 1342 |
+
model_kwargs["output_router_logits"] = True
|
| 1343 |
+
|
| 1344 |
+
outputs = model(**model_kwargs)
|
| 1345 |
+
if self.aux_loss_enabled:
|
| 1346 |
+
aux_loss = outputs.aux_loss
|
| 1347 |
+
|
| 1348 |
+
shift_logits = outputs.logits[:, :-1, :]
|
| 1349 |
+
per_token_logps = selective_log_softmax(shift_logits, batch["input_ids"][:, 1:])
|
| 1350 |
+
per_token_logps[batch["completion_mask"][:, 1:] == 0] = 0.0
|
| 1351 |
+
completion_logps = per_token_logps.sum(-1)
|
| 1352 |
+
|
| 1353 |
+
if completion_logps.shape[0] != len(batch["label"]):
|
| 1354 |
+
raise ValueError(
|
| 1355 |
+
"There is a mismatch between the number of examples in this batch and the number of "
|
| 1356 |
+
"examples for which an output sequence was predicted."
|
| 1357 |
+
)
|
| 1358 |
+
|
| 1359 |
+
device = outputs.logits.device
|
| 1360 |
+
bool_labels = torch.as_tensor(batch["label"], dtype=torch.bool, device=device)
|
| 1361 |
+
chosen_idx = torch.nonzero(bool_labels, as_tuple=False).view(-1)
|
| 1362 |
+
rejected_idx = torch.nonzero(~bool_labels, as_tuple=False).view(-1)
|
| 1363 |
+
|
| 1364 |
+
policy_chosen_logps = completion_logps.index_select(0, chosen_idx)
|
| 1365 |
+
policy_rejected_logps = completion_logps.index_select(0, rejected_idx)
|
| 1366 |
+
policy_chosen_logits = outputs.logits.index_select(0, chosen_idx)
|
| 1367 |
+
policy_rejected_logits = outputs.logits.index_select(0, rejected_idx)
|
| 1368 |
+
|
| 1369 |
+
if self.precompute_ref_logps:
|
| 1370 |
+
ref_chosen_logps = batch["ref_logps"].index_select(0, chosen_idx)
|
| 1371 |
+
ref_rejected_logps = batch["ref_logps"].index_select(0, rejected_idx)
|
| 1372 |
+
if self.calculate_KL:
|
| 1373 |
+
ref_KL_logps = batch["ref_KL_logps"]
|
| 1374 |
+
else:
|
| 1375 |
+
ref_KL_logps = None
|
| 1376 |
+
else:
|
| 1377 |
+
ref_model_kwargs = {k: v for k, v in model_kwargs.items() if k != "output_router_logits"}
|
| 1378 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 1379 |
+
if is_peft_model(self.model) and self.ref_model is None:
|
| 1380 |
+
ref_model_unwrapped = self.accelerator.unwrap_model(self.model)
|
| 1381 |
+
with use_adapter(
|
| 1382 |
+
ref_model_unwrapped, adapter_name="ref" if "ref" in ref_model_unwrapped.peft_config else None
|
| 1383 |
+
):
|
| 1384 |
+
ref_KL_logps = self._compute_kl_logps(self.model, batch)
|
| 1385 |
+
ref_outputs = self.model(**ref_model_kwargs)
|
| 1386 |
+
else:
|
| 1387 |
+
ref_KL_logps = self._compute_kl_logps(self.ref_model, batch)
|
| 1388 |
+
ref_outputs = self.ref_model(**ref_model_kwargs)
|
| 1389 |
+
ref_shift_logits = ref_outputs.logits[:, :-1, :]
|
| 1390 |
+
ref_per_token_logps = selective_log_softmax(ref_shift_logits, batch["input_ids"][:, 1:])
|
| 1391 |
+
ref_per_token_logps[batch["completion_mask"][:, 1:] == 0] = 0.0
|
| 1392 |
+
ref_completion_logps = ref_per_token_logps.sum(-1)
|
| 1393 |
+
ref_chosen_logps = ref_completion_logps.index_select(0, chosen_idx)
|
| 1394 |
+
ref_rejected_logps = ref_completion_logps.index_select(0, rejected_idx)
|
| 1395 |
+
|
| 1396 |
+
if self.calculate_KL:
|
| 1397 |
+
kl = (policy_KL_logps - ref_KL_logps).mean().detach()
|
| 1398 |
+
kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0)
|
| 1399 |
+
else:
|
| 1400 |
+
kl = torch.zeros(1).to(policy_chosen_logps.device)
|
| 1401 |
+
# Chosen losses
|
| 1402 |
+
if policy_chosen_logps.shape[0] != 0 or ref_chosen_logps.shape[0] != 0:
|
| 1403 |
+
chosen_logratios = policy_chosen_logps - ref_chosen_logps
|
| 1404 |
+
|
| 1405 |
+
if self.loss_type == "kto":
|
| 1406 |
+
# Eqn (7) of the KTO paper (https://huggingface.co/papers/2402.01306)
|
| 1407 |
+
chosen_losses = 1 - F.sigmoid(self.beta * (chosen_logratios - kl))
|
| 1408 |
+
elif self.loss_type == "apo_zero_unpaired":
|
| 1409 |
+
# Unpaired variant of Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266)
|
| 1410 |
+
# Use this loss when you believe the chosen outputs are better than your model's default output
|
| 1411 |
+
chosen_losses = 1 - F.sigmoid(self.beta * chosen_logratios)
|
| 1412 |
+
|
| 1413 |
+
chosen_rewards = self.beta * chosen_logratios.detach()
|
| 1414 |
+
|
| 1415 |
+
else:
|
| 1416 |
+
# lists can't be empty -- if they are, then accelerate.gather will hang
|
| 1417 |
+
chosen_losses = torch.Tensor([]).to(self.accelerator.device)
|
| 1418 |
+
chosen_rewards = torch.Tensor([]).to(self.accelerator.device)
|
| 1419 |
+
# Rejected losses
|
| 1420 |
+
if policy_rejected_logps.shape[0] != 0 or ref_rejected_logps.shape[0] != 0:
|
| 1421 |
+
rejected_logratios = policy_rejected_logps - ref_rejected_logps
|
| 1422 |
+
|
| 1423 |
+
if self.loss_type == "kto":
|
| 1424 |
+
rejected_losses = 1 - F.sigmoid(self.beta * (kl - rejected_logratios))
|
| 1425 |
+
elif self.loss_type == "apo_zero_unpaired":
|
| 1426 |
+
rejected_losses = F.sigmoid(self.beta * rejected_logratios)
|
| 1427 |
+
|
| 1428 |
+
rejected_rewards = self.beta * rejected_logratios.detach()
|
| 1429 |
+
else:
|
| 1430 |
+
# lists can't be empty -- if they are, then accelerate.gather will hang
|
| 1431 |
+
rejected_losses = torch.Tensor([]).to(self.accelerator.device)
|
| 1432 |
+
rejected_rewards = torch.Tensor([]).to(self.accelerator.device)
|
| 1433 |
+
losses = torch.cat(
|
| 1434 |
+
(self.desirable_weight * chosen_losses, self.undesirable_weight * rejected_losses),
|
| 1435 |
+
0,
|
| 1436 |
+
)
|
| 1437 |
+
|
| 1438 |
+
self._metrics[mode]["kl"].append(kl.item())
|
| 1439 |
+
|
| 1440 |
+
all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item()
|
| 1441 |
+
all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item()
|
| 1442 |
+
|
| 1443 |
+
if all_num_chosen > 0:
|
| 1444 |
+
self._metrics[mode]["rewards/chosen"].append(
|
| 1445 |
+
self.accelerator.gather_for_metrics(chosen_rewards.nansum()).nansum().item() / all_num_chosen
|
| 1446 |
+
)
|
| 1447 |
+
self._metrics[mode]["logps/chosen"].append(
|
| 1448 |
+
self.accelerator.gather_for_metrics(policy_chosen_logps.nansum()).nansum().item() / all_num_chosen
|
| 1449 |
+
)
|
| 1450 |
+
self._metrics[mode]["logits/chosen"].append(
|
| 1451 |
+
self.accelerator.gather_for_metrics(policy_chosen_logits.nansum()).nansum().item() / all_num_chosen
|
| 1452 |
+
)
|
| 1453 |
+
|
| 1454 |
+
if all_num_rejected > 0:
|
| 1455 |
+
self._metrics[mode]["rewards/rejected"].append(
|
| 1456 |
+
self.accelerator.gather_for_metrics(rejected_rewards.nansum()).nansum().item() / all_num_rejected
|
| 1457 |
+
)
|
| 1458 |
+
self._metrics[mode]["logps/rejected"].append(
|
| 1459 |
+
self.accelerator.gather_for_metrics(policy_rejected_logps.nansum()).nansum().item() / all_num_rejected
|
| 1460 |
+
)
|
| 1461 |
+
self._metrics[mode]["logits/rejected"].append(
|
| 1462 |
+
self.accelerator.gather_for_metrics(policy_rejected_logits.nansum()).nansum().item() / all_num_rejected
|
| 1463 |
+
)
|
| 1464 |
+
|
| 1465 |
+
if all_num_chosen > 0 and all_num_rejected > 0:
|
| 1466 |
+
self._metrics[mode]["rewards/margins"].append(
|
| 1467 |
+
self._metrics[mode]["rewards/chosen"][-1] - self._metrics[mode]["rewards/rejected"][-1]
|
| 1468 |
+
)
|
| 1469 |
+
|
| 1470 |
+
loss = losses.nanmean()
|
| 1471 |
+
if self.aux_loss_enabled:
|
| 1472 |
+
loss += self.aux_loss_coef * aux_loss
|
| 1473 |
+
|
| 1474 |
+
return (loss, outputs) if return_outputs else loss
|
| 1475 |
+
|
| 1476 |
+
def evaluate(
|
| 1477 |
+
self,
|
| 1478 |
+
eval_dataset: Dataset | dict[str, Dataset] | None = None,
|
| 1479 |
+
ignore_keys: list[str] | None = None,
|
| 1480 |
+
metric_key_prefix: str = "eval",
|
| 1481 |
+
) -> dict[str, float]:
|
| 1482 |
+
# When a dataset is passed directly to `evaluate` (e.g. a held-out test set), preprocess it the same way
|
| 1483 |
+
# `__init__` does, so that `evaluate` accepts the same dataset types as the trainer. `_prepare_dataset` is
|
| 1484 |
+
# idempotent: it skips datasets that are already tokenized. A `str` selects a dataset that was already prepared
|
| 1485 |
+
# at init time, so it's left untouched.
|
| 1486 |
+
if not self._is_vision_dataset and eval_dataset is not None and not isinstance(eval_dataset, str):
|
| 1487 |
+
if isinstance(eval_dataset, dict):
|
| 1488 |
+
eval_dataset = {
|
| 1489 |
+
key: self._prepare_dataset(dataset, self.processing_class, self.args, key)
|
| 1490 |
+
for key, dataset in eval_dataset.items()
|
| 1491 |
+
}
|
| 1492 |
+
else:
|
| 1493 |
+
eval_dataset = self._prepare_dataset(eval_dataset, self.processing_class, self.args, "eval")
|
| 1494 |
+
# With `precompute_ref_log_probs`, `_compute_loss` reads the reference log-probs from the batch, so they
|
| 1495 |
+
# must be precomputed here as well, mirroring `__init__`.
|
| 1496 |
+
if self.precompute_ref_logps:
|
| 1497 |
+
batch_size = self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size
|
| 1498 |
+
if isinstance(eval_dataset, dict):
|
| 1499 |
+
eval_dataset = {
|
| 1500 |
+
name: self._precompute_ref_logps(dataset, name, batch_size)
|
| 1501 |
+
for name, dataset in eval_dataset.items()
|
| 1502 |
+
}
|
| 1503 |
+
else:
|
| 1504 |
+
eval_dataset = self._precompute_ref_logps(eval_dataset, "eval", batch_size)
|
| 1505 |
+
return super().evaluate(
|
| 1506 |
+
eval_dataset=eval_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix
|
| 1507 |
+
)
|
| 1508 |
+
|
| 1509 |
+
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 1510 |
+
try:
|
| 1511 |
+
if self.use_liger_kernel:
|
| 1512 |
+
return self._compute_loss_liger(model, inputs, return_outputs)
|
| 1513 |
+
return self._compute_loss(model, inputs, return_outputs)
|
| 1514 |
+
except ValueError as e:
|
| 1515 |
+
if "Image features and image tokens do not match" in str(e) and self.args.max_length is not None:
|
| 1516 |
+
raise ValueError(
|
| 1517 |
+
f"The current `max_length` ({self.args.max_length}) is too short and causes image placeholder "
|
| 1518 |
+
f"tokens in `input_ids` to be truncated, while the corresponding image features remain intact. "
|
| 1519 |
+
f"Please increase `max_length` or set it to `None` to disable truncation."
|
| 1520 |
+
) from e
|
| 1521 |
+
raise
|
| 1522 |
+
|
| 1523 |
+
# Override training step to add activation offloading context.
|
| 1524 |
+
def training_step(self, *args, **kwargs):
|
| 1525 |
+
with self.maybe_activation_offload_context:
|
| 1526 |
+
return super().training_step(*args, **kwargs)
|
| 1527 |
+
|
| 1528 |
+
def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
|
| 1529 |
+
mode = "train" if self.model.training else "eval"
|
| 1530 |
+
metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics
|
| 1531 |
+
# This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
|
| 1532 |
+
# start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
|
| 1533 |
+
if mode == "eval":
|
| 1534 |
+
metrics = {f"eval_{key}": val for key, val in metrics.items()}
|
| 1535 |
+
logs.update(metrics)
|
| 1536 |
+
super().log(logs, start_time)
|
| 1537 |
+
self._metrics[mode].clear()
|
| 1538 |
+
|
| 1539 |
+
# During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and
|
| 1540 |
+
# returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels.
|
| 1541 |
+
def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None):
|
| 1542 |
+
inputs = self._prepare_inputs(inputs)
|
| 1543 |
+
with torch.no_grad(), self.compute_loss_context_manager():
|
| 1544 |
+
if prediction_loss_only:
|
| 1545 |
+
loss = self.compute_loss(model, inputs, return_outputs=False) # logits aren't materialized with liger
|
| 1546 |
+
logits, labels = None, None
|
| 1547 |
+
else:
|
| 1548 |
+
loss, outputs = self.compute_loss(model, inputs, return_outputs=True)
|
| 1549 |
+
logits, labels = outputs.logits, inputs["input_ids"]
|
| 1550 |
+
return loss, logits, labels
|
| 1551 |
+
|
| 1552 |
+
# Ensure the model card is saved along with the checkpoint
|
| 1553 |
+
def _save_checkpoint(self, model, trial):
|
| 1554 |
+
if self.args.hub_model_id is None:
|
| 1555 |
+
model_name = Path(self.args.output_dir).name
|
| 1556 |
+
else:
|
| 1557 |
+
model_name = self.args.hub_model_id.split("/")[-1]
|
| 1558 |
+
self.create_model_card(model_name=model_name)
|
| 1559 |
+
super()._save_checkpoint(model, trial)
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/merge_model_callback.py
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import os
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from huggingface_hub import HfApi
|
| 20 |
+
from transformers import TrainerCallback
|
| 21 |
+
|
| 22 |
+
from ..import_utils import is_mergekit_available
|
| 23 |
+
from ..trainer.utils import get_config_model_id
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if is_mergekit_available():
|
| 27 |
+
from mergekit.config import MergeConfiguration
|
| 28 |
+
from mergekit.merge import MergeOptions, run_merge
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Logger for module-level logging
|
| 32 |
+
logger = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def upload_model_to_hf(folder_path: str, repo_id: str):
|
| 36 |
+
api = HfApi()
|
| 37 |
+
# Create the repository if it doesn't exist
|
| 38 |
+
repo = api.create_repo(repo_id, repo_type="model")
|
| 39 |
+
|
| 40 |
+
# Upload the folder to the specified repository
|
| 41 |
+
api.upload_folder(
|
| 42 |
+
folder_path=folder_path,
|
| 43 |
+
repo_id=repo.repo_id,
|
| 44 |
+
repo_type=repo.repo_type,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class MergeConfig:
|
| 49 |
+
r"""
|
| 50 |
+
Configuration class for merging two models using `mergekit`.
|
| 51 |
+
|
| 52 |
+
This class provides a structured way to configure and generate merge configurations for various merge methods, such
|
| 53 |
+
as `linear`, `ties`, `dare_ties`, and `slerp`.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
method (`str`, *optional*, defaults to `"linear"`):
|
| 57 |
+
Merge method to use. Supported methods include:
|
| 58 |
+
|
| 59 |
+
- `"linear"`: Linearly combines two models with specified weights.
|
| 60 |
+
- `"ties"`: Combines two models using the TIES method with density parameters.
|
| 61 |
+
- `"dare_ties"`: A variant of TIES for domain adaptation.
|
| 62 |
+
- `"slerp"`: Combines models using spherical linear interpolation.
|
| 63 |
+
|
| 64 |
+
Note:
|
| 65 |
+
|
| 66 |
+
For more details about the merge methods and how they are implemented, see the [MergeKit GitHub
|
| 67 |
+
repository](https://github.com/arcee-ai/mergekit?tab=readme-ov-file#merge-methods).
|
| 68 |
+
|
| 69 |
+
Attributes:
|
| 70 |
+
method (`str`): The merge method to use.
|
| 71 |
+
policy_model_path (`str` or `None`): Path to the policy model.
|
| 72 |
+
target_model_path (`str` or `None`): Path to the target model.
|
| 73 |
+
policy_model_weight (`float`): Weight for the policy model (for `linear` and `ties` methods).
|
| 74 |
+
target_model_weight (`float`): Weight for the target model (for `linear` and `ties` methods).
|
| 75 |
+
policy_model_density (`list[float]`): Density parameters for the policy model (for `ties` and `dare_ties`).
|
| 76 |
+
target_model_density (`list[float]`): Density parameters for the target model (for `ties` and `dare_ties`).
|
| 77 |
+
normalize (`float` or `None`): Normalization factor for the TIES method.
|
| 78 |
+
t_values (`float` or `None`): Interpolation factor for the SLERP method.
|
| 79 |
+
dtype (`str`): Data type to use for merging, e.g., `"float16"`.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(self, method: str = "linear"):
|
| 83 |
+
if not is_mergekit_available():
|
| 84 |
+
raise ImportError("MergeConfig requires the `mergekit` extra. To install, run `pip install mergekit`.")
|
| 85 |
+
self.method = method
|
| 86 |
+
self.policy_model_path = None
|
| 87 |
+
self.target_model_path = None
|
| 88 |
+
|
| 89 |
+
# Initialize relevant parameters based on the method
|
| 90 |
+
if method == "linear":
|
| 91 |
+
self.policy_model_weight = 0.5
|
| 92 |
+
self.target_model_weight = 0.5
|
| 93 |
+
self.dtype = "float16"
|
| 94 |
+
elif method == "ties":
|
| 95 |
+
self.policy_model_weight = 1.0
|
| 96 |
+
self.policy_model_density = [1.0, 0.7, 0.1]
|
| 97 |
+
self.target_model_weight = 1.0
|
| 98 |
+
self.target_model_density = [1.0]
|
| 99 |
+
self.normalize = 1.0
|
| 100 |
+
self.dtype = "float16"
|
| 101 |
+
elif method == "dare_ties":
|
| 102 |
+
self.policy_model_weight = 1.0
|
| 103 |
+
self.policy_model_density = [1.0, 0.7, 0.1]
|
| 104 |
+
self.target_model_weight = 1.0
|
| 105 |
+
self.target_model_density = [1.0]
|
| 106 |
+
self.normalize = 1.0
|
| 107 |
+
self.dtype = "float16"
|
| 108 |
+
elif method == "slerp":
|
| 109 |
+
self.t_values = 0.5
|
| 110 |
+
self.dtype = "float16"
|
| 111 |
+
else:
|
| 112 |
+
raise ValueError(f"Unsupported merge method: {method}")
|
| 113 |
+
|
| 114 |
+
def create_merge_config_linear(self) -> "MergeConfiguration":
|
| 115 |
+
"""
|
| 116 |
+
Creates a merge configuration for a linear merge of two models with specified weights.
|
| 117 |
+
"""
|
| 118 |
+
# Create the merge configuration dictionary
|
| 119 |
+
merge_config_dict = {
|
| 120 |
+
"dtype": self.dtype,
|
| 121 |
+
"merge_method": "linear",
|
| 122 |
+
"models": [
|
| 123 |
+
{"model": self.policy_model_path, "parameters": {"weight": self.policy_model_weight}},
|
| 124 |
+
{"model": self.target_model_path, "parameters": {"weight": self.target_model_weight}},
|
| 125 |
+
],
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
# Create the MergeConfiguration from the dictionary
|
| 129 |
+
merge_config = MergeConfiguration.model_validate(merge_config_dict)
|
| 130 |
+
|
| 131 |
+
return merge_config
|
| 132 |
+
|
| 133 |
+
def create_merge_config_ties(self) -> "MergeConfiguration":
|
| 134 |
+
"""
|
| 135 |
+
Creates a merge configuration for a TIES merge of two models, with specified weights and densities.
|
| 136 |
+
"""
|
| 137 |
+
# Create the TIES merge configuration dictionary
|
| 138 |
+
merge_config_dict = {
|
| 139 |
+
"merge_method": "ties",
|
| 140 |
+
"slices": None, # Optional slices if needed
|
| 141 |
+
"models": [
|
| 142 |
+
{
|
| 143 |
+
"model": {
|
| 144 |
+
"model": {"path": self.target_model_path, "revision": None},
|
| 145 |
+
"lora": None,
|
| 146 |
+
"override_architecture": None,
|
| 147 |
+
},
|
| 148 |
+
"parameters": {"density": self.target_model_density, "weight": self.target_model_weight},
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"model": {
|
| 152 |
+
"model": {"path": self.policy_model_path, "revision": None},
|
| 153 |
+
"lora": None,
|
| 154 |
+
"override_architecture": None,
|
| 155 |
+
},
|
| 156 |
+
"parameters": {"density": self.policy_model_density, "weight": self.policy_model_weight},
|
| 157 |
+
},
|
| 158 |
+
],
|
| 159 |
+
"parameters": {"normalize": self.normalize},
|
| 160 |
+
"base_model": {
|
| 161 |
+
"model": {"path": self.policy_model_path, "revision": None},
|
| 162 |
+
"lora": None,
|
| 163 |
+
"override_architecture": None,
|
| 164 |
+
},
|
| 165 |
+
"dtype": self.dtype,
|
| 166 |
+
"tokenizer_source": None,
|
| 167 |
+
"tokenizer": None,
|
| 168 |
+
"chat_template": None,
|
| 169 |
+
"out_dtype": None,
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
# Create the MergeConfiguration from the dictionary
|
| 173 |
+
merge_config = MergeConfiguration.model_validate(merge_config_dict)
|
| 174 |
+
|
| 175 |
+
return merge_config
|
| 176 |
+
|
| 177 |
+
def create_merge_config_dare_ties(self) -> "MergeConfiguration":
|
| 178 |
+
"""
|
| 179 |
+
Creates a merge configuration for a DARE TIES merge of two models, with specified weights and densities.
|
| 180 |
+
"""
|
| 181 |
+
# Create the DARE TIES merge configuration dictionary
|
| 182 |
+
merge_config_dict = {
|
| 183 |
+
"merge_method": "dare_ties",
|
| 184 |
+
"slices": None, # Optional slices if needed
|
| 185 |
+
"models": [
|
| 186 |
+
{
|
| 187 |
+
"model": {
|
| 188 |
+
"model": {"path": self.target_model_path, "revision": None},
|
| 189 |
+
"lora": None,
|
| 190 |
+
"override_architecture": None,
|
| 191 |
+
},
|
| 192 |
+
"parameters": {"density": self.target_model_density, "weight": self.target_model_weight},
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"model": {
|
| 196 |
+
"model": {"path": self.policy_model_path, "revision": None},
|
| 197 |
+
"lora": None,
|
| 198 |
+
"override_architecture": None,
|
| 199 |
+
},
|
| 200 |
+
"parameters": {"density": self.policy_model_density, "weight": self.policy_model_weight},
|
| 201 |
+
},
|
| 202 |
+
],
|
| 203 |
+
"parameters": {"normalize": self.normalize},
|
| 204 |
+
"base_model": {
|
| 205 |
+
"model": {"path": self.policy_model_path, "revision": None},
|
| 206 |
+
"lora": None,
|
| 207 |
+
"override_architecture": None,
|
| 208 |
+
},
|
| 209 |
+
"dtype": self.dtype,
|
| 210 |
+
"tokenizer_source": None,
|
| 211 |
+
"tokenizer": None,
|
| 212 |
+
"chat_template": None,
|
| 213 |
+
"out_dtype": None,
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
# Create the MergeConfiguration from the dictionary
|
| 217 |
+
merge_config = MergeConfiguration.model_validate(merge_config_dict)
|
| 218 |
+
|
| 219 |
+
return merge_config
|
| 220 |
+
|
| 221 |
+
def create_merge_config_slerp(self) -> "MergeConfiguration":
|
| 222 |
+
"""
|
| 223 |
+
Creates a merge configuration for a SLERP merge of a model with a base model.
|
| 224 |
+
"""
|
| 225 |
+
|
| 226 |
+
# Create the SLERP merge configuration dictionary
|
| 227 |
+
merge_config_dict = {
|
| 228 |
+
"merge_method": "slerp",
|
| 229 |
+
"slices": None, # Optional slices if needed
|
| 230 |
+
"models": [
|
| 231 |
+
{
|
| 232 |
+
"model": {
|
| 233 |
+
"model": {"path": self.target_model_path, "revision": None},
|
| 234 |
+
"lora": None,
|
| 235 |
+
"override_architecture": None,
|
| 236 |
+
},
|
| 237 |
+
"parameters": None, # No specific parameters for SLERP model
|
| 238 |
+
}
|
| 239 |
+
],
|
| 240 |
+
"parameters": {
|
| 241 |
+
"t": self.t_values # Set the t values for SLERP
|
| 242 |
+
},
|
| 243 |
+
"base_model": {
|
| 244 |
+
"model": {"path": self.policy_model_path, "revision": None},
|
| 245 |
+
"lora": None,
|
| 246 |
+
"override_architecture": None,
|
| 247 |
+
},
|
| 248 |
+
"dtype": self.dtype,
|
| 249 |
+
"tokenizer_source": None,
|
| 250 |
+
"tokenizer": None,
|
| 251 |
+
"chat_template": None,
|
| 252 |
+
"out_dtype": None,
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
# Create the MergeConfiguration from the dictionary
|
| 256 |
+
merge_config = MergeConfiguration.model_validate(merge_config_dict)
|
| 257 |
+
|
| 258 |
+
return merge_config
|
| 259 |
+
|
| 260 |
+
def create(self) -> "MergeConfiguration":
|
| 261 |
+
if self.method == "linear":
|
| 262 |
+
return self.create_merge_config_linear()
|
| 263 |
+
elif self.method == "ties":
|
| 264 |
+
return self.create_merge_config_ties()
|
| 265 |
+
elif self.method == "dare_ties":
|
| 266 |
+
return self.create_merge_config_dare_ties()
|
| 267 |
+
elif self.method == "slerp":
|
| 268 |
+
return self.create_merge_config_slerp()
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def merge_models(config: "MergeConfiguration", out_path: str):
|
| 272 |
+
"""
|
| 273 |
+
Merge two models using mergekit
|
| 274 |
+
|
| 275 |
+
Args:
|
| 276 |
+
config (`MergeConfiguration`): The merge configuration.
|
| 277 |
+
out_path (`str`): The output path for the merged model.
|
| 278 |
+
"""
|
| 279 |
+
if not is_mergekit_available():
|
| 280 |
+
raise ImportError("merge_models requires the `mergekit` extra. To install, run `pip install mergekit`.")
|
| 281 |
+
run_merge(
|
| 282 |
+
config,
|
| 283 |
+
out_path=out_path,
|
| 284 |
+
options=MergeOptions(
|
| 285 |
+
device="auto",
|
| 286 |
+
cuda=torch.cuda.is_available(),
|
| 287 |
+
copy_tokenizer=True,
|
| 288 |
+
lazy_unpickle=False,
|
| 289 |
+
low_cpu_memory=False,
|
| 290 |
+
),
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class MergeModelCallback(TrainerCallback):
|
| 295 |
+
r"""
|
| 296 |
+
A [`~transformers.TrainerCallback`] that merges the policy model (the model being trained) with another model based
|
| 297 |
+
on a merge configuration.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
merge_config ([`experimental.merge_model_callback.MergeConfig`], *optional*):
|
| 301 |
+
Configuration used for the merging process. If not provided, the default
|
| 302 |
+
[`~experimental.merge_model_callback.MergeConfig`] is used.
|
| 303 |
+
merge_at_every_checkpoint (`bool`, *optional*, defaults to `False`):
|
| 304 |
+
Whether to merge the model at every checkpoint.
|
| 305 |
+
push_to_hub (`bool`, *optional*, defaults to `False`):
|
| 306 |
+
Whether to push the merged model to the Hub after merging.
|
| 307 |
+
|
| 308 |
+
Example:
|
| 309 |
+
|
| 310 |
+
```python
|
| 311 |
+
>>> from trl.experimental.merge_model_callback import MergeConfig, MergeModelCallback
|
| 312 |
+
|
| 313 |
+
>>> config = MergeConfig()
|
| 314 |
+
>>> merge_callback = MergeModelCallback(config)
|
| 315 |
+
>>> trainer = DPOTrainer(..., callbacks=[merge_callback])
|
| 316 |
+
```
|
| 317 |
+
"""
|
| 318 |
+
|
| 319 |
+
def __init__(
|
| 320 |
+
self,
|
| 321 |
+
merge_config: "MergeConfig | None" = None,
|
| 322 |
+
merge_at_every_checkpoint: bool = False,
|
| 323 |
+
push_to_hub: bool = False,
|
| 324 |
+
):
|
| 325 |
+
if not is_mergekit_available():
|
| 326 |
+
raise ImportError(
|
| 327 |
+
"MergeModelCallback requires the `mergekit` extra. To install, run `pip install mergekit`."
|
| 328 |
+
)
|
| 329 |
+
self.merge_config = merge_config or MergeConfig()
|
| 330 |
+
self.merge_at_every_checkpoint = merge_at_every_checkpoint
|
| 331 |
+
self.push_to_hub = push_to_hub
|
| 332 |
+
|
| 333 |
+
def _merge_and_maybe_push(self, output_dir, global_step, model):
|
| 334 |
+
checkpoint_path = os.path.join(output_dir, f"checkpoint-{global_step}")
|
| 335 |
+
self.merge_config.policy_model_path = checkpoint_path
|
| 336 |
+
if self.merge_config.target_model_path is None:
|
| 337 |
+
self.merge_config.target_model_path = get_config_model_id(model.config)
|
| 338 |
+
merge_path = os.path.join(checkpoint_path, "merged")
|
| 339 |
+
|
| 340 |
+
merge_models(self.merge_config.create(), merge_path)
|
| 341 |
+
|
| 342 |
+
if self.push_to_hub:
|
| 343 |
+
repo_name = f"{output_dir}_checkpoint-{global_step}_merged"
|
| 344 |
+
upload_model_to_hf(merge_path, repo_name)
|
| 345 |
+
|
| 346 |
+
def on_save(self, args, state, control, model=None, **kwargs):
|
| 347 |
+
if self.merge_at_every_checkpoint:
|
| 348 |
+
self._merge_and_maybe_push(args.output_dir, state.global_step, model)
|
| 349 |
+
|
| 350 |
+
def on_train_end(self, args, state, control, model=None, **kwargs):
|
| 351 |
+
if not self.merge_at_every_checkpoint:
|
| 352 |
+
self._merge_and_maybe_push(args.output_dir, state.global_step, model)
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/minillm/__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 .minillm_config import MiniLLMConfig
|
| 16 |
+
from .minillm_trainer import MiniLLMTrainer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = ["MiniLLMConfig", "MiniLLMTrainer"]
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/minillm/minillm_config.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from ...trainer.grpo_config import GRPOConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class MiniLLMConfig(GRPOConfig):
|
| 24 |
+
"""
|
| 25 |
+
Configuration class for [`MiniLLMTrainer`].
|
| 26 |
+
|
| 27 |
+
This class includes only the parameters that are specific to MiniLLM training. For a full list of training
|
| 28 |
+
arguments, please refer to the [`~transformers.TrainingArguments`] and [`GRPOConfig`] documentation.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
teacher_model_init_kwargs (`dict[str, Any]`, *optional*):
|
| 32 |
+
Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the teacher model
|
| 33 |
+
from a string.
|
| 34 |
+
disable_dropout (`bool`, *optional*, defaults to `True`):
|
| 35 |
+
Whether to disable dropout in the model.
|
| 36 |
+
rkl_advantage (`bool`, *optional*, defaults to `True`):
|
| 37 |
+
Whether to add the reverse KL advantage to the reward advantage.
|
| 38 |
+
single_step_decomposition (`bool`, *optional*, defaults to `True`):
|
| 39 |
+
Whether to use single-step decomposition for the KL divergence computation.
|
| 40 |
+
kd_temperature (`float`, *optional*, defaults to `1.0`):
|
| 41 |
+
Temperature for knowledge distillation. Higher temperatures produce softer probability distributions over
|
| 42 |
+
classes.
|
| 43 |
+
gamma (`float`, *optional*, defaults to `0.0`):
|
| 44 |
+
Discount factor for future rewards in reinforcement learning.
|
| 45 |
+
length_normalization (`bool`, *optional*, defaults to `True`):
|
| 46 |
+
Whether to apply length normalization to the rewards.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
_VALID_DICT_FIELDS = GRPOConfig._VALID_DICT_FIELDS + ["teacher_model_init_kwargs"]
|
| 50 |
+
|
| 51 |
+
teacher_model_init_kwargs: dict[str, Any] | str | None = field(
|
| 52 |
+
default=None,
|
| 53 |
+
metadata={
|
| 54 |
+
"help": "Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the "
|
| 55 |
+
"teacher model from a string."
|
| 56 |
+
},
|
| 57 |
+
)
|
| 58 |
+
disable_dropout: bool = field(
|
| 59 |
+
default=True,
|
| 60 |
+
metadata={"help": "Whether to disable dropouts in `model`."},
|
| 61 |
+
)
|
| 62 |
+
rkl_advantage: bool = field(
|
| 63 |
+
default=True,
|
| 64 |
+
metadata={"help": "Whether to add the reverse KL advantage to the reward advantage."},
|
| 65 |
+
)
|
| 66 |
+
single_step_decomposition: bool = field(
|
| 67 |
+
default=True,
|
| 68 |
+
metadata={"help": "Whether to use single-step decomposition for the KL divergence computation."},
|
| 69 |
+
)
|
| 70 |
+
kd_temperature: float = field(
|
| 71 |
+
default=1.0,
|
| 72 |
+
metadata={
|
| 73 |
+
"help": "Temperature for knowledge distillation. Higher temperatures produce softer probability "
|
| 74 |
+
"distributions over classes."
|
| 75 |
+
},
|
| 76 |
+
)
|
| 77 |
+
gamma: float = field(
|
| 78 |
+
default=0.0,
|
| 79 |
+
metadata={"help": "Discount factor for future rewards in reinforcement learning."},
|
| 80 |
+
)
|
| 81 |
+
length_normalization: bool = field(
|
| 82 |
+
default=True,
|
| 83 |
+
metadata={"help": "Whether to apply length normalization to the rewards."},
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
def __post_init__(self):
|
| 87 |
+
# We do not use the post_init of GRPOConfig because:
|
| 88 |
+
# 1. num_generations can be < 2 in MiniLLMConfig. Scale_rewards must be set to "none" to avoid nan.
|
| 89 |
+
_BaseConfig.__post_init__(self)
|
| 90 |
+
|
| 91 |
+
self.scale_rewards = {True: "group", False: "none"}.get(self.scale_rewards, self.scale_rewards)
|
| 92 |
+
if self.num_generations == 1:
|
| 93 |
+
self.scale_rewards = "none"
|
| 94 |
+
|
| 95 |
+
num_processes = self.world_size
|
| 96 |
+
# The current default effective batch size
|
| 97 |
+
if self.generation_batch_size is None and self.steps_per_generation is None:
|
| 98 |
+
self.steps_per_generation = self.gradient_accumulation_steps
|
| 99 |
+
self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
|
| 100 |
+
elif self.generation_batch_size is not None and self.steps_per_generation is None:
|
| 101 |
+
# Just ensure the value is divisible by the global batch size
|
| 102 |
+
if self.generation_batch_size % (self.per_device_train_batch_size * num_processes) != 0:
|
| 103 |
+
raise ValueError(
|
| 104 |
+
f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size "
|
| 105 |
+
f"({self.per_device_train_batch_size * num_processes})."
|
| 106 |
+
)
|
| 107 |
+
self.steps_per_generation = self.generation_batch_size // (
|
| 108 |
+
self.per_device_train_batch_size * num_processes
|
| 109 |
+
)
|
| 110 |
+
elif self.generation_batch_size is None and self.steps_per_generation is not None:
|
| 111 |
+
self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
|
| 112 |
+
else:
|
| 113 |
+
raise ValueError(
|
| 114 |
+
"'generation_batch_size' and 'steps_per_generation' can not be both configured at the same time"
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
if self.do_eval and self.eval_strategy != "no":
|
| 118 |
+
# Determine the number of generations to use for evaluation
|
| 119 |
+
num_generations = self.num_generations_eval or self.num_generations
|
| 120 |
+
|
| 121 |
+
# Just ensure the value is divisible by the global batch size
|
| 122 |
+
if (self.per_device_eval_batch_size * num_processes) % num_generations != 0:
|
| 123 |
+
raise ValueError(
|
| 124 |
+
f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be "
|
| 125 |
+
f"divisible by the number of generations used for evaluation ({num_generations})."
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
# The generation batch must contain full prompt groups (no partials), so it must be divisible by
|
| 129 |
+
# num_generations.
|
| 130 |
+
if self.generation_batch_size % self.num_generations != 0:
|
| 131 |
+
raise ValueError(
|
| 132 |
+
f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations "
|
| 133 |
+
f"({self.num_generations})."
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
if self.delta is not None and self.use_liger_kernel:
|
| 137 |
+
raise ValueError("Liger kernel does not support two-sided GRPO loss yet.")
|
tasks/tasksmith-150751b5c0ba/environment/source/trl/experimental/minillm/minillm_trainer.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-150751b5c0ba/environment/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-150751b5c0ba/environment/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-150751b5c0ba/environment/source/trl/experimental/nash_md/nash_md_trainer.py
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
# 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-150751b5c0ba/environment/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-150751b5c0ba/environment/source/trl/experimental/online_dpo/online_dpo_config.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-150751b5c0ba/environment/source/trl/experimental/online_dpo/online_dpo_trainer.py
ADDED
|
@@ -0,0 +1,1357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 Version(transformers.__version__) >= Version("5.2.0"):
|
| 63 |
+
from transformers.trainer_pt_utils import nested_gather
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if is_bitsandbytes_available():
|
| 67 |
+
import bitsandbytes as bnb
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
if is_peft_available():
|
| 71 |
+
from peft import PeftConfig
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
if is_sagemaker_mp_enabled():
|
| 75 |
+
from smdistributed.modelparallel import __version__ as SMP_VERSION
|
| 76 |
+
|
| 77 |
+
IS_SAGEMAKER_MP_POST_1_10 = Version(SMP_VERSION) >= Version("1.10")
|
| 78 |
+
|
| 79 |
+
else:
|
| 80 |
+
IS_SAGEMAKER_MP_POST_1_10 = False
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
if is_vllm_available():
|
| 84 |
+
from vllm import LLM, SamplingParams
|
| 85 |
+
from vllm.sampling_params import StructuredOutputsParams
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
logger = get_logger(__name__)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# A reward function can be a string, interpreted as a model ID and loaded as a pretrained model, a pretrained model, or
|
| 92 |
+
# a callable that returns a list of floats (the rewards). The callable receives prompts, completions, and additional
|
| 93 |
+
# arguments from the trainer (refer to the trainer's source for details). To ensure forward compatibility, it should
|
| 94 |
+
# accept **kwargs.
|
| 95 |
+
RewardFunc = str | PreTrainedModel | Callable[..., list[float | None]]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class OnlineDPOTrainer(_BaseTrainer):
|
| 99 |
+
r"""
|
| 100 |
+
Initialize OnlineDPOTrainer.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
model (`str | nn.Module | PreTrainedModel`):
|
| 104 |
+
Model to be trained. Can be either:
|
| 105 |
+
|
| 106 |
+
- A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
|
| 107 |
+
path to a *directory* containing model weights saved using
|
| 108 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
| 109 |
+
using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in
|
| 110 |
+
`args.model_init_kwargs`.
|
| 111 |
+
- A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
|
| 112 |
+
ref_model ([`~transformers.PreTrainedModel`] or `torch.nn.Module` or `None`):
|
| 113 |
+
The reference model to use for training. If None is specified, the reference model will be created from the
|
| 114 |
+
model.
|
| 115 |
+
reward_funcs (`RewardFunc | list[RewardFunc]`):
|
| 116 |
+
Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
|
| 117 |
+
functions with the prompts and completions and sum the rewards. Can be either:
|
| 118 |
+
|
| 119 |
+
- A single reward function: Can be a string (path to model), a [`~transformers.PreTrainedModel`], or a
|
| 120 |
+
custom callable function.
|
| 121 |
+
- A list of reward functions: Must all be of compatible types.
|
| 122 |
+
args ([`experimental.online_dpo.OnlineDPOConfig`]):
|
| 123 |
+
The online DPO 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`] or [`~datasets.IterableDataset`]):
|
| 129 |
+
The dataset to use for training.
|
| 130 |
+
eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
|
| 131 |
+
The dataset to use for evaluation.
|
| 132 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`] 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 |
+
reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*):
|
| 137 |
+
Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
|
| 138 |
+
|
| 139 |
+
- A single processing class: Used when `reward_funcs` contains only one reward function.
|
| 140 |
+
- A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
|
| 141 |
+
|
| 142 |
+
If set to `None`, the tokenizer for each model-based reward function is automatically loaded using
|
| 143 |
+
[`~transformers.AutoTokenizer.from_pretrained`].
|
| 144 |
+
peft_config ([`~peft.PeftConfig`], *optional*):
|
| 145 |
+
PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
|
| 146 |
+
compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
|
| 147 |
+
The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
|
| 148 |
+
metric values.
|
| 149 |
+
callbacks (`list[transformers.TrainerCallback]`):
|
| 150 |
+
The callbacks to use for training.
|
| 151 |
+
optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
|
| 152 |
+
The optimizer and scheduler to use for training.
|
| 153 |
+
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
|
| 154 |
+
The function to use to preprocess the logits before computing the metrics.
|
| 155 |
+
"""
|
| 156 |
+
|
| 157 |
+
_tag_names = ["trl", "online-dpo"]
|
| 158 |
+
_name = "Online DPO"
|
| 159 |
+
_paper = {
|
| 160 |
+
"title": "Direct Language Model Alignment from Online AI Feedback",
|
| 161 |
+
"id": "2402.04792",
|
| 162 |
+
# docstyle-ignore
|
| 163 |
+
"citation": textwrap.dedent("""\
|
| 164 |
+
@article{guo2024direct,
|
| 165 |
+
title = {{Direct Language Model Alignment from Online AI Feedback}},
|
| 166 |
+
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},
|
| 167 |
+
year = 2024,
|
| 168 |
+
eprint = {arXiv:2402.04792}
|
| 169 |
+
}"""),
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
def __init__(
|
| 173 |
+
self,
|
| 174 |
+
model: PreTrainedModel | nn.Module | str,
|
| 175 |
+
ref_model: PreTrainedModel | nn.Module | None = None,
|
| 176 |
+
reward_funcs: RewardFunc | list[RewardFunc] | None = None,
|
| 177 |
+
args: OnlineDPOConfig | None = None,
|
| 178 |
+
data_collator: DataCollator | None = None,
|
| 179 |
+
train_dataset: Dataset | IterableDataset | None = None,
|
| 180 |
+
eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
|
| 181 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
|
| 182 |
+
reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
|
| 183 |
+
peft_config: "PeftConfig | None" = None,
|
| 184 |
+
compute_metrics: Callable[[EvalPrediction], dict] | None = None,
|
| 185 |
+
callbacks: list[TrainerCallback] | None = None,
|
| 186 |
+
optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
|
| 187 |
+
preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
|
| 188 |
+
) -> None:
|
| 189 |
+
if train_dataset is None:
|
| 190 |
+
raise ValueError("`train_dataset` is required")
|
| 191 |
+
|
| 192 |
+
if ref_model is model:
|
| 193 |
+
raise ValueError(
|
| 194 |
+
"`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the "
|
| 195 |
+
"same as `model`, either omit the `ref_model` argument or pass `None`."
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
self.ref_model = ref_model
|
| 199 |
+
|
| 200 |
+
if reward_funcs is None:
|
| 201 |
+
raise ValueError("`reward_funcs` must be provided.")
|
| 202 |
+
|
| 203 |
+
# Handle reward_funcs
|
| 204 |
+
if not isinstance(reward_funcs, list):
|
| 205 |
+
reward_funcs = [reward_funcs]
|
| 206 |
+
self.reward_func_names = []
|
| 207 |
+
|
| 208 |
+
# Process reward functions (convert strings to models, collect names)
|
| 209 |
+
model_init_kwargs = args.model_init_kwargs or {}
|
| 210 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 211 |
+
for i, reward_func in enumerate(reward_funcs):
|
| 212 |
+
if isinstance(reward_func, str):
|
| 213 |
+
# Load model from string path
|
| 214 |
+
reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained(
|
| 215 |
+
reward_func, num_labels=1, **model_init_kwargs
|
| 216 |
+
)
|
| 217 |
+
if isinstance(reward_funcs[i], nn.Module):
|
| 218 |
+
self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1])
|
| 219 |
+
else:
|
| 220 |
+
self.reward_func_names.append(reward_funcs[i].__name__)
|
| 221 |
+
self.reward_funcs = reward_funcs
|
| 222 |
+
|
| 223 |
+
# Handle reward processing classes for reward_funcs
|
| 224 |
+
if reward_processing_classes is None:
|
| 225 |
+
reward_processing_classes = [None] * len(reward_funcs)
|
| 226 |
+
elif not isinstance(reward_processing_classes, list):
|
| 227 |
+
reward_processing_classes = [reward_processing_classes]
|
| 228 |
+
else:
|
| 229 |
+
if len(reward_processing_classes) != len(reward_funcs):
|
| 230 |
+
raise ValueError("The number of reward processing classes must match the number of reward functions.")
|
| 231 |
+
|
| 232 |
+
self.reward_processing_classes = []
|
| 233 |
+
for reward_processing_class_i, reward_func in zip(reward_processing_classes, reward_funcs, strict=True):
|
| 234 |
+
if isinstance(reward_func, PreTrainedModel):
|
| 235 |
+
if reward_processing_class_i is None:
|
| 236 |
+
reward_processing_class_i = AutoTokenizer.from_pretrained(
|
| 237 |
+
reward_func.config._name_or_path, trust_remote_code=args.trust_remote_code
|
| 238 |
+
)
|
| 239 |
+
if reward_processing_class_i.pad_token_id is None:
|
| 240 |
+
reward_processing_class_i.pad_token = reward_processing_class_i.eos_token
|
| 241 |
+
# Set pad token ID on reward model config
|
| 242 |
+
reward_func.config.pad_token_id = reward_processing_class_i.pad_token_id
|
| 243 |
+
self.reward_processing_classes.append(reward_processing_class_i)
|
| 244 |
+
|
| 245 |
+
# Handle reward_weights
|
| 246 |
+
if args.reward_weights is not None:
|
| 247 |
+
if len(args.reward_weights) != len(self.reward_funcs):
|
| 248 |
+
raise ValueError(
|
| 249 |
+
f"Number of reward weights ({len(args.reward_weights)}) must match number of reward "
|
| 250 |
+
f"functions ({len(self.reward_funcs)})"
|
| 251 |
+
)
|
| 252 |
+
self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32)
|
| 253 |
+
else:
|
| 254 |
+
self.reward_weights = torch.ones(len(self.reward_funcs), dtype=torch.float32)
|
| 255 |
+
|
| 256 |
+
if args is None:
|
| 257 |
+
raise ValueError("`args` must be provided.")
|
| 258 |
+
|
| 259 |
+
# Check that the processing_class is provided
|
| 260 |
+
if processing_class is None:
|
| 261 |
+
raise ValueError("`processing_class` must be provided.")
|
| 262 |
+
|
| 263 |
+
model_init_kwargs = args.model_init_kwargs or {}
|
| 264 |
+
if isinstance(model, str):
|
| 265 |
+
model_id = model
|
| 266 |
+
|
| 267 |
+
# Handle dtype in model_init_kwargs
|
| 268 |
+
dtype = model_init_kwargs.get("dtype", "auto")
|
| 269 |
+
if isinstance(dtype, torch.dtype) or dtype == "auto" or dtype is None:
|
| 270 |
+
pass
|
| 271 |
+
elif isinstance(dtype, str):
|
| 272 |
+
dtype = getattr(torch, dtype)
|
| 273 |
+
model_init_kwargs["dtype"] = dtype
|
| 274 |
+
else:
|
| 275 |
+
raise ValueError(
|
| 276 |
+
"Invalid `dtype` passed to `OnlineDPOConfig`. Expected either 'auto' or a string "
|
| 277 |
+
f"representing a `torch.dtype` (e.g., 'float32'), but got {dtype}."
|
| 278 |
+
)
|
| 279 |
+
model_init_kwargs["device_map"] = model_init_kwargs.get("device_map", "auto")
|
| 280 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 281 |
+
|
| 282 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, **model_init_kwargs)
|
| 283 |
+
else:
|
| 284 |
+
if args.model_init_kwargs is not None:
|
| 285 |
+
raise ValueError(
|
| 286 |
+
"You passed `model_init_kwargs` to the `OnlineDPOConfig`, but your model is already instantiated. "
|
| 287 |
+
"This argument can only be used when the `model` argument is a string."
|
| 288 |
+
)
|
| 289 |
+
self.is_encoder_decoder = model.config.is_encoder_decoder
|
| 290 |
+
self.is_vision_model = model.config.model_type in MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES.keys()
|
| 291 |
+
|
| 292 |
+
# PEFT
|
| 293 |
+
if peft_config is not None:
|
| 294 |
+
if not is_peft_available():
|
| 295 |
+
raise ImportError(
|
| 296 |
+
"You passed `peft_config` but the `peft` library is not installed. "
|
| 297 |
+
"Install it with `pip install trl[peft]`."
|
| 298 |
+
)
|
| 299 |
+
if not isinstance(peft_config, PeftConfig):
|
| 300 |
+
raise TypeError(
|
| 301 |
+
f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
|
| 302 |
+
f"got {type(peft_config).__name__}."
|
| 303 |
+
)
|
| 304 |
+
if peft_config is not None or is_peft_model(model):
|
| 305 |
+
model = prepare_peft_model(model, peft_config, args)
|
| 306 |
+
|
| 307 |
+
# Enable gradient checkpointing if requested
|
| 308 |
+
if args.gradient_checkpointing:
|
| 309 |
+
model = self._enable_gradient_checkpointing(model, args)
|
| 310 |
+
|
| 311 |
+
# Disable dropout in the model and reference model
|
| 312 |
+
if args.disable_dropout:
|
| 313 |
+
disable_dropout_in_model(model)
|
| 314 |
+
if self.ref_model is not None:
|
| 315 |
+
disable_dropout_in_model(self.ref_model)
|
| 316 |
+
|
| 317 |
+
# Handle the ref_model
|
| 318 |
+
# Usually, the user wants the ref model to be the initial version of the model. When using PEFT, it's easy to
|
| 319 |
+
# get the ref model, as it's just the model with a disabled adapter. When not using PEFT, we need to create
|
| 320 |
+
# the ref model from the model by copying it and disable the gradients and set it in evaluation mode.
|
| 321 |
+
if ref_model is None: # No ref model provided, the most common case
|
| 322 |
+
if peft_config is None:
|
| 323 |
+
self.ref_model = create_reference_model(model) # copy, disable gradients, set eval mode
|
| 324 |
+
else:
|
| 325 |
+
self.ref_model = None # we don't need a ref model here, we can just disable the adapter.
|
| 326 |
+
else: # rare case, the user provided a ref model
|
| 327 |
+
self.ref_model = ref_model
|
| 328 |
+
self.ref_model.eval()
|
| 329 |
+
|
| 330 |
+
# Disable the gradient and set the reward model in eval mode
|
| 331 |
+
if reward_funcs is not None:
|
| 332 |
+
for reward_func in reward_funcs:
|
| 333 |
+
if isinstance(reward_func, PreTrainedModel):
|
| 334 |
+
reward_func.eval()
|
| 335 |
+
|
| 336 |
+
self.max_length = args.max_length
|
| 337 |
+
|
| 338 |
+
self.stats = {
|
| 339 |
+
"objective/kl": [],
|
| 340 |
+
"objective/entropy": [],
|
| 341 |
+
"objective/non_score_reward": [],
|
| 342 |
+
"rewards/chosen": [],
|
| 343 |
+
"rewards/rejected": [],
|
| 344 |
+
"rewards/accuracies": [],
|
| 345 |
+
"rewards/margins": [],
|
| 346 |
+
"logps/chosen": [],
|
| 347 |
+
"logps/rejected": [],
|
| 348 |
+
"val/contain_eos_token": [],
|
| 349 |
+
"beta": [],
|
| 350 |
+
}
|
| 351 |
+
if self.reward_funcs is not None:
|
| 352 |
+
self.stats["objective/rlhf_reward"] = []
|
| 353 |
+
self.stats["objective/scores_margin"] = []
|
| 354 |
+
self.stats["objective/scores"] = []
|
| 355 |
+
|
| 356 |
+
# Store generation parameters for later use
|
| 357 |
+
self.use_vllm = args.use_vllm
|
| 358 |
+
self.num_generations = 2 # Generate 2 completions per prompt for Online DPO
|
| 359 |
+
self.temperature = args.temperature
|
| 360 |
+
self.top_p = args.top_p
|
| 361 |
+
self.top_k = args.top_k
|
| 362 |
+
self.min_p = args.min_p
|
| 363 |
+
self.repetition_penalty = args.repetition_penalty
|
| 364 |
+
self.vllm_mode = args.vllm_mode if args.use_vllm else None
|
| 365 |
+
self.vllm_gpu_memory_utilization = args.vllm_gpu_memory_utilization
|
| 366 |
+
self.vllm_tensor_parallel_size = args.vllm_tensor_parallel_size
|
| 367 |
+
self.vllm_model_impl = args.vllm_model_impl
|
| 368 |
+
|
| 369 |
+
# Handle pad token for processors or tokenizers
|
| 370 |
+
if isinstance(processing_class, ProcessorMixin):
|
| 371 |
+
self._tokenizer = processing_class.tokenizer
|
| 372 |
+
elif isinstance(processing_class, PreTrainedTokenizerBase):
|
| 373 |
+
self._tokenizer = processing_class
|
| 374 |
+
else:
|
| 375 |
+
raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
|
| 376 |
+
|
| 377 |
+
if self._tokenizer.pad_token is None:
|
| 378 |
+
self._tokenizer.pad_token = self._tokenizer.eos_token
|
| 379 |
+
|
| 380 |
+
# Vision tokens for VLM support
|
| 381 |
+
self.image_token_id = getattr(processing_class, "image_token_id", None)
|
| 382 |
+
self.vision_start_token_id = getattr(processing_class, "vision_start_token_id", None)
|
| 383 |
+
self.vision_end_token_id = getattr(processing_class, "vision_end_token_id", None)
|
| 384 |
+
# Get the image token string for token collapsing
|
| 385 |
+
self.image_token = None
|
| 386 |
+
if self.image_token_id is not None:
|
| 387 |
+
self.image_token = self._tokenizer.decode([self.image_token_id])
|
| 388 |
+
|
| 389 |
+
# Define the collator if not provided
|
| 390 |
+
if data_collator is None:
|
| 391 |
+
data_collator = DPODataCollatorWithPadding(pad_token_id=self._tokenizer.pad_token_id)
|
| 392 |
+
|
| 393 |
+
# Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
|
| 394 |
+
# never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
|
| 395 |
+
# (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
|
| 396 |
+
# default to the recommended non-reentrant behavior here, while preserving any user-provided value.
|
| 397 |
+
if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
|
| 398 |
+
args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
|
| 399 |
+
args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
|
| 400 |
+
|
| 401 |
+
super().__init__(
|
| 402 |
+
model=model,
|
| 403 |
+
args=args,
|
| 404 |
+
data_collator=data_collator,
|
| 405 |
+
train_dataset=train_dataset,
|
| 406 |
+
eval_dataset=eval_dataset,
|
| 407 |
+
processing_class=processing_class,
|
| 408 |
+
compute_metrics=compute_metrics,
|
| 409 |
+
callbacks=callbacks,
|
| 410 |
+
optimizers=optimizers,
|
| 411 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
# Add tags for models that have been loaded with the correct transformers version
|
| 415 |
+
if hasattr(self.model, "add_model_tags"):
|
| 416 |
+
self.model.add_model_tags(self._tag_names)
|
| 417 |
+
|
| 418 |
+
self._beta = args.beta
|
| 419 |
+
|
| 420 |
+
# Set up generation configuration and vLLM after super().__init__
|
| 421 |
+
if self.use_vllm:
|
| 422 |
+
if not is_vllm_available():
|
| 423 |
+
raise ImportError(
|
| 424 |
+
"vLLM is not available and `use_vllm` is set to True. Please install vLLM with "
|
| 425 |
+
"`pip install trl[vllm]` to use it."
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
if self.vllm_mode == "server":
|
| 429 |
+
if self.accelerator.is_main_process:
|
| 430 |
+
if args.vllm_server_base_url is not None:
|
| 431 |
+
base_url = args.vllm_server_base_url
|
| 432 |
+
else:
|
| 433 |
+
base_url = f"http://{args.vllm_server_host}:{args.vllm_server_port}"
|
| 434 |
+
self.vllm_client = VLLMClient(
|
| 435 |
+
base_url=base_url, group_port=args.vllm_group_port, connection_timeout=args.vllm_server_timeout
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
# Determine device type (supports cuda, xpu, etc.)
|
| 439 |
+
accelerator_type = torch.accelerator.current_accelerator().type
|
| 440 |
+
current_device = getattr(torch, accelerator_type).current_device()
|
| 441 |
+
self.vllm_client.init_communicator(device=current_device)
|
| 442 |
+
else:
|
| 443 |
+
self.vllm_client = None
|
| 444 |
+
elif self.vllm_mode == "colocate":
|
| 445 |
+
# vLLM dynamically adjusts the size of the key-value cache based on available GPU memory at instantiation.
|
| 446 |
+
# A larger cache size improves speed, so we would expect gpu_memory_utilization=1.
|
| 447 |
+
# However, at this stage, the optimizer's weights are not yet loaded onto the GPU; they will be loaded
|
| 448 |
+
# after the first optimizer step and remain in GPU memory throughout training. So we must reserve enough
|
| 449 |
+
# space for them.
|
| 450 |
+
# Configure vLLM parameters
|
| 451 |
+
vllm_quantization = None
|
| 452 |
+
if is_bitsandbytes_available():
|
| 453 |
+
for _, module in model.named_modules():
|
| 454 |
+
if isinstance(module, bnb.nn.Linear4bit):
|
| 455 |
+
vllm_quantization = "bitsandbytes"
|
| 456 |
+
break
|
| 457 |
+
elif isinstance(module, bnb.nn.Linear8bitLt):
|
| 458 |
+
raise ValueError("vLLM does not support in-flight 8-bit quantization.")
|
| 459 |
+
vllm_kwargs = {
|
| 460 |
+
"model": model.name_or_path,
|
| 461 |
+
"tensor_parallel_size": self.vllm_tensor_parallel_size,
|
| 462 |
+
"gpu_memory_utilization": self.vllm_gpu_memory_utilization,
|
| 463 |
+
"model_impl": self.vllm_model_impl,
|
| 464 |
+
"max_num_seqs": self.args.per_device_train_batch_size * self.vllm_tensor_parallel_size,
|
| 465 |
+
"max_model_len": args.max_length + args.max_new_tokens, # max_length includes prompt + completion
|
| 466 |
+
"distributed_executor_backend": "external_launcher",
|
| 467 |
+
# Feed identical seed for tp groups to ensure sampling results are the same across workers
|
| 468 |
+
"seed": self.accelerator.process_index // self.vllm_tensor_parallel_size,
|
| 469 |
+
# Latest vLLM v1 memory profiler is misled by the high default value (i.e., 32768)
|
| 470 |
+
"max_num_batched_tokens": 4096,
|
| 471 |
+
"enable_sleep_mode": self.args.vllm_enable_sleep_mode,
|
| 472 |
+
"quantization": vllm_quantization,
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
# vLLM requires the environment variables to be set for distributed training.
|
| 476 |
+
os.environ["RANK"] = str(self.accelerator.process_index)
|
| 477 |
+
os.environ["LOCAL_RANK"] = str(self.accelerator.local_process_index)
|
| 478 |
+
os.environ["WORLD_SIZE"] = str(self.accelerator.num_processes)
|
| 479 |
+
# Ensure distributed rendezvous variables are set without colliding across concurrent runs
|
| 480 |
+
ensure_master_addr_port()
|
| 481 |
+
|
| 482 |
+
self.llm = LLM(**vllm_kwargs)
|
| 483 |
+
if self.args.vllm_enable_sleep_mode:
|
| 484 |
+
self.llm.sleep(level=2)
|
| 485 |
+
else:
|
| 486 |
+
raise ValueError(f"vllm_mode must be either 'server' or 'colocate', got '{self.vllm_mode}'.")
|
| 487 |
+
# vLLM specific sampling arguments
|
| 488 |
+
self.structured_outputs_regex = args.vllm_structured_outputs_regex
|
| 489 |
+
self._last_loaded_step = -1 # tag to avoid useless loading during grad accumulation
|
| 490 |
+
|
| 491 |
+
# Set up vLLM generation config
|
| 492 |
+
generation_kwargs = {
|
| 493 |
+
"n": 2, # 2 generations per prompt for Online DPO
|
| 494 |
+
"repetition_penalty": self.repetition_penalty,
|
| 495 |
+
"temperature": self.temperature,
|
| 496 |
+
"top_p": self.top_p,
|
| 497 |
+
"top_k": self.top_k,
|
| 498 |
+
"min_p": 0.0 if self.min_p is None else self.min_p,
|
| 499 |
+
"max_tokens": args.max_new_tokens,
|
| 500 |
+
"detokenize": False, # to avoid vllm to decode (we don't need it)
|
| 501 |
+
}
|
| 502 |
+
if args.generation_kwargs is not None:
|
| 503 |
+
generation_kwargs.update(args.generation_kwargs)
|
| 504 |
+
if self.structured_outputs_regex is not None:
|
| 505 |
+
if generation_kwargs.get("structured_outputs") is not None:
|
| 506 |
+
logger.warning(
|
| 507 |
+
"Both `vllm_structured_outputs_regex` and `generation_kwargs['structured_outputs']` are set; "
|
| 508 |
+
"`vllm_structured_outputs_regex` takes precedence."
|
| 509 |
+
)
|
| 510 |
+
generation_kwargs["structured_outputs"] = StructuredOutputsParams(regex=self.structured_outputs_regex)
|
| 511 |
+
elif isinstance(structured_outputs_kwargs := generation_kwargs.get("structured_outputs"), dict):
|
| 512 |
+
generation_kwargs["structured_outputs"] = StructuredOutputsParams(**structured_outputs_kwargs)
|
| 513 |
+
self.generation_config = SamplingParams(**generation_kwargs)
|
| 514 |
+
|
| 515 |
+
# When using vLLM, the main process is responsible for loading the model weights. This can cause process
|
| 516 |
+
# desynchronization and seems to lead to DeepSpeed hanging during initialization. To prevent this, we
|
| 517 |
+
# synchronize all processes after vLLM has been fully initialized.
|
| 518 |
+
self.accelerator.wait_for_everyone()
|
| 519 |
+
else:
|
| 520 |
+
# Set up transformers generation config
|
| 521 |
+
generation_kwargs = {
|
| 522 |
+
"max_new_tokens": args.max_new_tokens,
|
| 523 |
+
"do_sample": True,
|
| 524 |
+
"pad_token_id": self._tokenizer.pad_token_id,
|
| 525 |
+
"bos_token_id": self._tokenizer.bos_token_id,
|
| 526 |
+
"eos_token_id": self._tokenizer.eos_token_id,
|
| 527 |
+
"temperature": self.temperature,
|
| 528 |
+
"top_k": self.top_k,
|
| 529 |
+
"top_p": self.top_p,
|
| 530 |
+
"repetition_penalty": self.repetition_penalty,
|
| 531 |
+
"use_cache": True if not self.args.gradient_checkpointing else False,
|
| 532 |
+
}
|
| 533 |
+
# Add min_p if supported
|
| 534 |
+
if self.min_p is not None:
|
| 535 |
+
generation_kwargs["min_p"] = self.min_p
|
| 536 |
+
if args.generation_kwargs is not None:
|
| 537 |
+
generation_kwargs.update(args.generation_kwargs)
|
| 538 |
+
# Remove None values
|
| 539 |
+
generation_kwargs = {k: v for k, v in generation_kwargs.items() if v is not None}
|
| 540 |
+
self.generation_config = GenerationConfig(**generation_kwargs)
|
| 541 |
+
# Keep training-specific generation kwargs to overwrite model's original generation config
|
| 542 |
+
self.generation_kwargs = generation_kwargs
|
| 543 |
+
|
| 544 |
+
if self.ref_model is not None:
|
| 545 |
+
if self.is_deepspeed_enabled:
|
| 546 |
+
self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
|
| 547 |
+
elif self.is_fsdp_enabled:
|
| 548 |
+
self.ref_model = prepare_fsdp(self.ref_model, self.accelerator)
|
| 549 |
+
else:
|
| 550 |
+
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
|
| 551 |
+
if self.reward_funcs is not None:
|
| 552 |
+
for i, reward_func in enumerate(self.reward_funcs):
|
| 553 |
+
if isinstance(reward_func, PreTrainedModel):
|
| 554 |
+
if self.is_deepspeed_enabled:
|
| 555 |
+
self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator)
|
| 556 |
+
else:
|
| 557 |
+
# set device placement to True to make `prepare_model` move `reward_func` to device when using fsdp
|
| 558 |
+
self.reward_funcs[i] = self.accelerator.prepare_model(
|
| 559 |
+
reward_func, evaluation_mode=True, device_placement=True
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
@property
|
| 563 |
+
def beta(self):
|
| 564 |
+
if isinstance(self._beta, list):
|
| 565 |
+
epoch = self.state.epoch
|
| 566 |
+
return self._beta[epoch] if epoch < len(self._beta) else self._beta[-1]
|
| 567 |
+
else:
|
| 568 |
+
return self._beta
|
| 569 |
+
|
| 570 |
+
@staticmethod
|
| 571 |
+
def tokenize_row(feature, is_encoder_decoder: bool, tokenizer: PreTrainedTokenizerBase) -> dict[str, Any]:
|
| 572 |
+
"""Tokenize a single row from a DPO specific dataset."""
|
| 573 |
+
if not is_encoder_decoder:
|
| 574 |
+
batch = tokenizer(feature["prompt"], add_special_tokens=False)
|
| 575 |
+
# Add BOS token to head of prompt. Avoid adding if it's already there
|
| 576 |
+
if tokenizer.bos_token_id is not None:
|
| 577 |
+
prompt_len_input_ids = len(batch["input_ids"])
|
| 578 |
+
if prompt_len_input_ids == 0 or tokenizer.bos_token_id != batch["input_ids"][0]:
|
| 579 |
+
batch["input_ids"] = [tokenizer.bos_token_id] + batch["input_ids"]
|
| 580 |
+
batch["attention_mask"] = [1] + batch["attention_mask"]
|
| 581 |
+
else:
|
| 582 |
+
batch = tokenizer(feature["prompt"], add_special_tokens=True)
|
| 583 |
+
batch = {f"prompt_{key}": value for key, value in batch.items()}
|
| 584 |
+
return batch
|
| 585 |
+
|
| 586 |
+
def _enable_gradient_checkpointing(self, model: PreTrainedModel, args: OnlineDPOConfig) -> PreTrainedModel:
|
| 587 |
+
"""Enables gradient checkpointing for the model."""
|
| 588 |
+
# Ensure use_cache is disabled
|
| 589 |
+
model.config.use_cache = False
|
| 590 |
+
|
| 591 |
+
# Enable gradient checkpointing on the base model for PEFT
|
| 592 |
+
if is_peft_model(model):
|
| 593 |
+
model.base_model.gradient_checkpointing_enable()
|
| 594 |
+
# Enable gradient checkpointing for non-PEFT models
|
| 595 |
+
else:
|
| 596 |
+
model.gradient_checkpointing_enable()
|
| 597 |
+
|
| 598 |
+
model.enable_input_require_grads()
|
| 599 |
+
return model
|
| 600 |
+
|
| 601 |
+
def _generate_vllm(self, prompts, images=None):
|
| 602 |
+
eos_token_id = self._tokenizer.eos_token_id
|
| 603 |
+
pad_token_id = self._tokenizer.pad_token_id
|
| 604 |
+
|
| 605 |
+
# Generate completion_ids and prompt_ids based on mode
|
| 606 |
+
if self.vllm_mode == "server":
|
| 607 |
+
completion_ids, prompt_ids = self._generate_vllm_server(prompts, images)
|
| 608 |
+
elif self.vllm_mode == "colocate":
|
| 609 |
+
completion_ids, prompt_ids = self._generate_vllm_colocate(prompts, images)
|
| 610 |
+
|
| 611 |
+
# Shared padding, masking, and tensor conversion logic
|
| 612 |
+
max_prompt_length = max(len(ids) for ids in prompt_ids)
|
| 613 |
+
prompt_mask = [[0] * (max_prompt_length - len(ids)) + [1] * len(ids) for ids in prompt_ids]
|
| 614 |
+
prompt_ids = [[pad_token_id] * (max_prompt_length - len(ids)) + ids for ids in prompt_ids]
|
| 615 |
+
max_tokens = self.generation_config.max_tokens
|
| 616 |
+
completion_mask = [[1] * len(ids) + [0] * (max_tokens - len(ids)) for ids in completion_ids]
|
| 617 |
+
completion_ids = [
|
| 618 |
+
ids + [eos_token_id] if ids[-1] != eos_token_id and len(ids) < max_tokens else ids
|
| 619 |
+
for ids in completion_ids
|
| 620 |
+
]
|
| 621 |
+
completion_ids = [ids + [pad_token_id] * (max_tokens - len(ids)) for ids in completion_ids]
|
| 622 |
+
|
| 623 |
+
# Convert to tensors
|
| 624 |
+
prompt_ids = torch.tensor(prompt_ids, device=self.accelerator.device)
|
| 625 |
+
prompt_mask = torch.tensor(prompt_mask, device=self.accelerator.device)
|
| 626 |
+
completion_ids = torch.tensor(completion_ids, device=self.accelerator.device)
|
| 627 |
+
completion_mask = torch.tensor(completion_mask, device=self.accelerator.device)
|
| 628 |
+
|
| 629 |
+
return prompt_ids, prompt_mask, completion_ids, completion_mask
|
| 630 |
+
|
| 631 |
+
def _generate_vllm_server(self, prompts, images=None):
|
| 632 |
+
"""Generate completions using vLLM server mode"""
|
| 633 |
+
has_images = images is not None
|
| 634 |
+
|
| 635 |
+
# Update vLLM server weights if needed
|
| 636 |
+
if hasattr(self, "_last_loaded_step") and self.state.global_step != self._last_loaded_step:
|
| 637 |
+
self._move_model_to_vllm()
|
| 638 |
+
self._last_loaded_step = self.state.global_step
|
| 639 |
+
elif not hasattr(self, "_last_loaded_step"):
|
| 640 |
+
self._move_model_to_vllm()
|
| 641 |
+
self._last_loaded_step = self.state.global_step
|
| 642 |
+
|
| 643 |
+
# Apply chat template if conversational
|
| 644 |
+
if is_conversational({"prompt": prompts[0]}):
|
| 645 |
+
prompts_text = [apply_chat_template({"prompt": p}, self.processing_class)["prompt"] for p in prompts]
|
| 646 |
+
else:
|
| 647 |
+
prompts_text = prompts
|
| 648 |
+
# Gather all prompts to main process
|
| 649 |
+
all_prompts = gather_object(prompts_text)
|
| 650 |
+
if has_images:
|
| 651 |
+
all_images = gather_object(images)
|
| 652 |
+
|
| 653 |
+
if self.accelerator.is_main_process:
|
| 654 |
+
# Since 'prompts' contains 'num_generations' duplicates, we first take unique prompts, and generate
|
| 655 |
+
# num_generations outputs for each one. This is faster than generating outputs for each duplicate
|
| 656 |
+
# prompt individually.
|
| 657 |
+
ordered_set_of_prompts = all_prompts[:: self.num_generations]
|
| 658 |
+
if has_images:
|
| 659 |
+
ordered_set_of_images = [
|
| 660 |
+
[img] if img is not None else None for img in all_images[:: self.num_generations]
|
| 661 |
+
]
|
| 662 |
+
else:
|
| 663 |
+
ordered_set_of_images = None
|
| 664 |
+
completion_ids = self.vllm_client.generate(
|
| 665 |
+
prompts=ordered_set_of_prompts,
|
| 666 |
+
images=ordered_set_of_images,
|
| 667 |
+
n=self.num_generations,
|
| 668 |
+
repetition_penalty=self.repetition_penalty,
|
| 669 |
+
temperature=self.temperature,
|
| 670 |
+
top_p=self.top_p,
|
| 671 |
+
top_k=-1 if self.top_k is None else self.top_k,
|
| 672 |
+
min_p=0.0 if self.min_p is None else self.min_p,
|
| 673 |
+
max_tokens=self.generation_config.max_tokens,
|
| 674 |
+
structured_outputs_regex=self.structured_outputs_regex
|
| 675 |
+
if hasattr(self, "structured_outputs_regex")
|
| 676 |
+
else None,
|
| 677 |
+
generation_kwargs=self.args.generation_kwargs,
|
| 678 |
+
)["completion_ids"]
|
| 679 |
+
# Flatten: each prompt generates 2 completions
|
| 680 |
+
completion_ids = [[comp_id] for prompt_completions in completion_ids for comp_id in prompt_completions]
|
| 681 |
+
else:
|
| 682 |
+
completion_ids = [None] * (len(all_prompts) * 2)
|
| 683 |
+
|
| 684 |
+
# Broadcast completions to all processes
|
| 685 |
+
completion_ids = broadcast_object_list(completion_ids, from_process=0)
|
| 686 |
+
|
| 687 |
+
# Each process takes its slice
|
| 688 |
+
process_slice = slice(
|
| 689 |
+
self.accelerator.process_index * len(prompts) * 2,
|
| 690 |
+
(self.accelerator.process_index + 1) * len(prompts) * 2,
|
| 691 |
+
)
|
| 692 |
+
completion_ids = completion_ids[process_slice]
|
| 693 |
+
|
| 694 |
+
# Create prompt_ids by tokenizing locally
|
| 695 |
+
prompt_inputs = self.processing_class(
|
| 696 |
+
text=prompts_text,
|
| 697 |
+
return_tensors="pt",
|
| 698 |
+
padding=True,
|
| 699 |
+
padding_side="left",
|
| 700 |
+
add_special_tokens=False,
|
| 701 |
+
)
|
| 702 |
+
prompt_ids = []
|
| 703 |
+
for prompt_tokens in prompt_inputs["input_ids"]:
|
| 704 |
+
prompt_ids.extend([prompt_tokens.tolist(), prompt_tokens.tolist()]) # 2 copies for 2 completions
|
| 705 |
+
return completion_ids, prompt_ids
|
| 706 |
+
|
| 707 |
+
def _generate_vllm_colocate(self, prompts, images=None):
|
| 708 |
+
"""Generate completions using vLLM colocate mode"""
|
| 709 |
+
if self.args.vllm_enable_sleep_mode:
|
| 710 |
+
# wake up colocated vLLM instances if needed
|
| 711 |
+
torch.cuda.empty_cache() # required to avoid OOM in some cases
|
| 712 |
+
self.llm.wake_up(tags=["weights"])
|
| 713 |
+
|
| 714 |
+
# Update model weights if needed - only after gradient accumulation completes
|
| 715 |
+
if self.state.global_step != self._last_loaded_step:
|
| 716 |
+
self._move_model_to_vllm()
|
| 717 |
+
self._last_loaded_step = self.state.global_step
|
| 718 |
+
|
| 719 |
+
# Apply chat template if conversational
|
| 720 |
+
if is_conversational({"prompt": prompts[0]}):
|
| 721 |
+
prompts_text = [apply_chat_template({"prompt": p}, self.processing_class)["prompt"] for p in prompts]
|
| 722 |
+
else:
|
| 723 |
+
prompts_text = prompts
|
| 724 |
+
|
| 725 |
+
# Prepare vLLM inputs with images if available
|
| 726 |
+
if images is not None:
|
| 727 |
+
vllm_inputs = []
|
| 728 |
+
for prompt, image in zip(prompts_text, images, strict=True):
|
| 729 |
+
if image is not None:
|
| 730 |
+
vllm_inputs.append({"prompt": prompt, "multi_modal_data": {"image": image}})
|
| 731 |
+
else:
|
| 732 |
+
vllm_inputs.append(prompt)
|
| 733 |
+
else:
|
| 734 |
+
vllm_inputs = prompts_text
|
| 735 |
+
|
| 736 |
+
if self.args.vllm_enable_sleep_mode:
|
| 737 |
+
self.llm.wake_up(tags=["kv_cache"])
|
| 738 |
+
|
| 739 |
+
outputs = self.llm.generate(vllm_inputs, self.generation_config, use_tqdm=False)
|
| 740 |
+
|
| 741 |
+
completion_ids = [list(output.outputs[i].token_ids) for i in range(2) for output in outputs]
|
| 742 |
+
prompt_ids = [list(output.prompt_token_ids) for _ in range(2) for output in outputs]
|
| 743 |
+
if self.args.vllm_enable_sleep_mode:
|
| 744 |
+
self.llm.sleep(level=2)
|
| 745 |
+
|
| 746 |
+
return completion_ids, prompt_ids
|
| 747 |
+
|
| 748 |
+
def _sync_fsdp2_params_to_vllm(self, module: nn.Module):
|
| 749 |
+
# For FSDP2, module.state_dict() already covers all parameters, so no need for recursion
|
| 750 |
+
for name, param in module.state_dict().items():
|
| 751 |
+
# When using PEFT, we need to recover the original parameter name
|
| 752 |
+
name = name.removeprefix("base_model.model.").replace(".base_layer", "")
|
| 753 |
+
# Skip PEFT layers: they don’t exist in vLLM, and they are merged already.
|
| 754 |
+
if is_peft_model(module) and module.prefix in name:
|
| 755 |
+
continue
|
| 756 |
+
# When module to save, remove its prefix and discard the original module
|
| 757 |
+
if "original_module" in name:
|
| 758 |
+
continue
|
| 759 |
+
name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."])
|
| 760 |
+
|
| 761 |
+
if param.is_cpu:
|
| 762 |
+
param = param.to(torch.device("cuda"))
|
| 763 |
+
param = param.full_tensor()
|
| 764 |
+
|
| 765 |
+
if self.vllm_mode == "server" and self.accelerator.is_main_process:
|
| 766 |
+
self.vllm_client.update_named_param(name, param)
|
| 767 |
+
elif self.vllm_mode == "colocate":
|
| 768 |
+
llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
|
| 769 |
+
llm_model.load_weights([(name, param)])
|
| 770 |
+
|
| 771 |
+
def _move_model_to_vllm(self):
|
| 772 |
+
# For DeepSpeed ZeRO-3 and FSDP, we need to gather all parameters before operations
|
| 773 |
+
deepspeed_plugin = self.accelerator.state.deepspeed_plugin
|
| 774 |
+
zero_stage_3 = deepspeed_plugin is not None and deepspeed_plugin.zero_stage == 3
|
| 775 |
+
if zero_stage_3:
|
| 776 |
+
import deepspeed
|
| 777 |
+
|
| 778 |
+
gather_if_zero3 = deepspeed.zero.GatheredParameters
|
| 779 |
+
else:
|
| 780 |
+
gather_if_zero3 = nullcontext
|
| 781 |
+
|
| 782 |
+
if is_peft_model(self.model):
|
| 783 |
+
# With PEFT and FSDP/DeepSpeed ZeRO Stage 3, we must gather the full model at once before merging, as
|
| 784 |
+
# merging adapters in a sharded manner is not supported.
|
| 785 |
+
# TODO: does this work with FSDP?
|
| 786 |
+
with gather_if_zero3(list(self.model.parameters())):
|
| 787 |
+
self.model.merge_adapter()
|
| 788 |
+
|
| 789 |
+
# Update vLLM weights while parameters are gathered
|
| 790 |
+
if self.is_fsdp_enabled: # note if using FSDP, gather_if_zero3 is nullcontext
|
| 791 |
+
# Update vLLM weights while parameters are gathered
|
| 792 |
+
# For PEFT with FSDP we need to use the memory efficient post-order traversal
|
| 793 |
+
fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None)
|
| 794 |
+
fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1
|
| 795 |
+
if fsdp_version == 1:
|
| 796 |
+
self._sync_fsdp1_params_to_vllm(
|
| 797 |
+
self.model
|
| 798 |
+
) # use memory-efficient post-order traversal for FSDP
|
| 799 |
+
elif fsdp_version == 2:
|
| 800 |
+
self._sync_fsdp2_params_to_vllm(self.model)
|
| 801 |
+
else:
|
| 802 |
+
# DeepSpeed ZeRO-3 with PEFT
|
| 803 |
+
for name, param in self.model.named_parameters():
|
| 804 |
+
# When using PEFT, we need to recover the original parameter name
|
| 805 |
+
name = name.removeprefix("base_model.model.").replace(".base_layer", "")
|
| 806 |
+
# Skip PEFT layers: they don’t exist in vLLM, and they are merged already.
|
| 807 |
+
if self.model.prefix in name:
|
| 808 |
+
continue
|
| 809 |
+
# When module to save, remove its prefix and discard the original module
|
| 810 |
+
if "original_module" in name:
|
| 811 |
+
continue
|
| 812 |
+
name = self._fix_param_name_to_vllm(name, extra_prefixes=["modules_to_save.default."])
|
| 813 |
+
|
| 814 |
+
if self.vllm_mode == "server" and self.accelerator.is_main_process:
|
| 815 |
+
self.vllm_client.update_named_param(name, param.data)
|
| 816 |
+
elif self.vllm_mode == "colocate":
|
| 817 |
+
llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
|
| 818 |
+
llm_model.load_weights([(name, param.data)])
|
| 819 |
+
# Unmerge adapters while parameters are still gathered
|
| 820 |
+
self.model.unmerge_adapter()
|
| 821 |
+
# Parameters will automatically be repartitioned when exiting the context
|
| 822 |
+
else:
|
| 823 |
+
# For non-PEFT models, simply gather (if needed) and update each parameter individually.
|
| 824 |
+
if self.is_fsdp_enabled:
|
| 825 |
+
fsdp_plugin = getattr(self.accelerator.state, "fsdp_plugin", None)
|
| 826 |
+
fsdp_version = getattr(fsdp_plugin, "fsdp_version", 1) if fsdp_plugin else 1
|
| 827 |
+
if fsdp_version == 1:
|
| 828 |
+
self._sync_fsdp1_params_to_vllm(self.model) # use memory-efficient post-order traversal for FSDP
|
| 829 |
+
elif fsdp_version == 2:
|
| 830 |
+
self._sync_fsdp2_params_to_vllm(self.model)
|
| 831 |
+
else:
|
| 832 |
+
for name, param in self.model.named_parameters():
|
| 833 |
+
name = self._fix_param_name_to_vllm(name)
|
| 834 |
+
with gather_if_zero3([param]):
|
| 835 |
+
if self.vllm_mode == "server" and self.accelerator.is_main_process:
|
| 836 |
+
self.vllm_client.update_named_param(name, param.data)
|
| 837 |
+
elif self.vllm_mode == "colocate":
|
| 838 |
+
llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
|
| 839 |
+
llm_model.load_weights([(name, param.data)])
|
| 840 |
+
|
| 841 |
+
# Reset cache on vLLM
|
| 842 |
+
if self.vllm_mode == "server" and self.accelerator.is_main_process:
|
| 843 |
+
self.vllm_client.reset_prefix_cache()
|
| 844 |
+
elif self.vllm_mode == "colocate":
|
| 845 |
+
self.llm.reset_prefix_cache()
|
| 846 |
+
|
| 847 |
+
def _sync_fsdp1_params_to_vllm(self, module: nn.Module, prefix: str = "", visited=None):
|
| 848 |
+
"""Memory-efficient post-order traversal of FSDP modules to extract full parameters and sync with vLLM."""
|
| 849 |
+
# For FSDP1, we need to recurse into children and also use summon_full_params
|
| 850 |
+
if visited is None:
|
| 851 |
+
visited = set()
|
| 852 |
+
for child_name, child_module in module.named_children():
|
| 853 |
+
child_prefix = f"{prefix}.{child_name}" if prefix else child_name
|
| 854 |
+
self._sync_fsdp1_params_to_vllm(
|
| 855 |
+
child_module, prefix=child_prefix, visited=visited
|
| 856 |
+
) # recurse into the child
|
| 857 |
+
|
| 858 |
+
if isinstance(module, FSDP):
|
| 859 |
+
with FSDP.summon_full_params(module, recurse=False, writeback=False):
|
| 860 |
+
for param_name, param in module.named_parameters():
|
| 861 |
+
full_name = f"{prefix}.{param_name}" if prefix else param_name
|
| 862 |
+
full_name = self._fix_param_name_to_vllm(full_name, extra_prefixes=["_fsdp_wrapped_module."])
|
| 863 |
+
|
| 864 |
+
if full_name in visited:
|
| 865 |
+
continue # skip FSDP subtrees already traversed
|
| 866 |
+
visited.add(full_name)
|
| 867 |
+
|
| 868 |
+
if self.vllm_mode == "server" and self.accelerator.is_main_process:
|
| 869 |
+
self.vllm_client.update_named_param(full_name, param.data)
|
| 870 |
+
elif self.vllm_mode == "colocate":
|
| 871 |
+
llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model
|
| 872 |
+
llm_model.load_weights([(full_name, param.data)])
|
| 873 |
+
|
| 874 |
+
def _fix_param_name_to_vllm(self, name, extra_prefixes: list[str] | None = None):
|
| 875 |
+
"""Clean parameter names for vLLM compatibility"""
|
| 876 |
+
extra_prefixes = extra_prefixes or []
|
| 877 |
+
prefixes = ["_checkpoint_wrapped_module."] + extra_prefixes
|
| 878 |
+
for prefix in prefixes:
|
| 879 |
+
name = name.replace(prefix, "")
|
| 880 |
+
return name
|
| 881 |
+
|
| 882 |
+
def process_vision_row(
|
| 883 |
+
self, features: dict[str, list | torch.Tensor], processing_class=None
|
| 884 |
+
) -> dict[str, list[int]]:
|
| 885 |
+
"""
|
| 886 |
+
Process a vision row for VLM models (adapted from DPO trainer)
|
| 887 |
+
"""
|
| 888 |
+
processor = processing_class or self.processing_class
|
| 889 |
+
processed_features = processor(images=[features["image"]], text=features["prompt"], add_special_tokens=False)
|
| 890 |
+
|
| 891 |
+
prompt_input_ids = processed_features["input_ids"][0]
|
| 892 |
+
|
| 893 |
+
# Create the output dict with required fields
|
| 894 |
+
output = {
|
| 895 |
+
"prompt_input_ids": prompt_input_ids,
|
| 896 |
+
"prompt_attention_mask": processed_features["attention_mask"][0],
|
| 897 |
+
}
|
| 898 |
+
|
| 899 |
+
# Add vision-specific fields
|
| 900 |
+
if "pixel_values" in processed_features:
|
| 901 |
+
output["pixel_values"] = processed_features["pixel_values"][0]
|
| 902 |
+
if "pixel_attention_mask" in processed_features:
|
| 903 |
+
output["pixel_attention_mask"] = processed_features["pixel_attention_mask"][0]
|
| 904 |
+
if "image_sizes" in processed_features:
|
| 905 |
+
output["image_sizes"] = processed_features["image_sizes"][0]
|
| 906 |
+
|
| 907 |
+
return output
|
| 908 |
+
|
| 909 |
+
def _generate(self, model, prompts, images=None):
|
| 910 |
+
"""Generate completions using the model"""
|
| 911 |
+
device = next(model.parameters()).device
|
| 912 |
+
eos_token_id = self._tokenizer.eos_token_id
|
| 913 |
+
pad_token_id = self._tokenizer.pad_token_id
|
| 914 |
+
|
| 915 |
+
# Apply chat template and tokenize the input
|
| 916 |
+
inputs = [{"prompt": prompt} for prompt in prompts]
|
| 917 |
+
|
| 918 |
+
# Add images if provided (VLM support)
|
| 919 |
+
if images is not None:
|
| 920 |
+
for i, image in enumerate(images):
|
| 921 |
+
inputs[i]["image"] = image
|
| 922 |
+
|
| 923 |
+
# Apply chat template to get text prompts
|
| 924 |
+
prompts_text = [maybe_apply_chat_template(x, self.processing_class)["prompt"] for x in inputs]
|
| 925 |
+
|
| 926 |
+
# Handle image token collapsing/removal
|
| 927 |
+
# The chat template sometimes inserts a single image token into the prompt text. However, when this text is
|
| 928 |
+
# later tokenized, the single image token string is expanded into multiple image token IDs, depending on the
|
| 929 |
+
# image size. We need to handle this properly.
|
| 930 |
+
if self.image_token is not None and images is not None:
|
| 931 |
+
escaped_img_token = re.escape(self.image_token)
|
| 932 |
+
# Search for the image token in the chat template
|
| 933 |
+
if hasattr(self.processing_class, "chat_template") and self.processing_class.chat_template:
|
| 934 |
+
if re.search(escaped_img_token, self.processing_class.chat_template):
|
| 935 |
+
# Collapse repeated image tokens back into a single token
|
| 936 |
+
prompts_text = [
|
| 937 |
+
re.sub(rf"({escaped_img_token})+", self.image_token, text) for text in prompts_text
|
| 938 |
+
]
|
| 939 |
+
else:
|
| 940 |
+
# If the chat template doesn't use the image token, remove all instances
|
| 941 |
+
if self.vision_end_token_id is not None:
|
| 942 |
+
escaped_eoi_token = re.escape(self._tokenizer.decode([self.vision_end_token_id]))
|
| 943 |
+
prompts_text = [
|
| 944 |
+
re.sub(rf"({escaped_img_token})+{escaped_eoi_token}", "", text) for text in prompts_text
|
| 945 |
+
]
|
| 946 |
+
else:
|
| 947 |
+
# If vision_end_token_id is None, just remove the image tokens
|
| 948 |
+
prompts_text = [re.sub(rf"({escaped_img_token})+", "", text) for text in prompts_text]
|
| 949 |
+
|
| 950 |
+
# Prepare kwargs for processing class
|
| 951 |
+
kwargs = {}
|
| 952 |
+
if images is not None:
|
| 953 |
+
kwargs = {"images": [[img] for img in images]}
|
| 954 |
+
|
| 955 |
+
# Process inputs using the processing class (handles both VLM and LLM)
|
| 956 |
+
prompt_inputs = self.processing_class(
|
| 957 |
+
text=prompts_text,
|
| 958 |
+
return_tensors="pt",
|
| 959 |
+
padding=True,
|
| 960 |
+
padding_side="left",
|
| 961 |
+
add_special_tokens=False,
|
| 962 |
+
**kwargs,
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
prompt_inputs = {k: v.to(device) for k, v in prompt_inputs.items()}
|
| 966 |
+
# Convert vision inputs to model's dtype for proper computation
|
| 967 |
+
if "pixel_values" in prompt_inputs:
|
| 968 |
+
# Handle DataParallel wrapped models
|
| 969 |
+
model_dtype = getattr(model, "dtype", None)
|
| 970 |
+
if model_dtype is None and hasattr(model, "module"):
|
| 971 |
+
model_dtype = model.module.dtype
|
| 972 |
+
if model_dtype is not None:
|
| 973 |
+
prompt_inputs["pixel_values"] = prompt_inputs["pixel_values"].to(model_dtype)
|
| 974 |
+
|
| 975 |
+
# Sample 2 completions per prompt of size `max_new_tokens` from the model
|
| 976 |
+
prompt_ids = prompt_inputs["input_ids"].repeat(2, 1)
|
| 977 |
+
prompt_mask = prompt_inputs["attention_mask"].repeat(2, 1)
|
| 978 |
+
|
| 979 |
+
# Prepare vision inputs if available
|
| 980 |
+
vision_generation_kwargs = {}
|
| 981 |
+
if self.is_vision_model and images is not None:
|
| 982 |
+
if "pixel_values" in prompt_inputs:
|
| 983 |
+
vision_generation_kwargs["pixel_values"] = prompt_inputs["pixel_values"].repeat(2, 1, 1, 1)
|
| 984 |
+
if "pixel_attention_mask" in prompt_inputs:
|
| 985 |
+
vision_generation_kwargs["pixel_attention_mask"] = prompt_inputs["pixel_attention_mask"].repeat(2, 1)
|
| 986 |
+
if "image_sizes" in prompt_inputs:
|
| 987 |
+
vision_generation_kwargs["image_sizes"] = prompt_inputs["image_sizes"].repeat(2, 1)
|
| 988 |
+
if "image_grid_thw" in prompt_inputs:
|
| 989 |
+
vision_generation_kwargs["image_grid_thw"] = prompt_inputs["image_grid_thw"].repeat(2, 1)
|
| 990 |
+
|
| 991 |
+
with (
|
| 992 |
+
profiling_context(self, "transformers.generate"),
|
| 993 |
+
unwrap_model_for_generation(
|
| 994 |
+
model,
|
| 995 |
+
self.accelerator,
|
| 996 |
+
gather_deepspeed3_params=self.args.ds3_gather_for_generation,
|
| 997 |
+
generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
|
| 998 |
+
) as unwrapped_model,
|
| 999 |
+
torch.no_grad(),
|
| 1000 |
+
FSDP.summon_full_params(self.model_wrapped, recurse=False) if self.is_fsdp_enabled else nullcontext(),
|
| 1001 |
+
):
|
| 1002 |
+
# Setup cache implementation if specified
|
| 1003 |
+
if self.args.cache_implementation is not None:
|
| 1004 |
+
unwrapped_model.generation_config.cache_implementation = self.args.cache_implementation
|
| 1005 |
+
|
| 1006 |
+
# Standard generation
|
| 1007 |
+
output = unwrapped_model.generate(
|
| 1008 |
+
input_ids=prompt_ids,
|
| 1009 |
+
attention_mask=prompt_mask,
|
| 1010 |
+
generation_config=self.generation_config,
|
| 1011 |
+
**vision_generation_kwargs,
|
| 1012 |
+
)
|
| 1013 |
+
|
| 1014 |
+
completion_ids = output[:, prompt_ids.size(1) :]
|
| 1015 |
+
completion_ids, completion_mask = truncate_right(completion_ids, eos_token_id, pad_token_id)
|
| 1016 |
+
|
| 1017 |
+
return prompt_ids, prompt_mask, completion_ids, completion_mask
|
| 1018 |
+
|
| 1019 |
+
def _calculate_rewards_from_functions(self, prompts, completions, completion_ids_list, **reward_kwargs):
|
| 1020 |
+
"""
|
| 1021 |
+
Calculate rewards using reward functions
|
| 1022 |
+
"""
|
| 1023 |
+
device = self.accelerator.device
|
| 1024 |
+
rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device)
|
| 1025 |
+
|
| 1026 |
+
# Add trainer state to reward kwargs for dynamic reward shaping
|
| 1027 |
+
reward_kwargs["trainer_state"] = self.state
|
| 1028 |
+
|
| 1029 |
+
for i, (reward_func, reward_processing_class) in enumerate(
|
| 1030 |
+
zip(self.reward_funcs, self.reward_processing_classes, strict=True)
|
| 1031 |
+
):
|
| 1032 |
+
if isinstance(reward_func, nn.Module): # Model-based reward function
|
| 1033 |
+
# Handle conversational vs text input
|
| 1034 |
+
if is_conversational({"prompt": prompts[0]}):
|
| 1035 |
+
messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)]
|
| 1036 |
+
texts = [apply_chat_template(x, reward_processing_class)["text"] for x in messages]
|
| 1037 |
+
else:
|
| 1038 |
+
texts = [p + c for p, c in zip(prompts, completions, strict=True)]
|
| 1039 |
+
|
| 1040 |
+
# Tokenize and get reward scores
|
| 1041 |
+
reward_inputs = reward_processing_class(
|
| 1042 |
+
text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False
|
| 1043 |
+
)
|
| 1044 |
+
reward_inputs = {k: v.to(device) for k, v in reward_inputs.items()}
|
| 1045 |
+
|
| 1046 |
+
with torch.inference_mode():
|
| 1047 |
+
rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,)
|
| 1048 |
+
else:
|
| 1049 |
+
# Custom reward function
|
| 1050 |
+
output_reward_func = reward_func(
|
| 1051 |
+
prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs
|
| 1052 |
+
)
|
| 1053 |
+
# Convert None values to NaN
|
| 1054 |
+
output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func]
|
| 1055 |
+
rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device)
|
| 1056 |
+
|
| 1057 |
+
# Weight and sum across all reward functions
|
| 1058 |
+
if self.reward_weights is not None:
|
| 1059 |
+
total_rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
|
| 1060 |
+
else:
|
| 1061 |
+
total_rewards = rewards_per_func.nansum(dim=1)
|
| 1062 |
+
|
| 1063 |
+
return total_rewards
|
| 1064 |
+
|
| 1065 |
+
def _forward(self, model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs=None):
|
| 1066 |
+
# Get the number of tokens to truncate from prompt
|
| 1067 |
+
num_tokens_to_truncate = max(prompt_ids.size(1) + completion_ids.size(1) - self.max_length, 0)
|
| 1068 |
+
|
| 1069 |
+
# Truncate left to avoid oom
|
| 1070 |
+
prompt_ids = prompt_ids[:, num_tokens_to_truncate:]
|
| 1071 |
+
prompt_mask = prompt_mask[:, num_tokens_to_truncate:]
|
| 1072 |
+
|
| 1073 |
+
# Concat the prompt and completion
|
| 1074 |
+
prompt_completion_ids = torch.cat((prompt_ids, completion_ids), dim=1)
|
| 1075 |
+
prompt_completion_mask = torch.cat((prompt_mask, completion_mask), dim=1)
|
| 1076 |
+
|
| 1077 |
+
# Prepare model kwargs with vision inputs if available
|
| 1078 |
+
model_kwargs = {"attention_mask": prompt_completion_mask}
|
| 1079 |
+
if vision_inputs is not None:
|
| 1080 |
+
if "pixel_values" in vision_inputs:
|
| 1081 |
+
model_kwargs["pixel_values"] = vision_inputs["pixel_values"]
|
| 1082 |
+
if "pixel_attention_mask" in vision_inputs:
|
| 1083 |
+
model_kwargs["pixel_attention_mask"] = vision_inputs["pixel_attention_mask"]
|
| 1084 |
+
if "image_sizes" in vision_inputs:
|
| 1085 |
+
model_kwargs["image_sizes"] = vision_inputs["image_sizes"]
|
| 1086 |
+
if "image_grid_thw" in vision_inputs:
|
| 1087 |
+
model_kwargs["image_grid_thw"] = vision_inputs["image_grid_thw"]
|
| 1088 |
+
|
| 1089 |
+
# Get the logprobs of the completions from the model
|
| 1090 |
+
output = model(prompt_completion_ids, **model_kwargs)
|
| 1091 |
+
|
| 1092 |
+
# There is 1 offset, because the model predicts the next token
|
| 1093 |
+
prompt_len = prompt_ids.size(1)
|
| 1094 |
+
start_idx = prompt_len - 1 if prompt_len > 0 else 0
|
| 1095 |
+
# Only slice off the last logit when we have a prompt, otherwise we need all logits
|
| 1096 |
+
end_idx = -1 if prompt_len > 0 else None
|
| 1097 |
+
logits = output.logits[:, start_idx:end_idx]
|
| 1098 |
+
|
| 1099 |
+
# Take the completion tokens logprob
|
| 1100 |
+
logprobs = torch.take_along_dim(logits.log_softmax(dim=-1), completion_ids.unsqueeze(-1), dim=2).squeeze(-1)
|
| 1101 |
+
return logprobs
|
| 1102 |
+
|
| 1103 |
+
def training_step(
|
| 1104 |
+
self, model: nn.Module, inputs: dict[str, torch.Tensor | Any], num_items_in_batch: int | None = None
|
| 1105 |
+
) -> torch.Tensor:
|
| 1106 |
+
model.train()
|
| 1107 |
+
|
| 1108 |
+
prompts = inputs["prompt"]
|
| 1109 |
+
batch_size = len(prompts)
|
| 1110 |
+
|
| 1111 |
+
# Handle images for VLM support
|
| 1112 |
+
has_images = "image" in inputs
|
| 1113 |
+
images = None
|
| 1114 |
+
if has_images:
|
| 1115 |
+
images = inputs["image"]
|
| 1116 |
+
# Convert conversational prompts to include image tokens
|
| 1117 |
+
for prompt in prompts:
|
| 1118 |
+
if isinstance(prompt, list):
|
| 1119 |
+
for message in prompt:
|
| 1120 |
+
if not isinstance(message, dict):
|
| 1121 |
+
continue
|
| 1122 |
+
content = message.get("content")
|
| 1123 |
+
role = message.get("role")
|
| 1124 |
+
if isinstance(content, str):
|
| 1125 |
+
if role == "user":
|
| 1126 |
+
message["content"] = [{"type": "image"}, {"type": "text", "text": content}]
|
| 1127 |
+
elif role == "system":
|
| 1128 |
+
message["content"] = [{"type": "text", "text": content}]
|
| 1129 |
+
|
| 1130 |
+
if self.args.use_vllm:
|
| 1131 |
+
prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate_vllm(prompts, images)
|
| 1132 |
+
else:
|
| 1133 |
+
prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate(model, prompts, images)
|
| 1134 |
+
|
| 1135 |
+
contain_eos_token = torch.any(completion_ids == self._tokenizer.eos_token_id, dim=-1)
|
| 1136 |
+
|
| 1137 |
+
# Extract vision inputs if available for VLM support
|
| 1138 |
+
vision_inputs = None
|
| 1139 |
+
if has_images and self.is_vision_model and not self.args.use_vllm:
|
| 1140 |
+
# For vision models with transformers generation, we need to prepare vision inputs
|
| 1141 |
+
# Process the images to get vision inputs that can be passed through the forward pass
|
| 1142 |
+
vision_inputs = {}
|
| 1143 |
+
kwargs = {"images": [[img] for img in images]}
|
| 1144 |
+
processed = self.processing_class(
|
| 1145 |
+
text=[""] * len(images), # Dummy text for vision processing
|
| 1146 |
+
return_tensors="pt",
|
| 1147 |
+
**kwargs,
|
| 1148 |
+
)
|
| 1149 |
+
# Handle DataParallel wrapped models
|
| 1150 |
+
model_device = getattr(model, "device", None)
|
| 1151 |
+
model_dtype = getattr(model, "dtype", None)
|
| 1152 |
+
if model_device is None and hasattr(model, "module"):
|
| 1153 |
+
model_device = model.module.device
|
| 1154 |
+
model_dtype = model.module.dtype
|
| 1155 |
+
# Move vision tensors to device and convert to model dtype
|
| 1156 |
+
# Need to duplicate for 2 completions per prompt
|
| 1157 |
+
if "pixel_values" in processed:
|
| 1158 |
+
vision_inputs["pixel_values"] = (
|
| 1159 |
+
processed["pixel_values"].to(model_device, dtype=model_dtype).repeat(2, 1, 1, 1)
|
| 1160 |
+
)
|
| 1161 |
+
if "pixel_attention_mask" in processed:
|
| 1162 |
+
vision_inputs["pixel_attention_mask"] = processed["pixel_attention_mask"].to(model_device).repeat(2, 1)
|
| 1163 |
+
if "image_sizes" in processed:
|
| 1164 |
+
vision_inputs["image_sizes"] = processed["image_sizes"].to(model_device).repeat(2, 1)
|
| 1165 |
+
if "image_grid_thw" in processed:
|
| 1166 |
+
vision_inputs["image_grid_thw"] = processed["image_grid_thw"].to(model_device).repeat(2, 1)
|
| 1167 |
+
|
| 1168 |
+
logprobs = self._forward(model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs)
|
| 1169 |
+
with torch.no_grad():
|
| 1170 |
+
if self.ref_model is not None:
|
| 1171 |
+
ref_logprobs = self._forward(
|
| 1172 |
+
self.ref_model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs
|
| 1173 |
+
)
|
| 1174 |
+
else: # peft case: we just need to disable the adapter
|
| 1175 |
+
with self.model.disable_adapter():
|
| 1176 |
+
ref_logprobs = self._forward(
|
| 1177 |
+
self.model, prompt_ids, prompt_mask, completion_ids, completion_mask, vision_inputs
|
| 1178 |
+
)
|
| 1179 |
+
|
| 1180 |
+
# Decode the completions, and format them if the input is conversational
|
| 1181 |
+
device = logprobs.device
|
| 1182 |
+
completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
|
| 1183 |
+
if is_conversational({"prompt": prompts[0]}):
|
| 1184 |
+
completions = [[{"role": "assistant", "content": completion}] for completion in completions]
|
| 1185 |
+
|
| 1186 |
+
# Get the reward from reward functions
|
| 1187 |
+
# First create completion_ids_list for custom reward functions
|
| 1188 |
+
completion_ids_list = [completion_ids[i].tolist() for i in range(completion_ids.shape[0])]
|
| 1189 |
+
|
| 1190 |
+
# Extract additional fields from inputs for reward functions
|
| 1191 |
+
reward_kwargs = {}
|
| 1192 |
+
keys = [key for key in inputs if key not in ["prompt"]]
|
| 1193 |
+
for key in keys:
|
| 1194 |
+
if isinstance(inputs[key], (list, tuple)):
|
| 1195 |
+
# Repeat input fields to match number of completions (2 per prompt)
|
| 1196 |
+
reward_kwargs[key] = inputs[key] * 2
|
| 1197 |
+
else:
|
| 1198 |
+
reward_kwargs[key] = inputs[key]
|
| 1199 |
+
|
| 1200 |
+
# Calculate rewards using reward functions
|
| 1201 |
+
rewards = self._calculate_rewards_from_functions(
|
| 1202 |
+
prompts=2 * prompts, completions=completions, completion_ids_list=completion_ids_list, **reward_kwargs
|
| 1203 |
+
)
|
| 1204 |
+
|
| 1205 |
+
# Apply missing EOS penalty if configured
|
| 1206 |
+
if self.args.missing_eos_penalty is not None:
|
| 1207 |
+
rewards[~contain_eos_token] -= self.args.missing_eos_penalty
|
| 1208 |
+
|
| 1209 |
+
# Split rewards into chosen/rejected pairs
|
| 1210 |
+
first_half, second_half = rewards.split(batch_size)
|
| 1211 |
+
mask = first_half >= second_half
|
| 1212 |
+
|
| 1213 |
+
batch_range = torch.arange(batch_size, device=device)
|
| 1214 |
+
chosen_indices = batch_range + (~mask * batch_size)
|
| 1215 |
+
rejected_indices = batch_range + (mask * batch_size)
|
| 1216 |
+
|
| 1217 |
+
# Build tensor so that the first half is the chosen examples and the second half the rejected examples
|
| 1218 |
+
cr_indices = torch.cat((chosen_indices, rejected_indices), dim=0) # cr = chosen and rejected
|
| 1219 |
+
cr_logprobs = logprobs[cr_indices]
|
| 1220 |
+
cr_ref_logprobs = ref_logprobs[cr_indices]
|
| 1221 |
+
|
| 1222 |
+
# mask out the padding tokens
|
| 1223 |
+
padding_mask = ~completion_mask.bool()
|
| 1224 |
+
cr_padding_mask = padding_mask[cr_indices]
|
| 1225 |
+
|
| 1226 |
+
cr_logprobs_sum = (cr_logprobs * ~cr_padding_mask).sum(1)
|
| 1227 |
+
cr_ref_logprobs_sum = (cr_ref_logprobs * ~cr_padding_mask).sum(1)
|
| 1228 |
+
|
| 1229 |
+
# Split the chosen and rejected examples
|
| 1230 |
+
chosen_logprobs_sum, rejected_logprobs_sum = torch.split(cr_logprobs_sum, batch_size)
|
| 1231 |
+
chosen_ref_logprobs_sum, rejected_ref_logprobs_sum = torch.split(cr_ref_logprobs_sum, batch_size)
|
| 1232 |
+
pi_logratios = chosen_logprobs_sum - rejected_logprobs_sum
|
| 1233 |
+
ref_logratios = chosen_ref_logprobs_sum - rejected_ref_logprobs_sum
|
| 1234 |
+
|
| 1235 |
+
logits = pi_logratios - ref_logratios
|
| 1236 |
+
|
| 1237 |
+
if self.args.loss_type == "sigmoid":
|
| 1238 |
+
losses = -F.logsigmoid(self.beta * logits)
|
| 1239 |
+
elif self.args.loss_type == "ipo":
|
| 1240 |
+
losses = (logits - 1 / (2 * self.beta)) ** 2
|
| 1241 |
+
else:
|
| 1242 |
+
raise NotImplementedError(f"invalid loss type {self.args.loss_type}")
|
| 1243 |
+
|
| 1244 |
+
loss = losses.mean()
|
| 1245 |
+
|
| 1246 |
+
# Log everything
|
| 1247 |
+
if self.reward_funcs is not None:
|
| 1248 |
+
# When using reward_funcs, we have rewards instead of scores
|
| 1249 |
+
scores_margin = rewards[chosen_indices] - rewards[rejected_indices]
|
| 1250 |
+
self.stats["objective/scores_margin"].append(
|
| 1251 |
+
self.accelerator.gather_for_metrics(scores_margin.mean()).mean().item()
|
| 1252 |
+
)
|
| 1253 |
+
self.stats["objective/scores"].append(self.accelerator.gather_for_metrics(rewards.mean()).mean().item())
|
| 1254 |
+
self.stats["val/contain_eos_token"].append(contain_eos_token.float().mean().item())
|
| 1255 |
+
self.stats["logps/chosen"].append(self.accelerator.gather_for_metrics(chosen_logprobs_sum).mean().item())
|
| 1256 |
+
self.stats["logps/rejected"].append(self.accelerator.gather_for_metrics(rejected_logprobs_sum).mean().item())
|
| 1257 |
+
|
| 1258 |
+
kl = logprobs - ref_logprobs
|
| 1259 |
+
mean_kl = kl.sum(1).mean()
|
| 1260 |
+
self.stats["objective/kl"].append(self.accelerator.gather_for_metrics(mean_kl).mean().item())
|
| 1261 |
+
non_score_reward = (-self.beta * kl).sum(1)
|
| 1262 |
+
mean_non_score_reward = non_score_reward.mean()
|
| 1263 |
+
self.stats["objective/non_score_reward"].append(
|
| 1264 |
+
self.accelerator.gather_for_metrics(mean_non_score_reward).mean().item()
|
| 1265 |
+
)
|
| 1266 |
+
if self.reward_funcs is not None:
|
| 1267 |
+
# Calculate RLHF reward by combining rewards with non_score_reward
|
| 1268 |
+
rlhf_reward = rewards + non_score_reward
|
| 1269 |
+
self.stats["objective/rlhf_reward"].append(self.accelerator.gather_for_metrics(rlhf_reward).mean().item())
|
| 1270 |
+
|
| 1271 |
+
mean_entropy = -logprobs.sum(1).mean()
|
| 1272 |
+
self.stats["objective/entropy"].append(self.accelerator.gather_for_metrics(mean_entropy).mean().item())
|
| 1273 |
+
chosen_rewards = self.beta * (chosen_logprobs_sum - chosen_ref_logprobs_sum)
|
| 1274 |
+
gathered_chosen_rewards = self.accelerator.gather_for_metrics(chosen_rewards)
|
| 1275 |
+
self.stats["rewards/chosen"].append(gathered_chosen_rewards.mean().item())
|
| 1276 |
+
rejected_rewards = self.beta * (rejected_logprobs_sum - rejected_ref_logprobs_sum)
|
| 1277 |
+
gathered_rejected_rewards = self.accelerator.gather_for_metrics(rejected_rewards)
|
| 1278 |
+
self.stats["rewards/rejected"].append(gathered_rejected_rewards.mean().item())
|
| 1279 |
+
margin = gathered_chosen_rewards - gathered_rejected_rewards
|
| 1280 |
+
self.stats["rewards/margins"].append(margin.mean().item())
|
| 1281 |
+
accuracy = margin > 0
|
| 1282 |
+
self.stats["rewards/accuracies"].append(accuracy.float().mean().item())
|
| 1283 |
+
self.stats["beta"].append(self.beta)
|
| 1284 |
+
|
| 1285 |
+
if (
|
| 1286 |
+
self.args.torch_empty_cache_steps is not None
|
| 1287 |
+
and self.state.global_step % self.args.torch_empty_cache_steps == 0
|
| 1288 |
+
):
|
| 1289 |
+
empty_cache()
|
| 1290 |
+
|
| 1291 |
+
kwargs = {}
|
| 1292 |
+
|
| 1293 |
+
# For LOMO optimizers you need to explicitly use the learning rate
|
| 1294 |
+
if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]:
|
| 1295 |
+
kwargs["learning_rate"] = self._get_learning_rate()
|
| 1296 |
+
|
| 1297 |
+
if self.args.n_gpu > 1:
|
| 1298 |
+
loss = loss.mean() # mean() to average on multi-gpu parallel training
|
| 1299 |
+
|
| 1300 |
+
self.accelerator.backward(loss, **kwargs)
|
| 1301 |
+
|
| 1302 |
+
return loss.detach() / self.args.gradient_accumulation_steps
|
| 1303 |
+
|
| 1304 |
+
# Same as Trainer._maybe_log_save_evaluate but log our metrics
|
| 1305 |
+
def _maybe_log_save_evaluate(
|
| 1306 |
+
self, tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval, start_time, learning_rate=None
|
| 1307 |
+
):
|
| 1308 |
+
if self.control.should_log and self.state.global_step > self._globalstep_last_logged:
|
| 1309 |
+
logs: dict[str, float] = {}
|
| 1310 |
+
|
| 1311 |
+
# all_gather + mean() to get average loss over all processes
|
| 1312 |
+
if Version(transformers.__version__) >= Version("5.2.0"):
|
| 1313 |
+
tr_loss_scalar = nested_gather(tr_loss, self.args.parallel_mode).mean().item()
|
| 1314 |
+
else:
|
| 1315 |
+
tr_loss_scalar = self._nested_gather(tr_loss).mean().item()
|
| 1316 |
+
|
| 1317 |
+
# reset tr_loss to zero
|
| 1318 |
+
tr_loss -= tr_loss
|
| 1319 |
+
|
| 1320 |
+
logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)
|
| 1321 |
+
if grad_norm is not None:
|
| 1322 |
+
logs["grad_norm"] = grad_norm.detach().item() if isinstance(grad_norm, torch.Tensor) else grad_norm
|
| 1323 |
+
if learning_rate is not None:
|
| 1324 |
+
logs["learning_rate"] = learning_rate
|
| 1325 |
+
else:
|
| 1326 |
+
logs["learning_rate"] = self._get_learning_rate()
|
| 1327 |
+
|
| 1328 |
+
# Add our metrics
|
| 1329 |
+
for key, val in self.stats.items():
|
| 1330 |
+
logs[key] = sum(val) / len(val)
|
| 1331 |
+
self.stats = {key: [] for key in self.stats} # reset stats
|
| 1332 |
+
|
| 1333 |
+
self._total_loss_scalar += tr_loss_scalar
|
| 1334 |
+
self._globalstep_last_logged = self.state.global_step
|
| 1335 |
+
self.store_flos()
|
| 1336 |
+
self.log(logs, start_time)
|
| 1337 |
+
|
| 1338 |
+
metrics = None
|
| 1339 |
+
if self.control.should_evaluate:
|
| 1340 |
+
metrics = self._evaluate(trial, ignore_keys_for_eval)
|
| 1341 |
+
is_new_best_metric = self._determine_best_metric(metrics=metrics, trial=trial)
|
| 1342 |
+
|
| 1343 |
+
if self.args.save_strategy == "best":
|
| 1344 |
+
self.control.should_save = is_new_best_metric
|
| 1345 |
+
|
| 1346 |
+
if self.control.should_save:
|
| 1347 |
+
self._save_checkpoint(model, trial)
|
| 1348 |
+
self.control = self.callback_handler.on_save(self.args, self.state, self.control)
|
| 1349 |
+
|
| 1350 |
+
# Ensure the model card is saved along with the checkpoint
|
| 1351 |
+
def _save_checkpoint(self, model, trial):
|
| 1352 |
+
if self.args.hub_model_id is None:
|
| 1353 |
+
model_name = Path(self.args.output_dir).name
|
| 1354 |
+
else:
|
| 1355 |
+
model_name = self.args.hub_model_id.split("/")[-1]
|
| 1356 |
+
self.create_model_card(model_name=model_name)
|
| 1357 |
+
super()._save_checkpoint(model, trial)
|
tasks/tasksmith-150751b5c0ba/environment/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-150751b5c0ba/environment/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-150751b5c0ba/environment/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-150751b5c0ba/environment/source/trl/experimental/openreward/_spec.py
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-150751b5c0ba/environment/source/trl/experimental/openreward/environment.py
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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-150751b5c0ba/environment/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"]
|