Stage Harbor release files 501-1000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/dpo_trainer.py +1621 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/grpo_config.py +1061 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/grpo_trainer.py +0 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/kto_config.py +36 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/kto_trainer.py +36 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/model_config.py +178 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/reward_config.py +183 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/reward_trainer.py +757 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/rloo_config.py +668 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/rloo_trainer.py +1638 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/sft_config.py +336 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/sft_trainer.py +0 -0
- tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/utils.py +1501 -0
- tasks/tasksmith-03a6a091b12f/instruction.md +23 -0
- tasks/tasksmith-03a6a091b12f/solution/reference/trl/experimental/kto/kto_config.py +235 -0
- tasks/tasksmith-03a6a091b12f/solution/reference/trl/experimental/kto/kto_trainer.py +1491 -0
- tasks/tasksmith-03a6a091b12f/solution/solve.sh +6 -0
- tasks/tasksmith-03a6a091b12f/task.toml +571 -0
- tasks/tasksmith-03a6a091b12f/tests/Dockerfile +10 -0
- tasks/tasksmith-03a6a091b12f/tests/contract.json +1 -0
- tasks/tasksmith-03a6a091b12f/tests/grade.py +158 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.ai/AGENTS.md +97 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.cursor/BUGBOT.md +97 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml +67 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml +31 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/ISSUE_TEMPLATE/new-trainer-addition.yml +32 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/PULL_REQUEST_TEMPLATE.md +35 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/codeql/custom-queries.qls +19 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/dependabot.yml +11 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/build_documentation.yml +21 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/build_pr_documentation.yml +21 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/clear_cache.yml +32 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/codeQL.yml +26 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/docker-build.yml +96 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/pr_template_check.yml +82 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/publish.yml +43 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/slow-tests.yml +110 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/sync-huggingface-skills.yml +91 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/tests-experimental.yml +71 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/tests.yml +311 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/tests_latest.yml +68 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/tests_transformers_branch.yml +127 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/trufflehog.yml +18 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/upload_pr_documentation.yml +17 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.gitignore +152 -0
- tasks/tasksmith-03a6a091b12f/tests/source/.pre-commit-config.yaml +19 -0
- tasks/tasksmith-03a6a091b12f/tests/source/AGENTS.md +97 -0
- tasks/tasksmith-03a6a091b12f/tests/source/CITATION.cff +41 -0
- tasks/tasksmith-03a6a091b12f/tests/source/CLAUDE.md +97 -0
- tasks/tasksmith-03a6a091b12f/tests/source/CODE_OF_CONDUCT.md +133 -0
tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/dpo_trainer.py
ADDED
|
@@ -0,0 +1,1621 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 json
|
| 17 |
+
import os
|
| 18 |
+
import textwrap
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
from collections.abc import Callable
|
| 21 |
+
from dataclasses import dataclass
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import Any
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
import transformers
|
| 28 |
+
from accelerate import PartialState
|
| 29 |
+
from accelerate.logging import get_logger
|
| 30 |
+
from accelerate.utils import is_peft_model, tqdm
|
| 31 |
+
from datasets import Dataset, IterableDataset, IterableDatasetDict, concatenate_datasets
|
| 32 |
+
from datasets.fingerprint import Hasher
|
| 33 |
+
from packaging.version import Version
|
| 34 |
+
from torch.utils.data import DataLoader
|
| 35 |
+
from transformers import (
|
| 36 |
+
AutoProcessor,
|
| 37 |
+
DataCollator,
|
| 38 |
+
PreTrainedModel,
|
| 39 |
+
PreTrainedTokenizerBase,
|
| 40 |
+
ProcessorMixin,
|
| 41 |
+
)
|
| 42 |
+
from transformers.data.data_collator import DataCollatorMixin
|
| 43 |
+
from transformers.trainer_callback import TrainerCallback
|
| 44 |
+
from transformers.trainer_utils import EvalPrediction
|
| 45 |
+
from transformers.utils import is_liger_kernel_available, is_peft_available
|
| 46 |
+
|
| 47 |
+
from ..data_utils import apply_chat_template, extract_prompt, is_conversational, prepare_multimodal_messages
|
| 48 |
+
from ..models import get_act_offloading_ctx_manager, prepare_deepspeed, prepare_fsdp
|
| 49 |
+
from ..models.utils import disable_gradient_checkpointing
|
| 50 |
+
from .base_trainer import _BaseTrainer
|
| 51 |
+
from .callbacks import SyncRefModelCallback
|
| 52 |
+
from .dpo_config import DPOConfig
|
| 53 |
+
from .utils import (
|
| 54 |
+
create_model_from_path,
|
| 55 |
+
disable_dropout_in_model,
|
| 56 |
+
entropy_from_logits,
|
| 57 |
+
flush_left,
|
| 58 |
+
get_config_model_id,
|
| 59 |
+
hash_module,
|
| 60 |
+
pad,
|
| 61 |
+
selective_log_softmax,
|
| 62 |
+
use_adapter,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if is_peft_available():
|
| 67 |
+
import peft
|
| 68 |
+
from peft import LoraConfig, PeftConfig, PeftModel, get_peft_model
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if is_liger_kernel_available():
|
| 72 |
+
from liger_kernel.chunked_loss import LigerFusedLinearDPOLoss
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
logger = get_logger(__name__)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
FLASH_ATTENTION_VARIANTS = {
|
| 79 |
+
"flash_attention_2",
|
| 80 |
+
"flash_attention_3",
|
| 81 |
+
"kernels-community/flash-attn2",
|
| 82 |
+
"kernels-community/flash-attn3",
|
| 83 |
+
"kernels-community/vllm-flash-attn3",
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]:
|
| 88 |
+
return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@dataclass
|
| 92 |
+
class DataCollatorForPreference(DataCollatorMixin):
|
| 93 |
+
"""
|
| 94 |
+
Data collator used for preference data. Inputs are dynamically padded to the maximum length of a batch.
|
| 95 |
+
|
| 96 |
+
This collator expects each example in the input list to be a dictionary containing the keys `"prompt_ids"`,
|
| 97 |
+
`"chosen_ids"` and `"rejected_ids"`. The collator returns a dictionary containing the following keys:
|
| 98 |
+
- `"input_ids"`: Tensor of input IDs, padded to the maximum length of the batch. The first half of the batch
|
| 99 |
+
corresponds to the `"chosen_ids"` and the second half to the `"rejected_ids"`.
|
| 100 |
+
- `"attention_mask"`: Tensor of attention mask, padded to the maximum length of the batch.
|
| 101 |
+
- `"completion_mask"`: Tensor indicating the positions of the completion tokens, padded to the maximum length of
|
| 102 |
+
the batch.
|
| 103 |
+
|
| 104 |
+
Optionally, the examples can contain a `"ref_chosen_logps"` and `"ref_rejected_logps"` keys, in which case the
|
| 105 |
+
returned dictionary will also contain these keys with the corresponding tensors.
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
pad_token_id (`int`):
|
| 109 |
+
Token ID to use for padding.
|
| 110 |
+
max_length (`int`, *optional*):
|
| 111 |
+
Maximum length of the sequences after concatenation. Sequences longer than `max_length` are truncated
|
| 112 |
+
before padding, which avoids allocating oversized tensors for batches containing very long sequences.
|
| 113 |
+
truncation_mode (`str`, *optional*, defaults to `"keep_start"`):
|
| 114 |
+
Truncation mode when a concatenated sequence exceeds `max_length`. Possible values are `"keep_end"` and
|
| 115 |
+
`"keep_start"`.
|
| 116 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 117 |
+
If set, the sequences will be padded to a multiple of this value.
|
| 118 |
+
return_tensors (`str`, *optional*, defaults to `"pt"`):
|
| 119 |
+
Type of Tensor to return. Only `"pt"` is currently supported.
|
| 120 |
+
|
| 121 |
+
Examples:
|
| 122 |
+
```python
|
| 123 |
+
>>> from trl.trainer.dpo_trainer import DataCollatorForPreference
|
| 124 |
+
|
| 125 |
+
>>> collator = DataCollatorForPreference(pad_token_id=0)
|
| 126 |
+
>>> examples = [
|
| 127 |
+
... {"prompt_ids": [1, 2, 3], "chosen_ids": [4, 5], "rejected_ids": [6]},
|
| 128 |
+
... {"prompt_ids": [7, 8], "chosen_ids": [9], "rejected_ids": [10, 11]},
|
| 129 |
+
... ]
|
| 130 |
+
>>> collator(examples)
|
| 131 |
+
{'input_ids': tensor([[ 1, 2, 3, 4, 5],
|
| 132 |
+
[ 7, 8, 9, 0, 0],
|
| 133 |
+
[ 1, 2, 3, 6, 0],
|
| 134 |
+
[ 7, 8, 10, 11, 0]]),
|
| 135 |
+
'attention_mask': tensor([[1, 1, 1, 1, 1],
|
| 136 |
+
[1, 1, 1, 0, 0],
|
| 137 |
+
[1, 1, 1, 1, 0],
|
| 138 |
+
[1, 1, 1, 1, 0]]),
|
| 139 |
+
'completion_mask': tensor([[0, 0, 0, 1, 1],
|
| 140 |
+
[0, 0, 1, 0, 0],
|
| 141 |
+
[0, 0, 0, 1, 0],
|
| 142 |
+
[0, 0, 1, 1, 0]])}
|
| 143 |
+
```
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
pad_token_id: int
|
| 147 |
+
max_length: int | None = None
|
| 148 |
+
truncation_mode: str = "keep_start"
|
| 149 |
+
pad_to_multiple_of: int | None = None
|
| 150 |
+
return_tensors: str = "pt"
|
| 151 |
+
|
| 152 |
+
def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
|
| 153 |
+
prompt_chosen_ids = [example["prompt_ids"] + example["chosen_ids"] for example in examples]
|
| 154 |
+
prompt_rejected_ids = [example["prompt_ids"] + example["rejected_ids"] for example in examples]
|
| 155 |
+
chosen_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["chosen_ids"]) for example in examples]
|
| 156 |
+
rejected_mask = [[0] * len(example["prompt_ids"]) + [1] * len(example["rejected_ids"]) for example in examples]
|
| 157 |
+
|
| 158 |
+
if self.max_length is not None:
|
| 159 |
+
if self.truncation_mode == "keep_start":
|
| 160 |
+
sl = slice(None, self.max_length)
|
| 161 |
+
elif self.truncation_mode == "keep_end":
|
| 162 |
+
sl = slice(-self.max_length, None)
|
| 163 |
+
else:
|
| 164 |
+
raise ValueError(
|
| 165 |
+
f"Unsupported truncation mode: {self.truncation_mode}, expected 'keep_start' or 'keep_end'"
|
| 166 |
+
)
|
| 167 |
+
prompt_chosen_ids = [ids[sl] for ids in prompt_chosen_ids]
|
| 168 |
+
prompt_rejected_ids = [ids[sl] for ids in prompt_rejected_ids]
|
| 169 |
+
chosen_mask = [m[sl] for m in chosen_mask]
|
| 170 |
+
rejected_mask = [m[sl] for m in rejected_mask]
|
| 171 |
+
|
| 172 |
+
chosen_attention_mask = [[1] * len(ids) for ids in prompt_chosen_ids]
|
| 173 |
+
rejected_attention_mask = [[1] * len(ids) for ids in prompt_rejected_ids]
|
| 174 |
+
input_ids = prompt_chosen_ids + prompt_rejected_ids
|
| 175 |
+
attention_mask = chosen_attention_mask + rejected_attention_mask
|
| 176 |
+
completion_mask = chosen_mask + rejected_mask
|
| 177 |
+
|
| 178 |
+
# Convert to tensor
|
| 179 |
+
input_ids = [torch.tensor(ids) for ids in input_ids]
|
| 180 |
+
attention_mask = [torch.tensor(m, dtype=torch.long) for m in attention_mask]
|
| 181 |
+
completion_mask = [torch.tensor(m, dtype=torch.long) for m in completion_mask]
|
| 182 |
+
if "ref_chosen_logps" in examples[0]:
|
| 183 |
+
ref_chosen_logps = torch.tensor([example["ref_chosen_logps"] for example in examples])
|
| 184 |
+
if "ref_rejected_logps" in examples[0]:
|
| 185 |
+
ref_rejected_logps = torch.tensor([example["ref_rejected_logps"] for example in examples])
|
| 186 |
+
|
| 187 |
+
# Pad
|
| 188 |
+
output = {}
|
| 189 |
+
output["input_ids"] = pad(
|
| 190 |
+
input_ids,
|
| 191 |
+
padding_value=self.pad_token_id,
|
| 192 |
+
padding_side="right",
|
| 193 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 194 |
+
)
|
| 195 |
+
output["attention_mask"] = pad(
|
| 196 |
+
attention_mask,
|
| 197 |
+
padding_value=0,
|
| 198 |
+
padding_side="right",
|
| 199 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 200 |
+
)
|
| 201 |
+
output["completion_mask"] = pad(
|
| 202 |
+
completion_mask,
|
| 203 |
+
padding_value=0,
|
| 204 |
+
padding_side="right",
|
| 205 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 206 |
+
)
|
| 207 |
+
if "ref_chosen_logps" in examples[0]:
|
| 208 |
+
output["ref_chosen_logps"] = ref_chosen_logps
|
| 209 |
+
if "ref_rejected_logps" in examples[0]:
|
| 210 |
+
output["ref_rejected_logps"] = ref_rejected_logps
|
| 211 |
+
return output
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
@dataclass
|
| 215 |
+
class DataCollatorForVisionPreference(DataCollatorMixin):
|
| 216 |
+
"""
|
| 217 |
+
Data collator for vision-preference tasks.
|
| 218 |
+
|
| 219 |
+
Unlike text-only datasets, where the collator typically receives pre-tokenized inputs ready for batching,
|
| 220 |
+
vision-language data processing involves converting images into pixel values. This conversion is disk-intensive,
|
| 221 |
+
making upfront preprocessing of the entire dataset impractical. Therefore, this collator performs tokenization and
|
| 222 |
+
image processing on-the-fly to efficiently prepare batches.
|
| 223 |
+
|
| 224 |
+
Each input example should be a dictionary containing at least:
|
| 225 |
+
- An `"images"` key holding a list of images, or an `"image"` key holding a single image.
|
| 226 |
+
- Keys `"prompt"` `"chosen"` and `"rejected"` for the prompt and preference responses.
|
| 227 |
+
|
| 228 |
+
The collator outputs a dictionary including:
|
| 229 |
+
- `"input_ids"`: Tensor of token IDs.
|
| 230 |
+
- `"attention_mask"`: Tensor indicating attention mask.
|
| 231 |
+
- `"completion_mask"`: Tensor indicating which tokens correspond to completions.
|
| 232 |
+
- `"pixel_values"`: Tensor representing image pixel values.
|
| 233 |
+
|
| 234 |
+
Additional keys may be present depending on the processor, such as `"image_grid_thw"` or `"image_position_ids"`.
|
| 235 |
+
|
| 236 |
+
Args:
|
| 237 |
+
processor ([`~transformers.ProcessorMixin`]):
|
| 238 |
+
The processor used to tokenize text and process images. It must be a subclass of
|
| 239 |
+
[`~transformers.ProcessorMixin`] and include a `tokenizer` with a defined `pad_token_id`.
|
| 240 |
+
max_length (`int`, *optional*):
|
| 241 |
+
Maximum sequence length. Sequences longer than `max_length` are truncated before padding, which avoids
|
| 242 |
+
allocating oversized tensors for batches containing very long sequences. Only `"keep_start"` truncation
|
| 243 |
+
applies to vision datasets; `"keep_end"` is rejected upstream.
|
| 244 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 245 |
+
If set, the sequences will be padded to a multiple of this value.
|
| 246 |
+
return_tensors (`str`, *optional*, defaults to `"pt"`):
|
| 247 |
+
The tensor type to return. Currently, only `"pt"` (PyTorch tensors) is supported.
|
| 248 |
+
|
| 249 |
+
Example:
|
| 250 |
+
```python
|
| 251 |
+
>>> from trl.trainer.dpo_trainer import DataCollatorForVisionPreference
|
| 252 |
+
>>> from transformers import AutoProcessor
|
| 253 |
+
|
| 254 |
+
>>> processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
|
| 255 |
+
>>> collator = DataCollatorForVisionPreference(processor)
|
| 256 |
+
>>> examples = [
|
| 257 |
+
... {
|
| 258 |
+
... "images": [Image.open("image_0.png")],
|
| 259 |
+
... "prompt": [{"role": "user", "content": "What is this?"}],
|
| 260 |
+
... "chosen": [{"role": "assistant", "content": "This is a cat."}],
|
| 261 |
+
... "rejected": [{"role": "assistant", "content": "This is a dog."}],
|
| 262 |
+
... },
|
| 263 |
+
... {
|
| 264 |
+
... "images": [Image.open("image_1.png")],
|
| 265 |
+
... "prompt": [{"role": "user", "content": "Describe this image."}],
|
| 266 |
+
... "chosen": [{"role": "assistant", "content": "A beautiful landscape."}],
|
| 267 |
+
... "rejected": [{"role": "assistant", "content": "An urban cityscape."}],
|
| 268 |
+
... },
|
| 269 |
+
... ]
|
| 270 |
+
>>> collator(examples)
|
| 271 |
+
{'input_ids': tensor([[151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 3838, 374, 419, 30, 151645, 198, 151644, 77091, 198, 1986, 374, 264, 8251, 13, 151645, 198],
|
| 272 |
+
[151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 74785, 419, 2168, 13, 151645, 198, 151644, 77091, 198, 32, 6233, 18414, 13, 151645, 198, 151643],
|
| 273 |
+
[151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 3838, 374, 419, 30, 151645, 198, 151644, 77091, 198, 1986, 374, 264, 5562, 13, 151645, 198],
|
| 274 |
+
[151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655, 151655, 151655, 151655, 151653, 74785, 419, 2168, 13, 151645, 198, 151644, 77091, 198, 2082, 15662, 3283, 57518, 13, 151645, 198]]),
|
| 275 |
+
'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
|
| 276 |
+
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
|
| 277 |
+
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
|
| 278 |
+
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]),
|
| 279 |
+
'pixel_values': tensor([[-1.3251, 0.1347, -0.4784, ..., 0.4537, -0.0156, 1.2358],
|
| 280 |
+
[ 0.5727, 0.4997, -0.9164, ..., -0.5701, 0.7950, -0.7123],
|
| 281 |
+
[-0.0550, -0.8288, 1.0690, ..., -0.1293, -0.1151, 1.6055],
|
| 282 |
+
...,
|
| 283 |
+
[ 0.2953, 0.5581, 0.1785, ..., -0.7123, -0.7977, 0.1693],
|
| 284 |
+
[-0.7558, 1.0398, 1.3464, ..., -0.5417, -0.5417, 0.4395],
|
| 285 |
+
[ 0.8063, 0.6895, 0.4267, ..., -0.4422, 1.3354, 0.1266]]),
|
| 286 |
+
'image_grid_thw': tensor([[1, 4, 4],
|
| 287 |
+
[1, 4, 4],
|
| 288 |
+
[1, 4, 4],
|
| 289 |
+
[1, 4, 4]]),
|
| 290 |
+
'completion_mask': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1],
|
| 291 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0],
|
| 292 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1],
|
| 293 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]])}
|
| 294 |
+
```
|
| 295 |
+
"""
|
| 296 |
+
|
| 297 |
+
processor: ProcessorMixin
|
| 298 |
+
max_length: int | None = None
|
| 299 |
+
pad_to_multiple_of: int | None = None
|
| 300 |
+
return_tensors: str = "pt"
|
| 301 |
+
|
| 302 |
+
def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
|
| 303 |
+
if self.pad_to_multiple_of is not None:
|
| 304 |
+
raise NotImplementedError(
|
| 305 |
+
"Padding to a multiple of a value is not yet implemented for vision-language modeling and "
|
| 306 |
+
"prompt-completion data."
|
| 307 |
+
)
|
| 308 |
+
if "image" in examples[0]:
|
| 309 |
+
for example in examples:
|
| 310 |
+
example["images"] = [example.pop("image")]
|
| 311 |
+
images = [example["images"] for example in examples] * 2 # repeat for chosen and rejected
|
| 312 |
+
# Transformers requires at least one image in the batch, otherwise it throws an error
|
| 313 |
+
if all(img_list == [] for img_list in images):
|
| 314 |
+
images = None
|
| 315 |
+
if is_conversational(examples[0]): # conversational case
|
| 316 |
+
for example in examples:
|
| 317 |
+
example["prompt"] = prepare_multimodal_messages(example["prompt"], images=example["images"])
|
| 318 |
+
example["chosen"] = prepare_multimodal_messages(example["chosen"])
|
| 319 |
+
example["rejected"] = prepare_multimodal_messages(example["rejected"])
|
| 320 |
+
examples = [apply_chat_template(example, self.processor) for example in examples]
|
| 321 |
+
|
| 322 |
+
prompts = [example["prompt"] for example in examples] * 2 # repeat for chosen and rejected
|
| 323 |
+
chosens = [example["chosen"] for example in examples]
|
| 324 |
+
rejecteds = [example["rejected"] for example in examples]
|
| 325 |
+
|
| 326 |
+
processed_prompts = self.processor(
|
| 327 |
+
images=images,
|
| 328 |
+
text=prompts,
|
| 329 |
+
padding=True,
|
| 330 |
+
padding_side="left",
|
| 331 |
+
return_tensors=self.return_tensors,
|
| 332 |
+
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
|
| 333 |
+
)
|
| 334 |
+
processed_chosens = self.processor(
|
| 335 |
+
text=chosens,
|
| 336 |
+
padding=True,
|
| 337 |
+
padding_side="right",
|
| 338 |
+
return_tensors=self.return_tensors,
|
| 339 |
+
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
|
| 340 |
+
)
|
| 341 |
+
processed_rejecteds = self.processor(
|
| 342 |
+
text=rejecteds,
|
| 343 |
+
padding=True,
|
| 344 |
+
padding_side="right",
|
| 345 |
+
return_tensors=self.return_tensors,
|
| 346 |
+
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
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# Concatenate prompts and completions
|
| 350 |
+
prompt_ids, prompt_mask = processed_prompts["input_ids"], processed_prompts["attention_mask"]
|
| 351 |
+
chosen_ids, chosen_mask = processed_chosens["input_ids"], processed_chosens["attention_mask"]
|
| 352 |
+
rejected_ids, rejected_mask = processed_rejecteds["input_ids"], processed_rejecteds["attention_mask"]
|
| 353 |
+
pad_token_id = self.processor.tokenizer.pad_token_id or self.processor.tokenizer.eos_token_id
|
| 354 |
+
completion_ids = torch.cat(tuple(pad([chosen_ids, rejected_ids], padding_value=pad_token_id)))
|
| 355 |
+
completion_mask = torch.cat(tuple(pad([chosen_mask, rejected_mask], padding_value=0)))
|
| 356 |
+
input_ids = torch.cat((prompt_ids, completion_ids), dim=1)
|
| 357 |
+
attention_mask = torch.cat((prompt_mask, completion_mask), dim=1)
|
| 358 |
+
completion_mask = torch.cat((torch.zeros_like(prompt_mask), completion_mask), dim=1)
|
| 359 |
+
if "token_type_ids" in processed_prompts: # special case for Gemma
|
| 360 |
+
prompt_token_type_ids = processed_prompts["token_type_ids"]
|
| 361 |
+
chosen_type_ids = processed_chosens["token_type_ids"]
|
| 362 |
+
rejected_type_ids = processed_rejecteds["token_type_ids"]
|
| 363 |
+
completion_token_type_ids = torch.cat(tuple(pad([chosen_type_ids, rejected_type_ids], padding_value=0)))
|
| 364 |
+
token_type_ids = torch.cat((prompt_token_type_ids, completion_token_type_ids), dim=1)
|
| 365 |
+
if "mm_token_type_ids" in processed_prompts: # special case for Qwen2.5-VL
|
| 366 |
+
prompt_mm_token_type_ids = processed_prompts["mm_token_type_ids"]
|
| 367 |
+
mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, torch.zeros_like(completion_ids)), dim=1)
|
| 368 |
+
|
| 369 |
+
# Flush left to reduce padding
|
| 370 |
+
if "token_type_ids" in processed_prompts and "mm_token_type_ids" in processed_prompts:
|
| 371 |
+
attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids = flush_left(
|
| 372 |
+
attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids
|
| 373 |
+
)
|
| 374 |
+
elif "token_type_ids" in processed_prompts:
|
| 375 |
+
attention_mask, input_ids, completion_mask, token_type_ids = flush_left(
|
| 376 |
+
attention_mask, input_ids, completion_mask, token_type_ids
|
| 377 |
+
)
|
| 378 |
+
elif "mm_token_type_ids" in processed_prompts:
|
| 379 |
+
attention_mask, input_ids, completion_mask, mm_token_type_ids = flush_left(
|
| 380 |
+
attention_mask, input_ids, completion_mask, mm_token_type_ids
|
| 381 |
+
)
|
| 382 |
+
else:
|
| 383 |
+
attention_mask, input_ids, completion_mask = flush_left(attention_mask, input_ids, completion_mask)
|
| 384 |
+
|
| 385 |
+
if self.max_length is not None:
|
| 386 |
+
input_ids = input_ids[:, : self.max_length]
|
| 387 |
+
attention_mask = attention_mask[:, : self.max_length]
|
| 388 |
+
completion_mask = completion_mask[:, : self.max_length]
|
| 389 |
+
if "token_type_ids" in processed_prompts:
|
| 390 |
+
token_type_ids = token_type_ids[:, : self.max_length]
|
| 391 |
+
if "mm_token_type_ids" in processed_prompts:
|
| 392 |
+
mm_token_type_ids = mm_token_type_ids[:, : self.max_length]
|
| 393 |
+
|
| 394 |
+
# Build the output dictionary
|
| 395 |
+
output = processed_prompts # we take processed_prompts because it contains the images
|
| 396 |
+
output["input_ids"] = input_ids
|
| 397 |
+
output["attention_mask"] = attention_mask
|
| 398 |
+
output["completion_mask"] = completion_mask
|
| 399 |
+
if "token_type_ids" in processed_prompts:
|
| 400 |
+
output["token_type_ids"] = token_type_ids
|
| 401 |
+
if "mm_token_type_ids" in processed_prompts:
|
| 402 |
+
output["mm_token_type_ids"] = mm_token_type_ids
|
| 403 |
+
return output
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
class DPOTrainer(_BaseTrainer):
|
| 407 |
+
"""
|
| 408 |
+
Trainer for Direct Preference Optimization (DPO) method. This algorithm was initially proposed in the paper [Direct
|
| 409 |
+
Preference Optimization: Your Language Model is Secretly a Reward Model](https://huggingface.co/papers/2305.18290).
|
| 410 |
+
This class is a wrapper around the [`~transformers.Trainer`] class and inherits all of its attributes and methods.
|
| 411 |
+
|
| 412 |
+
Example:
|
| 413 |
+
|
| 414 |
+
```python
|
| 415 |
+
from trl import DPOTrainer
|
| 416 |
+
from datasets import load_dataset
|
| 417 |
+
|
| 418 |
+
dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
|
| 419 |
+
|
| 420 |
+
trainer = DPOTrainer(
|
| 421 |
+
model="Qwen/Qwen2.5-0.5B-Instruct",
|
| 422 |
+
train_dataset=dataset,
|
| 423 |
+
)
|
| 424 |
+
trainer.train()
|
| 425 |
+
```
|
| 426 |
+
|
| 427 |
+
Args:
|
| 428 |
+
model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]):
|
| 429 |
+
Model to be trained. Can be either:
|
| 430 |
+
|
| 431 |
+
- A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
|
| 432 |
+
path to a *directory* containing model weights saved using
|
| 433 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
| 434 |
+
using `<ModelArchitecture>.from_pretrained` (where `<ModelArchitecture>` is derived from the model
|
| 435 |
+
config) with the keyword arguments in `args.model_init_kwargs`.
|
| 436 |
+
- A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
|
| 437 |
+
- A [`~peft.PeftModel`] object. Only causal language models are supported.
|
| 438 |
+
ref_model ([`~transformers.PreTrainedModel`], *optional*):
|
| 439 |
+
Reference model used to compute the reference log probabilities.
|
| 440 |
+
|
| 441 |
+
- If provided, this model is used directly as the reference policy.
|
| 442 |
+
- If `None`, the trainer will automatically use the initial policy corresponding to `model`, i.e. the model
|
| 443 |
+
state before DPO training starts.
|
| 444 |
+
args ([`DPOConfig`], *optional*):
|
| 445 |
+
Configuration for this trainer. If `None`, a default configuration is used.
|
| 446 |
+
data_collator ([`~transformers.DataCollator`], *optional*):
|
| 447 |
+
Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`.
|
| 448 |
+
Will default to [`~trainer.dpo_trainer.DataCollatorForPreference`] if the model is a language model and
|
| 449 |
+
[`~trainer.dpo_trainer.DataCollatorForVisionPreference`] if the model is a vision-language model. Custom
|
| 450 |
+
collators must truncate sequences before padding; the trainer does not apply post-collation truncation.
|
| 451 |
+
train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
|
| 452 |
+
Dataset to use for training. This trainer supports both [language modeling](#language-modeling) type and
|
| 453 |
+
[prompt-completion](#prompt-completion) type. The format of the samples can be either:
|
| 454 |
+
|
| 455 |
+
- [Standard](dataset_formats#standard): Each sample contains plain text.
|
| 456 |
+
- [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
|
| 457 |
+
and content).
|
| 458 |
+
eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
|
| 459 |
+
Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
|
| 460 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`], *optional*):
|
| 461 |
+
Processing class used to process the data. The padding side must be set to "left". If `None`, the
|
| 462 |
+
processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A
|
| 463 |
+
padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
|
| 464 |
+
`tokenizer.eos_token` will be used as the default.
|
| 465 |
+
compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
|
| 466 |
+
The function that will be used to compute metrics at evaluation. Must take a
|
| 467 |
+
[`~transformers.EvalPrediction`] and return a dictionary string to metric values. When passing
|
| 468 |
+
[`SFTConfig`] with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a boolean
|
| 469 |
+
`compute_result` argument. This will be triggered after the last eval batch to signal that the function
|
| 470 |
+
needs to calculate and return the global summary statistics rather than accumulating the batch-level
|
| 471 |
+
statistics.
|
| 472 |
+
callbacks (list of [`~transformers.TrainerCallback`], *optional*):
|
| 473 |
+
List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
|
| 474 |
+
in [here](https://huggingface.co/docs/transformers/main_classes/callback).
|
| 475 |
+
|
| 476 |
+
If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
|
| 477 |
+
method.
|
| 478 |
+
optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`):
|
| 479 |
+
A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your
|
| 480 |
+
model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`.
|
| 481 |
+
peft_config ([`~peft.PeftConfig`], *optional*):
|
| 482 |
+
PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
|
| 483 |
+
"""
|
| 484 |
+
|
| 485 |
+
_tag_names = ["trl", "dpo"]
|
| 486 |
+
_name = "DPO"
|
| 487 |
+
_paper = {
|
| 488 |
+
"title": "Direct Preference Optimization: Your Language Model is Secretly a Reward Model",
|
| 489 |
+
"id": "2305.18290",
|
| 490 |
+
# docstyle-ignore
|
| 491 |
+
"citation": textwrap.dedent("""\
|
| 492 |
+
@inproceedings{rafailov2023direct,
|
| 493 |
+
title = {{Direct Preference Optimization: Your Language Model is Secretly a Reward Model}},
|
| 494 |
+
author = {Rafael Rafailov and Archit Sharma and Eric Mitchell and Christopher D. Manning and Stefano Ermon and Chelsea Finn},
|
| 495 |
+
year = 2023,
|
| 496 |
+
booktitle = {Advances in Neural Information Processing Systems 36: Annual Conference on Neural Information Processing Systems 2023, NeurIPS 2023, New Orleans, LA, USA, December 10 - 16, 2023},
|
| 497 |
+
url = {http://papers.nips.cc/paper_files/paper/2023/hash/a85b405ed65c6477a4fe8302b5e06ce7-Abstract-Conference.html},
|
| 498 |
+
editor = {Alice Oh and Tristan Naumann and Amir Globerson and Kate Saenko and Moritz Hardt and Sergey Levine},
|
| 499 |
+
}"""),
|
| 500 |
+
}
|
| 501 |
+
|
| 502 |
+
def __init__(
|
| 503 |
+
self,
|
| 504 |
+
model: "str | PreTrainedModel | PeftModel",
|
| 505 |
+
ref_model: PreTrainedModel | None = None,
|
| 506 |
+
args: DPOConfig | None = None,
|
| 507 |
+
data_collator: DataCollator | None = None,
|
| 508 |
+
train_dataset: Dataset | IterableDataset | None = None,
|
| 509 |
+
eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
|
| 510 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
|
| 511 |
+
compute_metrics: Callable[[EvalPrediction], dict] | None = None,
|
| 512 |
+
callbacks: list[TrainerCallback] | None = None,
|
| 513 |
+
optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
|
| 514 |
+
peft_config: "PeftConfig | None" = None,
|
| 515 |
+
):
|
| 516 |
+
# Args
|
| 517 |
+
if args is None:
|
| 518 |
+
model_name = model if isinstance(model, str) else get_config_model_id(model.config)
|
| 519 |
+
model_name = model_name.split("/")[-1]
|
| 520 |
+
args = DPOConfig(f"{model_name}-DPO")
|
| 521 |
+
|
| 522 |
+
if train_dataset is None:
|
| 523 |
+
raise ValueError("`train_dataset` is required")
|
| 524 |
+
elif isinstance(train_dataset, IterableDataset):
|
| 525 |
+
# IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate
|
| 526 |
+
# batches from multiple processes, leading to mismatch errors.
|
| 527 |
+
if args.accelerator_config.dispatch_batches is True:
|
| 528 |
+
logger.warning(
|
| 529 |
+
"You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` "
|
| 530 |
+
"is forced to `False` when using an `IterableDataset`. To remove this warning, unset "
|
| 531 |
+
"`dispatch_batches` in `DPOConfig` or set it to `False`."
|
| 532 |
+
)
|
| 533 |
+
args.accelerator_config.dispatch_batches = False
|
| 534 |
+
|
| 535 |
+
# Model
|
| 536 |
+
if isinstance(model, str):
|
| 537 |
+
model_init_kwargs = args.model_init_kwargs or {}
|
| 538 |
+
# Distributed training requires device_map=None ("auto" fails)
|
| 539 |
+
if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
|
| 540 |
+
model_init_kwargs["device_map"] = None
|
| 541 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 542 |
+
model = create_model_from_path(model, **model_init_kwargs)
|
| 543 |
+
else:
|
| 544 |
+
if args.model_init_kwargs is not None:
|
| 545 |
+
logger.warning(
|
| 546 |
+
"You passed `model_init_kwargs` to the `DPOConfig`, but your model is already instantiated. "
|
| 547 |
+
"The `model_init_kwargs` will be ignored."
|
| 548 |
+
)
|
| 549 |
+
# Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do
|
| 550 |
+
_is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False)
|
| 551 |
+
if ref_model is model:
|
| 552 |
+
raise ValueError(
|
| 553 |
+
"`model` and `ref_model` cannot be the same object. In most cases you should omit `ref_model` and "
|
| 554 |
+
"we'll initialize it to a copy of `model` for you."
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
# Processing class
|
| 558 |
+
if processing_class is None:
|
| 559 |
+
processing_class = AutoProcessor.from_pretrained(
|
| 560 |
+
get_config_model_id(model.config), trust_remote_code=args.trust_remote_code
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
# Handle pad token for processors or tokenizers
|
| 564 |
+
if isinstance(processing_class, ProcessorMixin):
|
| 565 |
+
self._tokenizer = processing_class.tokenizer
|
| 566 |
+
self._is_vlm = True
|
| 567 |
+
elif isinstance(processing_class, PreTrainedTokenizerBase):
|
| 568 |
+
self._tokenizer = processing_class
|
| 569 |
+
self._is_vlm = False
|
| 570 |
+
else:
|
| 571 |
+
raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
|
| 572 |
+
|
| 573 |
+
if self._tokenizer.pad_token is None:
|
| 574 |
+
self._tokenizer.pad_token = self._tokenizer.eos_token
|
| 575 |
+
|
| 576 |
+
# PEFT
|
| 577 |
+
if peft_config is not None:
|
| 578 |
+
if not is_peft_available():
|
| 579 |
+
raise ImportError(
|
| 580 |
+
"You passed `peft_config` but the `peft` library is not installed. "
|
| 581 |
+
"Install it with `pip install trl[peft]`."
|
| 582 |
+
)
|
| 583 |
+
if not isinstance(peft_config, PeftConfig):
|
| 584 |
+
raise TypeError(
|
| 585 |
+
f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
|
| 586 |
+
f"got {type(peft_config).__name__}."
|
| 587 |
+
)
|
| 588 |
+
if is_peft_model(model):
|
| 589 |
+
raise ValueError(
|
| 590 |
+
"You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge "
|
| 591 |
+
"and unload the existing adapter, save the resulting base model, and then pass that base model along "
|
| 592 |
+
"with the new `peft_config` to the trainer."
|
| 593 |
+
)
|
| 594 |
+
# Create PEFT model
|
| 595 |
+
# ZeRO-3 + PEFT for non-quantized models:
|
| 596 |
+
# - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16.
|
| 597 |
+
# - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter,
|
| 598 |
+
# so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step.
|
| 599 |
+
# - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch.
|
| 600 |
+
# - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for
|
| 601 |
+
# non-quantized bf16 training.
|
| 602 |
+
# - See:
|
| 603 |
+
# - TRL issue: https://github.com/huggingface/trl/issues/6089
|
| 604 |
+
# - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072
|
| 605 |
+
# - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg
|
| 606 |
+
get_peft_model_kwargs = {}
|
| 607 |
+
if (
|
| 608 |
+
args.deepspeed_plugin is not None
|
| 609 |
+
and args.deepspeed_plugin.zero_stage == 3
|
| 610 |
+
and not _is_quantized_model
|
| 611 |
+
and Version(peft.__version__) >= Version("0.12.0")
|
| 612 |
+
):
|
| 613 |
+
get_peft_model_kwargs["autocast_adapter_dtype"] = False
|
| 614 |
+
model = get_peft_model(model, peft_config, **get_peft_model_kwargs)
|
| 615 |
+
|
| 616 |
+
elif is_peft_model(model) and ref_model is None:
|
| 617 |
+
# If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy
|
| 618 |
+
# of the "default" adapter, so that we can use it as the reference model during DPO training. PEFT only
|
| 619 |
+
# supports one adapter per model when the LoRA config uses `target_parameters` (see peft#3340), so in that
|
| 620 |
+
# case we skip the "ref" adapter and compute the reference log probs with adapters disabled, i.e. with the
|
| 621 |
+
# base model.
|
| 622 |
+
default_config = model.peft_config["default"]
|
| 623 |
+
if isinstance(default_config, LoraConfig) and default_config.target_parameters:
|
| 624 |
+
logger.warning(
|
| 625 |
+
"PEFT can't add a frozen reference adapter alongside one that uses `target_parameters` "
|
| 626 |
+
"(peft#3340), so the reference log probs are computed from the base model (adapters disabled). "
|
| 627 |
+
"If you wrapped the model only to apply LoRA, pass a `peft_config` to the trainer instead; if you "
|
| 628 |
+
"wrapped it deliberately (pretrained adapter or custom init), note that the base model matches "
|
| 629 |
+
"your adapter only when it's freshly zero-initialized. If it is, this warning is safe to ignore."
|
| 630 |
+
)
|
| 631 |
+
else:
|
| 632 |
+
model.add_adapter("ref", default_config)
|
| 633 |
+
for name, param in model.named_parameters():
|
| 634 |
+
if ".default." in name:
|
| 635 |
+
ref_name = name.replace(".default.", ".ref.")
|
| 636 |
+
ref_param = model.get_parameter(ref_name)
|
| 637 |
+
ref_param.data.copy_(param.data)
|
| 638 |
+
|
| 639 |
+
# When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally
|
| 640 |
+
# handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489
|
| 641 |
+
if is_peft_model(model) and args.gradient_checkpointing:
|
| 642 |
+
model.enable_input_require_grads()
|
| 643 |
+
|
| 644 |
+
# When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the
|
| 645 |
+
# original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by
|
| 646 |
+
# passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for
|
| 647 |
+
# quantized models. See: https://github.com/huggingface/peft/issues/2889
|
| 648 |
+
if _is_quantized_model:
|
| 649 |
+
for param in model.parameters():
|
| 650 |
+
if param.requires_grad:
|
| 651 |
+
param.data = param.data.to(torch.bfloat16)
|
| 652 |
+
|
| 653 |
+
# Data collator
|
| 654 |
+
self.padding_free = args.padding_free
|
| 655 |
+
if self.padding_free:
|
| 656 |
+
logger.warning(
|
| 657 |
+
"`padding_free=True` is temporarily unavailable after a refactor and is currently disabled. Falling "
|
| 658 |
+
"back to standard padding (`padding_free=False`). This feature is planned to return in a future "
|
| 659 |
+
"update; for now, please set `padding_free=False` explicitly."
|
| 660 |
+
)
|
| 661 |
+
self.padding_free = False
|
| 662 |
+
dataset_sample = next(iter(train_dataset))
|
| 663 |
+
self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample
|
| 664 |
+
if self._is_vision_dataset and not self._is_vlm:
|
| 665 |
+
raise ValueError(
|
| 666 |
+
"The dataset appears to be vision-related (contains 'image' or 'images' keys), but the provided "
|
| 667 |
+
"model does not seem to be a vision-language model. Please check your model and dataset."
|
| 668 |
+
)
|
| 669 |
+
if self._is_vision_dataset and args.max_length is not None and args.truncation_mode == "keep_end":
|
| 670 |
+
raise ValueError(
|
| 671 |
+
"truncation_mode='keep_end' is not supported for vision-language models. Image tokens reside "
|
| 672 |
+
"inside the prompt portion of the sequence; depending on the example, keep_end may silently "
|
| 673 |
+
"drop them, causing pixel_values to be forwarded to the model with no corresponding visual "
|
| 674 |
+
"tokens in input_ids. Use truncation_mode='keep_start' (the default) or set max_length=None."
|
| 675 |
+
)
|
| 676 |
+
if self._is_vision_dataset and args.precompute_ref_log_probs:
|
| 677 |
+
raise ValueError(
|
| 678 |
+
"`precompute_ref_log_probs=True` is not supported for vision datasets. For vision-language "
|
| 679 |
+
"models, all data processing is performed on the fly rather than upfront, and running a full "
|
| 680 |
+
"forward pass of the reference model over the entire dataset is not supported for large "
|
| 681 |
+
"multimodal models. Set `precompute_ref_log_probs=False`."
|
| 682 |
+
)
|
| 683 |
+
if data_collator is None and not self._is_vision_dataset:
|
| 684 |
+
# Get the pad token: if not provided, use the one from the processing class or the eos token
|
| 685 |
+
# if the processing class does not have a pad token.
|
| 686 |
+
pad_token = args.pad_token or self._tokenizer.pad_token or self._tokenizer.eos_token
|
| 687 |
+
if pad_token not in self._tokenizer.get_vocab():
|
| 688 |
+
raise ValueError(
|
| 689 |
+
f"The specified `pad_token` ('{pad_token}') is not found in the vocabulary of the given "
|
| 690 |
+
f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `pad_token` exists "
|
| 691 |
+
"in the vocabulary before using it as a padding token."
|
| 692 |
+
)
|
| 693 |
+
self._tokenizer.pad_token = pad_token
|
| 694 |
+
data_collator = DataCollatorForPreference(
|
| 695 |
+
pad_token_id=self._tokenizer.pad_token_id,
|
| 696 |
+
max_length=args.max_length,
|
| 697 |
+
truncation_mode=args.truncation_mode,
|
| 698 |
+
pad_to_multiple_of=args.pad_to_multiple_of,
|
| 699 |
+
)
|
| 700 |
+
elif data_collator is None and self._is_vision_dataset:
|
| 701 |
+
data_collator = DataCollatorForVisionPreference(
|
| 702 |
+
processor=processing_class,
|
| 703 |
+
max_length=args.max_length,
|
| 704 |
+
pad_to_multiple_of=args.pad_to_multiple_of,
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
# Training arguments
|
| 708 |
+
self.beta = args.beta
|
| 709 |
+
self.precompute_ref_logps = args.precompute_ref_log_probs
|
| 710 |
+
self.loss_types = args.loss_type # args.loss_type is already a list
|
| 711 |
+
self.loss_weights = args.loss_weights or [1.0] * len(self.loss_types)
|
| 712 |
+
self.ld_alpha = args.ld_alpha
|
| 713 |
+
self.f_divergence_type = args.f_divergence_type
|
| 714 |
+
self.f_alpha_divergence_coef = args.f_alpha_divergence_coef
|
| 715 |
+
self.label_smoothing = args.label_smoothing
|
| 716 |
+
self.use_weighting = args.use_weighting
|
| 717 |
+
if self.use_weighting and any(loss_type in {"aot", "aot_unpaired"} for loss_type in self.loss_types):
|
| 718 |
+
raise NotImplementedError(
|
| 719 |
+
"WPO-style weighting is not implemented for 'aot' or 'aot_unpaired' because those losses sort "
|
| 720 |
+
"samples, which would misalign per-pair weights."
|
| 721 |
+
)
|
| 722 |
+
if "robust" in self.loss_types and not (0.0 <= self.label_smoothing < 0.5):
|
| 723 |
+
logger.warning(
|
| 724 |
+
"The `label_smoothing` parameter should lie in [0.0, 0.5) for the 'robust' loss. You provided "
|
| 725 |
+
f"{self.label_smoothing}."
|
| 726 |
+
)
|
| 727 |
+
if "exo_pair" in self.loss_types and self.label_smoothing == 0.0:
|
| 728 |
+
raise ValueError(
|
| 729 |
+
"Label smoothing must be greater than 0.0 when using 'exo_pair' loss. The EXO paper recommends a "
|
| 730 |
+
"value of 1e-3."
|
| 731 |
+
)
|
| 732 |
+
self.use_liger_kernel = args.use_liger_kernel
|
| 733 |
+
if args.use_liger_kernel:
|
| 734 |
+
if not is_liger_kernel_available():
|
| 735 |
+
raise ImportError(
|
| 736 |
+
"You set `use_liger_kernel=True` but the liger kernel is not available. "
|
| 737 |
+
"Please install liger-kernel first: `pip install liger-kernel`"
|
| 738 |
+
)
|
| 739 |
+
if len(self.loss_types) != 1:
|
| 740 |
+
raise NotImplementedError(
|
| 741 |
+
"Multiple loss types are not yet supported when using Liger kernel. If you need this feature, "
|
| 742 |
+
"please open a feature request at https://github.com/huggingface/trl/issues."
|
| 743 |
+
)
|
| 744 |
+
self.liger_loss_fn = LigerFusedLinearDPOLoss(beta=args.beta, loss_type=self.loss_types[0])
|
| 745 |
+
if compute_metrics is not None:
|
| 746 |
+
raise ValueError(
|
| 747 |
+
"compute_metrics is not supported with the Liger kernel. compute_metrics requires to be able to "
|
| 748 |
+
"recover the logits from the forward pass, but Liger kernel does not materialize logits."
|
| 749 |
+
)
|
| 750 |
+
if self.precompute_ref_logps:
|
| 751 |
+
raise ValueError(
|
| 752 |
+
"Liger DPO loss does not support precomputing reference log probabilities. Either disable "
|
| 753 |
+
"`precompute_ref_log_probs` or set `use_liger_kernel` to False."
|
| 754 |
+
)
|
| 755 |
+
if is_peft_model(model):
|
| 756 |
+
raise NotImplementedError("Liger DPO loss is not implemented for PEFT models.")
|
| 757 |
+
|
| 758 |
+
# Dataset
|
| 759 |
+
# Skip dataset preparation if it's a VLM, where preprocessing (e.g., image-to-pixel conversion) is too costly
|
| 760 |
+
# and done on the fly instead.
|
| 761 |
+
skip_prepare_dataset = self._is_vision_dataset
|
| 762 |
+
if not skip_prepare_dataset:
|
| 763 |
+
train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train")
|
| 764 |
+
if eval_dataset is not None:
|
| 765 |
+
if isinstance(eval_dataset, dict):
|
| 766 |
+
eval_dataset = {
|
| 767 |
+
key: self._prepare_dataset(dataset, processing_class, args, key)
|
| 768 |
+
for key, dataset in eval_dataset.items()
|
| 769 |
+
}
|
| 770 |
+
else:
|
| 771 |
+
eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval")
|
| 772 |
+
|
| 773 |
+
# Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
|
| 774 |
+
# never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
|
| 775 |
+
# (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
|
| 776 |
+
# default to the recommended non-reentrant behavior here, while preserving any user-provided value.
|
| 777 |
+
if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
|
| 778 |
+
args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
|
| 779 |
+
args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
|
| 780 |
+
|
| 781 |
+
super().__init__(
|
| 782 |
+
model=model,
|
| 783 |
+
args=args,
|
| 784 |
+
data_collator=data_collator,
|
| 785 |
+
train_dataset=train_dataset,
|
| 786 |
+
eval_dataset=eval_dataset,
|
| 787 |
+
processing_class=processing_class,
|
| 788 |
+
compute_metrics=compute_metrics,
|
| 789 |
+
callbacks=callbacks,
|
| 790 |
+
optimizers=optimizers,
|
| 791 |
+
)
|
| 792 |
+
|
| 793 |
+
# Initialize activation offloading context
|
| 794 |
+
if self.args.activation_offloading:
|
| 795 |
+
self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model)
|
| 796 |
+
else:
|
| 797 |
+
self.maybe_activation_offload_context = contextlib.nullcontext()
|
| 798 |
+
|
| 799 |
+
# Reference model
|
| 800 |
+
if ref_model is None:
|
| 801 |
+
if is_peft_model(self.model) or args.precompute_ref_log_probs:
|
| 802 |
+
# If PEFT is used, the reference model is not needed since the adapter can be disabled to revert to the
|
| 803 |
+
# initial model. If precompute_ref_log_probs is True, the reference model does not need to be kept in
|
| 804 |
+
# memory during training.
|
| 805 |
+
self.ref_model = None
|
| 806 |
+
else:
|
| 807 |
+
ref_model_init_kwargs = args.model_init_kwargs or {}
|
| 808 |
+
# Distributed training requires device_map=None ("auto" fails)
|
| 809 |
+
if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
|
| 810 |
+
ref_model_init_kwargs["device_map"] = None
|
| 811 |
+
ref_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 812 |
+
ref_model_path = get_config_model_id(self.model.config)
|
| 813 |
+
self.ref_model = create_model_from_path(ref_model_path, **ref_model_init_kwargs)
|
| 814 |
+
else:
|
| 815 |
+
self.ref_model = ref_model
|
| 816 |
+
|
| 817 |
+
# Disable dropout in the models
|
| 818 |
+
if args.disable_dropout:
|
| 819 |
+
disable_dropout_in_model(model)
|
| 820 |
+
if self.ref_model is not None:
|
| 821 |
+
disable_dropout_in_model(self.ref_model)
|
| 822 |
+
|
| 823 |
+
# Initialize the metrics
|
| 824 |
+
self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
|
| 825 |
+
self._total_train_tokens = 0
|
| 826 |
+
|
| 827 |
+
# Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
|
| 828 |
+
# model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
|
| 829 |
+
# self.model_accepts_loss_kwargs to False to enable scaling.
|
| 830 |
+
self.model_accepts_loss_kwargs = False
|
| 831 |
+
|
| 832 |
+
# Add tags to the model
|
| 833 |
+
self.model.add_model_tags(self._tag_names)
|
| 834 |
+
|
| 835 |
+
if self.ref_model is not None:
|
| 836 |
+
if self.is_deepspeed_enabled:
|
| 837 |
+
self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
|
| 838 |
+
elif self.is_fsdp_enabled:
|
| 839 |
+
self.ref_model = prepare_fsdp(self.ref_model, self.accelerator)
|
| 840 |
+
else:
|
| 841 |
+
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
|
| 842 |
+
|
| 843 |
+
if args.sync_ref_model:
|
| 844 |
+
if is_peft_model(self.model):
|
| 845 |
+
raise NotImplementedError(
|
| 846 |
+
"You passed `sync_ref_model=True` while using a PEFT model, which is currently not supported. "
|
| 847 |
+
"With PEFT, DPOTrainer does not keep a separate reference model in memory; instead, it recovers "
|
| 848 |
+
"reference behavior by temporarily disabling the adapter. As a result, there is no standalone "
|
| 849 |
+
"`ref_model` instance to synchronize. Use `sync_ref_model=False`, or opt for full fine-tuning if "
|
| 850 |
+
"you need a synced reference model. If you need `sync_ref_model` to work with PEFT, please open a "
|
| 851 |
+
"feature request at https://github.com/huggingface/trl/issues."
|
| 852 |
+
)
|
| 853 |
+
if args.precompute_ref_log_probs:
|
| 854 |
+
raise ValueError(
|
| 855 |
+
"You cannot use `sync_ref_model=True` together with `precompute_ref_log_probs=True`. "
|
| 856 |
+
"`precompute_ref_log_probs=True` assumes a fixed reference model, but with `sync_ref_model=True` "
|
| 857 |
+
"the reference model is periodically updated during training, making any precomputed reference "
|
| 858 |
+
"log-probs stale. Set `precompute_ref_log_probs=False` or disable `sync_ref_model`."
|
| 859 |
+
)
|
| 860 |
+
self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator))
|
| 861 |
+
|
| 862 |
+
if args.precompute_ref_log_probs:
|
| 863 |
+
if isinstance(self.train_dataset, IterableDataset) or isinstance(
|
| 864 |
+
self.eval_dataset, (IterableDataset, IterableDatasetDict)
|
| 865 |
+
):
|
| 866 |
+
raise ValueError(
|
| 867 |
+
"`precompute_ref_log_probs=True` is not supported with IterableDataset. Please use a map-style "
|
| 868 |
+
"Dataset or set `precompute_ref_log_probs=False`."
|
| 869 |
+
)
|
| 870 |
+
|
| 871 |
+
self.train_dataset = self._precompute_ref_logps(
|
| 872 |
+
self.train_dataset,
|
| 873 |
+
"train",
|
| 874 |
+
self.args.precompute_ref_batch_size or self.args.per_device_train_batch_size,
|
| 875 |
+
)
|
| 876 |
+
if self.eval_dataset is not None:
|
| 877 |
+
if isinstance(self.eval_dataset, dict):
|
| 878 |
+
self.eval_dataset = {
|
| 879 |
+
name: self._precompute_ref_logps(
|
| 880 |
+
dataset, name, self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size
|
| 881 |
+
)
|
| 882 |
+
for name, dataset in self.eval_dataset.items()
|
| 883 |
+
}
|
| 884 |
+
else:
|
| 885 |
+
self.eval_dataset = self._precompute_ref_logps(
|
| 886 |
+
self.eval_dataset,
|
| 887 |
+
"eval",
|
| 888 |
+
self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size,
|
| 889 |
+
)
|
| 890 |
+
|
| 891 |
+
def _tokenize(
|
| 892 |
+
self,
|
| 893 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin,
|
| 894 |
+
input: str | list,
|
| 895 |
+
**kwargs,
|
| 896 |
+
) -> dict[str, list]:
|
| 897 |
+
"""Tokenize a single example for dataset preprocessing.
|
| 898 |
+
|
| 899 |
+
Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for
|
| 900 |
+
non-conversational input (str). For VLMs, normalizes the batch dimension that processors emit even for single
|
| 901 |
+
examples.
|
| 902 |
+
|
| 903 |
+
Args:
|
| 904 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]):
|
| 905 |
+
The tokenizer or processor to use.
|
| 906 |
+
input (`str` or `list`):
|
| 907 |
+
A string for non-conversational input, or a list of message dicts for conversational input.
|
| 908 |
+
**kwargs:
|
| 909 |
+
Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`, `return_assistant_tokens_mask`).
|
| 910 |
+
|
| 911 |
+
Returns:
|
| 912 |
+
`dict` with at least an `"input_ids"` key mapping to a flat `list[int]`.
|
| 913 |
+
"""
|
| 914 |
+
if isinstance(input, list): # conversational: list of message dicts
|
| 915 |
+
if self._is_vlm:
|
| 916 |
+
input = prepare_multimodal_messages(input)
|
| 917 |
+
result = processing_class.apply_chat_template(input, tokenize=True, return_dict=True, **kwargs)
|
| 918 |
+
else: # non-conversational: plain text string
|
| 919 |
+
result = processing_class(text=input)
|
| 920 |
+
# VLMs emit a batch dimension even for single examples; unwrap it
|
| 921 |
+
if self._is_vlm:
|
| 922 |
+
return {k: v[0] for k, v in result.items()}
|
| 923 |
+
return result
|
| 924 |
+
|
| 925 |
+
def _prepare_dataset(
|
| 926 |
+
self,
|
| 927 |
+
dataset: Dataset | IterableDataset,
|
| 928 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin,
|
| 929 |
+
args: DPOConfig,
|
| 930 |
+
dataset_name: str,
|
| 931 |
+
) -> Dataset | IterableDataset:
|
| 932 |
+
# Build the kwargs for the `map` function
|
| 933 |
+
map_kwargs = {}
|
| 934 |
+
if isinstance(dataset, Dataset): # IterableDataset does not support num_proc
|
| 935 |
+
map_kwargs["num_proc"] = args.dataset_num_proc
|
| 936 |
+
|
| 937 |
+
with PartialState().main_process_first():
|
| 938 |
+
# Extract the prompt if needed
|
| 939 |
+
first_example = next(iter(dataset))
|
| 940 |
+
if "prompt" not in first_example:
|
| 941 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 942 |
+
map_kwargs["desc"] = f"Extracting prompt from {dataset_name} dataset"
|
| 943 |
+
dataset = dataset.map(extract_prompt, **map_kwargs)
|
| 944 |
+
|
| 945 |
+
# Add EOS token if needed: non-conversational only
|
| 946 |
+
first_example = next(iter(dataset))
|
| 947 |
+
if not is_conversational(first_example):
|
| 948 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 949 |
+
map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset"
|
| 950 |
+
|
| 951 |
+
def add_eos(example, eos_token):
|
| 952 |
+
if not example["chosen"].endswith(eos_token):
|
| 953 |
+
example["chosen"] = example["chosen"] + eos_token
|
| 954 |
+
if not example["rejected"].endswith(eos_token):
|
| 955 |
+
example["rejected"] = example["rejected"] + eos_token
|
| 956 |
+
return example
|
| 957 |
+
|
| 958 |
+
dataset = dataset.map(add_eos, fn_kwargs={"eos_token": self._tokenizer.eos_token}, **map_kwargs)
|
| 959 |
+
|
| 960 |
+
# Tokenize the dataset
|
| 961 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 962 |
+
map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset"
|
| 963 |
+
|
| 964 |
+
def tokenize_fn(example, processing_class):
|
| 965 |
+
tools = example.get("tools")
|
| 966 |
+
tools = json.loads(tools) if isinstance(tools, str) else tools
|
| 967 |
+
output = {}
|
| 968 |
+
if is_conversational(example):
|
| 969 |
+
prompt_ids = self._tokenize(
|
| 970 |
+
processing_class,
|
| 971 |
+
example["prompt"],
|
| 972 |
+
tools=tools,
|
| 973 |
+
add_generation_prompt=True,
|
| 974 |
+
**example.get("chat_template_kwargs", {}),
|
| 975 |
+
)["input_ids"]
|
| 976 |
+
prompt_chosen_ids = self._tokenize(
|
| 977 |
+
processing_class,
|
| 978 |
+
example["prompt"] + example["chosen"],
|
| 979 |
+
tools=tools,
|
| 980 |
+
**example.get("chat_template_kwargs", {}),
|
| 981 |
+
)["input_ids"]
|
| 982 |
+
prompt_rejected_ids = self._tokenize(
|
| 983 |
+
processing_class,
|
| 984 |
+
example["prompt"] + example["rejected"],
|
| 985 |
+
tools=tools,
|
| 986 |
+
**example.get("chat_template_kwargs", {}),
|
| 987 |
+
)["input_ids"]
|
| 988 |
+
else:
|
| 989 |
+
prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"]
|
| 990 |
+
prompt_chosen_ids = self._tokenize(processing_class, example["prompt"] + example["chosen"])[
|
| 991 |
+
"input_ids"
|
| 992 |
+
]
|
| 993 |
+
prompt_rejected_ids = self._tokenize(processing_class, example["prompt"] + example["rejected"])[
|
| 994 |
+
"input_ids"
|
| 995 |
+
]
|
| 996 |
+
|
| 997 |
+
# Check if the tokenized prompt starts with the tokenized prompt+completion
|
| 998 |
+
if not prompt_chosen_ids[: len(prompt_ids)] == prompt_ids:
|
| 999 |
+
logger.warning(
|
| 1000 |
+
"Mismatch between tokenized prompt and the start of tokenized prompt+chosen. "
|
| 1001 |
+
"This may be due to unexpected tokenizer behavior, whitespace issues, or special "
|
| 1002 |
+
"token handling. Verify that the tokenizer is processing text consistently."
|
| 1003 |
+
)
|
| 1004 |
+
if not prompt_rejected_ids[: len(prompt_ids)] == prompt_ids:
|
| 1005 |
+
logger.warning(
|
| 1006 |
+
"Mismatch between tokenized prompt and the start of tokenized prompt+rejected. "
|
| 1007 |
+
"This may be due to unexpected tokenizer behavior, whitespace issues, or special "
|
| 1008 |
+
"token handling. Verify that the tokenizer is processing text consistently."
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
output["prompt_ids"] = prompt_ids
|
| 1012 |
+
output["chosen_ids"] = prompt_chosen_ids[len(prompt_ids) :]
|
| 1013 |
+
output["rejected_ids"] = prompt_rejected_ids[len(prompt_ids) :]
|
| 1014 |
+
return output
|
| 1015 |
+
|
| 1016 |
+
dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs)
|
| 1017 |
+
|
| 1018 |
+
return dataset
|
| 1019 |
+
|
| 1020 |
+
def _set_signature_columns_if_needed(self):
|
| 1021 |
+
# If `self.args.remove_unused_columns` is True, non-signature columns are removed.
|
| 1022 |
+
# By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids"
|
| 1023 |
+
# and "attention_mask").
|
| 1024 |
+
if self._signature_columns is None:
|
| 1025 |
+
if self._is_vision_dataset:
|
| 1026 |
+
self._signature_columns = [
|
| 1027 |
+
"prompt",
|
| 1028 |
+
"chosen",
|
| 1029 |
+
"rejected",
|
| 1030 |
+
"image",
|
| 1031 |
+
"images",
|
| 1032 |
+
"tools",
|
| 1033 |
+
"chat_template_kwargs",
|
| 1034 |
+
]
|
| 1035 |
+
else:
|
| 1036 |
+
self._signature_columns = [
|
| 1037 |
+
"prompt_ids",
|
| 1038 |
+
"chosen_ids",
|
| 1039 |
+
"rejected_ids",
|
| 1040 |
+
"ref_chosen_logps",
|
| 1041 |
+
"ref_rejected_logps",
|
| 1042 |
+
]
|
| 1043 |
+
|
| 1044 |
+
def _precompute_ref_logps(self, dataset: Dataset, name: str, batch_size: int) -> Dataset:
|
| 1045 |
+
model_hash = hash_module(self.ref_model or self.model)
|
| 1046 |
+
fingerprint = Hasher.hash((dataset._fingerprint, model_hash))
|
| 1047 |
+
cache_file = dataset._get_cache_file_path(fingerprint)
|
| 1048 |
+
|
| 1049 |
+
if os.path.exists(cache_file):
|
| 1050 |
+
return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1)
|
| 1051 |
+
|
| 1052 |
+
dataloader = DataLoader(
|
| 1053 |
+
dataset,
|
| 1054 |
+
batch_size=batch_size,
|
| 1055 |
+
collate_fn=self.data_collator,
|
| 1056 |
+
num_workers=self.args.dataloader_num_workers,
|
| 1057 |
+
pin_memory=self.args.dataloader_pin_memory,
|
| 1058 |
+
shuffle=False,
|
| 1059 |
+
)
|
| 1060 |
+
data_loader = self.accelerator.prepare(dataloader)
|
| 1061 |
+
ref_chosen_logps = []
|
| 1062 |
+
ref_rejected_logps = []
|
| 1063 |
+
for padded_batch in tqdm(iterable=data_loader, desc=f"Computing reference log probs for {name} dataset"):
|
| 1064 |
+
ref_chosen_logp, ref_rejected_logp = self.compute_ref_log_probs(padded_batch)
|
| 1065 |
+
ref_chosen_logp, ref_rejected_logp = self.accelerator.gather_for_metrics(
|
| 1066 |
+
(ref_chosen_logp, ref_rejected_logp)
|
| 1067 |
+
)
|
| 1068 |
+
ref_chosen_logps.append(ref_chosen_logp.cpu())
|
| 1069 |
+
ref_rejected_logps.append(ref_rejected_logp.cpu())
|
| 1070 |
+
|
| 1071 |
+
ref_chosen_logps = torch.cat(ref_chosen_logps)
|
| 1072 |
+
ref_rejected_logps = torch.cat(ref_rejected_logps)
|
| 1073 |
+
|
| 1074 |
+
if self.accelerator.is_main_process:
|
| 1075 |
+
|
| 1076 |
+
def add_ref_logps(batch, indices):
|
| 1077 |
+
return {
|
| 1078 |
+
"ref_chosen_logps": ref_chosen_logps[indices],
|
| 1079 |
+
"ref_rejected_logps": ref_rejected_logps[indices],
|
| 1080 |
+
}
|
| 1081 |
+
|
| 1082 |
+
dataset.map(
|
| 1083 |
+
add_ref_logps,
|
| 1084 |
+
with_indices=True,
|
| 1085 |
+
batched=True,
|
| 1086 |
+
remove_columns=dataset.column_names,
|
| 1087 |
+
new_fingerprint=fingerprint,
|
| 1088 |
+
desc=f"Caching reference log probs for {name} dataset",
|
| 1089 |
+
)
|
| 1090 |
+
self.accelerator.wait_for_everyone()
|
| 1091 |
+
|
| 1092 |
+
return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1)
|
| 1093 |
+
|
| 1094 |
+
def compute_ref_log_probs(self, inputs):
|
| 1095 |
+
"""Computes reference log probabilities for a single padded batch."""
|
| 1096 |
+
device = self.accelerator.device
|
| 1097 |
+
|
| 1098 |
+
_non_model_keys = {"completion_mask", "ref_chosen_logps", "ref_rejected_logps"}
|
| 1099 |
+
model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys}
|
| 1100 |
+
model_kwargs["use_cache"] = False
|
| 1101 |
+
|
| 1102 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 1103 |
+
if self.ref_model is None:
|
| 1104 |
+
if is_peft_model(self.model):
|
| 1105 |
+
model = self.accelerator.unwrap_model(self.model)
|
| 1106 |
+
with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None):
|
| 1107 |
+
ref_outputs = self.model(**model_kwargs)
|
| 1108 |
+
else:
|
| 1109 |
+
ref_outputs = self.model(**model_kwargs)
|
| 1110 |
+
else:
|
| 1111 |
+
ref_outputs = self.ref_model(**model_kwargs)
|
| 1112 |
+
|
| 1113 |
+
input_ids = inputs["input_ids"]
|
| 1114 |
+
completion_mask = inputs["completion_mask"]
|
| 1115 |
+
shift_labels = input_ids[..., 1:]
|
| 1116 |
+
shift_completion_mask = completion_mask[..., 1:]
|
| 1117 |
+
ref_shift_logits = ref_outputs.logits[..., :-1, :]
|
| 1118 |
+
ref_per_token_logps = selective_log_softmax(ref_shift_logits, shift_labels)
|
| 1119 |
+
ref_per_token_logps[shift_completion_mask == 0] = 0.0
|
| 1120 |
+
|
| 1121 |
+
if self.ld_alpha is None:
|
| 1122 |
+
ref_logps = ref_per_token_logps.sum(dim=1)
|
| 1123 |
+
else:
|
| 1124 |
+
comp_pos = shift_completion_mask.cumsum(dim=1)
|
| 1125 |
+
comp_lens = shift_completion_mask.sum(dim=1).long()
|
| 1126 |
+
chosen_lens, rejected_lens = comp_lens.chunk(2, dim=0)
|
| 1127 |
+
shared_lens = torch.minimum(chosen_lens, rejected_lens)
|
| 1128 |
+
shared_lens = torch.cat([shared_lens, shared_lens], dim=0).to(device)
|
| 1129 |
+
shared_mask = (comp_pos > 0) & (comp_pos <= shared_lens.unsqueeze(1))
|
| 1130 |
+
tail_mask = comp_pos > shared_lens.unsqueeze(1)
|
| 1131 |
+
shared_logps = (ref_per_token_logps * shared_mask).sum(dim=1)
|
| 1132 |
+
tail_logps = (ref_per_token_logps * tail_mask).sum(dim=1)
|
| 1133 |
+
ref_logps = shared_logps + self.ld_alpha * tail_logps
|
| 1134 |
+
|
| 1135 |
+
ref_chosen_logps, ref_rejected_logps = ref_logps.chunk(2, dim=0)
|
| 1136 |
+
return ref_chosen_logps, ref_rejected_logps
|
| 1137 |
+
|
| 1138 |
+
def _compute_loss_liger(self, model, inputs, return_outputs):
|
| 1139 |
+
if return_outputs:
|
| 1140 |
+
raise RuntimeError(
|
| 1141 |
+
"return_outputs=True is not supported with the Liger DPO loss. The Liger loss computes the loss "
|
| 1142 |
+
"without materializing logits, so outputs cannot be returned."
|
| 1143 |
+
)
|
| 1144 |
+
|
| 1145 |
+
mode = "train" if self.model.training else "eval"
|
| 1146 |
+
|
| 1147 |
+
_non_model_keys = {"completion_mask", "ref_chosen_logps", "ref_rejected_logps"}
|
| 1148 |
+
model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys}
|
| 1149 |
+
model_kwargs["use_cache"] = False
|
| 1150 |
+
|
| 1151 |
+
# `base_model` gives the backbone model (skipping `lm_head`) — text decoder for LMs, multimodal wrapper for
|
| 1152 |
+
# VLMs (so vision-token injection runs before the text decoder). `get_decoder()` won't do: on VLMs it
|
| 1153 |
+
# returns just the text stack and feeds image-placeholder IDs through it.
|
| 1154 |
+
# Pre-5.0 transformers VLMs set `base_model_prefix = ""` so `base_model is self` (re-runs `lm_head`).
|
| 1155 |
+
# Fall back to `.model` there.
|
| 1156 |
+
if self._is_vlm and Version(transformers.__version__) < Version("5.0.0"):
|
| 1157 |
+
backbone, ref_backbone = model.model, self.ref_model.model
|
| 1158 |
+
else:
|
| 1159 |
+
backbone, ref_backbone = model.base_model, self.ref_model.base_model
|
| 1160 |
+
|
| 1161 |
+
outputs = backbone(**model_kwargs)
|
| 1162 |
+
hidden_states = outputs.last_hidden_state[:, :-1].contiguous()
|
| 1163 |
+
lm_head = model.get_output_embeddings()
|
| 1164 |
+
weight = lm_head.weight
|
| 1165 |
+
bias = lm_head.bias
|
| 1166 |
+
|
| 1167 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 1168 |
+
ref_outputs = ref_backbone(**model_kwargs)
|
| 1169 |
+
ref_lm_head = self.ref_model.get_output_embeddings()
|
| 1170 |
+
ref_hidden_states = ref_outputs.last_hidden_state[:, :-1].contiguous()
|
| 1171 |
+
ref_weight = ref_lm_head.weight
|
| 1172 |
+
ref_bias = ref_lm_head.bias
|
| 1173 |
+
|
| 1174 |
+
input_ids = model_kwargs["input_ids"]
|
| 1175 |
+
completion_mask = inputs["completion_mask"]
|
| 1176 |
+
shift_completion_mask = completion_mask[:, 1:]
|
| 1177 |
+
labels = input_ids[:, 1:].clone()
|
| 1178 |
+
labels[shift_completion_mask == 0] = -100
|
| 1179 |
+
|
| 1180 |
+
loss, metrics = self.liger_loss_fn(
|
| 1181 |
+
weight, hidden_states, labels, bias, ref_hidden_states, ref_weight, ref_bias
|
| 1182 |
+
)
|
| 1183 |
+
|
| 1184 |
+
(
|
| 1185 |
+
chosen_logps,
|
| 1186 |
+
rejected_logps,
|
| 1187 |
+
chosen_logits_mean,
|
| 1188 |
+
rejected_logits_mean,
|
| 1189 |
+
nll_loss,
|
| 1190 |
+
chosen_rewards,
|
| 1191 |
+
rejected_rewards,
|
| 1192 |
+
) = metrics
|
| 1193 |
+
|
| 1194 |
+
if mode == "train":
|
| 1195 |
+
num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item()
|
| 1196 |
+
self._total_train_tokens += num_tokens_in_batch
|
| 1197 |
+
self._metrics[mode]["num_tokens"] = [self._total_train_tokens]
|
| 1198 |
+
|
| 1199 |
+
avg_chosen_logits = self.accelerator.gather_for_metrics(chosen_logits_mean).mean().item()
|
| 1200 |
+
avg_rejected_logits = self.accelerator.gather_for_metrics(rejected_logits_mean).mean().item()
|
| 1201 |
+
self._metrics[mode]["logits/chosen"].append(avg_chosen_logits)
|
| 1202 |
+
self._metrics[mode]["logits/rejected"].append(avg_rejected_logits)
|
| 1203 |
+
|
| 1204 |
+
agg_chosen_rewards = self.accelerator.gather(chosen_rewards)
|
| 1205 |
+
agg_rejected_rewards = self.accelerator.gather(rejected_rewards)
|
| 1206 |
+
self._metrics[mode]["rewards/chosen"].append(agg_chosen_rewards.mean().item())
|
| 1207 |
+
self._metrics[mode]["rewards/rejected"].append(agg_rejected_rewards.mean().item())
|
| 1208 |
+
|
| 1209 |
+
reward_accuracies = (chosen_rewards > rejected_rewards).float()
|
| 1210 |
+
agg_reward_accuracies = self.accelerator.gather(reward_accuracies)
|
| 1211 |
+
self._metrics[mode]["rewards/accuracies"].append(agg_reward_accuracies.mean().item())
|
| 1212 |
+
|
| 1213 |
+
margins = chosen_rewards - rejected_rewards
|
| 1214 |
+
agg_margins = self.accelerator.gather(margins)
|
| 1215 |
+
self._metrics[mode]["rewards/margins"].append(agg_margins.mean().item())
|
| 1216 |
+
|
| 1217 |
+
self._metrics[mode]["logps/chosen"].append(self.accelerator.gather(chosen_logps).mean().item())
|
| 1218 |
+
self._metrics[mode]["logps/rejected"].append(self.accelerator.gather(rejected_logps).mean().item())
|
| 1219 |
+
|
| 1220 |
+
return loss
|
| 1221 |
+
|
| 1222 |
+
def _compute_loss(self, model, inputs, return_outputs):
|
| 1223 |
+
mode = "train" if self.model.training else "eval"
|
| 1224 |
+
device = self.accelerator.device
|
| 1225 |
+
|
| 1226 |
+
_non_model_keys = {"completion_mask", "ref_chosen_logps", "ref_rejected_logps"}
|
| 1227 |
+
model_kwargs = {k: v for k, v in inputs.items() if k not in _non_model_keys}
|
| 1228 |
+
model_kwargs["use_cache"] = False
|
| 1229 |
+
outputs = model(**model_kwargs)
|
| 1230 |
+
|
| 1231 |
+
input_ids = inputs["input_ids"]
|
| 1232 |
+
completion_mask = inputs["completion_mask"]
|
| 1233 |
+
shift_logits = outputs.logits[..., :-1, :]
|
| 1234 |
+
shift_labels = input_ids[..., 1:]
|
| 1235 |
+
shift_completion_mask = completion_mask[..., 1:]
|
| 1236 |
+
per_token_logps = selective_log_softmax(shift_logits, shift_labels)
|
| 1237 |
+
per_token_logps[shift_completion_mask == 0] = 0.0 # mask out non-completion tokens
|
| 1238 |
+
if self.ld_alpha is None:
|
| 1239 |
+
logps = per_token_logps.sum(dim=1) # sum over sequence length
|
| 1240 |
+
else:
|
| 1241 |
+
comp_pos = shift_completion_mask.cumsum(dim=1)
|
| 1242 |
+
comp_lens = shift_completion_mask.sum(dim=1).long()
|
| 1243 |
+
chosen_lens, rejected_lens = comp_lens.chunk(2, dim=0)
|
| 1244 |
+
shared_lens = torch.minimum(chosen_lens, rejected_lens)
|
| 1245 |
+
shared_lens = torch.cat([shared_lens, shared_lens], dim=0).to(device)
|
| 1246 |
+
shared_mask = (comp_pos > 0) & (comp_pos <= shared_lens.unsqueeze(1)) # shared: 1 <= pos <= shared_len
|
| 1247 |
+
tail_mask = comp_pos > shared_lens.unsqueeze(1) # tail: pos > shared_len
|
| 1248 |
+
shared_logps = (per_token_logps * shared_mask).sum(dim=1)
|
| 1249 |
+
tail_logps = (per_token_logps * tail_mask).sum(dim=1)
|
| 1250 |
+
logps = shared_logps + self.ld_alpha * tail_logps
|
| 1251 |
+
chosen_logps, rejected_logps = logps.chunk(2, dim=0) # batch is [chosen, rejected]
|
| 1252 |
+
|
| 1253 |
+
if self.precompute_ref_logps:
|
| 1254 |
+
ref_chosen_logps, ref_rejected_logps = inputs["ref_chosen_logps"], inputs["ref_rejected_logps"]
|
| 1255 |
+
else:
|
| 1256 |
+
# When gradient checkpointing is enabled with use_reentrant=True (default), calling the model inside a
|
| 1257 |
+
# torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True").
|
| 1258 |
+
# Temporarily disable checkpointing to avoid this warning during inference.
|
| 1259 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 1260 |
+
if is_peft_model(model) and self.ref_model is None:
|
| 1261 |
+
# When training a PEFT adapter, how we obtain the reference depends on the setup:
|
| 1262 |
+
# - New adapter: disabling adapters yields the base model.
|
| 1263 |
+
# - Re-training an existing adapter: an initial copy is loaded under the name "ref".
|
| 1264 |
+
model = self.accelerator.unwrap_model(model)
|
| 1265 |
+
with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None):
|
| 1266 |
+
ref_outputs = self.model(**model_kwargs)
|
| 1267 |
+
else:
|
| 1268 |
+
ref_outputs = self.ref_model(**model_kwargs)
|
| 1269 |
+
|
| 1270 |
+
ref_shift_logits = ref_outputs.logits[..., :-1, :]
|
| 1271 |
+
ref_per_token_logps = selective_log_softmax(ref_shift_logits, shift_labels)
|
| 1272 |
+
ref_per_token_logps[shift_completion_mask == 0] = 0.0 # mask out non-completion tokens
|
| 1273 |
+
if self.ld_alpha is None:
|
| 1274 |
+
ref_logps = ref_per_token_logps.sum(dim=1) # sum over sequence length
|
| 1275 |
+
else:
|
| 1276 |
+
# reuse comp_pos/shared_mask/tail_mask computed above (they depend only on completion_mask)
|
| 1277 |
+
ref_shared_logps = (ref_per_token_logps * shared_mask).sum(dim=1)
|
| 1278 |
+
ref_tail_logps = (ref_per_token_logps * tail_mask).sum(dim=1)
|
| 1279 |
+
ref_logps = ref_shared_logps + self.ld_alpha * ref_tail_logps
|
| 1280 |
+
ref_chosen_logps, ref_rejected_logps = ref_logps.chunk(2, dim=0) # batch is [chosen, rejected]
|
| 1281 |
+
|
| 1282 |
+
# Get the log ratios for the chosen and rejected responses
|
| 1283 |
+
chosen_logratios = chosen_logps - ref_chosen_logps
|
| 1284 |
+
rejected_logratios = rejected_logps - ref_rejected_logps
|
| 1285 |
+
|
| 1286 |
+
if self.f_divergence_type == "reverse_kl": # standard DPO
|
| 1287 |
+
chosen_scores = chosen_logratios
|
| 1288 |
+
rejected_scores = rejected_logratios
|
| 1289 |
+
elif self.f_divergence_type == "forward_kl":
|
| 1290 |
+
# f'(t) = 1 - 1/t -> drop constant -> -exp(-logratio)
|
| 1291 |
+
chosen_scores = -torch.exp(-chosen_logratios)
|
| 1292 |
+
rejected_scores = -torch.exp(-rejected_logratios)
|
| 1293 |
+
elif self.f_divergence_type == "js_divergence":
|
| 1294 |
+
# f'(t) = log(2t/(t+1)) -> drop log 2
|
| 1295 |
+
chosen_scores = F.logsigmoid(chosen_logratios)
|
| 1296 |
+
rejected_scores = F.logsigmoid(rejected_logratios)
|
| 1297 |
+
elif self.f_divergence_type == "alpha_divergence":
|
| 1298 |
+
# alpha-divergence: f'(t) = (t^(α-1) - 1)/(α-1)
|
| 1299 |
+
if abs(self.f_alpha_divergence_coef - 1.0) < 1e-6: # limit case f'(t) -> log(t), fall back to reverse_kl
|
| 1300 |
+
chosen_scores = chosen_logratios
|
| 1301 |
+
rejected_scores = rejected_logratios
|
| 1302 |
+
else:
|
| 1303 |
+
coef = 1.0 / (self.f_alpha_divergence_coef - 1.0)
|
| 1304 |
+
t_chosen = (self.f_alpha_divergence_coef - 1.0) * chosen_logratios
|
| 1305 |
+
t_rejected = (self.f_alpha_divergence_coef - 1.0) * rejected_logratios
|
| 1306 |
+
dtype = t_chosen.dtype
|
| 1307 |
+
# Clamp max so exp(.) stays representable after casting back
|
| 1308 |
+
clamp_max = {torch.float16: 11.0, torch.bfloat16: 80.0, torch.float32: 80.0}[dtype]
|
| 1309 |
+
t_chosen_float = torch.clamp(t_chosen.float(), max=clamp_max)
|
| 1310 |
+
t_rejected_float = torch.clamp(t_rejected.float(), max=clamp_max)
|
| 1311 |
+
chosen_scores = torch.exp(t_chosen_float).to(dtype) * coef
|
| 1312 |
+
rejected_scores = torch.exp(t_rejected_float).to(dtype) * coef
|
| 1313 |
+
else:
|
| 1314 |
+
raise ValueError(f"Unknown f_divergence_type: {self.f_divergence_type}")
|
| 1315 |
+
|
| 1316 |
+
delta_score = chosen_scores - rejected_scores
|
| 1317 |
+
|
| 1318 |
+
loss = 0.0
|
| 1319 |
+
for loss_type, loss_weight in zip(self.loss_types, self.loss_weights, strict=True):
|
| 1320 |
+
if loss_type == "sigmoid":
|
| 1321 |
+
per_sequence_loss = -F.logsigmoid(self.beta * delta_score)
|
| 1322 |
+
|
| 1323 |
+
elif loss_type == "hinge":
|
| 1324 |
+
per_sequence_loss = torch.relu(1 - self.beta * delta_score)
|
| 1325 |
+
|
| 1326 |
+
elif loss_type == "ipo":
|
| 1327 |
+
# IPO uses sequence-level log-prob differences; in code these are token-summed over the completion,
|
| 1328 |
+
# which makes the squared loss scale with completion length. We therefore normalize by the number of
|
| 1329 |
+
# completion tokens (average per token) to make β/loss comparable across variable lengths. This length
|
| 1330 |
+
# normalization is not explicitly discussed in the IPO paper; we confirmed this choice with the IPO
|
| 1331 |
+
# authors, and the results reported in the paper correspond to this normalized form.
|
| 1332 |
+
chosen_mask, rejected_mask = completion_mask.chunk(2, dim=0)
|
| 1333 |
+
chosen_avg_score = chosen_scores / chosen_mask.sum(dim=1).clamp(min=1.0)
|
| 1334 |
+
rejected_avg_score = rejected_scores / rejected_mask.sum(dim=1).clamp(min=1.0)
|
| 1335 |
+
ipo_delta = chosen_avg_score - rejected_avg_score
|
| 1336 |
+
# (Eq. 17) of the paper where beta is the regularization parameter for the IPO loss, denoted by τ.
|
| 1337 |
+
per_sequence_loss = (ipo_delta - 1 / (2 * self.beta)) ** 2
|
| 1338 |
+
|
| 1339 |
+
elif loss_type == "exo_pair":
|
| 1340 |
+
# Implements EXO-pref from the paper https://huggingface.co/papers/2402.00856, (Eq. 16)
|
| 1341 |
+
# Minimize KL(p_fθ || p_rh) for K=2; p_fθ = softmax(βπ * (log πθ − log π_ref)) over {chosen, rejected}
|
| 1342 |
+
# p_rh = [(1−ε), ε]; expanded KL gives the weighted logsigmoid form below
|
| 1343 |
+
epsilon = torch.tensor(self.label_smoothing, device=device)
|
| 1344 |
+
qw = torch.sigmoid(self.beta * delta_score)
|
| 1345 |
+
log_qw = F.logsigmoid(self.beta * delta_score)
|
| 1346 |
+
log_pw = torch.log1p(-epsilon)
|
| 1347 |
+
ql = torch.sigmoid(-self.beta * delta_score)
|
| 1348 |
+
log_ql = F.logsigmoid(-self.beta * delta_score)
|
| 1349 |
+
log_pl = torch.log(epsilon)
|
| 1350 |
+
per_sequence_loss = qw * (log_qw - log_pw) + ql * (log_ql - log_pl)
|
| 1351 |
+
|
| 1352 |
+
elif loss_type == "nca_pair":
|
| 1353 |
+
chosen_rewards = self.beta * chosen_scores
|
| 1354 |
+
rejected_rewards = self.beta * rejected_scores
|
| 1355 |
+
per_sequence_loss = (
|
| 1356 |
+
-F.logsigmoid(chosen_rewards)
|
| 1357 |
+
- 0.5 * F.logsigmoid(-chosen_rewards)
|
| 1358 |
+
- 0.5 * F.logsigmoid(-rejected_rewards)
|
| 1359 |
+
)
|
| 1360 |
+
|
| 1361 |
+
elif loss_type == "robust":
|
| 1362 |
+
clean_loss_term = -(1 - self.label_smoothing) * F.logsigmoid(self.beta * delta_score)
|
| 1363 |
+
flipped_loss_term = -self.label_smoothing * F.logsigmoid(-self.beta * delta_score)
|
| 1364 |
+
per_sequence_loss = (clean_loss_term - flipped_loss_term) / (1 - 2 * self.label_smoothing)
|
| 1365 |
+
|
| 1366 |
+
elif loss_type == "bco_pair":
|
| 1367 |
+
chosen_rewards = self.beta * chosen_scores
|
| 1368 |
+
rejected_rewards = self.beta * rejected_scores
|
| 1369 |
+
per_sequence_loss = -F.logsigmoid(chosen_rewards) - F.logsigmoid(-rejected_rewards)
|
| 1370 |
+
|
| 1371 |
+
elif loss_type == "sppo_hard":
|
| 1372 |
+
# In the paper (https://huggingface.co/papers/2405.00675), SPPO employs a soft probability approach,
|
| 1373 |
+
# estimated using the PairRM score. The probability calculation is conducted outside of the trainer
|
| 1374 |
+
# class. The version described here is the hard probability version, where P in Equation (4.7) of
|
| 1375 |
+
# Algorithm 1 is set to 1 for the winner and 0 for the loser.
|
| 1376 |
+
winner_margin_error = (chosen_scores - 0.5 / self.beta) ** 2
|
| 1377 |
+
loser_margin_error = (rejected_scores + 0.5 / self.beta) ** 2
|
| 1378 |
+
per_sequence_loss = winner_margin_error + loser_margin_error
|
| 1379 |
+
|
| 1380 |
+
elif loss_type == "aot":
|
| 1381 |
+
logratios = chosen_logps - rejected_logps
|
| 1382 |
+
ref_logratios = ref_chosen_logps - ref_rejected_logps
|
| 1383 |
+
logratios_sorted, _ = torch.sort(logratios, dim=0)
|
| 1384 |
+
ref_logratios_sorted, _ = torch.sort(ref_logratios, dim=0)
|
| 1385 |
+
delta = logratios_sorted - ref_logratios_sorted
|
| 1386 |
+
per_sequence_loss = (
|
| 1387 |
+
-F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing)
|
| 1388 |
+
- F.logsigmoid(-self.beta * delta) * self.label_smoothing
|
| 1389 |
+
)
|
| 1390 |
+
|
| 1391 |
+
elif loss_type == "aot_unpaired":
|
| 1392 |
+
chosen_logratios_sorted, _ = torch.sort(chosen_logratios, dim=0)
|
| 1393 |
+
rejected_logratios_sorted, _ = torch.sort(rejected_logratios, dim=0)
|
| 1394 |
+
delta = chosen_logratios_sorted - rejected_logratios_sorted
|
| 1395 |
+
per_sequence_loss = (
|
| 1396 |
+
-F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing)
|
| 1397 |
+
- F.logsigmoid(-self.beta * delta) * self.label_smoothing
|
| 1398 |
+
)
|
| 1399 |
+
|
| 1400 |
+
elif loss_type == "apo_zero":
|
| 1401 |
+
# Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266)
|
| 1402 |
+
# Use this loss when you believe the chosen outputs are better than your model's default output
|
| 1403 |
+
# Increase chosen likelihood and decrease rejected likelihood
|
| 1404 |
+
losses_chosen = 1 - torch.sigmoid(self.beta * chosen_logratios)
|
| 1405 |
+
losses_rejected = torch.sigmoid(self.beta * rejected_logratios)
|
| 1406 |
+
per_sequence_loss = losses_chosen + losses_rejected
|
| 1407 |
+
|
| 1408 |
+
elif loss_type == "apo_down":
|
| 1409 |
+
# Eqn (8) of the APO paper (https://huggingface.co/papers/2408.06266)
|
| 1410 |
+
# Use this loss when you believe the chosen outputs are worse than your model's default output.
|
| 1411 |
+
# Decrease chosen likelihood and decrease rejected likelihood more
|
| 1412 |
+
losses_chosen = torch.sigmoid(self.beta * chosen_logratios)
|
| 1413 |
+
losses_rejected = 1 - torch.sigmoid(self.beta * delta_score)
|
| 1414 |
+
per_sequence_loss = losses_chosen + losses_rejected
|
| 1415 |
+
|
| 1416 |
+
elif loss_type == "discopop":
|
| 1417 |
+
# Eqn (5) of the DiscoPOP paper (https://huggingface.co/papers/2406.08414)
|
| 1418 |
+
logits = delta_score * self.beta
|
| 1419 |
+
# Modulate the mixing coefficient based on the log ratio magnitudes
|
| 1420 |
+
log_ratio_modulation = torch.sigmoid(logits / self.args.discopop_tau)
|
| 1421 |
+
logistic_component = -F.logsigmoid(logits)
|
| 1422 |
+
exp_component = torch.exp(-logits)
|
| 1423 |
+
# Blend between logistic and exponential component based on log ratio modulation
|
| 1424 |
+
per_sequence_loss = (
|
| 1425 |
+
logistic_component * (1 - log_ratio_modulation) + exp_component * log_ratio_modulation
|
| 1426 |
+
)
|
| 1427 |
+
|
| 1428 |
+
elif loss_type == "sft":
|
| 1429 |
+
chosen_logits, _ = shift_logits.chunk(2, dim=0)
|
| 1430 |
+
chosen_labels, _ = shift_labels.chunk(2, dim=0)
|
| 1431 |
+
chosen_mask, _ = shift_completion_mask.chunk(2, dim=0)
|
| 1432 |
+
batch_loss = F.cross_entropy(chosen_logits[chosen_mask.bool()], chosen_labels[chosen_mask.bool()])
|
| 1433 |
+
# Implementation convenience: expand the scalar SFT loss to a per-sequence tensor so it matches the
|
| 1434 |
+
# shape of other losses; only the mean is used, so this is a no-op numerically.
|
| 1435 |
+
per_sequence_loss = batch_loss.expand(chosen_logits.size(0))
|
| 1436 |
+
|
| 1437 |
+
elif loss_type == "sigmoid_norm":
|
| 1438 |
+
chosen_mask, rejected_mask = completion_mask.chunk(2, dim=0)
|
| 1439 |
+
chosen_avg_score = chosen_scores / chosen_mask.sum(dim=1).clamp(min=1.0)
|
| 1440 |
+
rejected_avg_score = rejected_scores / rejected_mask.sum(dim=1).clamp(min=1.0)
|
| 1441 |
+
delta = chosen_avg_score - rejected_avg_score
|
| 1442 |
+
per_sequence_loss = -F.logsigmoid(self.beta * delta)
|
| 1443 |
+
|
| 1444 |
+
else:
|
| 1445 |
+
raise ValueError(
|
| 1446 |
+
f"Unknown loss type: {loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'exo_pair', "
|
| 1447 |
+
"'nca_pair', 'robust', 'bco_pair', 'sppo_hard', 'aot', 'aot_unpaired', 'apo_zero', 'apo_down', "
|
| 1448 |
+
"'discopop', 'sft', 'sigmoid_norm']"
|
| 1449 |
+
)
|
| 1450 |
+
|
| 1451 |
+
if self.use_weighting:
|
| 1452 |
+
# Eq (2) of the WPO paper: https://huggingface.co/papers/2406.11827
|
| 1453 |
+
completion_lengths = shift_completion_mask.sum(dim=1).clamp_min(1)
|
| 1454 |
+
with torch.no_grad():
|
| 1455 |
+
lse1 = torch.logsumexp(shift_logits, dim=-1)
|
| 1456 |
+
lse2 = torch.logsumexp(2.0 * shift_logits, dim=-1)
|
| 1457 |
+
log_denom = lse2 - 2.0 * lse1
|
| 1458 |
+
aligned_logps = (per_token_logps - log_denom) * shift_completion_mask
|
| 1459 |
+
mean_logps = aligned_logps.sum(dim=1) / completion_lengths
|
| 1460 |
+
weights = torch.exp(mean_logps)
|
| 1461 |
+
chosen_weights, rejected_weights = weights.chunk(2, dim=0)
|
| 1462 |
+
per_sequence_loss *= chosen_weights * rejected_weights
|
| 1463 |
+
|
| 1464 |
+
loss += per_sequence_loss.mean() * loss_weight
|
| 1465 |
+
|
| 1466 |
+
# Log the metrics
|
| 1467 |
+
# Entropy
|
| 1468 |
+
per_token_entropy = entropy_from_logits(shift_logits.detach())
|
| 1469 |
+
mask = shift_completion_mask
|
| 1470 |
+
entropy_sum = (per_token_entropy * mask).sum()
|
| 1471 |
+
total_tokens = mask.sum()
|
| 1472 |
+
|
| 1473 |
+
# Gather counts across ranks and weight-average
|
| 1474 |
+
entropy_sum = self.accelerator.gather_for_metrics(entropy_sum).sum()
|
| 1475 |
+
total_tokens = self.accelerator.gather_for_metrics(total_tokens).sum()
|
| 1476 |
+
entropy = (entropy_sum / total_tokens).item() if total_tokens > 0 else 0.0
|
| 1477 |
+
self._metrics[mode]["entropy"].append(entropy)
|
| 1478 |
+
|
| 1479 |
+
# Number of tokens
|
| 1480 |
+
if mode == "train":
|
| 1481 |
+
num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item()
|
| 1482 |
+
self._total_train_tokens += num_tokens_in_batch
|
| 1483 |
+
self._metrics[mode]["num_tokens"] = [self._total_train_tokens]
|
| 1484 |
+
|
| 1485 |
+
# Average logits for chosen and rejected completions
|
| 1486 |
+
chosen_logits, rejected_logits = shift_logits.detach().chunk(2, dim=0)
|
| 1487 |
+
chosen_mask, rejected_mask = shift_completion_mask.chunk(2, dim=0)
|
| 1488 |
+
total_chosen_logits = chosen_logits[chosen_mask.bool()].mean(-1).sum()
|
| 1489 |
+
total_chosen_tokens = chosen_mask.sum()
|
| 1490 |
+
total_rejected_logits = rejected_logits[rejected_mask.bool()].mean(-1).sum()
|
| 1491 |
+
total_rejected_tokens = rejected_mask.sum()
|
| 1492 |
+
total_chosen_logits = self.accelerator.gather_for_metrics(total_chosen_logits).sum().item()
|
| 1493 |
+
total_chosen_tokens = self.accelerator.gather_for_metrics(total_chosen_tokens).sum().item()
|
| 1494 |
+
total_rejected_logits = self.accelerator.gather_for_metrics(total_rejected_logits).sum().item()
|
| 1495 |
+
total_rejected_tokens = self.accelerator.gather_for_metrics(total_rejected_tokens).sum().item()
|
| 1496 |
+
avg_chosen_logits = total_chosen_logits / total_chosen_tokens if total_chosen_tokens > 0 else 0.0
|
| 1497 |
+
avg_rejected_logits = total_rejected_logits / total_rejected_tokens if total_rejected_tokens > 0 else 0.0
|
| 1498 |
+
self._metrics[mode]["logits/chosen"].append(avg_chosen_logits)
|
| 1499 |
+
self._metrics[mode]["logits/rejected"].append(avg_rejected_logits)
|
| 1500 |
+
|
| 1501 |
+
# Token accuracy for the chosen completions
|
| 1502 |
+
predictions = chosen_logits.argmax(dim=-1)
|
| 1503 |
+
chosen_mask = shift_completion_mask[: len(shift_completion_mask) // 2].bool()
|
| 1504 |
+
chosen_labels = shift_labels[: len(shift_labels) // 2]
|
| 1505 |
+
correct_predictions = (predictions == chosen_labels) & chosen_mask
|
| 1506 |
+
total_tokens = chosen_mask.sum()
|
| 1507 |
+
correct_tokens = correct_predictions.sum()
|
| 1508 |
+
correct_tokens = self.accelerator.gather_for_metrics(correct_tokens)
|
| 1509 |
+
total_tokens = self.accelerator.gather_for_metrics(total_tokens)
|
| 1510 |
+
total_sum = total_tokens.sum()
|
| 1511 |
+
accuracy = (correct_tokens.sum() / total_sum).item() if total_sum > 0 else 0.0
|
| 1512 |
+
self._metrics[mode]["mean_token_accuracy"].append(accuracy)
|
| 1513 |
+
|
| 1514 |
+
# Rewards for chosen and rejected completions
|
| 1515 |
+
chosen_rewards = self.beta * chosen_logratios.detach()
|
| 1516 |
+
rejected_rewards = self.beta * rejected_logratios.detach()
|
| 1517 |
+
agg_chosen_rewards = self.accelerator.gather(chosen_rewards)
|
| 1518 |
+
agg_rejected_rewards = self.accelerator.gather(rejected_rewards)
|
| 1519 |
+
self._metrics[mode]["rewards/chosen"].append(agg_chosen_rewards.mean().item())
|
| 1520 |
+
self._metrics[mode]["rewards/rejected"].append(agg_rejected_rewards.mean().item())
|
| 1521 |
+
|
| 1522 |
+
# Reward accuracy
|
| 1523 |
+
reward_accuracies = (chosen_rewards > rejected_rewards).float()
|
| 1524 |
+
agg_reward_accuracies = self.accelerator.gather(reward_accuracies)
|
| 1525 |
+
self._metrics[mode]["rewards/accuracies"].append(agg_reward_accuracies.mean().item())
|
| 1526 |
+
|
| 1527 |
+
# Reward margins
|
| 1528 |
+
margins = chosen_rewards - rejected_rewards
|
| 1529 |
+
agg_margins = self.accelerator.gather(margins)
|
| 1530 |
+
self._metrics[mode]["rewards/margins"].append(agg_margins.mean().item())
|
| 1531 |
+
|
| 1532 |
+
# Average log probabilities for chosen and rejected completions
|
| 1533 |
+
self._metrics[mode]["logps/chosen"].append(self.accelerator.gather(chosen_logps).mean().item())
|
| 1534 |
+
self._metrics[mode]["logps/rejected"].append(self.accelerator.gather(rejected_logps).mean().item())
|
| 1535 |
+
|
| 1536 |
+
return (loss, outputs) if return_outputs else loss
|
| 1537 |
+
|
| 1538 |
+
def evaluate(
|
| 1539 |
+
self,
|
| 1540 |
+
eval_dataset: Dataset | dict[str, Dataset] | None = None,
|
| 1541 |
+
ignore_keys: list[str] | None = None,
|
| 1542 |
+
metric_key_prefix: str = "eval",
|
| 1543 |
+
) -> dict[str, float]:
|
| 1544 |
+
# When a dataset is passed directly to `evaluate` (e.g. a held-out test set), preprocess it the same way
|
| 1545 |
+
# `__init__` does, so that `evaluate` accepts the same dataset types as the trainer. `_prepare_dataset` is
|
| 1546 |
+
# idempotent: it skips datasets that are already tokenized. A `str` selects a dataset that was already prepared
|
| 1547 |
+
# at init time, so it's left untouched.
|
| 1548 |
+
if not self._is_vision_dataset and eval_dataset is not None and not isinstance(eval_dataset, str):
|
| 1549 |
+
if isinstance(eval_dataset, dict):
|
| 1550 |
+
eval_dataset = {
|
| 1551 |
+
key: self._prepare_dataset(dataset, self.processing_class, self.args, key)
|
| 1552 |
+
for key, dataset in eval_dataset.items()
|
| 1553 |
+
}
|
| 1554 |
+
else:
|
| 1555 |
+
eval_dataset = self._prepare_dataset(eval_dataset, self.processing_class, self.args, "eval")
|
| 1556 |
+
# With `precompute_ref_log_probs`, `_compute_loss` reads the reference log-probs from the batch, so they
|
| 1557 |
+
# must be precomputed here as well, mirroring `__init__`.
|
| 1558 |
+
if self.precompute_ref_logps:
|
| 1559 |
+
batch_size = self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size
|
| 1560 |
+
if isinstance(eval_dataset, dict):
|
| 1561 |
+
eval_dataset = {
|
| 1562 |
+
name: self._precompute_ref_logps(dataset, name, batch_size)
|
| 1563 |
+
for name, dataset in eval_dataset.items()
|
| 1564 |
+
}
|
| 1565 |
+
else:
|
| 1566 |
+
eval_dataset = self._precompute_ref_logps(eval_dataset, "eval", batch_size)
|
| 1567 |
+
return super().evaluate(
|
| 1568 |
+
eval_dataset=eval_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix
|
| 1569 |
+
)
|
| 1570 |
+
|
| 1571 |
+
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 1572 |
+
try:
|
| 1573 |
+
if self.use_liger_kernel:
|
| 1574 |
+
return self._compute_loss_liger(model, inputs, return_outputs)
|
| 1575 |
+
return self._compute_loss(model, inputs, return_outputs)
|
| 1576 |
+
except ValueError as e:
|
| 1577 |
+
if "Image features and image tokens do not match" in str(e) and self.args.max_length is not None:
|
| 1578 |
+
raise ValueError(
|
| 1579 |
+
f"The current `max_length` ({self.args.max_length}) is too short and causes image placeholder "
|
| 1580 |
+
f"tokens in `input_ids` to be truncated, while the corresponding image features remain intact. "
|
| 1581 |
+
f"Please increase `max_length` or set it to `None` to disable truncation."
|
| 1582 |
+
) from e
|
| 1583 |
+
raise
|
| 1584 |
+
|
| 1585 |
+
# Override training step to add activation offloading context.
|
| 1586 |
+
def training_step(self, *args, **kwargs):
|
| 1587 |
+
with self.maybe_activation_offload_context:
|
| 1588 |
+
return super().training_step(*args, **kwargs)
|
| 1589 |
+
|
| 1590 |
+
def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
|
| 1591 |
+
mode = "train" if self.model.training else "eval"
|
| 1592 |
+
metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics
|
| 1593 |
+
# This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
|
| 1594 |
+
# start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
|
| 1595 |
+
if mode == "eval":
|
| 1596 |
+
metrics = {f"eval_{key}": val for key, val in metrics.items()}
|
| 1597 |
+
logs.update(metrics)
|
| 1598 |
+
super().log(logs, start_time)
|
| 1599 |
+
self._metrics[mode].clear()
|
| 1600 |
+
|
| 1601 |
+
# During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and
|
| 1602 |
+
# returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels.
|
| 1603 |
+
def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None):
|
| 1604 |
+
inputs = self._prepare_inputs(inputs)
|
| 1605 |
+
with torch.no_grad(), self.compute_loss_context_manager():
|
| 1606 |
+
if prediction_loss_only:
|
| 1607 |
+
loss = self.compute_loss(model, inputs, return_outputs=False) # logits aren't materialized with liger
|
| 1608 |
+
logits, labels = None, None
|
| 1609 |
+
else:
|
| 1610 |
+
loss, outputs = self.compute_loss(model, inputs, return_outputs=True)
|
| 1611 |
+
logits, labels = outputs.logits, inputs["input_ids"]
|
| 1612 |
+
return loss, logits, labels
|
| 1613 |
+
|
| 1614 |
+
# Ensure the model card is saved along with the checkpoint
|
| 1615 |
+
def _save_checkpoint(self, model, trial):
|
| 1616 |
+
if self.args.hub_model_id is None:
|
| 1617 |
+
model_name = Path(self.args.output_dir).name
|
| 1618 |
+
else:
|
| 1619 |
+
model_name = self.args.hub_model_id.split("/")[-1]
|
| 1620 |
+
self.create_model_card(model_name=model_name)
|
| 1621 |
+
super()._save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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 .base_config import _BaseConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class GRPOConfig(_BaseConfig):
|
| 24 |
+
# docstyle-ignore
|
| 25 |
+
r"""
|
| 26 |
+
Configuration class for the [`GRPOTrainer`].
|
| 27 |
+
|
| 28 |
+
This class includes only the parameters that are specific to GRPO training. For a full list of training arguments,
|
| 29 |
+
please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
|
| 30 |
+
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 |
+
> Parameters that control the model and reference model
|
| 38 |
+
|
| 39 |
+
model_init_kwargs (`str`, `dict[str, Any]`, *optional*):
|
| 40 |
+
Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
|
| 41 |
+
argument of the [`GRPOTrainer`] is provided as a string.
|
| 42 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 43 |
+
Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to
|
| 44 |
+
[`~transformers.AutoModelForCausalLM.from_pretrained`] and
|
| 45 |
+
[`~transformers.AutoProcessor.from_pretrained`]. Also applied to reward-model and reward-tokenizer loads.
|
| 46 |
+
router_aux_loss_coef (`float`, *optional*, defaults to `0.001`):
|
| 47 |
+
Coefficient of the load-balancing auxiliary loss. Only has an effect when training a Mixture-of-Experts
|
| 48 |
+
(MoE) model; for other models it does nothing. The auxiliary loss is added to the training loss with this
|
| 49 |
+
weight. Set to `0.0` to disable it.
|
| 50 |
+
disable_dropout (`bool`, *optional*, defaults to `False`):
|
| 51 |
+
Whether to disable dropout in the model. This is useful for training with a reference model, as it prevents
|
| 52 |
+
the model from generating different logprobs for the same input.
|
| 53 |
+
cast_lm_head_to_fp32 (`bool`, *optional*, defaults to `False`):
|
| 54 |
+
Whether to cast the language modeling head of the policy and reference models to float32. As recommended by
|
| 55 |
+
the [ScaleRL](https://huggingface.co/papers/2510.13786) recipe. This flag is only supported when the model
|
| 56 |
+
has untied word embedding and language modeling head layers i.e. `tie_word_embeddings` in the model config
|
| 57 |
+
is False.
|
| 58 |
+
|
| 59 |
+
> Parameters that control the data preprocessing
|
| 60 |
+
|
| 61 |
+
remove_unused_columns (`bool`, *optional*, defaults to `False`):
|
| 62 |
+
Whether to only keep the column `"prompt"` in the dataset. If you use a custom reward function that
|
| 63 |
+
requires any column other than `"prompts"` and `"completions"`, you should keep this to `False`.
|
| 64 |
+
num_generations (`int`, *optional*, defaults to `8`):
|
| 65 |
+
Number of generations per prompt to sample. The effective batch size (num_processes * per_device_batch_size
|
| 66 |
+
* gradient_accumulation_steps) must be evenly divisible by this value.
|
| 67 |
+
num_generations_eval (`int` or `None`, *optional*):
|
| 68 |
+
Number of generations to sample during evaluation. This allows using fewer generations during evaluation to
|
| 69 |
+
save computation. If `None`, uses the value of `num_generations`.
|
| 70 |
+
max_completion_length (`int` or `None`, *optional*, defaults to `256`):
|
| 71 |
+
Maximum length of the generated completion.
|
| 72 |
+
ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
|
| 74 |
+
improving generation speed. However, disabling this option allows training models that exceed the VRAM
|
| 75 |
+
capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible
|
| 76 |
+
with vLLM generation.
|
| 77 |
+
shuffle_dataset (`bool`, *optional*, defaults to `True`):
|
| 78 |
+
Whether to shuffle the training dataset.
|
| 79 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 80 |
+
If set, the prompts ids and completions ids will be padded to a multiple of this value.
|
| 81 |
+
|
| 82 |
+
> Parameters that control generation
|
| 83 |
+
|
| 84 |
+
generation_batch_size (`int`, *optional*):
|
| 85 |
+
Batch size to use for generation. If `None`, it defaults to the effective training batch size:
|
| 86 |
+
`per_device_train_batch_size * num_processes * steps_per_generation`. In other words, there is one
|
| 87 |
+
generation batch processed per optimization step. Mutually exclusive with `steps_per_generation`.
|
| 88 |
+
steps_per_generation (`int`, *optional*):
|
| 89 |
+
Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`. Mutually exclusive
|
| 90 |
+
with `generation_batch_size`.
|
| 91 |
+
temperature (`float`, defaults to `1.0`):
|
| 92 |
+
Temperature for sampling. The higher the temperature, the more random the completions.
|
| 93 |
+
top_p (`float`, *optional*, defaults to `1.0`):
|
| 94 |
+
Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to
|
| 95 |
+
`1.0` to consider all tokens.
|
| 96 |
+
top_k (`int`, *optional*, defaults to `0`):
|
| 97 |
+
Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is
|
| 98 |
+
disabled and all tokens are considered.
|
| 99 |
+
min_p (`float`, *optional*):
|
| 100 |
+
Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
|
| 101 |
+
value between `0.0` and `1.0`. Typical values are in the `0.01-0.2` range.
|
| 102 |
+
generation_kwargs (`dict[str, Any]`, *optional*):
|
| 103 |
+
Additional keyword arguments to pass to [`~transformers.GenerationConfig`] (if using transformers) or
|
| 104 |
+
`SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the
|
| 105 |
+
generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict
|
| 106 |
+
with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them.
|
| 107 |
+
chat_template_kwargs (`dict[str, Any]`, *optional*):
|
| 108 |
+
Additional keyword arguments to pass to the `apply_chat_template` function when generating completions.
|
| 109 |
+
repetition_penalty (`float`, *optional*, defaults to `1.0`):
|
| 110 |
+
Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far.
|
| 111 |
+
Values > `1.0` encourage the model to use new tokens, while values < `1.0` encourage the model to repeat
|
| 112 |
+
tokens.
|
| 113 |
+
cache_implementation (`str`, *optional*):
|
| 114 |
+
Implementation of the cache method for faster generation when `use_vllm` is set to `False`.
|
| 115 |
+
|
| 116 |
+
> Parameters that control generation acceleration powered by vLLM
|
| 117 |
+
|
| 118 |
+
use_vllm (`bool`, *optional*, defaults to `False`):
|
| 119 |
+
Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation
|
| 120 |
+
instead of the default model.generate(). Requires `vllm` to be installed.
|
| 121 |
+
vllm_mode (`str`, *optional*, defaults to `"colocate"`):
|
| 122 |
+
Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `"server"` or
|
| 123 |
+
`"colocate"`.
|
| 124 |
+
|
| 125 |
+
- `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM
|
| 126 |
+
server is running (start with `trl vllm-serve`).
|
| 127 |
+
- `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a
|
| 128 |
+
separate server but may cause resource contention with training.
|
| 129 |
+
vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
|
| 130 |
+
Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use
|
| 131 |
+
the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model
|
| 132 |
+
implementation.
|
| 133 |
+
vllm_structured_outputs_regex (`str`, *optional*):
|
| 134 |
+
Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled.
|
| 135 |
+
|
| 136 |
+
> Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`)
|
| 137 |
+
|
| 138 |
+
vllm_server_base_url (`str`, *optional*):
|
| 139 |
+
Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `vllm_server_host` and
|
| 140 |
+
`vllm_server_port` are ignored.
|
| 141 |
+
vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
|
| 142 |
+
Host of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
|
| 143 |
+
vllm_server_port (`int`, *optional*, defaults to `8000`):
|
| 144 |
+
Port of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
|
| 145 |
+
vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
|
| 146 |
+
Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the
|
| 147 |
+
timeout, a `ConnectionError` is raised.
|
| 148 |
+
vllm_group_port (`int`, *optional*, defaults to `51216`):
|
| 149 |
+
Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port
|
| 150 |
+
is occupied, there is no need to change it.
|
| 151 |
+
|
| 152 |
+
> Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`)
|
| 153 |
+
|
| 154 |
+
vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`):
|
| 155 |
+
Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to
|
| 156 |
+
`"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
|
| 157 |
+
launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.
|
| 158 |
+
vllm_max_model_length (`int`, *optional*):
|
| 159 |
+
Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus
|
| 160 |
+
`max_completion_length`; if omitted, it is inferred from the model config.
|
| 161 |
+
vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
|
| 162 |
+
Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to
|
| 163 |
+
`"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
|
| 164 |
+
launching the vLLM server via the `--vllm_tensor_parallel_size` flag.
|
| 165 |
+
vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
|
| 166 |
+
Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but
|
| 167 |
+
waking the engine adds host–device transfer latency.
|
| 168 |
+
|
| 169 |
+
> Parameters that control generation acceleration powered by transformers continuous batching
|
| 170 |
+
|
| 171 |
+
use_transformers_continuous_batching (`bool`, *optional*, defaults to `False`):
|
| 172 |
+
Whether to use transformers' continuous batching engine for generating completions. Requires
|
| 173 |
+
`transformers>=5.8.0`.
|
| 174 |
+
transformers_continuous_batching_config (`dict`, *optional*):
|
| 175 |
+
Keyword arguments for [`~transformers.generation.ContinuousBatchingConfig`].
|
| 176 |
+
|
| 177 |
+
> Parameters that control the training
|
| 178 |
+
|
| 179 |
+
beta (`float`, *optional*, defaults to `0.0`):
|
| 180 |
+
KL coefficient. If `0.0` (default), the reference model is not loaded, reducing memory usage and improving
|
| 181 |
+
training speed. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement
|
| 182 |
+
learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`.
|
| 183 |
+
num_iterations (`int`, *optional*, defaults to `1`):
|
| 184 |
+
Number of iterations per batch (denoted as μ in the algorithm).
|
| 185 |
+
epsilon (`float`, *optional*, defaults to `0.2`):
|
| 186 |
+
Epsilon value for clipping.
|
| 187 |
+
delta (`float`, *optional*):
|
| 188 |
+
Enables the upper clipping bound in two-sided GRPO loss when set to a float. If `None` (default), standard
|
| 189 |
+
GRPO clipping is used. Recommended to be greater than `1 + ε` when enabled. This method is introduced in
|
| 190 |
+
the [INTELLECT-2 tech report](https://huggingface.co/papers/2505.07291).
|
| 191 |
+
epsilon_high (`float`, *optional*):
|
| 192 |
+
Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound
|
| 193 |
+
specified in argument `epsilon`. Paper [DAPO](https://huggingface.co/papers/2503.14476) recommends `0.28`.
|
| 194 |
+
When used with `loss_type='cispo'`, this corresponds to the ε_max param specified in the [ScaleRL
|
| 195 |
+
paper](https://huggingface.co/papers/2510.13786) and the recommended value is `5.0`.
|
| 196 |
+
sapo_temperature_neg (`float`, *optional*, defaults to `1.05`):
|
| 197 |
+
Temperature for tokens with non-positive advantage scores used in the `sapo` loss function. This parameter
|
| 198 |
+
is introduced in the [Soft Adaptive Policy Optimization paper](https://huggingface.co/papers/2511.20347).
|
| 199 |
+
sapo_temperature_pos (`float`, *optional*, defaults to `1.0`):
|
| 200 |
+
Temperature for tokens with positive advantage scores used in the `sapo` loss function. This parameter is
|
| 201 |
+
introduced in the [Soft Adaptive Policy Optimization paper](https://huggingface.co/papers/2511.20347).
|
| 202 |
+
vespo_k_pos (`float`, *optional*, defaults to `2.0`):
|
| 203 |
+
k parameter for positive advantages, it is the power exponent in the VESPO loss. Controls how aggressively
|
| 204 |
+
we down-weight samples with low importance weights (when the importance sampling ratio < 1).
|
| 205 |
+
vespo_lambda_pos (`float`, *optional*, defaults to `3.0`):
|
| 206 |
+
lambda parameter for positive advantages, it is the decay factor in the VESPO loss. Controls how
|
| 207 |
+
aggressively we down-weight samples with high importance weights (when the importance sampling ratio > 1).
|
| 208 |
+
vespo_k_neg (`float`, *optional*, defaults to `3.0`):
|
| 209 |
+
k parameter for negative advantages, it is the power exponent in the VESPO loss. Controls how aggressively
|
| 210 |
+
we down-weight samples with low importance weights (when the importance sampling ratio < 1).
|
| 211 |
+
vespo_lambda_neg (`float`, *optional*, defaults to `2.0`):
|
| 212 |
+
lambda parameter for negative advantages, it is the exponential decay factor in the VESPO loss. Controls
|
| 213 |
+
how aggressively we down-weight samples with high importance weights (when the importance sampling ratio >
|
| 214 |
+
1).
|
| 215 |
+
importance_sampling_level (`str`, *optional*, defaults to `"token"`):
|
| 216 |
+
Controls whether importance sampling ratios are computed at the `"token"` or `"sequence"` level. `"token"`
|
| 217 |
+
keeps the raw per-token log-probability ratios (one weight per token). `"sequence"` averages the
|
| 218 |
+
log-probability ratios across valid tokens to produce a single ratio per sequence. The [GSPO
|
| 219 |
+
paper](https://huggingface.co/papers/2507.18071) shows that sequence-level sampling often yields more
|
| 220 |
+
stable training and better alignment with sequence-level rewards.
|
| 221 |
+
reward_weights (`list[float]`, *optional*):
|
| 222 |
+
Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are
|
| 223 |
+
weighted equally with weight `1.0`.
|
| 224 |
+
multi_objective_aggregation (`str`, *optional*, defaults to `"sum_then_normalize"`):
|
| 225 |
+
Method to aggregate multiple reward functions. Supported values are:
|
| 226 |
+
|
| 227 |
+
- `"sum_then_normalize"` (default): First sums the weighted rewards from each reward function, then applies
|
| 228 |
+
reward scaling/normalization as specified by `scale_rewards` (see `scale_rewards` for details).
|
| 229 |
+
- `"normalize_then_sum"`: First normalizes/scales each reward function across generations (within each
|
| 230 |
+
group), then sums the normalized rewards using the specified weights. The aggregated reward is then
|
| 231 |
+
normalized at the batch level when forming advantages. This is the suggested approach from the paper
|
| 232 |
+
[GDPO: Group reward-Decoupled Normalization Policy Optimization for Multi-reward RL
|
| 233 |
+
Optimization](https://huggingface.co/papers/2601.05242).
|
| 234 |
+
scale_rewards (`str` or `bool`, *optional*, defaults to `"group"`):
|
| 235 |
+
Specifies the scaling strategy for rewards. Supported values are:
|
| 236 |
+
|
| 237 |
+
- `True` or `"group"` (default): rewards are scaled by the standard deviation within each group, ensuring
|
| 238 |
+
unit variance within a group.
|
| 239 |
+
- `"batch"`: rewards are scaled by the standard deviation across the entire batch, as recommended in the
|
| 240 |
+
[PPO Lite paper](https://huggingface.co/papers/2508.08221).
|
| 241 |
+
- `False` or `"none"`: no scaling is applied. The [Dr. GRPO
|
| 242 |
+
paper](https://huggingface.co/papers/2503.20783) recommends not scaling rewards, as scaling by the
|
| 243 |
+
standard deviation introduces a question-level difficulty bias.
|
| 244 |
+
loss_type (`str`, *optional*, defaults to `"dapo"`):
|
| 245 |
+
Specifies the loss formulation to use. Supported values are:
|
| 246 |
+
|
| 247 |
+
- `"grpo"`: Aggregates token-level losses by normalizing over sequence length. Not recommended due to
|
| 248 |
+
length bias—this approach tends to prefer shorter completions with positive advantages and longer ones
|
| 249 |
+
with negative advantages.
|
| 250 |
+
- `"dr_grpo"`: Aggregates token-level losses by normalizing with a global constant. This method was
|
| 251 |
+
introduced in the [Dr. GRPO paper](https://huggingface.co/papers/2503.20783) to eliminate length bias.
|
| 252 |
+
The value of the constant corresponds to `max_completion_length`.
|
| 253 |
+
- `"dapo"` (default): Aggregates token-level losses by normalizing with the number of active token in the
|
| 254 |
+
global accumulated batch. This method was introduced in the [DAPO
|
| 255 |
+
paper](https://huggingface.co/papers/2503.14476) to eliminate length bias.
|
| 256 |
+
- `"bnpo"`: Aggregates token-level losses by normalizing with the number of active token in the local
|
| 257 |
+
batch. Note that normalization is performed over the local batch only, so results may slightly vary
|
| 258 |
+
depending on the local batch size, despite a constant effective batch size. When using
|
| 259 |
+
`per_device_train_batch_size==1`, the loss is equivalent to the GRPO loss.
|
| 260 |
+
- `"cispo"`: Clips the importance sampling weights instead of the advantage scaled importance weights. The
|
| 261 |
+
clipped weights are then multiplied with the advantages and policy model's log probs. Individual token
|
| 262 |
+
losses are aggregated by normalizing with the number of active tokens in the global accumulated batch.
|
| 263 |
+
This method was introduced in the [MiniMax-M1 paper](https://huggingface.co/papers/2506.13585).
|
| 264 |
+
- `"sapo"`: Soft Adaptive Policy Optimization loss, as introduced in the [Soft Adaptive Policy Optimization
|
| 265 |
+
paper](https://huggingface.co/papers/2511.20347). Replaces hard clipping with a smooth,
|
| 266 |
+
temperature-controlled gate that adaptively attenuates off-policy updates while preserving useful
|
| 267 |
+
learning signals.
|
| 268 |
+
- `"luspo"`: Length-Unbiased Sequence Policy Optimization loss. A sequence-level loss that scales each
|
| 269 |
+
sequence's loss by its length. This is a modification of GSPO and requires
|
| 270 |
+
`importance_sampling_level="sequence"`. Introduced in the [LUSPO
|
| 271 |
+
paper](https://huggingface.co/papers/2602.05261).
|
| 272 |
+
- `"vespo"`: Variational Sequence-Level Soft Policy Optimization. Replaces hard clipping with a smooth,
|
| 273 |
+
asymmetric Gamma weighting function applied directly to sequence-level importance weights. Introduced in
|
| 274 |
+
the [VESPO paper](https://huggingface.co/papers/2602.10693).
|
| 275 |
+
mask_truncated_completions (`bool`, *optional*, defaults to `False`):
|
| 276 |
+
When enabled, truncated completions are excluded from the loss calculation, preventing them from being
|
| 277 |
+
incorrectly penalized and introducing noise during training. According to the
|
| 278 |
+
[DAPO](https://huggingface.co/papers/2503.14476) paper, this is a good practice for training stability.
|
| 279 |
+
sync_ref_model (`bool`, *optional*, defaults to `False`):
|
| 280 |
+
Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using
|
| 281 |
+
the `ref_model_mixup_alpha` parameter. This synchronization originates from the
|
| 282 |
+
[TR-DPO](https://huggingface.co/papers/2404.09656) paper.
|
| 283 |
+
ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`):
|
| 284 |
+
α parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which controls the mix
|
| 285 |
+
between the current policy and the previous reference policy during updates. The reference policy is
|
| 286 |
+
updated according to the equation: `π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you
|
| 287 |
+
must set `sync_ref_model=True`.
|
| 288 |
+
ref_model_sync_steps (`int`, *optional*, defaults to `512`):
|
| 289 |
+
τ parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which determines how
|
| 290 |
+
frequently the current policy is synchronized with the reference policy. To use this parameter, you must
|
| 291 |
+
set `sync_ref_model=True`.
|
| 292 |
+
top_entropy_quantile (`float`, *optional*, defaults to `1.0`):
|
| 293 |
+
ρ parameter from [Beyond the 80/20 Rule](https://huggingface.co/papers/2506.01939). Keeps in the policy
|
| 294 |
+
loss term only the top-ρ quantile of tokens by entropy of the probability distribution at each sequence
|
| 295 |
+
position, improving results. Range: `[0.0-1.0]`. A value of `0.0` masks all but the highest entropy token;
|
| 296 |
+
`1.0` keeps all tokens. The paper recommends a value of `0.2`. If used with
|
| 297 |
+
`mask_truncated_completions=True`, only tokens from non-truncated completions are considered.
|
| 298 |
+
max_tool_calling_iterations (`int`, *optional*):
|
| 299 |
+
Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and generation
|
| 300 |
+
stops when the model generates a response turn with no tool calls or when the total response length reaches
|
| 301 |
+
`max_model_length`.
|
| 302 |
+
vllm_importance_sampling_correction (`bool`, *optional*, defaults to `True`):
|
| 303 |
+
Whether to apply Importance Sampling (IS) to correct for the mismatch between vLLM completion logprobs and
|
| 304 |
+
recomputed training logprobs. If set to `False`, no IS is applied regardless of
|
| 305 |
+
`vllm_importance_sampling_mode`. When `True`, the selected mode determines how the IS ratios are computed
|
| 306 |
+
and constrained.
|
| 307 |
+
vllm_importance_sampling_mode (`str`, *optional*, defaults to `"sequence_mask"`):
|
| 308 |
+
Specifies how Importance Sampling is performed when `vllm_importance_sampling_correction=True`. Possible
|
| 309 |
+
values are:
|
| 310 |
+
|
| 311 |
+
- `"token_truncate"`: Token-level truncated IS (default). Per-token ratios are clipped to
|
| 312 |
+
[C_min, C_max].
|
| 313 |
+
- `"token_mask"`: Token-level masked IS. Per-token ratios outside [C_min, C_max] are set to zero.
|
| 314 |
+
- `"sequence_truncate"`: Sequence-level truncated IS. A single sequence ratio is clipped to
|
| 315 |
+
[C_min, C_max] and applied to all tokens in the sequence.
|
| 316 |
+
- `"sequence_mask"`: Sequence-level masked IS. Sequences with ratios outside [C_min, C_max] are masked
|
| 317 |
+
out.
|
| 318 |
+
vllm_importance_sampling_clip_max (`float`, *optional*, defaults to `3.0`):
|
| 319 |
+
Importance sampling upper bound C_max used by `vllm_importance_sampling_mode`. For `*_truncate` modes,
|
| 320 |
+
importance ratios are clipped from above at C_max. For `*_mask` modes, ratios larger than C_max are set to
|
| 321 |
+
zero.
|
| 322 |
+
vllm_importance_sampling_clip_min (`float`, *optional*):
|
| 323 |
+
Importance sampling lower bound C_min used by `vllm_importance_sampling_mode`. For `*_truncate` modes,
|
| 324 |
+
ratios are clipped from below at C_min. For `*_mask` modes, ratios below C_min are set to zero. To strictly
|
| 325 |
+
mask ratios below C_min without upper bound, set `vllm_importance_sampling_clip_max=None`.
|
| 326 |
+
off_policy_mask_threshold (`float`, *optional*):
|
| 327 |
+
Threshold for off-policy sequence masking. If `None`, off-policy sequence masking is disabled. When set,
|
| 328 |
+
sequences with negative advantages and high KL divergence are masked out to stabilize training. This
|
| 329 |
+
parameter corresponds to the `delta` threshold in Equation 9 of the [DeepSeek-V3.2
|
| 330 |
+
paper](https://huggingface.co/papers/2512.02556). It expects a positive value (e.g., 0.5).
|
| 331 |
+
use_bias_correction_kl (`bool`, *optional*, defaults to `False`):
|
| 332 |
+
Whether to use the unbiased KL divergence estimator with importance sampling correction. This corrects the
|
| 333 |
+
KL divergence estimate by multiplying it with the importance sampling ratio. This is described in the
|
| 334 |
+
[DeepSeek-V3.2 paper](https://huggingface.co/papers/2512.02556).
|
| 335 |
+
|
| 336 |
+
> Parameters that control the logging
|
| 337 |
+
|
| 338 |
+
log_completions (`bool`, *optional*, defaults to `False`):
|
| 339 |
+
Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is installed,
|
| 340 |
+
it prints the sample. If `wandb` and/or `trackio` logging is enabled, it logs it to `wandb` and/or
|
| 341 |
+
`trackio`.
|
| 342 |
+
num_completions_to_print (`int`, *optional*):
|
| 343 |
+
Number of completions to print with `rich`. If `None`, all completions are logged.
|
| 344 |
+
log_unique_prompts (`bool`, *optional*, defaults to `False`):
|
| 345 |
+
Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all prompts are
|
| 346 |
+
logged.
|
| 347 |
+
log_completions_hub_repo (`str`, *optional*):
|
| 348 |
+
Hugging Face Hub repository to save the completions. Should be a complete repository name like
|
| 349 |
+
`'username/reponame'` or `'orgname/reponame'`, or just `'reponame'` in which case the repository will be
|
| 350 |
+
created in the currently-logged-in Hugging Face user's namespace. Note that this repository will be public
|
| 351 |
+
unless you set `hub_private_repo=True` or your organization's default is to create private repositories."
|
| 352 |
+
|
| 353 |
+
> Deprecated parameters
|
| 354 |
+
|
| 355 |
+
use_transformers_paged:
|
| 356 |
+
|
| 357 |
+
<Deprecated version="1.2.0">
|
| 358 |
+
|
| 359 |
+
Parameter `use_transformers_paged` is deprecated and will be removed in version v2.0.0. Use
|
| 360 |
+
`use_transformers_continuous_batching` instead.
|
| 361 |
+
|
| 362 |
+
</Deprecated>
|
| 363 |
+
|
| 364 |
+
vllm_importance_sampling_cap:
|
| 365 |
+
|
| 366 |
+
<Deprecated version="1.6.0">
|
| 367 |
+
|
| 368 |
+
Parameter `vllm_importance_sampling_cap` is deprecated and will be removed in v2.0.0. Use
|
| 369 |
+
`vllm_importance_sampling_clip_max` instead.
|
| 370 |
+
|
| 371 |
+
</Deprecated>
|
| 372 |
+
|
| 373 |
+
> [!NOTE]
|
| 374 |
+
> These parameters have default values different from [`~transformers.TrainingArguments`]:
|
| 375 |
+
> - `logging_steps`: Defaults to `10` instead of `500`.
|
| 376 |
+
> - `gradient_checkpointing`: Defaults to `True` instead of `False`.
|
| 377 |
+
> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
|
| 378 |
+
> - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.
|
| 379 |
+
"""
|
| 380 |
+
|
| 381 |
+
_VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + [
|
| 382 |
+
"model_init_kwargs",
|
| 383 |
+
"transformers_continuous_batching_config",
|
| 384 |
+
]
|
| 385 |
+
|
| 386 |
+
# Parameters whose default values are overridden from TrainingArguments
|
| 387 |
+
learning_rate: float = field(
|
| 388 |
+
default=1e-6,
|
| 389 |
+
metadata={"help": "The initial learning rate for AdamW."},
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
# Parameters that control the model and reference model
|
| 393 |
+
model_init_kwargs: dict[str, Any] | str | None = field(
|
| 394 |
+
default=None,
|
| 395 |
+
metadata={
|
| 396 |
+
"help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` "
|
| 397 |
+
"argument of the `GRPOTrainer` is provided as a string."
|
| 398 |
+
},
|
| 399 |
+
)
|
| 400 |
+
trust_remote_code: bool = field(
|
| 401 |
+
default=False,
|
| 402 |
+
metadata={
|
| 403 |
+
"help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
|
| 404 |
+
"Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`. Also applied to "
|
| 405 |
+
"reward-model and reward-tokenizer loads."
|
| 406 |
+
},
|
| 407 |
+
)
|
| 408 |
+
router_aux_loss_coef: float = field(
|
| 409 |
+
default=0.001,
|
| 410 |
+
metadata={
|
| 411 |
+
"help": "Coefficient of the load-balancing auxiliary loss. Only has an effect when training a "
|
| 412 |
+
"Mixture-of-Experts (MoE) model; for other models it does nothing. The auxiliary loss is added to the "
|
| 413 |
+
"training loss with this weight. Set to `0.0` to disable it."
|
| 414 |
+
},
|
| 415 |
+
)
|
| 416 |
+
disable_dropout: bool = field(
|
| 417 |
+
default=False,
|
| 418 |
+
metadata={
|
| 419 |
+
"help": "Whether to disable dropout in the model. This is useful for training with a reference model, as "
|
| 420 |
+
"it prevents the model from generating different logprobs for the same input."
|
| 421 |
+
},
|
| 422 |
+
)
|
| 423 |
+
cast_lm_head_to_fp32: bool = field(
|
| 424 |
+
default=False,
|
| 425 |
+
metadata={
|
| 426 |
+
"help": "Whether to cast the language modeling head of the policy and reference, models to float32."
|
| 427 |
+
"As recommended by the [ScaleRL](https://huggingface.co/papers/2510.13786) recipe. This flag is only "
|
| 428 |
+
"supported when the model has untied word embedding and language modeling head layers i.e. "
|
| 429 |
+
"`tie_word_embeddings` in the model config is False."
|
| 430 |
+
},
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
# Parameters that control the data preprocessing
|
| 434 |
+
# The default value remove_unused_columns is overwritten from the parent class, because in GRPO we usually rely on
|
| 435 |
+
# additional columns to compute the reward
|
| 436 |
+
remove_unused_columns: bool | None = field(
|
| 437 |
+
default=False,
|
| 438 |
+
metadata={
|
| 439 |
+
"help": "Whether to only keep the column 'prompt' in the dataset. If you use a custom reward function "
|
| 440 |
+
"that requires any column other than 'prompts' and 'completions', you should keep this to `False`."
|
| 441 |
+
},
|
| 442 |
+
)
|
| 443 |
+
num_generations: int | None = field(
|
| 444 |
+
default=8,
|
| 445 |
+
metadata={
|
| 446 |
+
"help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size "
|
| 447 |
+
"* gradient_accumulation_steps) must be evenly divisible by this value."
|
| 448 |
+
},
|
| 449 |
+
)
|
| 450 |
+
num_generations_eval: int | None = field(
|
| 451 |
+
default=None,
|
| 452 |
+
metadata={
|
| 453 |
+
"help": "Number of generations to sample during evaluation. This allows using fewer generations during "
|
| 454 |
+
"evaluation to save computation. If `None`, uses the value of `num_generations`."
|
| 455 |
+
},
|
| 456 |
+
)
|
| 457 |
+
max_completion_length: int | None = field(
|
| 458 |
+
default=256,
|
| 459 |
+
metadata={"help": "Maximum length of the generated completion."},
|
| 460 |
+
)
|
| 461 |
+
ds3_gather_for_generation: bool = field(
|
| 462 |
+
default=True,
|
| 463 |
+
metadata={
|
| 464 |
+
"help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for "
|
| 465 |
+
"generation, improving generation speed. However, disabling this option allows training models that "
|
| 466 |
+
"exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option "
|
| 467 |
+
"is not compatible with vLLM generation."
|
| 468 |
+
},
|
| 469 |
+
)
|
| 470 |
+
shuffle_dataset: bool | None = field(
|
| 471 |
+
default=True,
|
| 472 |
+
metadata={"help": "Whether to shuffle the training dataset."},
|
| 473 |
+
)
|
| 474 |
+
pad_to_multiple_of: int | None = field(
|
| 475 |
+
default=None,
|
| 476 |
+
metadata={"help": "If set, the prompts ids and completions ids will be padded to a multiple of this value."},
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
# Parameters that control generation
|
| 480 |
+
generation_batch_size: int | None = field(
|
| 481 |
+
default=None,
|
| 482 |
+
metadata={
|
| 483 |
+
"help": "Batch size to use for generation. If `None`, it defaults to the effective training batch size: "
|
| 484 |
+
"`per_device_train_batch_size * num_processes * steps_per_generation`."
|
| 485 |
+
},
|
| 486 |
+
)
|
| 487 |
+
steps_per_generation: int | None = field(
|
| 488 |
+
default=None,
|
| 489 |
+
metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."},
|
| 490 |
+
)
|
| 491 |
+
temperature: float = field(
|
| 492 |
+
default=1.0,
|
| 493 |
+
metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."},
|
| 494 |
+
)
|
| 495 |
+
top_p: float = field(
|
| 496 |
+
default=1.0,
|
| 497 |
+
metadata={
|
| 498 |
+
"help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. "
|
| 499 |
+
"Set to 1.0 to consider all tokens."
|
| 500 |
+
},
|
| 501 |
+
)
|
| 502 |
+
top_k: int = field(
|
| 503 |
+
default=0,
|
| 504 |
+
metadata={
|
| 505 |
+
"help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, "
|
| 506 |
+
"top-k-filtering is disabled and all tokens are considered."
|
| 507 |
+
},
|
| 508 |
+
)
|
| 509 |
+
min_p: float | None = field(
|
| 510 |
+
default=None,
|
| 511 |
+
metadata={
|
| 512 |
+
"help": "Minimum token probability, which will be scaled by the probability of the most likely token. It "
|
| 513 |
+
"must be a value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range."
|
| 514 |
+
},
|
| 515 |
+
)
|
| 516 |
+
generation_kwargs: dict | None = field(
|
| 517 |
+
default=None,
|
| 518 |
+
metadata={
|
| 519 |
+
"help": "Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or "
|
| 520 |
+
"`SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the "
|
| 521 |
+
"generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that "
|
| 522 |
+
"conflict with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them."
|
| 523 |
+
},
|
| 524 |
+
)
|
| 525 |
+
chat_template_kwargs: dict | None = field(
|
| 526 |
+
default=None,
|
| 527 |
+
metadata={
|
| 528 |
+
"help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating "
|
| 529 |
+
"completions."
|
| 530 |
+
},
|
| 531 |
+
)
|
| 532 |
+
repetition_penalty: float = field(
|
| 533 |
+
default=1.0,
|
| 534 |
+
metadata={
|
| 535 |
+
"help": "Float that penalizes new tokens based on whether they appear in the prompt and the generated "
|
| 536 |
+
"text so far. Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model "
|
| 537 |
+
"to repeat tokens."
|
| 538 |
+
},
|
| 539 |
+
)
|
| 540 |
+
cache_implementation: str | None = field(
|
| 541 |
+
default=None,
|
| 542 |
+
metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."},
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
# Parameters that control generation acceleration powered by vLLM
|
| 546 |
+
use_vllm: bool = field(
|
| 547 |
+
default=False,
|
| 548 |
+
metadata={
|
| 549 |
+
"help": "Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for "
|
| 550 |
+
"generation instead of the default model.generate(). Requires `vllm` to be installed."
|
| 551 |
+
},
|
| 552 |
+
)
|
| 553 |
+
vllm_mode: str = field(
|
| 554 |
+
default="colocate",
|
| 555 |
+
metadata={
|
| 556 |
+
"help": "Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or "
|
| 557 |
+
"`'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure "
|
| 558 |
+
"a TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same "
|
| 559 |
+
"process and share the training GPUs. This avoids the need for a separate server but may cause resource "
|
| 560 |
+
"contention with training."
|
| 561 |
+
},
|
| 562 |
+
)
|
| 563 |
+
vllm_model_impl: str = field(
|
| 564 |
+
default="vllm",
|
| 565 |
+
metadata={
|
| 566 |
+
"help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: "
|
| 567 |
+
"Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for "
|
| 568 |
+
"model implementation."
|
| 569 |
+
},
|
| 570 |
+
)
|
| 571 |
+
vllm_enable_sleep_mode: bool = field(
|
| 572 |
+
default=False,
|
| 573 |
+
metadata={
|
| 574 |
+
"help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory "
|
| 575 |
+
"usage low, but waking the engine adds host–device transfer latency."
|
| 576 |
+
},
|
| 577 |
+
)
|
| 578 |
+
vllm_structured_outputs_regex: str | None = field(
|
| 579 |
+
default=None,
|
| 580 |
+
metadata={"help": "Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled."},
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
# Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`)
|
| 584 |
+
vllm_server_base_url: str | None = field(
|
| 585 |
+
default=None,
|
| 586 |
+
metadata={
|
| 587 |
+
"help": "Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` "
|
| 588 |
+
"and `vllm_server_port` are ignored."
|
| 589 |
+
},
|
| 590 |
+
)
|
| 591 |
+
vllm_server_host: str = field(
|
| 592 |
+
default="0.0.0.0",
|
| 593 |
+
metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
|
| 594 |
+
)
|
| 595 |
+
vllm_server_port: int = field(
|
| 596 |
+
default=8000,
|
| 597 |
+
metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
|
| 598 |
+
)
|
| 599 |
+
vllm_server_timeout: float = field(
|
| 600 |
+
default=240.0,
|
| 601 |
+
metadata={
|
| 602 |
+
"help": "Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up "
|
| 603 |
+
"after the timeout, a `ConnectionError` is raised."
|
| 604 |
+
},
|
| 605 |
+
)
|
| 606 |
+
vllm_group_port: int = field(
|
| 607 |
+
default=51216,
|
| 608 |
+
metadata={
|
| 609 |
+
"help": "Port number for the weight update group. This is used to communicate with the vLLM server. "
|
| 610 |
+
"Unless the port is occupied, there is no need to change it.",
|
| 611 |
+
},
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
# Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`)
|
| 615 |
+
vllm_gpu_memory_utilization: float = field(
|
| 616 |
+
default=0.3,
|
| 617 |
+
metadata={
|
| 618 |
+
"help": "Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set "
|
| 619 |
+
"to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when "
|
| 620 |
+
"launching the vLLM server via the `--vllm_gpu_memory_utilization` flag."
|
| 621 |
+
},
|
| 622 |
+
)
|
| 623 |
+
vllm_max_model_length: int | None = field(
|
| 624 |
+
default=None,
|
| 625 |
+
metadata={
|
| 626 |
+
"help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus "
|
| 627 |
+
"`max_completion_length`; if omitted, it is inferred from the model config."
|
| 628 |
+
},
|
| 629 |
+
)
|
| 630 |
+
vllm_tensor_parallel_size: int = field(
|
| 631 |
+
default=1,
|
| 632 |
+
metadata={
|
| 633 |
+
"help": "Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set "
|
| 634 |
+
"to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when "
|
| 635 |
+
"launching the vLLM server via the `--vllm_tensor_parallel_size` flag."
|
| 636 |
+
},
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
# Parameters that control the training
|
| 640 |
+
beta: float = field(
|
| 641 |
+
default=0.0,
|
| 642 |
+
metadata={
|
| 643 |
+
"help": "KL coefficient. If `0.0` (default), the reference model is not loaded, reducing memory usage and "
|
| 644 |
+
"improving training speed. [DeepSeek-R1 incentivizes reasoning in LLMs through reinforcement "
|
| 645 |
+
"learning](https://huggingface.co/papers/2501.12948) use a value of `0.001`."
|
| 646 |
+
},
|
| 647 |
+
)
|
| 648 |
+
num_iterations: int = field(
|
| 649 |
+
default=1,
|
| 650 |
+
metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."},
|
| 651 |
+
)
|
| 652 |
+
epsilon: float = field(
|
| 653 |
+
default=0.2,
|
| 654 |
+
metadata={"help": "Epsilon value for clipping."},
|
| 655 |
+
)
|
| 656 |
+
delta: float | None = field(
|
| 657 |
+
default=None,
|
| 658 |
+
metadata={
|
| 659 |
+
"help": "Enables the upper clipping bound in two-sided GRPO loss when set to a float. If `None` "
|
| 660 |
+
"(default), standard GRPO clipping is used. Recommended to be greater than `1 + ε` when enabled. This "
|
| 661 |
+
"method is introduced in the [INTELLECT-2 tech report](https://huggingface.co/papers/2505.07291)."
|
| 662 |
+
},
|
| 663 |
+
)
|
| 664 |
+
epsilon_high: float | None = field(
|
| 665 |
+
default=None,
|
| 666 |
+
metadata={
|
| 667 |
+
"help": "Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the "
|
| 668 |
+
"lower-bound specified in argument `epsilon`. Paper DAPO recommends `0.28`. "
|
| 669 |
+
"When used with `loss_type='cispo'`, this corresponds to the ε_max param specified in the "
|
| 670 |
+
"[ScaleRL paper](https://huggingface.co/papers/2510.13786) and the recommended value is `5.0`."
|
| 671 |
+
},
|
| 672 |
+
)
|
| 673 |
+
sapo_temperature_neg: float = field(
|
| 674 |
+
default=1.05,
|
| 675 |
+
metadata={
|
| 676 |
+
"help": "Temperature for tokens with non-positive advantage scores used in the `sapo` loss function. "
|
| 677 |
+
"This parameter is introduced in the [Soft Adaptive Policy Optimization "
|
| 678 |
+
"paper](https://huggingface.co/papers/2511.20347)."
|
| 679 |
+
},
|
| 680 |
+
)
|
| 681 |
+
sapo_temperature_pos: float = field(
|
| 682 |
+
default=1.0,
|
| 683 |
+
metadata={
|
| 684 |
+
"help": "Temperature for tokens with positive advantage scores used in the `sapo` loss function. "
|
| 685 |
+
"This parameter is introduced in the [Soft Adaptive Policy Optimization "
|
| 686 |
+
"paper](https://huggingface.co/papers/2511.20347)."
|
| 687 |
+
},
|
| 688 |
+
)
|
| 689 |
+
vespo_k_pos: float = field(
|
| 690 |
+
default=2.0,
|
| 691 |
+
metadata={
|
| 692 |
+
"help": "k parameter for positive advantages, it is the power exponent in the VESPO loss. Controls how "
|
| 693 |
+
"aggressively we down-weight samples with low importance weights (when the importance sampling ratio < 1)."
|
| 694 |
+
},
|
| 695 |
+
)
|
| 696 |
+
vespo_lambda_pos: float = field(
|
| 697 |
+
default=3.0,
|
| 698 |
+
metadata={
|
| 699 |
+
"help": "lambda parameter for positive advantages, it is the decay factor in the VESPO loss. Controls "
|
| 700 |
+
"how aggressively we down-weight samples with high importance weights (when the importance sampling ratio "
|
| 701 |
+
"> 1)."
|
| 702 |
+
},
|
| 703 |
+
)
|
| 704 |
+
vespo_k_neg: float = field(
|
| 705 |
+
default=3.0,
|
| 706 |
+
metadata={
|
| 707 |
+
"help": "k parameter for negative advantages, it is the power exponent in the VESPO loss. Controls how "
|
| 708 |
+
"aggressively we down-weight samples with low importance weights (when the importance sampling ratio < 1)."
|
| 709 |
+
},
|
| 710 |
+
)
|
| 711 |
+
vespo_lambda_neg: float = field(
|
| 712 |
+
default=2.0,
|
| 713 |
+
metadata={
|
| 714 |
+
"help": "lambda parameter for negative advantages, it is the exponential decay factor in the VESPO loss. "
|
| 715 |
+
"Controls how aggressively we down-weight samples with high importance weights (when the importance "
|
| 716 |
+
"sampling ratio > 1)."
|
| 717 |
+
},
|
| 718 |
+
)
|
| 719 |
+
importance_sampling_level: str = field(
|
| 720 |
+
default="token",
|
| 721 |
+
metadata={
|
| 722 |
+
"help": "Controls whether importance sampling ratios are computed at the `'token'` or `'sequence'` level. "
|
| 723 |
+
"`'token'` keeps the raw per-token log-probability ratios (one weight per token). `'sequence'` averages "
|
| 724 |
+
"the log-probability ratios across valid tokens to produce a single ratio per sequence. The GSPO paper "
|
| 725 |
+
"shows that sequence-level sampling often yields more stable training and better alignment with "
|
| 726 |
+
"sequence-level rewards."
|
| 727 |
+
},
|
| 728 |
+
)
|
| 729 |
+
reward_weights: list[float] | None = field(
|
| 730 |
+
default=None,
|
| 731 |
+
metadata={
|
| 732 |
+
"help": "Weights for each reward function. Must match the number of reward functions. If `None`, all "
|
| 733 |
+
"rewards are weighted equally with weight `1.0`."
|
| 734 |
+
},
|
| 735 |
+
)
|
| 736 |
+
multi_objective_aggregation: str = field(
|
| 737 |
+
default="sum_then_normalize",
|
| 738 |
+
metadata={
|
| 739 |
+
"help": "Method to aggregate multiple reward functions. Supported values are: "
|
| 740 |
+
"`'sum_then_normalize'` (default): First sums the weighted rewards from each reward function, then "
|
| 741 |
+
"applies reward scaling/normalization as specified by `scale_rewards` (see `scale_rewards` for details). "
|
| 742 |
+
"`'normalize_then_sum'`: First normalizes/scales each reward function across generations (within each "
|
| 743 |
+
"group), then sums the normalized rewards using the specified weights. The aggregated reward is then "
|
| 744 |
+
"normalized at the batch level when forming advantages. This is the suggested approach from the paper "
|
| 745 |
+
"GDPO: Group reward-Decoupled Normalization Policy Optimization for Multi-reward RL Optimization."
|
| 746 |
+
},
|
| 747 |
+
)
|
| 748 |
+
scale_rewards: str = field(
|
| 749 |
+
default="group",
|
| 750 |
+
metadata={
|
| 751 |
+
"help": "Specifies the scaling strategy for rewards. Supported values are: "
|
| 752 |
+
"`True` or `group'` (default): rewards are scaled by the standard deviation within each group, ensuring "
|
| 753 |
+
"unit variance within a group. "
|
| 754 |
+
"`'batch'`: rewards are scaled by the standard deviation across the entire batch, as recommended in the "
|
| 755 |
+
"PPO Lite paper. "
|
| 756 |
+
"`False` or `'none'`: no scaling is applied. The Dr. GRPO paper recommends not scaling rewards, as "
|
| 757 |
+
"scaling by the standard deviation introduces a question-level difficulty bias."
|
| 758 |
+
},
|
| 759 |
+
)
|
| 760 |
+
loss_type: str = field(
|
| 761 |
+
default="dapo",
|
| 762 |
+
metadata={
|
| 763 |
+
"help": "Specifies the loss formulation to use. Supported values are 'grpo', 'dapo', 'bnpo', and "
|
| 764 |
+
"'dr_grpo'. "
|
| 765 |
+
"'grpo': Aggregates token-level losses by normalizing over sequence length. Not recommended due to length "
|
| 766 |
+
"bias—this approach tends to prefer shorter completions with positive advantages and longer ones with "
|
| 767 |
+
"negative advantages. "
|
| 768 |
+
"'dapo' (default): Aggregates token-level losses by normalizing with the number of active token in the "
|
| 769 |
+
"global accumulated batch. This method was introduced in the DAPO paper to eliminate length bias. "
|
| 770 |
+
"'dr_grpo': Aggregates token-level losses by normalizing with a global constant. This method was "
|
| 771 |
+
"introduced in the Dr. GRPO paper to eliminate length bias. The value of the constant corresponds to "
|
| 772 |
+
"`max_completion_length`. "
|
| 773 |
+
"'bnpo': Aggregates token-level losses by normalizing with the number of active token in the local batch. "
|
| 774 |
+
"Note that normalization is performed over the local batch only, so results may slightly vary depending "
|
| 775 |
+
"on the local batch size, despite a constant effective batch size. When using "
|
| 776 |
+
"`per_device_train_batch_size==1`, the loss is equivalent to the GRPO loss."
|
| 777 |
+
"'cispo': Clips the importance sampling weights instead of the advantage scaled importance weights. "
|
| 778 |
+
"The clipped weights are then multiplied with the advantages and policy model's log probs. "
|
| 779 |
+
"Individual token losses are aggregated by normalizing with the number of active tokens in "
|
| 780 |
+
"the global accumulated batch. This method was introduced in the "
|
| 781 |
+
"[MiniMax-M1 paper](https://huggingface.co/papers/2506.13585). "
|
| 782 |
+
"'sapo': Soft Adaptive Policy Optimization loss, as introduced in the "
|
| 783 |
+
"[Soft Adaptive Policy Optimization paper](https://huggingface.co/papers/2511.20347). "
|
| 784 |
+
"Replaces hard clipping with a smooth, temperature-controlled gate that adaptively attenuates "
|
| 785 |
+
"off-policy updates while preserving useful learning signals."
|
| 786 |
+
"'luspo': Length-Unbiased Sequence Policy Optimization loss. A sequence-level loss that scales each "
|
| 787 |
+
"sequence's loss by its length. This is a modification of GSPO and requires "
|
| 788 |
+
"`importance_sampling_level='sequence'`. Introduced in the [LUSPO "
|
| 789 |
+
"paper](https://huggingface.co/papers/2602.05261)."
|
| 790 |
+
"'vespo': Variational Sequence-Level Soft Policy Optimization. Replaces hard clipping with a smooth, "
|
| 791 |
+
"asymmetric Gamma weighting function applied directly to sequence-level importance weights. Introduced in "
|
| 792 |
+
"the [VESPO paper](https://huggingface.co/papers/2602.10693)."
|
| 793 |
+
},
|
| 794 |
+
)
|
| 795 |
+
mask_truncated_completions: bool = field(
|
| 796 |
+
default=False,
|
| 797 |
+
metadata={
|
| 798 |
+
"help": "When enabled, truncated completions are excluded from the loss calculation, preventing them from "
|
| 799 |
+
"being incorrectly penalized and introducing noise during training. According to the DAPO paper, this is "
|
| 800 |
+
"a good practice for training stability."
|
| 801 |
+
},
|
| 802 |
+
)
|
| 803 |
+
sync_ref_model: bool = field(
|
| 804 |
+
default=False,
|
| 805 |
+
metadata={
|
| 806 |
+
"help": "Whether to synchronize the reference model with the active model every `ref_model_sync_steps` "
|
| 807 |
+
"steps, using the `ref_model_mixup_alpha` parameter."
|
| 808 |
+
},
|
| 809 |
+
)
|
| 810 |
+
ref_model_mixup_alpha: float = field(
|
| 811 |
+
default=0.6,
|
| 812 |
+
metadata={
|
| 813 |
+
"help": "α parameter from the TR-DPO paper, which controls the mix between the current policy and the "
|
| 814 |
+
"previous reference policy during updates. The reference policy is updated according to the equation: "
|
| 815 |
+
"`π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`."
|
| 816 |
+
},
|
| 817 |
+
)
|
| 818 |
+
ref_model_sync_steps: int = field(
|
| 819 |
+
default=512,
|
| 820 |
+
metadata={
|
| 821 |
+
"help": "τ parameter from the TR-DPO paper, which determines how frequently the current policy is "
|
| 822 |
+
"synchronized with the reference policy. To use this parameter, you must set `sync_ref_model=True`."
|
| 823 |
+
},
|
| 824 |
+
)
|
| 825 |
+
top_entropy_quantile: float = field(
|
| 826 |
+
default=1.0,
|
| 827 |
+
metadata={
|
| 828 |
+
"help": "ρ parameter from Beyond the 80/20 Rule. Keeps in the policy loss term only the top-ρ quantile of "
|
| 829 |
+
"tokens by entropy of the probability distribution at each sequence position, improving results. Range: "
|
| 830 |
+
"[0.0-1.0]. A value of `0.0` masks all but the highest entropy token; `1.0` keeps all tokens. The paper "
|
| 831 |
+
"recommends a value of `0.2`. If used with `mask_truncated_completions=True`, only tokens from "
|
| 832 |
+
"non-truncated completions are considered."
|
| 833 |
+
},
|
| 834 |
+
)
|
| 835 |
+
max_tool_calling_iterations: int | None = field(
|
| 836 |
+
default=None,
|
| 837 |
+
metadata={
|
| 838 |
+
"help": "Maximum number of tool-calling turns when training an agent. If `None`, there is no limit and "
|
| 839 |
+
"generation stops when the model generates a response turn with no tool calls or when the total "
|
| 840 |
+
"response length reaches `max_model_length`."
|
| 841 |
+
},
|
| 842 |
+
)
|
| 843 |
+
vllm_importance_sampling_correction: bool = field(
|
| 844 |
+
default=True,
|
| 845 |
+
metadata={
|
| 846 |
+
"help": "Whether to apply Importance Sampling (IS) to correct for the mismatch between vLLM "
|
| 847 |
+
"completion logprobs and recomputed training logprobs. If set to `False`, no IS is applied "
|
| 848 |
+
"regardless of `vllm_importance_sampling_mode`. When `True`, the selected mode determines how "
|
| 849 |
+
"IS ratios are computed and constrained."
|
| 850 |
+
},
|
| 851 |
+
)
|
| 852 |
+
vllm_importance_sampling_mode: str = field(
|
| 853 |
+
default="sequence_mask",
|
| 854 |
+
metadata={
|
| 855 |
+
"help": "Specifies how Importance Sampling (IS) is performed when "
|
| 856 |
+
"vllm_importance_sampling_correction=True. Modes are defined along two orthogonal "
|
| 857 |
+
"dimensions: (1) constraint, which determines how to handle ratios outside the bounds "
|
| 858 |
+
"[C_min, C_max]—either truncation (clip to range, ρ ← clamp(ρ, C_min, C_max)) or "
|
| 859 |
+
"masking (set ratios above C_max or below C_min to zero); and (2) granularity, which determines whether "
|
| 860 |
+
"ratios are computed per token or as a single sequence-level ratio applied to all tokens. "
|
| 861 |
+
"Supported options are: 'token_truncate', 'token_mask', 'sequence_truncate', and "
|
| 862 |
+
"'sequence_mask'."
|
| 863 |
+
},
|
| 864 |
+
)
|
| 865 |
+
vllm_importance_sampling_clip_max: float | None = field(
|
| 866 |
+
default=3.0,
|
| 867 |
+
metadata={
|
| 868 |
+
"help": "Importance sampling upper bound C_max used by `vllm_importance_sampling_mode`. For '*_truncate' "
|
| 869 |
+
"modes, ratios are clipped from above at C_max. For '*_mask' modes, ratios larger than C_max are set to "
|
| 870 |
+
"zero."
|
| 871 |
+
},
|
| 872 |
+
)
|
| 873 |
+
vllm_importance_sampling_clip_min: float | None = field(
|
| 874 |
+
default=None,
|
| 875 |
+
metadata={
|
| 876 |
+
"help": "Importance sampling lower bound C_min used by `vllm_importance_sampling_mode`. For `*_truncate` "
|
| 877 |
+
"modes, ratios are clipped from below at C_min. For `*_mask` modes, ratios below C_min are set to "
|
| 878 |
+
"zero. To strictly mask ratios below C_min without upper bound, set `vllm_importance_sampling_clip_max=None`."
|
| 879 |
+
},
|
| 880 |
+
)
|
| 881 |
+
off_policy_mask_threshold: float | None = field(
|
| 882 |
+
default=None,
|
| 883 |
+
metadata={
|
| 884 |
+
"help": "Threshold for off-policy sequence masking. If `None`, off-policy sequence masking is disabled. "
|
| 885 |
+
"When set, sequences with negative advantages and high KL divergence are masked out to stabilize "
|
| 886 |
+
"training. This parameter corresponds to the `delta` threshold in Equation 9 of the [DeepSeek-V3.2 "
|
| 887 |
+
"paper](https://huggingface.co/papers/2512.02556). It expects a positive value (e.g., 0.5)."
|
| 888 |
+
},
|
| 889 |
+
)
|
| 890 |
+
use_bias_correction_kl: bool = field(
|
| 891 |
+
default=False,
|
| 892 |
+
metadata={
|
| 893 |
+
"help": "Whether to use the unbiased KL divergence estimator with importance sampling correction. This "
|
| 894 |
+
"corrects the KL divergence estimate by multiplying it with the importance sampling ratio. "
|
| 895 |
+
"This is described in the [DeepSeek-V3.2 paper](https://huggingface.co/papers/2512.02556)."
|
| 896 |
+
},
|
| 897 |
+
)
|
| 898 |
+
|
| 899 |
+
# Parameters that control the logging
|
| 900 |
+
log_completions: bool = field(
|
| 901 |
+
default=False,
|
| 902 |
+
metadata={
|
| 903 |
+
"help": "Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is "
|
| 904 |
+
"installed, it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`."
|
| 905 |
+
},
|
| 906 |
+
)
|
| 907 |
+
num_completions_to_print: int | None = field(
|
| 908 |
+
default=None,
|
| 909 |
+
metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."},
|
| 910 |
+
)
|
| 911 |
+
log_unique_prompts: bool = field(
|
| 912 |
+
default=False,
|
| 913 |
+
metadata={
|
| 914 |
+
"help": "Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all "
|
| 915 |
+
"prompts are logged."
|
| 916 |
+
},
|
| 917 |
+
)
|
| 918 |
+
log_completions_hub_repo: str | None = field(
|
| 919 |
+
default=None,
|
| 920 |
+
metadata={
|
| 921 |
+
"help": "Hugging Face Hub repository to save the completions. Should be a complete repository name like "
|
| 922 |
+
"`'username/reponame'` or `'orgname/reponame'`, or just `'reponame'` in which case the repository will "
|
| 923 |
+
"be created in the currently-logged-in Hugging Face user's namespace. Note that this repository will be "
|
| 924 |
+
"public unless you set `hub_private_repo=True` or your organization's default is to create private "
|
| 925 |
+
"repositories."
|
| 926 |
+
},
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
# Parameters that control generation acceleration powered by transformers continuous batching
|
| 930 |
+
use_transformers_continuous_batching: bool = field(
|
| 931 |
+
default=False,
|
| 932 |
+
metadata={
|
| 933 |
+
"help": "Whether to use transformers' continuous batching engine for generating completions. Requires "
|
| 934 |
+
"transformers>=5.8.0."
|
| 935 |
+
},
|
| 936 |
+
)
|
| 937 |
+
transformers_continuous_batching_config: dict | None = field(
|
| 938 |
+
default=None,
|
| 939 |
+
metadata={"help": "Keyword arguments for `transformers.generation.ContinuousBatchingConfig`."},
|
| 940 |
+
)
|
| 941 |
+
|
| 942 |
+
# Deprecated parameters
|
| 943 |
+
use_transformers_paged: bool = field(
|
| 944 |
+
default=False,
|
| 945 |
+
metadata={"help": "Deprecated. Use `use_transformers_continuous_batching` instead."},
|
| 946 |
+
)
|
| 947 |
+
vllm_importance_sampling_cap: float | None = field(
|
| 948 |
+
default=None,
|
| 949 |
+
metadata={
|
| 950 |
+
"help": "Deprecated, use `vllm_importance_sampling_clip_max` instead. "
|
| 951 |
+
"Importance sampling cap C used by `vllm_importance_sampling_mode`. For '*_truncate' modes, "
|
| 952 |
+
"ratios are clipped from above at C. For '*_mask' modes, ratios larger than C are set to zero."
|
| 953 |
+
},
|
| 954 |
+
)
|
| 955 |
+
|
| 956 |
+
def __post_init__(self):
|
| 957 |
+
super().__post_init__()
|
| 958 |
+
|
| 959 |
+
if self.use_transformers_paged:
|
| 960 |
+
warnings.warn(
|
| 961 |
+
"`use_transformers_paged` is deprecated and will be removed in v2.0.0. Use "
|
| 962 |
+
"`use_transformers_continuous_batching` instead.",
|
| 963 |
+
FutureWarning,
|
| 964 |
+
stacklevel=3,
|
| 965 |
+
)
|
| 966 |
+
self.use_transformers_continuous_batching = True
|
| 967 |
+
|
| 968 |
+
if self.parallelism_config is not None and (
|
| 969 |
+
self.parallelism_config.cp_enabled or self.parallelism_config.sp_enabled
|
| 970 |
+
):
|
| 971 |
+
raise ValueError(
|
| 972 |
+
"GRPOTrainer does not support sequence-dim parallelism (`parallelism_config.cp_size > 1` or "
|
| 973 |
+
"`parallelism_config.sp_size > 1`) yet. GRPO builds model inputs after generation inside the trainer, "
|
| 974 |
+
"so Transformers' context-parallel / Ulysses sequence-parallel input sharding cannot be applied to the "
|
| 975 |
+
"raw generation batch. Set both `cp_size=1` and `sp_size=1`, or disable `parallelism_config`."
|
| 976 |
+
)
|
| 977 |
+
|
| 978 |
+
self.scale_rewards = {True: "group", False: "none"}.get(self.scale_rewards, self.scale_rewards)
|
| 979 |
+
|
| 980 |
+
if self.log_completions_hub_repo is not None and not self.log_completions:
|
| 981 |
+
raise ValueError(
|
| 982 |
+
"log_completions_hub_repo is set, but log_completions is False. Enable log_completions to upload "
|
| 983 |
+
"completions to the Hub, or unset log_completions_hub_repo."
|
| 984 |
+
)
|
| 985 |
+
|
| 986 |
+
num_processes = self.world_size
|
| 987 |
+
# The current default effective batch size
|
| 988 |
+
if self.generation_batch_size is None and self.steps_per_generation is None:
|
| 989 |
+
self.steps_per_generation = self.gradient_accumulation_steps
|
| 990 |
+
self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
|
| 991 |
+
elif self.generation_batch_size is not None and self.steps_per_generation is None:
|
| 992 |
+
# Just ensure the value is divisible by the global batch size
|
| 993 |
+
if self.generation_batch_size % (self.per_device_train_batch_size * num_processes) != 0:
|
| 994 |
+
raise ValueError(
|
| 995 |
+
f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size "
|
| 996 |
+
f"({self.per_device_train_batch_size * num_processes})."
|
| 997 |
+
)
|
| 998 |
+
self.steps_per_generation = self.generation_batch_size // (
|
| 999 |
+
self.per_device_train_batch_size * num_processes
|
| 1000 |
+
)
|
| 1001 |
+
elif self.generation_batch_size is None and self.steps_per_generation is not None:
|
| 1002 |
+
self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
|
| 1003 |
+
else:
|
| 1004 |
+
raise ValueError(
|
| 1005 |
+
"'generation_batch_size' and 'steps_per_generation' can not be both configured at the same time"
|
| 1006 |
+
)
|
| 1007 |
+
|
| 1008 |
+
if self.do_eval and self.eval_strategy != "no":
|
| 1009 |
+
# Determine the number of generations to use for evaluation
|
| 1010 |
+
num_generations = self.num_generations_eval or self.num_generations
|
| 1011 |
+
|
| 1012 |
+
# Just ensure the value is divisible by the global batch size
|
| 1013 |
+
if (self.per_device_eval_batch_size * num_processes) % num_generations != 0:
|
| 1014 |
+
raise ValueError(
|
| 1015 |
+
f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be "
|
| 1016 |
+
f"divisible by the number of generations used for evaluation ({num_generations})."
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
# The generation batch must contain full prompt groups (no partials), so it must be divisible by
|
| 1020 |
+
# num_generations.
|
| 1021 |
+
if self.generation_batch_size % self.num_generations != 0:
|
| 1022 |
+
raise ValueError(
|
| 1023 |
+
f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations "
|
| 1024 |
+
f"({self.num_generations})."
|
| 1025 |
+
)
|
| 1026 |
+
|
| 1027 |
+
if self.num_generations < 2:
|
| 1028 |
+
raise ValueError(
|
| 1029 |
+
"GRPO requires at least 2 generations per prompt to calculate the advantages. You provided "
|
| 1030 |
+
f"{self.num_generations}, which is less than the minimum required."
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
if self.vllm_importance_sampling_cap is not None:
|
| 1034 |
+
warnings.warn(
|
| 1035 |
+
"The `vllm_importance_sampling_cap` argument is deprecated and will be removed in v2.0.0. "
|
| 1036 |
+
"Use `vllm_importance_sampling_clip_max` instead.",
|
| 1037 |
+
FutureWarning,
|
| 1038 |
+
stacklevel=2,
|
| 1039 |
+
)
|
| 1040 |
+
self.vllm_importance_sampling_clip_max = self.vllm_importance_sampling_cap
|
| 1041 |
+
|
| 1042 |
+
if (
|
| 1043 |
+
self.vllm_importance_sampling_clip_min is not None
|
| 1044 |
+
and self.vllm_importance_sampling_clip_max is not None
|
| 1045 |
+
and self.vllm_importance_sampling_clip_min >= self.vllm_importance_sampling_clip_max
|
| 1046 |
+
):
|
| 1047 |
+
raise ValueError(
|
| 1048 |
+
f"vllm_importance_sampling_clip_min ({self.vllm_importance_sampling_clip_min}) must be less than "
|
| 1049 |
+
f"vllm_importance_sampling_clip_max ({self.vllm_importance_sampling_clip_max})."
|
| 1050 |
+
)
|
| 1051 |
+
|
| 1052 |
+
if (
|
| 1053 |
+
self.vllm_importance_sampling_correction
|
| 1054 |
+
and self.vllm_importance_sampling_mode in ("token_truncate", "sequence_truncate")
|
| 1055 |
+
and self.vllm_importance_sampling_clip_min is None
|
| 1056 |
+
and self.vllm_importance_sampling_clip_max is None
|
| 1057 |
+
):
|
| 1058 |
+
raise ValueError(
|
| 1059 |
+
"At least one of `vllm_importance_sampling_clip_min` or `vllm_importance_sampling_clip_max` "
|
| 1060 |
+
"must be set when `vllm_importance_sampling_mode` is a `*_truncate` mode."
|
| 1061 |
+
)
|
tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/grpo_trainer.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/kto_config.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 17 |
+
|
| 18 |
+
from ..import_utils import suppress_experimental_warning
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
with suppress_experimental_warning():
|
| 22 |
+
from ..experimental.kto import KTOConfig as _KTOConfig
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class KTOConfig(_KTOConfig):
|
| 27 |
+
def __post_init__(self):
|
| 28 |
+
warnings.warn(
|
| 29 |
+
"The `KTOConfig` is now located in `trl.experimental`. Please update your imports to "
|
| 30 |
+
"`from trl.experimental.kto import KTOConfig`. For more information, see "
|
| 31 |
+
"https://github.com/huggingface/trl/issues/4223. Promoting KTO to the stable API is a high-priority task. "
|
| 32 |
+
"Until then, this current path (`from trl import KTOConfig`) will remain, but API changes may occur.",
|
| 33 |
+
FutureWarning,
|
| 34 |
+
stacklevel=3,
|
| 35 |
+
)
|
| 36 |
+
super().__post_init__()
|
tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/kto_trainer.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 17 |
+
|
| 18 |
+
from ..import_utils import suppress_experimental_warning
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
with suppress_experimental_warning():
|
| 22 |
+
from ..experimental.kto import KTOTrainer as _KTOTrainer
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class KTOTrainer(_KTOTrainer):
|
| 27 |
+
def __init__(self, *args, **kwargs):
|
| 28 |
+
warnings.warn(
|
| 29 |
+
"The `KTOTrainer` is now located in `trl.experimental`. Please update your imports to "
|
| 30 |
+
"`from trl.experimental.kto import KTOTrainer`. For more information, see "
|
| 31 |
+
"https://github.com/huggingface/trl/issues/4223. Promoting KTO to the stable API is a high-priority task. "
|
| 32 |
+
"Until then, this current path (`from trl import KTOTrainer`) will remain, but API changes may occur.",
|
| 33 |
+
FutureWarning,
|
| 34 |
+
stacklevel=2,
|
| 35 |
+
)
|
|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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 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class ModelConfig:
|
| 20 |
+
"""
|
| 21 |
+
Configuration class for the models.
|
| 22 |
+
|
| 23 |
+
Using [`~transformers.HfArgumentParser`] we can turn this class into
|
| 24 |
+
[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
|
| 25 |
+
command line.
|
| 26 |
+
|
| 27 |
+
Parameters:
|
| 28 |
+
model_name_or_path (`str`, *optional*):
|
| 29 |
+
Model checkpoint for weights initialization.
|
| 30 |
+
model_revision (`str`, *optional*, defaults to `"main"`):
|
| 31 |
+
Specific model version to use. It can be a branch name, a tag name, or a commit id.
|
| 32 |
+
dtype (`Literal["auto", "bfloat16", "float16", "float32"]`, *optional*, defaults to `"float32"`):
|
| 33 |
+
Override the default `torch.dtype` and load the model under this dtype. Possible values are
|
| 34 |
+
|
| 35 |
+
- `"bfloat16"`: `torch.bfloat16`
|
| 36 |
+
- `"float16"`: `torch.float16`
|
| 37 |
+
- `"float32"`: `torch.float32`
|
| 38 |
+
- `"auto"`: Automatically derive the dtype from the model's weights.
|
| 39 |
+
|
| 40 |
+
attn_implementation (`str`, *optional*):
|
| 41 |
+
Which attention implementation to use. More information in the [Kernels Hub Integrations
|
| 42 |
+
Guide](kernels_hub).
|
| 43 |
+
use_peft (`bool`, *optional*, defaults to `False`):
|
| 44 |
+
Whether to use PEFT for training.
|
| 45 |
+
lora_r (`int`, *optional*, defaults to `16`):
|
| 46 |
+
LoRA R value.
|
| 47 |
+
lora_alpha (`int`, *optional*, defaults to `32`):
|
| 48 |
+
LoRA alpha.
|
| 49 |
+
lora_dropout (`float`, *optional*, defaults to `0.05`):
|
| 50 |
+
LoRA dropout.
|
| 51 |
+
lora_target_modules (`str | list[str]`, *optional*):
|
| 52 |
+
LoRA target modules.
|
| 53 |
+
lora_target_parameters (`str | list[str]`, *optional*):
|
| 54 |
+
List of target parameters for LoRA.
|
| 55 |
+
lora_modules_to_save (`list[str]`, *optional*):
|
| 56 |
+
Model layers to unfreeze & train.
|
| 57 |
+
lora_task_type (`str`, *optional*, defaults to `"CAUSAL_LM"`):
|
| 58 |
+
Task type to pass for LoRA (use `"SEQ_CLS"` for reward modeling).
|
| 59 |
+
use_rslora (`bool`, *optional*, defaults to `False`):
|
| 60 |
+
Whether to use Rank-Stabilized LoRA, which sets the adapter scaling factor to `lora_alpha/√r`, instead of
|
| 61 |
+
the original default value of `lora_alpha/r`.
|
| 62 |
+
use_dora (`bool`, *optional*, defaults to `False`):
|
| 63 |
+
Enable [Weight-Decomposed Low-Rank Adaptation (DoRA)](https://huggingface.co/papers/2402.09353). This
|
| 64 |
+
technique decomposes the updates of the weights into two parts, magnitude and direction. Direction is
|
| 65 |
+
handled by normal LoRA, whereas the magnitude is handled by a separate learnable parameter. This can
|
| 66 |
+
improve the performance of LoRA, especially at low ranks. Right now, DoRA only supports linear and Conv2D
|
| 67 |
+
layers. DoRA introduces a bigger overhead than pure LoRA, so it is recommended to merge weights for
|
| 68 |
+
inference.
|
| 69 |
+
load_in_8bit (`bool`, *optional*, defaults to `False`):
|
| 70 |
+
Whether to use 8 bit precision for the base model. Works only with LoRA.
|
| 71 |
+
load_in_4bit (`bool`, *optional*, defaults to `False`):
|
| 72 |
+
Whether to use 4 bit precision for the base model. Works only with LoRA.
|
| 73 |
+
bnb_4bit_quant_type (`str`, *optional*, defaults to `"nf4"`):
|
| 74 |
+
Quantization type (`"fp4"` or `"nf4"`).
|
| 75 |
+
use_bnb_nested_quant (`bool`, *optional*, defaults to `False`):
|
| 76 |
+
Whether to use nested quantization.
|
| 77 |
+
bnb_4bit_quant_storage (`str`, *optional*):
|
| 78 |
+
Quantization storage dtype.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
model_name_or_path: str | None = field(
|
| 82 |
+
default=None,
|
| 83 |
+
metadata={"help": "Model checkpoint for weights initialization."},
|
| 84 |
+
)
|
| 85 |
+
model_revision: str = field(
|
| 86 |
+
default="main",
|
| 87 |
+
metadata={"help": "Specific model version to use. It can be a branch name, a tag name, or a commit id."},
|
| 88 |
+
)
|
| 89 |
+
dtype: str | None = field(
|
| 90 |
+
default="float32",
|
| 91 |
+
metadata={
|
| 92 |
+
"help": "Override the default `torch.dtype` and load the model under this dtype. It defaults to `'float32'`.",
|
| 93 |
+
"choices": ["auto", "bfloat16", "float16", "float32"],
|
| 94 |
+
},
|
| 95 |
+
)
|
| 96 |
+
attn_implementation: str | None = field(
|
| 97 |
+
default=None,
|
| 98 |
+
metadata={
|
| 99 |
+
"help": "Which attention implementation to use. You can run `--attn_implementation=flash_attention_2`, in "
|
| 100 |
+
"which case you must install this manually by running `pip install flash-attn --no-build-isolation`."
|
| 101 |
+
},
|
| 102 |
+
)
|
| 103 |
+
use_peft: bool = field(
|
| 104 |
+
default=False,
|
| 105 |
+
metadata={"help": "Whether to use PEFT for training."},
|
| 106 |
+
)
|
| 107 |
+
lora_r: int = field(
|
| 108 |
+
default=16,
|
| 109 |
+
metadata={"help": "LoRA R value."},
|
| 110 |
+
)
|
| 111 |
+
lora_alpha: int = field(
|
| 112 |
+
default=32,
|
| 113 |
+
metadata={"help": "LoRA alpha."},
|
| 114 |
+
)
|
| 115 |
+
lora_dropout: float = field(
|
| 116 |
+
default=0.05,
|
| 117 |
+
metadata={"help": "LoRA dropout."},
|
| 118 |
+
)
|
| 119 |
+
lora_target_modules: list[str] | None = field(
|
| 120 |
+
default=None,
|
| 121 |
+
metadata={"help": "LoRA target modules."},
|
| 122 |
+
)
|
| 123 |
+
lora_target_parameters: list[str] | None = field(
|
| 124 |
+
default=None,
|
| 125 |
+
metadata={"help": "List of target parameters for LoRA."},
|
| 126 |
+
)
|
| 127 |
+
lora_modules_to_save: list[str] | None = field(
|
| 128 |
+
default=None,
|
| 129 |
+
metadata={"help": "Model layers to unfreeze & train."},
|
| 130 |
+
)
|
| 131 |
+
lora_task_type: str = field(
|
| 132 |
+
default="CAUSAL_LM",
|
| 133 |
+
metadata={"help": "Task type to pass for LoRA (use 'SEQ_CLS' for reward modeling)."},
|
| 134 |
+
)
|
| 135 |
+
use_rslora: bool = field(
|
| 136 |
+
default=False,
|
| 137 |
+
metadata={
|
| 138 |
+
"help": "Whether to use Rank-Stabilized LoRA, which sets the adapter scaling factor to `lora_alpha/√r`, "
|
| 139 |
+
"instead of the original default value of `lora_alpha/r`."
|
| 140 |
+
},
|
| 141 |
+
)
|
| 142 |
+
use_dora: bool = field(
|
| 143 |
+
default=False,
|
| 144 |
+
metadata={
|
| 145 |
+
"help": "Enable Weight-Decomposed Low-Rank Adaptation (DoRA). This technique decomposes the updates of "
|
| 146 |
+
"the weights into two parts, magnitude and direction. Direction is handled by normal LoRA, whereas the "
|
| 147 |
+
"magnitude is handled by a separate learnable parameter. This can improve the performance of LoRA, "
|
| 148 |
+
"especially at low ranks. Right now, DoRA only supports linear and Conv2D layers. DoRA introduces a "
|
| 149 |
+
"bigger overhead than pure LoRA, so it is recommended to merge weights for inference."
|
| 150 |
+
},
|
| 151 |
+
)
|
| 152 |
+
load_in_8bit: bool = field(
|
| 153 |
+
default=False,
|
| 154 |
+
metadata={"help": "Whether to use 8 bit precision for the base model. Works only with LoRA."},
|
| 155 |
+
)
|
| 156 |
+
load_in_4bit: bool = field(
|
| 157 |
+
default=False,
|
| 158 |
+
metadata={"help": "Whether to use 4 bit precision for the base model. Works only with LoRA."},
|
| 159 |
+
)
|
| 160 |
+
bnb_4bit_quant_type: str = field(
|
| 161 |
+
default="nf4",
|
| 162 |
+
metadata={"help": "Quantization type.", "choices": ["fp4", "nf4"]},
|
| 163 |
+
)
|
| 164 |
+
use_bnb_nested_quant: bool = field(
|
| 165 |
+
default=False,
|
| 166 |
+
metadata={"help": "Whether to use nested quantization."},
|
| 167 |
+
)
|
| 168 |
+
bnb_4bit_quant_storage: str | None = field(
|
| 169 |
+
default=None,
|
| 170 |
+
metadata={"help": "Quantization storage dtype"},
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
def __post_init__(self):
|
| 174 |
+
if self.load_in_8bit and self.load_in_4bit:
|
| 175 |
+
raise ValueError("You can't use 8 bit and 4 bit precision at the same time")
|
| 176 |
+
|
| 177 |
+
if hasattr(self.lora_target_modules, "__len__") and len(self.lora_target_modules) == 1:
|
| 178 |
+
self.lora_target_modules = self.lora_target_modules[0]
|
tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/reward_config.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 .base_config import _BaseConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class RewardConfig(_BaseConfig):
|
| 24 |
+
# docstyle-ignore
|
| 25 |
+
r"""
|
| 26 |
+
Configuration class for the [`RewardTrainer`].
|
| 27 |
+
|
| 28 |
+
This class includes only the parameters that are specific to Reward 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 |
+
> Parameters that control the model
|
| 38 |
+
|
| 39 |
+
model_init_kwargs (`dict[str, Any]`, *optional*):
|
| 40 |
+
Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
|
| 41 |
+
argument of the [`RewardTrainer`] is provided as a string.
|
| 42 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 43 |
+
Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to
|
| 44 |
+
[`~transformers.AutoModelForSequenceClassification.from_pretrained`] and
|
| 45 |
+
[`~transformers.AutoTokenizer.from_pretrained`].
|
| 46 |
+
chat_template_path (`str`, *optional*):
|
| 47 |
+
If specified, sets the model's chat template. This can either be the path to a tokenizer (local directory
|
| 48 |
+
or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, you must
|
| 49 |
+
ensure that any special tokens referenced in the template are added to the tokenizer and that the model's
|
| 50 |
+
embedding layer is resized accordingly.
|
| 51 |
+
disable_dropout (`bool`, *optional*, defaults to `True`):
|
| 52 |
+
Whether to disable dropout in the model.
|
| 53 |
+
|
| 54 |
+
> Parameters that control the data preprocessing
|
| 55 |
+
|
| 56 |
+
dataset_num_proc (`int`, *optional*):
|
| 57 |
+
Number of processes to use for processing the dataset.
|
| 58 |
+
eos_token (`str`, *optional*):
|
| 59 |
+
Token used to indicate the end of a turn or sequence. If `None`, it defaults to
|
| 60 |
+
`processing_class.eos_token`.
|
| 61 |
+
max_length (`int` or `None`, *optional*, defaults to `1024`):
|
| 62 |
+
Maximum length of the tokenized sequence. Samples are filtered out if either chosen or rejected sequence
|
| 63 |
+
exceeds this value. If `None`, no filtering is applied.
|
| 64 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 65 |
+
If set, the sequences will be padded to a multiple of this value.
|
| 66 |
+
|
| 67 |
+
> Parameters that control the training
|
| 68 |
+
|
| 69 |
+
center_rewards_coefficient (`float`, *optional*):
|
| 70 |
+
Coefficient to incentivize the reward model to output mean-zero rewards (proposed by
|
| 71 |
+
https://huggingface.co/papers/2312.09244, Eq. 2). Recommended value: `0.01`.
|
| 72 |
+
activation_offloading (`bool`, *optional*, defaults to `False`):
|
| 73 |
+
Whether to offload the activations to the CPU.
|
| 74 |
+
|
| 75 |
+
> Deprecated parameters
|
| 76 |
+
|
| 77 |
+
pad_token:
|
| 78 |
+
|
| 79 |
+
<Deprecated version="1.1.0">
|
| 80 |
+
|
| 81 |
+
Parameter `pad_token` is deprecated and will be removed in version v2.0.0. Set `tokenizer.pad_token`
|
| 82 |
+
directly and pass it as `processing_class` to the trainer instead.
|
| 83 |
+
|
| 84 |
+
</Deprecated>
|
| 85 |
+
|
| 86 |
+
> [!NOTE]
|
| 87 |
+
> These parameters have default values different from [`~transformers.TrainingArguments`]:
|
| 88 |
+
> - `logging_steps`: Defaults to `10` instead of `500`.
|
| 89 |
+
> - `gradient_checkpointing`: Defaults to `True` instead of `False`.
|
| 90 |
+
> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
|
| 91 |
+
> - `learning_rate`: Defaults to `1e-4` instead of `5e-5`.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
_VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
|
| 95 |
+
|
| 96 |
+
# Parameters whose default values are overridden from TrainingArguments
|
| 97 |
+
learning_rate: float = field(
|
| 98 |
+
default=1e-4,
|
| 99 |
+
metadata={"help": "The initial learning rate for AdamW."},
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# Parameters that control the model
|
| 103 |
+
model_init_kwargs: dict[str, Any] | str | None = field(
|
| 104 |
+
default=None,
|
| 105 |
+
metadata={
|
| 106 |
+
"help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of "
|
| 107 |
+
"the `RewardTrainer` is provided as a string."
|
| 108 |
+
},
|
| 109 |
+
)
|
| 110 |
+
trust_remote_code: bool = field(
|
| 111 |
+
default=False,
|
| 112 |
+
metadata={
|
| 113 |
+
"help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
|
| 114 |
+
"Forwarded to `AutoModelForSequenceClassification.from_pretrained` and `AutoTokenizer.from_pretrained`."
|
| 115 |
+
},
|
| 116 |
+
)
|
| 117 |
+
chat_template_path: str | None = field(
|
| 118 |
+
default=None,
|
| 119 |
+
metadata={
|
| 120 |
+
"help": "If specified, sets the model's chat template. This can either be the path to a tokenizer (local "
|
| 121 |
+
"directory or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, "
|
| 122 |
+
"you must ensure that any special tokens referenced in the template are added to the tokenizer and "
|
| 123 |
+
"that the model's embedding layer is resized accordingly."
|
| 124 |
+
},
|
| 125 |
+
)
|
| 126 |
+
disable_dropout: bool = field(
|
| 127 |
+
default=True,
|
| 128 |
+
metadata={"help": "Whether to disable dropout in the model."},
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Parameters that control the data preprocessing
|
| 132 |
+
dataset_num_proc: int | None = field(
|
| 133 |
+
default=None,
|
| 134 |
+
metadata={"help": "Number of processes to use for processing the dataset."},
|
| 135 |
+
)
|
| 136 |
+
eos_token: str | None = field(
|
| 137 |
+
default=None,
|
| 138 |
+
metadata={
|
| 139 |
+
"help": "Token used to indicate the end of a turn or sequence. If `None`, it defaults to `processing_class.eos_token`."
|
| 140 |
+
},
|
| 141 |
+
)
|
| 142 |
+
max_length: int | None = field(
|
| 143 |
+
default=1024,
|
| 144 |
+
metadata={
|
| 145 |
+
"help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from "
|
| 146 |
+
"the right. If `None`, no truncation is applied."
|
| 147 |
+
},
|
| 148 |
+
)
|
| 149 |
+
pad_to_multiple_of: int | None = field(
|
| 150 |
+
default=None,
|
| 151 |
+
metadata={"help": "If set, the sequences will be padded to a multiple of this value."},
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
# Parameters that control the training
|
| 155 |
+
center_rewards_coefficient: float | None = field(
|
| 156 |
+
default=None,
|
| 157 |
+
metadata={
|
| 158 |
+
"help": "Coefficient to incentivize the reward model to output mean-zero rewards (proposed by "
|
| 159 |
+
"https://huggingface.co/papers/2312.09244, Eq. 2). Recommended value: `0.01`."
|
| 160 |
+
},
|
| 161 |
+
)
|
| 162 |
+
activation_offloading: bool = field(
|
| 163 |
+
default=False,
|
| 164 |
+
metadata={"help": "Whether to offload the activations to the CPU."},
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# Deprecated parameters
|
| 168 |
+
pad_token: str | None = field(
|
| 169 |
+
default=None,
|
| 170 |
+
metadata={
|
| 171 |
+
"help": "Deprecated. Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead."
|
| 172 |
+
},
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
def __post_init__(self):
|
| 176 |
+
super().__post_init__()
|
| 177 |
+
if self.pad_token is not None:
|
| 178 |
+
warnings.warn(
|
| 179 |
+
"`pad_token` is deprecated and will be removed in v2.0.0. "
|
| 180 |
+
"Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead.",
|
| 181 |
+
FutureWarning,
|
| 182 |
+
stacklevel=3,
|
| 183 |
+
)
|
tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/reward_trainer.py
ADDED
|
@@ -0,0 +1,757 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import warnings
|
| 21 |
+
from collections import defaultdict
|
| 22 |
+
from collections.abc import Callable
|
| 23 |
+
from contextlib import contextmanager
|
| 24 |
+
from dataclasses import dataclass
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn as nn
|
| 30 |
+
import transformers
|
| 31 |
+
from accelerate import PartialState
|
| 32 |
+
from accelerate.logging import get_logger
|
| 33 |
+
from accelerate.utils import is_peft_model
|
| 34 |
+
from datasets import Dataset, IterableDataset
|
| 35 |
+
from packaging.version import Version
|
| 36 |
+
from transformers import (
|
| 37 |
+
AutoModelForSequenceClassification,
|
| 38 |
+
AutoTokenizer,
|
| 39 |
+
DataCollator,
|
| 40 |
+
PreTrainedModel,
|
| 41 |
+
PreTrainedTokenizerBase,
|
| 42 |
+
TrainerCallback,
|
| 43 |
+
set_seed,
|
| 44 |
+
)
|
| 45 |
+
from transformers.data.data_collator import DataCollatorMixin
|
| 46 |
+
from transformers.modeling_layers import GenericForSequenceClassification
|
| 47 |
+
from transformers.trainer_utils import EvalPrediction
|
| 48 |
+
from transformers.utils import is_peft_available
|
| 49 |
+
|
| 50 |
+
from ..chat_template_utils import clone_chat_template
|
| 51 |
+
from ..data_utils import is_conversational
|
| 52 |
+
from ..models import get_act_offloading_ctx_manager
|
| 53 |
+
from .base_trainer import _BaseTrainer
|
| 54 |
+
from .reward_config import RewardConfig
|
| 55 |
+
from .utils import create_model_from_path, disable_dropout_in_model, get_config_model_id, pad
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if is_peft_available():
|
| 59 |
+
import peft
|
| 60 |
+
from peft import PeftConfig, PeftModel, get_peft_model
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
logger = get_logger(__name__)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# Loading a CausalLM checkpoint into AutoModelForSequenceClassification triggers harmless warnings:
|
| 67 |
+
# - MISSING score.weight : the new seq-clf head was not in the checkpoint and is randomly initialized.
|
| 68 |
+
# - UNEXPECTED lm_head.weight: the causal LM head is in the checkpoint but absent from seq-clf (>= 4.57.0 only).
|
| 69 |
+
# Both are expected consequences of intentional cross-architecture loading. We suppress them to avoid
|
| 70 |
+
# confusing users.
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# Old approach using logging filter (for transformers < 4.57.0)
|
| 74 |
+
# Note: in transformers < 4.57.0, only the MISSING score.weight warning is emitted; lm_head.weight is not reported.
|
| 75 |
+
@contextmanager
|
| 76 |
+
def _suppress_seqcls_cross_arch_keys(logger: logging.Logger):
|
| 77 |
+
pattern = re.compile(
|
| 78 |
+
r"^Some weights of \S+ were not initialized from the model checkpoint at \S+ and are newly initialized: "
|
| 79 |
+
r"\[.*\]\nYou should probably TRAIN this model on a down-stream task to be able to use it for predictions and "
|
| 80 |
+
r"inference\.$"
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
class _Filter(logging.Filter):
|
| 84 |
+
def filter(self, record: logging.LogRecord) -> bool:
|
| 85 |
+
return not pattern.search(record.getMessage())
|
| 86 |
+
|
| 87 |
+
f = _Filter()
|
| 88 |
+
logger.addFilter(f)
|
| 89 |
+
try:
|
| 90 |
+
yield
|
| 91 |
+
finally:
|
| 92 |
+
logger.removeFilter(f)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# New approach using scoped override (for transformers >= 4.57.0)
|
| 96 |
+
@contextmanager
|
| 97 |
+
def _ignore_seqcls_cross_arch_keys():
|
| 98 |
+
# Scoped override: ignore the expected seq-clf head key (newly added) and the causal LM head
|
| 99 |
+
# key (present in the checkpoint but absent from seq-clf).
|
| 100 |
+
old_missing = getattr(GenericForSequenceClassification, "_keys_to_ignore_on_load_missing", None)
|
| 101 |
+
old_unexpected = getattr(GenericForSequenceClassification, "_keys_to_ignore_on_load_unexpected", None)
|
| 102 |
+
|
| 103 |
+
merged_missing = list(old_missing) if old_missing is not None else []
|
| 104 |
+
if r"^score\.weight$" not in merged_missing:
|
| 105 |
+
merged_missing.append(r"^score\.weight$")
|
| 106 |
+
|
| 107 |
+
merged_unexpected = list(old_unexpected) if old_unexpected is not None else []
|
| 108 |
+
if r"^lm_head\." not in merged_unexpected:
|
| 109 |
+
merged_unexpected.append(r"^lm_head\.")
|
| 110 |
+
|
| 111 |
+
GenericForSequenceClassification._keys_to_ignore_on_load_missing = merged_missing
|
| 112 |
+
GenericForSequenceClassification._keys_to_ignore_on_load_unexpected = merged_unexpected
|
| 113 |
+
try:
|
| 114 |
+
yield
|
| 115 |
+
finally:
|
| 116 |
+
GenericForSequenceClassification._keys_to_ignore_on_load_missing = old_missing
|
| 117 |
+
GenericForSequenceClassification._keys_to_ignore_on_load_unexpected = old_unexpected
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# Version-aware wrapper that chooses the appropriate approach
|
| 121 |
+
@contextmanager
|
| 122 |
+
def suppress_seqcls_warning():
|
| 123 |
+
# Use the new approach for transformers >= 4.57.0, old approach for earlier versions
|
| 124 |
+
# The old approach is needed for 4.56.2 to avoid meta tensor issues with device_map=None
|
| 125 |
+
if Version(transformers.__version__) >= Version("4.57.0"):
|
| 126 |
+
with _ignore_seqcls_cross_arch_keys():
|
| 127 |
+
yield
|
| 128 |
+
else:
|
| 129 |
+
# Get the transformers logger
|
| 130 |
+
transformers_logger = logging.getLogger("transformers.modeling_utils")
|
| 131 |
+
with _suppress_seqcls_cross_arch_keys(transformers_logger):
|
| 132 |
+
yield
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]:
|
| 136 |
+
return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@dataclass
|
| 140 |
+
class DataCollatorForPreference(DataCollatorMixin):
|
| 141 |
+
"""
|
| 142 |
+
Data collator used for preference data. Inputs are dynamically padded to the maximum length of a batch.
|
| 143 |
+
|
| 144 |
+
This collator expects each example in the input list to be a dictionary containing the `"chosen_ids"` and
|
| 145 |
+
`"rejected_ids"` keys. The collator returns a dictionary containing the following keys:
|
| 146 |
+
- `"input_ids"`: Tensor of input IDs, padded to the maximum length of the batch. The first half of the batch
|
| 147 |
+
corresponds to the `"chosen_ids"` and the second half to the `"rejected_ids"`.
|
| 148 |
+
- `"attention_mask"`: Tensor of attention mask, padded to the maximum length of the batch.
|
| 149 |
+
|
| 150 |
+
Optionally, the examples can contain a `"margin"` key, in which case the returned dictionary will also contain a
|
| 151 |
+
`"margin"` key with a tensor of margins.
|
| 152 |
+
|
| 153 |
+
Args:
|
| 154 |
+
pad_token_id (`int`):
|
| 155 |
+
Token ID to use for padding.
|
| 156 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 157 |
+
If set, the sequences will be padded to a multiple of this value.
|
| 158 |
+
return_tensors (`str`, *optional*, defaults to `"pt"`):
|
| 159 |
+
Type of Tensor to return. Only `"pt"` is currently supported.
|
| 160 |
+
|
| 161 |
+
Examples:
|
| 162 |
+
```python
|
| 163 |
+
>>> from trl.trainer.reward_trainer import DataCollatorForPreference
|
| 164 |
+
|
| 165 |
+
>>> collator = DataCollatorForPreference(pad_token_id=0)
|
| 166 |
+
>>> examples = [
|
| 167 |
+
... {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5]},
|
| 168 |
+
... {"chosen_ids": [6, 7], "rejected_ids": [8]},
|
| 169 |
+
... ]
|
| 170 |
+
>>> collator(examples)
|
| 171 |
+
{'input_ids': tensor([[1, 2, 3],
|
| 172 |
+
[6, 7, 0],
|
| 173 |
+
[4, 5, 0],
|
| 174 |
+
[8, 0, 0]]),
|
| 175 |
+
'attention_mask': tensor([[1, 1, 1],
|
| 176 |
+
[1, 1, 0],
|
| 177 |
+
[1, 1, 0],
|
| 178 |
+
[1, 0, 0]])}
|
| 179 |
+
|
| 180 |
+
>>> examples = [
|
| 181 |
+
... {"chosen_ids": [1, 2, 3], "rejected_ids": [4, 5], "margin": 0.5},
|
| 182 |
+
... {"chosen_ids": [6, 7], "rejected_ids": [8], "margin": 0.0},
|
| 183 |
+
... ]
|
| 184 |
+
>>> collator(examples)
|
| 185 |
+
{'input_ids': tensor([[1, 2, 3],
|
| 186 |
+
[6, 7, 0],
|
| 187 |
+
[4, 5, 0],
|
| 188 |
+
[8, 0, 0]]),
|
| 189 |
+
'attention_mask': tensor([[1, 1, 1],
|
| 190 |
+
[1, 1, 0],
|
| 191 |
+
[1, 1, 0],
|
| 192 |
+
[1, 0, 0]]),
|
| 193 |
+
'margin': tensor([0.5, 0.0])}
|
| 194 |
+
```
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
pad_token_id: int
|
| 198 |
+
pad_to_multiple_of: int | None = None
|
| 199 |
+
return_tensors: str = "pt"
|
| 200 |
+
|
| 201 |
+
def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
|
| 202 |
+
# Convert to tensor
|
| 203 |
+
chosen_ids = [torch.tensor(example["chosen_ids"]) for example in examples]
|
| 204 |
+
rejected_ids = [torch.tensor(example["rejected_ids"]) for example in examples]
|
| 205 |
+
if "margin" in examples[0]:
|
| 206 |
+
margins = torch.tensor([example["margin"] for example in examples], dtype=torch.float)
|
| 207 |
+
input_ids = chosen_ids + rejected_ids
|
| 208 |
+
attention_mask = [torch.ones_like(ids) for ids in input_ids]
|
| 209 |
+
|
| 210 |
+
output = {}
|
| 211 |
+
|
| 212 |
+
# Pad
|
| 213 |
+
output["input_ids"] = pad(
|
| 214 |
+
input_ids,
|
| 215 |
+
padding_value=self.pad_token_id,
|
| 216 |
+
padding_side="right",
|
| 217 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 218 |
+
)
|
| 219 |
+
output["attention_mask"] = pad(
|
| 220 |
+
attention_mask,
|
| 221 |
+
padding_value=0,
|
| 222 |
+
padding_side="right",
|
| 223 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 224 |
+
)
|
| 225 |
+
if "margin" in examples[0]:
|
| 226 |
+
output["margin"] = margins
|
| 227 |
+
return output
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class RewardTrainer(_BaseTrainer):
|
| 231 |
+
"""
|
| 232 |
+
Trainer for Outcome-supervised Reward Models (ORM).
|
| 233 |
+
|
| 234 |
+
This class is a wrapper around the [`~transformers.Trainer`] class and inherits all of its attributes and methods.
|
| 235 |
+
|
| 236 |
+
Example:
|
| 237 |
+
|
| 238 |
+
```python
|
| 239 |
+
from trl import RewardTrainer
|
| 240 |
+
from datasets import load_dataset
|
| 241 |
+
|
| 242 |
+
dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train")
|
| 243 |
+
|
| 244 |
+
trainer = RewardTrainer(
|
| 245 |
+
model="Qwen/Qwen2.5-0.5B-Instruct",
|
| 246 |
+
train_dataset=dataset,
|
| 247 |
+
)
|
| 248 |
+
trainer.train()
|
| 249 |
+
```
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]):
|
| 253 |
+
Model to be trained. Can be either:
|
| 254 |
+
|
| 255 |
+
- A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
|
| 256 |
+
path to a *directory* containing model weights saved using
|
| 257 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
| 258 |
+
using `AutoModelForSequenceClassification.from_pretrained` with the keyword arguments in
|
| 259 |
+
`args.model_init_kwargs`.
|
| 260 |
+
- A sequence classification [`~transformers.PreTrainedModel`] object.
|
| 261 |
+
- A sequence classification [`~peft.PeftModel`] object.
|
| 262 |
+
args ([`RewardConfig`], *optional*):
|
| 263 |
+
Configuration for this trainer. If `None`, a default configuration is used.
|
| 264 |
+
data_collator ([`~transformers.DataCollator`], *optional*):
|
| 265 |
+
Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`.
|
| 266 |
+
Will default to [`~trainer.reward_trainer.DataCollatorForPreference`].
|
| 267 |
+
train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
|
| 268 |
+
Dataset to use for training. This trainer supports [preference](#preference) type (both implicit and
|
| 269 |
+
explicit prompt). The format of the samples can be either:
|
| 270 |
+
|
| 271 |
+
- [Standard](dataset_formats#standard): Each sample contains plain text.
|
| 272 |
+
- [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
|
| 273 |
+
and content).
|
| 274 |
+
|
| 275 |
+
The trainer also supports processed datasets (tokenized) as long as they contain `chosen_ids` and
|
| 276 |
+
`rejected_ids` fields.
|
| 277 |
+
eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
|
| 278 |
+
Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
|
| 279 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`], *optional*):
|
| 280 |
+
Tokenizer used to process the data. If `None`, the tokenizer is loaded from the model's name with
|
| 281 |
+
[`~transformers.AutoTokenizer.from_pretrained`]. A padding token, `processing_class.pad_token`, must be
|
| 282 |
+
set. If the processing class has not set a padding token, `processing_class.eos_token` will be used as the
|
| 283 |
+
default.
|
| 284 |
+
compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
|
| 285 |
+
The function that will be used to compute metrics at evaluation. Must take a
|
| 286 |
+
[`~transformers.EvalPrediction`] and return a dictionary string to metric values. When passing
|
| 287 |
+
[`RewardConfig`] with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a
|
| 288 |
+
boolean `compute_result` argument. This will be triggered after the last eval batch to signal that the
|
| 289 |
+
function needs to calculate and return the global summary statistics rather than accumulating the
|
| 290 |
+
batch-level statistics.
|
| 291 |
+
callbacks (list of [`~transformers.TrainerCallback`], *optional*):
|
| 292 |
+
List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
|
| 293 |
+
in [here](https://huggingface.co/docs/transformers/main_classes/callback).
|
| 294 |
+
|
| 295 |
+
If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
|
| 296 |
+
method.
|
| 297 |
+
optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`):
|
| 298 |
+
A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your
|
| 299 |
+
model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`.
|
| 300 |
+
optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *optional*):
|
| 301 |
+
A tuple containing the optimizer class and keyword arguments to use. Overrides `optim` and `optim_args` in
|
| 302 |
+
`args`. Incompatible with the `optimizers` argument.
|
| 303 |
+
|
| 304 |
+
Unlike `optimizers`, this argument avoids the need to place model parameters on the correct devices before
|
| 305 |
+
initializing the Trainer.
|
| 306 |
+
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*):
|
| 307 |
+
A function that preprocess the logits right before caching them at each evaluation step. Must take two
|
| 308 |
+
tensors, the logits and the labels, and return the logits once processed as desired. The modifications made
|
| 309 |
+
by this function will be reflected in the predictions received by `compute_metrics`.
|
| 310 |
+
|
| 311 |
+
Note that the labels (second parameter) will be `None` if the dataset does not have them.
|
| 312 |
+
peft_config ([`~peft.PeftConfig`], *optional*):
|
| 313 |
+
PEFT configuration used to wrap the model. If `None`, the model is not wrapped. Note that if the loaded
|
| 314 |
+
model is a causal LM, it's highly recommended to set `modules_to_save=["score"]` in the PEFT configuration
|
| 315 |
+
to ensure that the reward head is properly trained.
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
_tag_names = ["trl", "reward-trainer"]
|
| 319 |
+
_name = "Reward"
|
| 320 |
+
_template_file = "rm_model_card.md"
|
| 321 |
+
|
| 322 |
+
def __init__(
|
| 323 |
+
self,
|
| 324 |
+
model: "str | PreTrainedModel | PeftModel",
|
| 325 |
+
args: RewardConfig | None = None,
|
| 326 |
+
data_collator: DataCollator | None = None,
|
| 327 |
+
train_dataset: Dataset | IterableDataset | None = None,
|
| 328 |
+
eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
|
| 329 |
+
processing_class: PreTrainedTokenizerBase | None = None,
|
| 330 |
+
compute_metrics: Callable[[EvalPrediction], dict] | None = None,
|
| 331 |
+
callbacks: list[TrainerCallback] | None = None,
|
| 332 |
+
optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
|
| 333 |
+
optimizer_cls_and_kwargs: tuple[type[torch.optim.Optimizer], dict[str, Any]] | None = None,
|
| 334 |
+
preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
|
| 335 |
+
peft_config: "PeftConfig | None" = None,
|
| 336 |
+
):
|
| 337 |
+
# Args
|
| 338 |
+
if args is None:
|
| 339 |
+
model_name = model if isinstance(model, str) else get_config_model_id(model.config)
|
| 340 |
+
model_name = model_name.split("/")[-1]
|
| 341 |
+
args = RewardConfig(f"{model_name}-Reward")
|
| 342 |
+
|
| 343 |
+
if train_dataset is None:
|
| 344 |
+
raise ValueError("`train_dataset` is required")
|
| 345 |
+
elif isinstance(train_dataset, IterableDataset):
|
| 346 |
+
# IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate
|
| 347 |
+
# batches from multiple processes, leading to mismatch errors.
|
| 348 |
+
if args.accelerator_config.dispatch_batches is True:
|
| 349 |
+
logger.warning(
|
| 350 |
+
"You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` "
|
| 351 |
+
"is forced to `False` when using an `IterableDataset`. To remove this warning, unset "
|
| 352 |
+
"`dispatch_batches` in `RewardConfig` or set it to `False`."
|
| 353 |
+
)
|
| 354 |
+
args.accelerator_config.dispatch_batches = False
|
| 355 |
+
|
| 356 |
+
# Model
|
| 357 |
+
# As AutoModelForSequenceClassification.from_pretrained() will add a random head for the model, set_seed must
|
| 358 |
+
# be done before loading the model to ensure reproducibility.
|
| 359 |
+
set_seed(args.seed)
|
| 360 |
+
if isinstance(model, str):
|
| 361 |
+
model_init_kwargs = args.model_init_kwargs or {}
|
| 362 |
+
# Distributed training requires device_map=None ("auto" fails)
|
| 363 |
+
if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
|
| 364 |
+
model_init_kwargs["device_map"] = None
|
| 365 |
+
model_init_kwargs["num_labels"] = 1 # the only output of the model is the reward score
|
| 366 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 367 |
+
with suppress_seqcls_warning():
|
| 368 |
+
model = create_model_from_path(model, AutoModelForSequenceClassification, **model_init_kwargs)
|
| 369 |
+
else:
|
| 370 |
+
if args.model_init_kwargs is not None:
|
| 371 |
+
logger.warning(
|
| 372 |
+
"You passed `model_init_kwargs` to the `RewardConfig`, but your model is already instantiated. "
|
| 373 |
+
"The `model_init_kwargs` will be ignored."
|
| 374 |
+
)
|
| 375 |
+
# Validate that the model has num_labels = 1 (required for reward models)
|
| 376 |
+
if getattr(model.config, "num_labels", None) != 1:
|
| 377 |
+
raise ValueError(
|
| 378 |
+
f"The model has `num_labels={model.config.num_labels}`, but reward models require `num_labels=1` "
|
| 379 |
+
"to output a single scalar reward per sequence. Please instantiate your model with `num_labels=1` "
|
| 380 |
+
"or pass a model name as a string to have it configured automatically."
|
| 381 |
+
)
|
| 382 |
+
# Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do
|
| 383 |
+
_is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False)
|
| 384 |
+
|
| 385 |
+
# Processing class
|
| 386 |
+
if processing_class is None:
|
| 387 |
+
processing_class = AutoTokenizer.from_pretrained(
|
| 388 |
+
get_config_model_id(model.config), trust_remote_code=args.trust_remote_code
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
# Handle pad token for processors or tokenizers
|
| 392 |
+
if args.eos_token is not None:
|
| 393 |
+
if args.eos_token not in processing_class.get_vocab():
|
| 394 |
+
raise ValueError(
|
| 395 |
+
f"The specified `eos_token` ('{args.eos_token}') is not found in the vocabulary of the given "
|
| 396 |
+
f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `eos_token` exists "
|
| 397 |
+
"in the vocabulary before using it as an EOS token."
|
| 398 |
+
)
|
| 399 |
+
processing_class.eos_token = args.eos_token
|
| 400 |
+
|
| 401 |
+
if args.chat_template_path is not None:
|
| 402 |
+
if os.path.isfile(args.chat_template_path) and args.chat_template_path.endswith((".jinja", ".j2")):
|
| 403 |
+
with open(args.chat_template_path, encoding="utf-8") as chat_template_file:
|
| 404 |
+
processing_class.chat_template = chat_template_file.read()
|
| 405 |
+
added_tokens = []
|
| 406 |
+
else:
|
| 407 |
+
model, processing_class, added_tokens = clone_chat_template(
|
| 408 |
+
model, processing_class, args.chat_template_path
|
| 409 |
+
)
|
| 410 |
+
else:
|
| 411 |
+
added_tokens = []
|
| 412 |
+
|
| 413 |
+
# PEFT
|
| 414 |
+
if peft_config is not None:
|
| 415 |
+
if not is_peft_available():
|
| 416 |
+
raise ImportError(
|
| 417 |
+
"You passed `peft_config` but the `peft` library is not installed. "
|
| 418 |
+
"Install it with `pip install trl[peft]`."
|
| 419 |
+
)
|
| 420 |
+
if not isinstance(peft_config, PeftConfig):
|
| 421 |
+
raise TypeError(
|
| 422 |
+
f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
|
| 423 |
+
f"got {type(peft_config).__name__}."
|
| 424 |
+
)
|
| 425 |
+
if is_peft_model(model):
|
| 426 |
+
raise ValueError(
|
| 427 |
+
"You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge "
|
| 428 |
+
"and unload the existing adapter, save the resulting base model, and then pass that base model along "
|
| 429 |
+
"with the new `peft_config` to the trainer."
|
| 430 |
+
)
|
| 431 |
+
if added_tokens:
|
| 432 |
+
# Ensure that the added tokens are trainable
|
| 433 |
+
if peft_config.trainable_token_indices is None:
|
| 434 |
+
peft_config.trainable_token_indices = {"embed_tokens": added_tokens}
|
| 435 |
+
elif "embed_tokens" not in peft_config.trainable_token_indices:
|
| 436 |
+
peft_config.trainable_token_indices["embed_tokens"] = added_tokens
|
| 437 |
+
else:
|
| 438 |
+
peft_config.trainable_token_indices["embed_tokens"].extend(added_tokens)
|
| 439 |
+
# Ensure that the lm_head is trainable
|
| 440 |
+
if peft_config.modules_to_save is None or "lm_head" not in peft_config.modules_to_save:
|
| 441 |
+
logger.warning(
|
| 442 |
+
"Cloning chat template added new tokens to the tokenizer, but 'lm_head' is not in PEFT's "
|
| 443 |
+
"`modules_to_save`. As a result, the model may not learn to generate outputs with these new "
|
| 444 |
+
"tokens, leading to degraded generation quality. To fix this, add "
|
| 445 |
+
"`modules_to_save=['lm_head']` to your PEFT configuration."
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
if peft_config.modules_to_save is None:
|
| 449 |
+
peft_config.modules_to_save = ["lm_head"]
|
| 450 |
+
else:
|
| 451 |
+
peft_config.modules_to_save.append("lm_head")
|
| 452 |
+
# Create PEFT model
|
| 453 |
+
# ZeRO-3 + PEFT for non-quantized models:
|
| 454 |
+
# - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16.
|
| 455 |
+
# - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter,
|
| 456 |
+
# so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step.
|
| 457 |
+
# - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch.
|
| 458 |
+
# - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for
|
| 459 |
+
# non-quantized bf16 training.
|
| 460 |
+
# - See:
|
| 461 |
+
# - TRL issue: https://github.com/huggingface/trl/issues/6089
|
| 462 |
+
# - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072
|
| 463 |
+
# - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg
|
| 464 |
+
get_peft_model_kwargs = {}
|
| 465 |
+
if (
|
| 466 |
+
args.deepspeed_plugin is not None
|
| 467 |
+
and args.deepspeed_plugin.zero_stage == 3
|
| 468 |
+
and not _is_quantized_model
|
| 469 |
+
and Version(peft.__version__) >= Version("0.12.0")
|
| 470 |
+
):
|
| 471 |
+
get_peft_model_kwargs["autocast_adapter_dtype"] = False
|
| 472 |
+
model = get_peft_model(model, peft_config, **get_peft_model_kwargs)
|
| 473 |
+
|
| 474 |
+
# When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally
|
| 475 |
+
# handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489
|
| 476 |
+
if is_peft_model(model) and args.gradient_checkpointing:
|
| 477 |
+
model.enable_input_require_grads()
|
| 478 |
+
|
| 479 |
+
# When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the
|
| 480 |
+
# original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by
|
| 481 |
+
# passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for
|
| 482 |
+
# quantized models. See: https://github.com/huggingface/peft/issues/2889
|
| 483 |
+
if _is_quantized_model:
|
| 484 |
+
for param in model.parameters():
|
| 485 |
+
if param.requires_grad:
|
| 486 |
+
param.data = param.data.to(torch.bfloat16)
|
| 487 |
+
|
| 488 |
+
# Disable dropout in the model
|
| 489 |
+
if args.disable_dropout:
|
| 490 |
+
disable_dropout_in_model(model)
|
| 491 |
+
|
| 492 |
+
# Pad token (needed for SequenceClassification models)
|
| 493 |
+
# If not provided, use the one from the processing class or the eos token if the processing class does not have
|
| 494 |
+
# a pad token.
|
| 495 |
+
pad_token = args.pad_token or processing_class.pad_token or processing_class.eos_token
|
| 496 |
+
if pad_token not in processing_class.get_vocab():
|
| 497 |
+
raise ValueError(
|
| 498 |
+
f"The specified `pad_token` ('{pad_token}') is not found in the vocabulary of the given "
|
| 499 |
+
f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `pad_token` exists "
|
| 500 |
+
"in the vocabulary before using it as a padding token."
|
| 501 |
+
)
|
| 502 |
+
processing_class.pad_token = pad_token
|
| 503 |
+
# SequenceClassification models need `config.pad_token_id` to locate the last non-pad token.
|
| 504 |
+
model.config.pad_token_id = processing_class.pad_token_id
|
| 505 |
+
|
| 506 |
+
# Data collator
|
| 507 |
+
if data_collator is None:
|
| 508 |
+
data_collator = DataCollatorForPreference(
|
| 509 |
+
pad_token_id=processing_class.pad_token_id,
|
| 510 |
+
pad_to_multiple_of=args.pad_to_multiple_of,
|
| 511 |
+
)
|
| 512 |
+
|
| 513 |
+
# Dataset
|
| 514 |
+
train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train")
|
| 515 |
+
if eval_dataset is not None:
|
| 516 |
+
if isinstance(eval_dataset, dict):
|
| 517 |
+
eval_dataset = {
|
| 518 |
+
key: self._prepare_dataset(dataset, processing_class, args, key)
|
| 519 |
+
for key, dataset in eval_dataset.items()
|
| 520 |
+
}
|
| 521 |
+
else:
|
| 522 |
+
eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval")
|
| 523 |
+
|
| 524 |
+
# Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
|
| 525 |
+
# never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
|
| 526 |
+
# (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
|
| 527 |
+
# default to the recommended non-reentrant behavior here, while preserving any user-provided value.
|
| 528 |
+
if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
|
| 529 |
+
args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
|
| 530 |
+
args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
|
| 531 |
+
|
| 532 |
+
super().__init__(
|
| 533 |
+
model=model,
|
| 534 |
+
args=args,
|
| 535 |
+
data_collator=data_collator,
|
| 536 |
+
train_dataset=train_dataset,
|
| 537 |
+
eval_dataset=eval_dataset,
|
| 538 |
+
processing_class=processing_class,
|
| 539 |
+
compute_metrics=compute_metrics,
|
| 540 |
+
callbacks=callbacks,
|
| 541 |
+
optimizers=optimizers,
|
| 542 |
+
optimizer_cls_and_kwargs=optimizer_cls_and_kwargs,
|
| 543 |
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
# During evaluation, Trainer calls compute_loss() only if can_return_loss is True and label_names is empty.
|
| 547 |
+
self.can_return_loss = True
|
| 548 |
+
self.label_names = []
|
| 549 |
+
|
| 550 |
+
# Initialize activation offloading context
|
| 551 |
+
if self.args.activation_offloading:
|
| 552 |
+
self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model)
|
| 553 |
+
else:
|
| 554 |
+
self.maybe_activation_offload_context = contextlib.nullcontext()
|
| 555 |
+
|
| 556 |
+
# Initialize the metrics
|
| 557 |
+
self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
|
| 558 |
+
self._total_train_tokens = 0
|
| 559 |
+
|
| 560 |
+
# Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
|
| 561 |
+
# model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
|
| 562 |
+
# self.model_accepts_loss_kwargs to False to enable scaling.
|
| 563 |
+
self.model_accepts_loss_kwargs = False
|
| 564 |
+
|
| 565 |
+
# Add tags to the model
|
| 566 |
+
self.model.add_model_tags(self._tag_names)
|
| 567 |
+
|
| 568 |
+
def _prepare_dataset(
|
| 569 |
+
self,
|
| 570 |
+
dataset: Dataset | IterableDataset,
|
| 571 |
+
processing_class: PreTrainedTokenizerBase,
|
| 572 |
+
args: RewardConfig,
|
| 573 |
+
dataset_name: str,
|
| 574 |
+
) -> Dataset | IterableDataset:
|
| 575 |
+
# If the dataset is already preprocessed (tokenized), skip the processing steps.
|
| 576 |
+
column_names = get_dataset_column_names(dataset)
|
| 577 |
+
is_processed = "chosen_ids" in column_names and "rejected_ids" in column_names
|
| 578 |
+
has_legacy_processed_columns = "chosen_input_ids" in column_names and "rejected_input_ids" in column_names
|
| 579 |
+
if has_legacy_processed_columns and not is_processed:
|
| 580 |
+
warnings.warn(
|
| 581 |
+
"Detected legacy dataset columns `chosen_input_ids`/`rejected_input_ids`; they are deprecated and "
|
| 582 |
+
"will not be supported in v1. Please migrate to `chosen_ids`/`rejected_ids`.",
|
| 583 |
+
FutureWarning,
|
| 584 |
+
stacklevel=2,
|
| 585 |
+
)
|
| 586 |
+
dataset = dataset.rename_column("chosen_input_ids", "chosen_ids")
|
| 587 |
+
dataset = dataset.rename_column("rejected_input_ids", "rejected_ids")
|
| 588 |
+
is_processed = True
|
| 589 |
+
|
| 590 |
+
# Build the kwargs for the `map` function
|
| 591 |
+
map_kwargs = {}
|
| 592 |
+
if isinstance(dataset, Dataset): # IterableDataset does not support num_proc
|
| 593 |
+
map_kwargs["num_proc"] = args.dataset_num_proc
|
| 594 |
+
|
| 595 |
+
with PartialState().main_process_first():
|
| 596 |
+
if not is_processed:
|
| 597 |
+
# Add EOS token if needed: non-conversational only
|
| 598 |
+
first_example = next(iter(dataset))
|
| 599 |
+
if not is_conversational(first_example):
|
| 600 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 601 |
+
map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset"
|
| 602 |
+
|
| 603 |
+
def add_eos(example, eos_token):
|
| 604 |
+
if not example["chosen"].endswith(eos_token):
|
| 605 |
+
example["chosen"] = example["chosen"] + eos_token
|
| 606 |
+
if "rejected" in example and not example["rejected"].endswith(eos_token):
|
| 607 |
+
example["rejected"] = example["rejected"] + eos_token
|
| 608 |
+
return example
|
| 609 |
+
|
| 610 |
+
dataset = dataset.map(
|
| 611 |
+
add_eos,
|
| 612 |
+
fn_kwargs={"eos_token": processing_class.eos_token},
|
| 613 |
+
**map_kwargs,
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
# Tokenize the dataset
|
| 617 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 618 |
+
map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset"
|
| 619 |
+
|
| 620 |
+
def tokenize_fn(example, processing_class):
|
| 621 |
+
tools = example.get("tools")
|
| 622 |
+
tools = json.loads(tools) if isinstance(tools, str) else tools
|
| 623 |
+
if "prompt" in example: # explicit prompt case
|
| 624 |
+
example["chosen"] = example["prompt"] + example["chosen"]
|
| 625 |
+
example["rejected"] = example["prompt"] + example["rejected"]
|
| 626 |
+
|
| 627 |
+
if is_conversational(example):
|
| 628 |
+
chosen_ids = processing_class.apply_chat_template(
|
| 629 |
+
example["chosen"],
|
| 630 |
+
tools=tools,
|
| 631 |
+
return_dict=True,
|
| 632 |
+
**example.get("chat_template_kwargs", {}),
|
| 633 |
+
)["input_ids"]
|
| 634 |
+
rejected_ids = processing_class.apply_chat_template(
|
| 635 |
+
example["rejected"],
|
| 636 |
+
tools=tools,
|
| 637 |
+
return_dict=True,
|
| 638 |
+
**example.get("chat_template_kwargs", {}),
|
| 639 |
+
)["input_ids"]
|
| 640 |
+
output = {"chosen_ids": chosen_ids, "rejected_ids": rejected_ids}
|
| 641 |
+
else:
|
| 642 |
+
output = {
|
| 643 |
+
"chosen_ids": processing_class(text=example["chosen"])["input_ids"],
|
| 644 |
+
"rejected_ids": processing_class(text=example["rejected"])["input_ids"],
|
| 645 |
+
}
|
| 646 |
+
return output
|
| 647 |
+
|
| 648 |
+
dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs)
|
| 649 |
+
|
| 650 |
+
# Filter samples that are longer than `max_length`
|
| 651 |
+
if args.max_length is not None:
|
| 652 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 653 |
+
map_kwargs["desc"] = f"Filtering {dataset_name} >{args.max_length} tokens"
|
| 654 |
+
dataset = dataset.filter(
|
| 655 |
+
lambda example: len(example["chosen_ids"]) <= args.max_length
|
| 656 |
+
and len(example["rejected_ids"]) <= args.max_length,
|
| 657 |
+
**map_kwargs,
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
return dataset
|
| 661 |
+
|
| 662 |
+
def _set_signature_columns_if_needed(self):
|
| 663 |
+
# If `self.args.remove_unused_columns` is True, non-signature columns are removed.
|
| 664 |
+
# By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids"
|
| 665 |
+
# and "attention_mask").
|
| 666 |
+
if self._signature_columns is None:
|
| 667 |
+
self._signature_columns = ["chosen_ids", "rejected_ids", "margin"]
|
| 668 |
+
|
| 669 |
+
def evaluate(
|
| 670 |
+
self,
|
| 671 |
+
eval_dataset: Dataset | dict[str, Dataset] | None = None,
|
| 672 |
+
ignore_keys: list[str] | None = None,
|
| 673 |
+
metric_key_prefix: str = "eval",
|
| 674 |
+
) -> dict[str, float]:
|
| 675 |
+
# When a dataset is passed directly to `evaluate` (e.g. a held-out test set), preprocess it the same way
|
| 676 |
+
# `__init__` does, so that `evaluate` accepts the same dataset types as the trainer. `_prepare_dataset` is
|
| 677 |
+
# idempotent: it skips datasets that are already tokenized. A `str` selects a dataset that was already prepared
|
| 678 |
+
# at init time, so it's left untouched.
|
| 679 |
+
if eval_dataset is not None and not isinstance(eval_dataset, str):
|
| 680 |
+
if isinstance(eval_dataset, dict):
|
| 681 |
+
eval_dataset = {
|
| 682 |
+
key: self._prepare_dataset(dataset, self.processing_class, self.args, key)
|
| 683 |
+
for key, dataset in eval_dataset.items()
|
| 684 |
+
}
|
| 685 |
+
else:
|
| 686 |
+
eval_dataset = self._prepare_dataset(eval_dataset, self.processing_class, self.args, "eval")
|
| 687 |
+
return super().evaluate(
|
| 688 |
+
eval_dataset=eval_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 692 |
+
mode = "train" if self.model.training else "eval"
|
| 693 |
+
|
| 694 |
+
# If not set, defaults from model config and may warn since cache isn't compatible with gradient checkpointing
|
| 695 |
+
inputs["use_cache"] = False
|
| 696 |
+
outputs = model(**inputs)
|
| 697 |
+
|
| 698 |
+
# Split the rewards into chosen and rejected
|
| 699 |
+
rewards_chosen, rewards_rejected = torch.chunk(outputs.logits.squeeze(-1), chunks=2)
|
| 700 |
+
|
| 701 |
+
# Calculate loss, optionally modulate with margin
|
| 702 |
+
if "margin" in inputs:
|
| 703 |
+
loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected - inputs["margin"]).mean()
|
| 704 |
+
else:
|
| 705 |
+
loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected).mean()
|
| 706 |
+
|
| 707 |
+
if self.args.center_rewards_coefficient is not None:
|
| 708 |
+
loss += self.args.center_rewards_coefficient * torch.mean((rewards_chosen + rewards_rejected) ** 2)
|
| 709 |
+
|
| 710 |
+
if mode == "train":
|
| 711 |
+
num_tokens_in_batch = self.accelerator.gather_for_metrics(inputs["attention_mask"].sum()).sum().item()
|
| 712 |
+
self._total_train_tokens += num_tokens_in_batch
|
| 713 |
+
self._metrics[mode]["num_tokens"] = [self._total_train_tokens]
|
| 714 |
+
|
| 715 |
+
# Compute min, mean, max, accuracy and margin
|
| 716 |
+
with torch.no_grad():
|
| 717 |
+
all_rewards = self.accelerator.gather(outputs.logits)
|
| 718 |
+
self._metrics[mode]["min_reward"].append(all_rewards.min().item())
|
| 719 |
+
self._metrics[mode]["mean_reward"].append(all_rewards.mean().item())
|
| 720 |
+
self._metrics[mode]["max_reward"].append(all_rewards.max().item())
|
| 721 |
+
|
| 722 |
+
mean_accuracy = (rewards_chosen > rewards_rejected).float().mean()
|
| 723 |
+
mean_accuracy = self.accelerator.gather_for_metrics(mean_accuracy).mean().item()
|
| 724 |
+
self._metrics[mode]["accuracy"].append(mean_accuracy)
|
| 725 |
+
|
| 726 |
+
mean_margin = (rewards_chosen - rewards_rejected).mean()
|
| 727 |
+
mean_margin = self.accelerator.gather_for_metrics(mean_margin).mean()
|
| 728 |
+
self._metrics[mode]["margin"].append(mean_margin.item())
|
| 729 |
+
|
| 730 |
+
return (loss, outputs) if return_outputs else loss
|
| 731 |
+
|
| 732 |
+
# Override training step to add activation offloading context.
|
| 733 |
+
def training_step(self, *args, **kwargs):
|
| 734 |
+
with self.maybe_activation_offload_context:
|
| 735 |
+
return super().training_step(*args, **kwargs)
|
| 736 |
+
|
| 737 |
+
def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
|
| 738 |
+
mode = "train" if self.model.training else "eval"
|
| 739 |
+
metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics
|
| 740 |
+
|
| 741 |
+
# This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
|
| 742 |
+
# start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
|
| 743 |
+
if mode == "eval":
|
| 744 |
+
metrics = {f"eval_{key}": val for key, val in metrics.items()}
|
| 745 |
+
|
| 746 |
+
logs.update(metrics)
|
| 747 |
+
super().log(logs, start_time)
|
| 748 |
+
self._metrics[mode].clear()
|
| 749 |
+
|
| 750 |
+
# Ensure the model card is saved along with the checkpoint
|
| 751 |
+
def _save_checkpoint(self, model, trial):
|
| 752 |
+
if self.args.hub_model_id is None:
|
| 753 |
+
model_name = Path(self.args.output_dir).name
|
| 754 |
+
else:
|
| 755 |
+
model_name = self.args.hub_model_id.split("/")[-1]
|
| 756 |
+
self.create_model_card(model_name=model_name)
|
| 757 |
+
super()._save_checkpoint(model, trial)
|
tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/rloo_config.py
ADDED
|
@@ -0,0 +1,668 @@
|
|
|
|
|
|
|
|
|
|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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 .base_config import _BaseConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class RLOOConfig(_BaseConfig):
|
| 24 |
+
# docstyle-ignore
|
| 25 |
+
r"""
|
| 26 |
+
Configuration class for the [`RLOOTrainer`].
|
| 27 |
+
|
| 28 |
+
This class includes only the parameters that are specific to RLOO training. For a full list of training arguments,
|
| 29 |
+
please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
|
| 30 |
+
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 |
+
> Parameters that control the model and reference model
|
| 38 |
+
|
| 39 |
+
model_init_kwargs (`str`, `dict[str, Any]`, *optional*):
|
| 40 |
+
Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
|
| 41 |
+
argument of the [`RLOOTrainer`] is provided as a string.
|
| 42 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 43 |
+
Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to
|
| 44 |
+
[`~transformers.AutoModelForCausalLM.from_pretrained`] and
|
| 45 |
+
[`~transformers.AutoProcessor.from_pretrained`]. Also applied to reward-model and reward-tokenizer loads.
|
| 46 |
+
router_aux_loss_coef (`float`, *optional*, defaults to `0.001`):
|
| 47 |
+
Coefficient of the load-balancing auxiliary loss. Only has an effect when training a Mixture-of-Experts
|
| 48 |
+
(MoE) model; for other models it does nothing. The auxiliary loss is added to the training loss with this
|
| 49 |
+
weight. Set to `0.0` to disable it.
|
| 50 |
+
disable_dropout (`bool`, *optional*, defaults to `False`):
|
| 51 |
+
Whether to disable dropout in the model. This is useful for training with a reference model, as it prevents
|
| 52 |
+
the model from generating different logprobs for the same input.
|
| 53 |
+
|
| 54 |
+
> Parameters that control the data preprocessing
|
| 55 |
+
|
| 56 |
+
remove_unused_columns (`bool`, *optional*, defaults to `False`):
|
| 57 |
+
Whether to only keep the column `"prompt"` in the dataset. If you use a custom reward function that
|
| 58 |
+
requires any column other than `"prompts"` and `"completions"`, you should keep this to `False`.
|
| 59 |
+
num_generations (`int`, *optional*, defaults to `2`):
|
| 60 |
+
Number of generations per prompt to sample. The effective batch size (num_processes * per_device_batch_size
|
| 61 |
+
* gradient_accumulation_steps) must be evenly divisible by this value.
|
| 62 |
+
num_generations_eval (`int` or `None`, *optional*):
|
| 63 |
+
Number of generations to sample during evaluation. This allows using fewer generations during evaluation to
|
| 64 |
+
save computation. If `None`, uses the value of `num_generations`.
|
| 65 |
+
max_completion_length (`int` or `None`, *optional*, defaults to `256`):
|
| 66 |
+
Maximum length of the generated completion.
|
| 67 |
+
ds3_gather_for_generation (`bool`, *optional*, defaults to `True`):
|
| 68 |
+
This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for generation,
|
| 69 |
+
improving generation speed. However, disabling this option allows training models that exceed the VRAM
|
| 70 |
+
capacity of a single GPU, albeit at the cost of slower generation. Disabling this option is not compatible
|
| 71 |
+
with vLLM generation.
|
| 72 |
+
shuffle_dataset (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether to shuffle the training dataset.
|
| 74 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 75 |
+
If set, the prompts ids and completions ids will be padded to a multiple of this value.
|
| 76 |
+
|
| 77 |
+
> Parameters that control generation
|
| 78 |
+
|
| 79 |
+
generation_batch_size (`int`, *optional*):
|
| 80 |
+
Batch size to use for generation. If `None`, it defaults to the effective training batch size:
|
| 81 |
+
`per_device_train_batch_size * num_processes * steps_per_generation`. In other words, there is one
|
| 82 |
+
generation batch processed per optimization step. Mutually exclusive with `steps_per_generation`.
|
| 83 |
+
steps_per_generation (`int`, *optional*):
|
| 84 |
+
Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`. Mutually exclusive
|
| 85 |
+
with `generation_batch_size`.
|
| 86 |
+
temperature (`float`, defaults to `1.0`):
|
| 87 |
+
Temperature for sampling. The higher the temperature, the more random the completions.
|
| 88 |
+
top_p (`float`, *optional*, defaults to `1.0`):
|
| 89 |
+
Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to
|
| 90 |
+
`1.0` to consider all tokens.
|
| 91 |
+
top_k (`int`, *optional*, defaults to `0`):
|
| 92 |
+
Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, top-k-filtering is
|
| 93 |
+
disabled and all tokens are considered.
|
| 94 |
+
min_p (`float`, *optional*):
|
| 95 |
+
Minimum token probability, which will be scaled by the probability of the most likely token. It must be a
|
| 96 |
+
value between `0.0` and `1.0`. Typical values are in the `0.01-0.2` range.
|
| 97 |
+
generation_kwargs (`dict[str, Any]`, *optional*):
|
| 98 |
+
Additional keyword arguments to pass to [`~transformers.GenerationConfig`] (if using transformers) or
|
| 99 |
+
`SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the
|
| 100 |
+
generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that conflict
|
| 101 |
+
with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them.
|
| 102 |
+
chat_template_kwargs (`dict[str, Any]`, *optional*):
|
| 103 |
+
Additional keyword arguments to pass to the `apply_chat_template` function when generating completions.
|
| 104 |
+
repetition_penalty (`float`, *optional*, defaults to `1.0`):
|
| 105 |
+
Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far.
|
| 106 |
+
Values > `1.0` encourage the model to use new tokens, while values < `1.0` encourage the model to repeat
|
| 107 |
+
tokens.
|
| 108 |
+
cache_implementation (`str`, *optional*):
|
| 109 |
+
Implementation of the cache method for faster generation when `use_vllm` is set to `False`.
|
| 110 |
+
|
| 111 |
+
> Parameters that control generation acceleration powered by vLLM
|
| 112 |
+
|
| 113 |
+
use_vllm (`bool`, *optional*, defaults to `False`):
|
| 114 |
+
Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for generation
|
| 115 |
+
instead of the default model.generate(). Requires `vllm` to be installed.
|
| 116 |
+
vllm_mode (`str`, *optional*, defaults to `"colocate"`):
|
| 117 |
+
Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `"server"` or
|
| 118 |
+
`"colocate"`.
|
| 119 |
+
|
| 120 |
+
- `"server"`: The trainer will send generation requests to a separate vLLM server. Make sure a TRL vLLM
|
| 121 |
+
server is running (start with `trl vllm-serve`).
|
| 122 |
+
- `"colocate"`: vLLM will run in the same process and share the training GPUs. This avoids the need for a
|
| 123 |
+
separate server but may cause resource contention with training.
|
| 124 |
+
vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
|
| 125 |
+
Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use
|
| 126 |
+
the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model
|
| 127 |
+
implementation.
|
| 128 |
+
vllm_structured_outputs_regex (`str`, *optional*):
|
| 129 |
+
Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled.
|
| 130 |
+
|
| 131 |
+
> Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`)
|
| 132 |
+
|
| 133 |
+
vllm_server_base_url (`str`, *optional*):
|
| 134 |
+
Base URL for the vLLM server (e.g., `"http://localhost:8000"`). If provided, `vllm_server_host` and
|
| 135 |
+
`vllm_server_port` are ignored.
|
| 136 |
+
vllm_server_host (`str`, *optional*, defaults to `"0.0.0.0"`):
|
| 137 |
+
Host of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
|
| 138 |
+
vllm_server_port (`int`, *optional*, defaults to `8000`):
|
| 139 |
+
Port of the vLLM server to connect to. Ignored if `vllm_server_base_url` is provided.
|
| 140 |
+
vllm_server_timeout (`float`, *optional*, defaults to `240.0`):
|
| 141 |
+
Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up after the
|
| 142 |
+
timeout, a `ConnectionError` is raised.
|
| 143 |
+
vllm_group_port (`int`, *optional*, defaults to `51216`):
|
| 144 |
+
Port number for the weight update group. This is used to communicate with the vLLM server. Unless the port
|
| 145 |
+
is occupied, there is no need to change it.
|
| 146 |
+
|
| 147 |
+
> Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`)
|
| 148 |
+
|
| 149 |
+
vllm_gpu_memory_utilization (`float`, *optional*, defaults to `0.3`):
|
| 150 |
+
Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set to
|
| 151 |
+
`"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
|
| 152 |
+
launching the vLLM server via the `--vllm_gpu_memory_utilization` flag.
|
| 153 |
+
vllm_max_model_length (`int`, *optional*):
|
| 154 |
+
Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus
|
| 155 |
+
`max_completion_length`; if omitted, it is inferred from the model config.
|
| 156 |
+
vllm_tensor_parallel_size (`int`, *optional*, defaults to `1`):
|
| 157 |
+
Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set to
|
| 158 |
+
`"colocate"`. If you are using `vllm_mode="server"`, this parameter must be passed separately when
|
| 159 |
+
launching the vLLM server via the `--vllm_tensor_parallel_size` flag.
|
| 160 |
+
vllm_enable_sleep_mode (`bool`, *optional*, defaults to `False`):
|
| 161 |
+
Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory usage low, but
|
| 162 |
+
waking the engine adds host–device transfer latency.
|
| 163 |
+
|
| 164 |
+
> Parameters that control generation acceleration powered by transformers continuous batching
|
| 165 |
+
|
| 166 |
+
use_transformers_continuous_batching (`bool`, *optional*, defaults to `False`):
|
| 167 |
+
Whether to use transformers' continuous batching engine for generating completions. Requires
|
| 168 |
+
`transformers>=5.8.0`.
|
| 169 |
+
transformers_continuous_batching_config (`dict`, *optional*):
|
| 170 |
+
Keyword arguments for [`~transformers.generation.ContinuousBatchingConfig`].
|
| 171 |
+
|
| 172 |
+
> Parameters that control the training
|
| 173 |
+
|
| 174 |
+
beta (`float`, *optional*, defaults to `0.05`):
|
| 175 |
+
KL coefficient. If `0.0`, the reference model is not loaded, reducing memory usage and improving training
|
| 176 |
+
speed.
|
| 177 |
+
num_iterations (`int`, *optional*, defaults to `1`):
|
| 178 |
+
Number of iterations per batch (denoted as μ in the algorithm).
|
| 179 |
+
epsilon (`float`, *optional*, defaults to `0.2`):
|
| 180 |
+
Epsilon value for clipping.
|
| 181 |
+
epsilon_high (`float`, *optional*):
|
| 182 |
+
Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the lower-bound
|
| 183 |
+
specified in argument `epsilon`. Paper [DAPO](https://huggingface.co/papers/2503.14476) recommends `0.28`.
|
| 184 |
+
reward_weights (`list[float]`, *optional*):
|
| 185 |
+
Weights for each reward function. Must match the number of reward functions. If `None`, all rewards are
|
| 186 |
+
weighted equally with weight `1.0`.
|
| 187 |
+
normalize_advantages (`bool`, *optional*, defaults to `False`):
|
| 188 |
+
Whether to normalize advantages. Normalization is done per generation batch to have mean `0.0` and standard
|
| 189 |
+
deviation of `1.0`.
|
| 190 |
+
reward_clip_range (`tuple[float, float]`, *optional*):
|
| 191 |
+
Clip range for rewards as (min, max). If `None`, no clipping is applied.
|
| 192 |
+
mask_truncated_completions (`bool`, *optional*, defaults to `False`):
|
| 193 |
+
When enabled, truncated completions are excluded from the loss calculation, preventing them from being
|
| 194 |
+
incorrectly penalized and introducing noise during training. According to the
|
| 195 |
+
[DAPO](https://huggingface.co/papers/2503.14476) paper, this is a good practice for training stability.
|
| 196 |
+
sync_ref_model (`bool`, *optional*, defaults to `False`):
|
| 197 |
+
Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using
|
| 198 |
+
the `ref_model_mixup_alpha` parameter. This synchronization originates from the
|
| 199 |
+
[TR-DPO](https://huggingface.co/papers/2404.09656) paper.
|
| 200 |
+
ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`):
|
| 201 |
+
α parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which controls the mix
|
| 202 |
+
between the current policy and the previous reference policy during updates. The reference policy is
|
| 203 |
+
updated according to the equation: `π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you
|
| 204 |
+
must set `sync_ref_model=True`.
|
| 205 |
+
ref_model_sync_steps (`int`, *optional*, defaults to `512`):
|
| 206 |
+
τ parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which determines how
|
| 207 |
+
frequently the current policy is synchronized with the reference policy. To use this parameter, you must
|
| 208 |
+
set `sync_ref_model=True`.
|
| 209 |
+
|
| 210 |
+
> Parameters that control the logging
|
| 211 |
+
|
| 212 |
+
log_completions (`bool`, *optional*, defaults to `False`):
|
| 213 |
+
Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is installed,
|
| 214 |
+
it prints the sample. If `wandb` and/or `trackio` logging is enabled, it logs it to `wandb` and/or
|
| 215 |
+
`trackio`.
|
| 216 |
+
num_completions_to_print (`int`, *optional*):
|
| 217 |
+
Number of completions to print with `rich`. If `None`, all completions are logged.
|
| 218 |
+
log_unique_prompts (`bool`, *optional*, defaults to `False`):
|
| 219 |
+
Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all prompts are
|
| 220 |
+
logged.
|
| 221 |
+
|
| 222 |
+
> Deprecated parameters
|
| 223 |
+
|
| 224 |
+
use_transformers_paged:
|
| 225 |
+
|
| 226 |
+
<Deprecated version="1.2.0">
|
| 227 |
+
|
| 228 |
+
Parameter `use_transformers_paged` is deprecated and will be removed in version v2.0.0. Use
|
| 229 |
+
`use_transformers_continuous_batching` instead.
|
| 230 |
+
|
| 231 |
+
</Deprecated>
|
| 232 |
+
|
| 233 |
+
> [!NOTE]
|
| 234 |
+
> These parameters have default values different from [`~transformers.TrainingArguments`]:
|
| 235 |
+
> - `logging_steps`: Defaults to `10` instead of `500`.
|
| 236 |
+
> - `gradient_checkpointing`: Defaults to `True` instead of `False`.
|
| 237 |
+
> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
|
| 238 |
+
> - `learning_rate`: Defaults to `1e-6` instead of `5e-5`.
|
| 239 |
+
"""
|
| 240 |
+
|
| 241 |
+
_VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + [
|
| 242 |
+
"model_init_kwargs",
|
| 243 |
+
"transformers_continuous_batching_config",
|
| 244 |
+
]
|
| 245 |
+
|
| 246 |
+
# Parameters whose default values are overridden from TrainingArguments
|
| 247 |
+
learning_rate: float = field(
|
| 248 |
+
default=1e-6,
|
| 249 |
+
metadata={"help": "The initial learning rate for AdamW."},
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
# Parameters that control the model and reference model
|
| 253 |
+
model_init_kwargs: dict[str, Any] | str | None = field(
|
| 254 |
+
default=None,
|
| 255 |
+
metadata={
|
| 256 |
+
"help": "Keyword arguments for `transformers.AutoModelForCausalLM.from_pretrained`, used when the `model` "
|
| 257 |
+
"argument of the `RLOOTrainer` is provided as a string."
|
| 258 |
+
},
|
| 259 |
+
)
|
| 260 |
+
trust_remote_code: bool = field(
|
| 261 |
+
default=False,
|
| 262 |
+
metadata={
|
| 263 |
+
"help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
|
| 264 |
+
"Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`. Also applied to "
|
| 265 |
+
"reward-model and reward-tokenizer loads."
|
| 266 |
+
},
|
| 267 |
+
)
|
| 268 |
+
router_aux_loss_coef: float = field(
|
| 269 |
+
default=0.001,
|
| 270 |
+
metadata={
|
| 271 |
+
"help": "Coefficient of the load-balancing auxiliary loss. Only has an effect when training a "
|
| 272 |
+
"Mixture-of-Experts (MoE) model; for other models it does nothing. The auxiliary loss is added to the "
|
| 273 |
+
"training loss with this weight. Set to `0.0` to disable it."
|
| 274 |
+
},
|
| 275 |
+
)
|
| 276 |
+
disable_dropout: bool = field(
|
| 277 |
+
default=False,
|
| 278 |
+
metadata={
|
| 279 |
+
"help": "Whether to disable dropout in the model. This is useful for training with a reference model, as "
|
| 280 |
+
"it prevents the model from generating different logprobs for the same input."
|
| 281 |
+
},
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
# Parameters that control the data preprocessing
|
| 285 |
+
# The default value remove_unused_columns is overwritten from the parent class, because in RLOO we usually rely on
|
| 286 |
+
# additional columns to compute the reward
|
| 287 |
+
remove_unused_columns: bool | None = field(
|
| 288 |
+
default=False,
|
| 289 |
+
metadata={
|
| 290 |
+
"help": "Whether to only keep the column 'prompt' in the dataset. If you use a custom reward function "
|
| 291 |
+
"that requires any column other than 'prompts' and 'completions', you should keep this to `False`."
|
| 292 |
+
},
|
| 293 |
+
)
|
| 294 |
+
num_generations: int | None = field(
|
| 295 |
+
default=2,
|
| 296 |
+
metadata={
|
| 297 |
+
"help": "Number of generations to sample. The effective batch size (num_processes * per_device_batch_size "
|
| 298 |
+
"* gradient_accumulation_steps) must be evenly divisible by this value."
|
| 299 |
+
},
|
| 300 |
+
)
|
| 301 |
+
num_generations_eval: int | None = field(
|
| 302 |
+
default=None,
|
| 303 |
+
metadata={
|
| 304 |
+
"help": "Number of generations to sample during evaluation. This allows using fewer generations during "
|
| 305 |
+
"evaluation to save computation. If `None`, uses the value of `num_generations`."
|
| 306 |
+
},
|
| 307 |
+
)
|
| 308 |
+
max_completion_length: int | None = field(
|
| 309 |
+
default=256,
|
| 310 |
+
metadata={"help": "Maximum length of the generated completion."},
|
| 311 |
+
)
|
| 312 |
+
ds3_gather_for_generation: bool = field(
|
| 313 |
+
default=True,
|
| 314 |
+
metadata={
|
| 315 |
+
"help": "This setting applies to DeepSpeed ZeRO-3. If enabled, the policy model weights are gathered for "
|
| 316 |
+
"generation, improving generation speed. However, disabling this option allows training models that "
|
| 317 |
+
"exceed the VRAM capacity of a single GPU, albeit at the cost of slower generation. Disabling this option "
|
| 318 |
+
"is not compatible with vLLM generation."
|
| 319 |
+
},
|
| 320 |
+
)
|
| 321 |
+
shuffle_dataset: bool | None = field(
|
| 322 |
+
default=True,
|
| 323 |
+
metadata={"help": "Whether to shuffle the training dataset."},
|
| 324 |
+
)
|
| 325 |
+
pad_to_multiple_of: int | None = field(
|
| 326 |
+
default=None,
|
| 327 |
+
metadata={"help": "If set, the prompts ids and completions ids will be padded to a multiple of this value."},
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
# Parameters that control generation
|
| 331 |
+
generation_batch_size: int | None = field(
|
| 332 |
+
default=None,
|
| 333 |
+
metadata={
|
| 334 |
+
"help": "Batch size to use for generation. If `None`, it defaults to the effective training batch size: "
|
| 335 |
+
"`per_device_train_batch_size * num_processes * steps_per_generation`."
|
| 336 |
+
},
|
| 337 |
+
)
|
| 338 |
+
steps_per_generation: int | None = field(
|
| 339 |
+
default=None,
|
| 340 |
+
metadata={"help": "Number of steps per generation. If `None`, it defaults to `gradient_accumulation_steps`."},
|
| 341 |
+
)
|
| 342 |
+
temperature: float = field(
|
| 343 |
+
default=1.0,
|
| 344 |
+
metadata={"help": "Temperature for sampling. The higher the temperature, the more random the completions."},
|
| 345 |
+
)
|
| 346 |
+
top_p: float = field(
|
| 347 |
+
default=1.0,
|
| 348 |
+
metadata={
|
| 349 |
+
"help": "Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. "
|
| 350 |
+
"Set to 1.0 to consider all tokens."
|
| 351 |
+
},
|
| 352 |
+
)
|
| 353 |
+
top_k: int = field(
|
| 354 |
+
default=0,
|
| 355 |
+
metadata={
|
| 356 |
+
"help": "Number of highest probability vocabulary tokens to keep for top-k-filtering. If `0`, "
|
| 357 |
+
"top-k-filtering is disabled and all tokens are considered."
|
| 358 |
+
},
|
| 359 |
+
)
|
| 360 |
+
min_p: float | None = field(
|
| 361 |
+
default=None,
|
| 362 |
+
metadata={
|
| 363 |
+
"help": "Minimum token probability, which will be scaled by the probability of the most likely token. It "
|
| 364 |
+
"must be a value between 0.0 and 1.0. Typical values are in the 0.01-0.2 range."
|
| 365 |
+
},
|
| 366 |
+
)
|
| 367 |
+
generation_kwargs: dict | None = field(
|
| 368 |
+
default=None,
|
| 369 |
+
metadata={
|
| 370 |
+
"help": "Additional keyword arguments to pass to `GenerationConfig` (if using transformers) or "
|
| 371 |
+
"`SamplingParams` (if using vLLM) when sampling completions. This can be used to further customize the "
|
| 372 |
+
"generation behavior, such as setting `suppress_tokens`, `num_beams`, etc. If it contains keys that "
|
| 373 |
+
"conflict with the other generation parameters (like `min_p`, `top_p`, etc.), they will override them."
|
| 374 |
+
},
|
| 375 |
+
)
|
| 376 |
+
chat_template_kwargs: dict | None = field(
|
| 377 |
+
default=None,
|
| 378 |
+
metadata={
|
| 379 |
+
"help": "Additional keyword arguments to pass to the `apply_chat_template` function when generating "
|
| 380 |
+
"completions."
|
| 381 |
+
},
|
| 382 |
+
)
|
| 383 |
+
repetition_penalty: float = field(
|
| 384 |
+
default=1.0,
|
| 385 |
+
metadata={
|
| 386 |
+
"help": "Float that penalizes new tokens based on whether they appear in the prompt and the generated "
|
| 387 |
+
"text so far. Values > 1.0 encourage the model to use new tokens, while values < 1.0 encourage the model "
|
| 388 |
+
"to repeat tokens."
|
| 389 |
+
},
|
| 390 |
+
)
|
| 391 |
+
cache_implementation: str | None = field(
|
| 392 |
+
default=None,
|
| 393 |
+
metadata={"help": "Implementation of the cache method for faster generation when use_vllm is set to False."},
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
# Parameters that control generation acceleration powered by vLLM
|
| 397 |
+
use_vllm: bool = field(
|
| 398 |
+
default=False,
|
| 399 |
+
metadata={
|
| 400 |
+
"help": "Whether to use vLLM for generating completions. If set to `True`, the trainer will use vLLM for "
|
| 401 |
+
"generation instead of the default model.generate(). Requires `vllm` to be installed."
|
| 402 |
+
},
|
| 403 |
+
)
|
| 404 |
+
vllm_mode: str = field(
|
| 405 |
+
default="colocate",
|
| 406 |
+
metadata={
|
| 407 |
+
"help": "Mode to use for vLLM integration when `use_vllm` is set to `True`. Must be one of `'server'` or "
|
| 408 |
+
"`'colocate'`. `'server'`: The trainer will send generation requests to a separate vLLM server. Make sure "
|
| 409 |
+
"a TRL vLLM server is running (start with `trl vllm-serve`). `'colocate'`: vLLM will run in the same "
|
| 410 |
+
"process and share the training GPUs. This avoids the need for a separate server but may cause resource "
|
| 411 |
+
"contention with training."
|
| 412 |
+
},
|
| 413 |
+
)
|
| 414 |
+
vllm_model_impl: str = field(
|
| 415 |
+
default="vllm",
|
| 416 |
+
metadata={
|
| 417 |
+
"help": "Model implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: "
|
| 418 |
+
"Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for "
|
| 419 |
+
"model implementation."
|
| 420 |
+
},
|
| 421 |
+
)
|
| 422 |
+
vllm_enable_sleep_mode: bool = field(
|
| 423 |
+
default=False,
|
| 424 |
+
metadata={
|
| 425 |
+
"help": "Enable vLLM sleep mode to offload weights/cache during the optimizer step. Keeps GPU memory "
|
| 426 |
+
"usage low, but waking the engine adds host–device transfer latency."
|
| 427 |
+
},
|
| 428 |
+
)
|
| 429 |
+
vllm_structured_outputs_regex: str | None = field(
|
| 430 |
+
default=None,
|
| 431 |
+
metadata={"help": "Regex for vLLM structured outputs. If `None` (default), structured outputs is disabled."},
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
# Parameters that control the vLLM server (only used when `vllm_mode` is `"server"`)
|
| 435 |
+
vllm_server_base_url: str | None = field(
|
| 436 |
+
default=None,
|
| 437 |
+
metadata={
|
| 438 |
+
"help": "Base URL for the vLLM server (e.g., 'http://localhost:8000'). If provided, `vllm_server_host` "
|
| 439 |
+
"and `vllm_server_port` are ignored."
|
| 440 |
+
},
|
| 441 |
+
)
|
| 442 |
+
vllm_server_host: str = field(
|
| 443 |
+
default="0.0.0.0",
|
| 444 |
+
metadata={"help": "Host of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
|
| 445 |
+
)
|
| 446 |
+
vllm_server_port: int = field(
|
| 447 |
+
default=8000,
|
| 448 |
+
metadata={"help": "Port of the vLLM server to connect to. Ignored if vllm_server_base_url is provided."},
|
| 449 |
+
)
|
| 450 |
+
vllm_server_timeout: float = field(
|
| 451 |
+
default=240.0,
|
| 452 |
+
metadata={
|
| 453 |
+
"help": "Total timeout duration in seconds to wait for the vLLM server to be up. If the server is not up "
|
| 454 |
+
"after the timeout, a `ConnectionError` is raised."
|
| 455 |
+
},
|
| 456 |
+
)
|
| 457 |
+
vllm_group_port: int = field(
|
| 458 |
+
default=51216,
|
| 459 |
+
metadata={
|
| 460 |
+
"help": "Port number for the weight update group. This is used to communicate with the vLLM server. "
|
| 461 |
+
"Unless the port is occupied, there is no need to change it.",
|
| 462 |
+
},
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
# Parameters that control colocated vLLM execution (only used when `vllm_mode` is `"colocate"`)
|
| 466 |
+
vllm_gpu_memory_utilization: float = field(
|
| 467 |
+
default=0.3,
|
| 468 |
+
metadata={
|
| 469 |
+
"help": "Control the GPU memory utilization for vLLM. This setting only applies when `vllm_mode` is set "
|
| 470 |
+
"to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when "
|
| 471 |
+
"launching the vLLM server via the `--vllm_gpu_memory_utilization` flag."
|
| 472 |
+
},
|
| 473 |
+
)
|
| 474 |
+
vllm_max_model_length: int | None = field(
|
| 475 |
+
default=None,
|
| 476 |
+
metadata={
|
| 477 |
+
"help": "Context window for vLLM. Set it to at least the maximum prompt length in the dataset plus "
|
| 478 |
+
"`max_completion_length`; if omitted, it is inferred from the model config."
|
| 479 |
+
},
|
| 480 |
+
)
|
| 481 |
+
vllm_tensor_parallel_size: int = field(
|
| 482 |
+
default=1,
|
| 483 |
+
metadata={
|
| 484 |
+
"help": "Control the tensor parallel size for vLLM. This setting only applies when `vllm_mode` is set "
|
| 485 |
+
"to `'colocate'`. If you are using `vllm_mode='server'`, this parameter must be passed separately when "
|
| 486 |
+
"launching the vLLM server via the `--vllm_tensor_parallel_size` flag."
|
| 487 |
+
},
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
# Parameters that control the training
|
| 491 |
+
beta: float = field(
|
| 492 |
+
default=0.05,
|
| 493 |
+
metadata={
|
| 494 |
+
"help": "KL coefficient. If `0.0`, the reference model is not loaded, reducing memory usage and improving "
|
| 495 |
+
"training speed."
|
| 496 |
+
},
|
| 497 |
+
)
|
| 498 |
+
num_iterations: int = field(
|
| 499 |
+
default=1,
|
| 500 |
+
metadata={"help": "Number of iterations per batch (denoted as μ in the algorithm)."},
|
| 501 |
+
)
|
| 502 |
+
epsilon: float = field(
|
| 503 |
+
default=0.2,
|
| 504 |
+
metadata={"help": "Epsilon value for clipping."},
|
| 505 |
+
)
|
| 506 |
+
epsilon_high: float | None = field(
|
| 507 |
+
default=None,
|
| 508 |
+
metadata={
|
| 509 |
+
"help": "Upper-bound epsilon value for clipping. If not specified, it defaults to the same value as the "
|
| 510 |
+
"lower-bound specified in argument `epsilon`. Paper DAPO recommends `0.28`."
|
| 511 |
+
},
|
| 512 |
+
)
|
| 513 |
+
reward_weights: list[float] | None = field(
|
| 514 |
+
default=None,
|
| 515 |
+
metadata={
|
| 516 |
+
"help": "Weights for each reward function. Must match the number of reward functions. If `None`, all "
|
| 517 |
+
"rewards are weighted equally with weight `1.0`."
|
| 518 |
+
},
|
| 519 |
+
)
|
| 520 |
+
normalize_advantages: bool = field(
|
| 521 |
+
default=False,
|
| 522 |
+
metadata={
|
| 523 |
+
"help": "Whether to normalize advantages. Normalization is done per generation batch to have mean `0.0` "
|
| 524 |
+
"and standard deviation of `1.0`."
|
| 525 |
+
},
|
| 526 |
+
)
|
| 527 |
+
reward_clip_range: tuple[float, float] | None = field(
|
| 528 |
+
default=None,
|
| 529 |
+
metadata={"help": "Clip range for rewards as (min, max). If None, no clipping is applied."},
|
| 530 |
+
)
|
| 531 |
+
mask_truncated_completions: bool = field(
|
| 532 |
+
default=False,
|
| 533 |
+
metadata={
|
| 534 |
+
"help": "When enabled, truncated completions are excluded from the loss calculation, preventing them from "
|
| 535 |
+
"being incorrectly penalized and introducing noise during training. According to the DAPO paper, this is "
|
| 536 |
+
"a good practice for training stability."
|
| 537 |
+
},
|
| 538 |
+
)
|
| 539 |
+
sync_ref_model: bool = field(
|
| 540 |
+
default=False,
|
| 541 |
+
metadata={
|
| 542 |
+
"help": "Whether to synchronize the reference model with the active model every `ref_model_sync_steps` "
|
| 543 |
+
"steps, using the `ref_model_mixup_alpha` parameter."
|
| 544 |
+
},
|
| 545 |
+
)
|
| 546 |
+
ref_model_mixup_alpha: float = field(
|
| 547 |
+
default=0.6,
|
| 548 |
+
metadata={
|
| 549 |
+
"help": "α parameter from the TR-DPO paper, which controls the mix between the current policy and the "
|
| 550 |
+
"previous reference policy during updates. The reference policy is updated according to the equation: "
|
| 551 |
+
"`π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you must set `sync_ref_model=True`."
|
| 552 |
+
},
|
| 553 |
+
)
|
| 554 |
+
ref_model_sync_steps: int = field(
|
| 555 |
+
default=512,
|
| 556 |
+
metadata={
|
| 557 |
+
"help": "τ parameter from the TR-DPO paper, which determines how frequently the current policy is "
|
| 558 |
+
"synchronized with the reference policy. To use this parameter, you must set `sync_ref_model=True`."
|
| 559 |
+
},
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
# Parameters that control the logging
|
| 563 |
+
log_completions: bool = field(
|
| 564 |
+
default=False,
|
| 565 |
+
metadata={
|
| 566 |
+
"help": "Whether to log a sample of (prompt, completion) pairs every `logging_steps` steps. If `rich` is "
|
| 567 |
+
"installed, it prints the sample. If `wandb` logging is enabled, it logs it to `wandb`."
|
| 568 |
+
},
|
| 569 |
+
)
|
| 570 |
+
num_completions_to_print: int | None = field(
|
| 571 |
+
default=None,
|
| 572 |
+
metadata={"help": "Number of completions to print with `rich`. If `None`, all completions are logged."},
|
| 573 |
+
)
|
| 574 |
+
log_unique_prompts: bool = field(
|
| 575 |
+
default=False,
|
| 576 |
+
metadata={
|
| 577 |
+
"help": "Whether to log unique prompts. If `True`, only unique prompts are logged. If `False`, all "
|
| 578 |
+
"prompts are logged."
|
| 579 |
+
},
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
# Parameters that control generation acceleration powered by transformers continuous batching
|
| 583 |
+
use_transformers_continuous_batching: bool = field(
|
| 584 |
+
default=False,
|
| 585 |
+
metadata={
|
| 586 |
+
"help": "Whether to use transformers' continuous batching engine for generating completions. Requires "
|
| 587 |
+
"transformers>=5.8.0."
|
| 588 |
+
},
|
| 589 |
+
)
|
| 590 |
+
transformers_continuous_batching_config: dict | None = field(
|
| 591 |
+
default=None,
|
| 592 |
+
metadata={"help": "Keyword arguments for `transformers.generation.ContinuousBatchingConfig`."},
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
# Deprecated parameters
|
| 596 |
+
use_transformers_paged: bool = field(
|
| 597 |
+
default=False,
|
| 598 |
+
metadata={"help": "Deprecated. Use `use_transformers_continuous_batching` instead."},
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
def __post_init__(self):
|
| 602 |
+
super().__post_init__()
|
| 603 |
+
|
| 604 |
+
if self.use_transformers_paged:
|
| 605 |
+
warnings.warn(
|
| 606 |
+
"`use_transformers_paged` is deprecated and will be removed in v2.0.0. Use "
|
| 607 |
+
"`use_transformers_continuous_batching` instead.",
|
| 608 |
+
FutureWarning,
|
| 609 |
+
stacklevel=3,
|
| 610 |
+
)
|
| 611 |
+
self.use_transformers_continuous_batching = True
|
| 612 |
+
|
| 613 |
+
if self.parallelism_config is not None and (
|
| 614 |
+
self.parallelism_config.cp_enabled or self.parallelism_config.sp_enabled
|
| 615 |
+
):
|
| 616 |
+
raise ValueError(
|
| 617 |
+
"RLOOTrainer does not support sequence-dim parallelism (`parallelism_config.cp_size > 1` or "
|
| 618 |
+
"`parallelism_config.sp_size > 1`) yet. RLOO builds model inputs after generation inside the trainer, "
|
| 619 |
+
"so Transformers' context-parallel / Ulysses sequence-parallel input sharding cannot be applied to the "
|
| 620 |
+
"raw generation batch. Set both `cp_size=1` and `sp_size=1`, or disable `parallelism_config`."
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
num_processes = self.world_size
|
| 624 |
+
# The current default effective batch size
|
| 625 |
+
if self.generation_batch_size is None and self.steps_per_generation is None:
|
| 626 |
+
self.steps_per_generation = self.gradient_accumulation_steps
|
| 627 |
+
self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
|
| 628 |
+
elif self.generation_batch_size is not None and self.steps_per_generation is None:
|
| 629 |
+
# Just ensure the value is divisible by the global batch size
|
| 630 |
+
if self.generation_batch_size % (self.per_device_train_batch_size * num_processes) != 0:
|
| 631 |
+
raise ValueError(
|
| 632 |
+
f"generation_batch_size ({self.generation_batch_size}) must be divisible by the global batch size "
|
| 633 |
+
f"({self.per_device_train_batch_size * num_processes})."
|
| 634 |
+
)
|
| 635 |
+
self.steps_per_generation = self.generation_batch_size // (
|
| 636 |
+
self.per_device_train_batch_size * num_processes
|
| 637 |
+
)
|
| 638 |
+
elif self.generation_batch_size is None and self.steps_per_generation is not None:
|
| 639 |
+
self.generation_batch_size = self.per_device_train_batch_size * num_processes * self.steps_per_generation
|
| 640 |
+
else:
|
| 641 |
+
raise ValueError(
|
| 642 |
+
"'generation_batch_size' and 'steps_per_generation' can not be both configured at the same time"
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
if self.do_eval and self.eval_strategy != "no":
|
| 646 |
+
# Determine the number of generations to use for evaluation
|
| 647 |
+
num_generations = self.num_generations_eval or self.num_generations
|
| 648 |
+
|
| 649 |
+
# Just ensure the value is divisible by the global batch size
|
| 650 |
+
if (self.per_device_eval_batch_size * num_processes) % num_generations != 0:
|
| 651 |
+
raise ValueError(
|
| 652 |
+
f"The global eval batch size ({self.per_device_eval_batch_size} * {num_processes}) must be "
|
| 653 |
+
f"divisible by the number of generations used for evaluation ({num_generations})."
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
# The generation batch must contain full prompt groups (no partials), so it must be divisible by
|
| 657 |
+
# num_generations.
|
| 658 |
+
if self.generation_batch_size % self.num_generations != 0:
|
| 659 |
+
raise ValueError(
|
| 660 |
+
f"generation_batch_size ({self.generation_batch_size}) must be divisible by num_generations "
|
| 661 |
+
f"({self.num_generations})."
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
if self.num_generations < 2:
|
| 665 |
+
raise ValueError(
|
| 666 |
+
"RLOO requires at least 2 generations per prompt to calculate the advantages. You provided "
|
| 667 |
+
f"{self.num_generations}, which is less than the minimum required."
|
| 668 |
+
)
|
tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/rloo_trainer.py
ADDED
|
@@ -0,0 +1,1638 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 atexit
|
| 17 |
+
import copy
|
| 18 |
+
import inspect
|
| 19 |
+
import math
|
| 20 |
+
import textwrap
|
| 21 |
+
import time
|
| 22 |
+
from collections import defaultdict, deque
|
| 23 |
+
from collections.abc import Callable
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import Any
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import pandas as pd
|
| 29 |
+
import torch
|
| 30 |
+
import torch.utils.data
|
| 31 |
+
import transformers
|
| 32 |
+
from accelerate.logging import get_logger
|
| 33 |
+
from accelerate.utils import gather, gather_object, is_peft_model, set_seed
|
| 34 |
+
from datasets import Dataset, IterableDataset
|
| 35 |
+
from packaging.version import Version
|
| 36 |
+
from torch import nn
|
| 37 |
+
from torch.utils.data import Sampler
|
| 38 |
+
from transformers import (
|
| 39 |
+
AutoModelForSequenceClassification,
|
| 40 |
+
AutoProcessor,
|
| 41 |
+
AutoTokenizer,
|
| 42 |
+
GenerationConfig,
|
| 43 |
+
PreTrainedModel,
|
| 44 |
+
PreTrainedTokenizerBase,
|
| 45 |
+
ProcessorMixin,
|
| 46 |
+
TrainerCallback,
|
| 47 |
+
is_trackio_available,
|
| 48 |
+
is_wandb_available,
|
| 49 |
+
)
|
| 50 |
+
from transformers.utils import is_peft_available, is_rich_available
|
| 51 |
+
|
| 52 |
+
from ..data_utils import apply_chat_template, is_conversational, prepare_multimodal_messages
|
| 53 |
+
from ..distributed import DistributedBackend
|
| 54 |
+
from ..extras.profiling import profiling_context, profiling_decorator
|
| 55 |
+
from ..generation.vllm_generation import VLLMGeneration
|
| 56 |
+
from ..models import prepare_deepspeed, prepare_fsdp, unwrap_model_for_generation
|
| 57 |
+
from ..models.utils import disable_gradient_checkpointing
|
| 58 |
+
from .base_trainer import _BaseTrainer
|
| 59 |
+
from .callbacks import SyncRefModelCallback
|
| 60 |
+
from .rloo_config import RLOOConfig
|
| 61 |
+
from .utils import (
|
| 62 |
+
RepeatSampler,
|
| 63 |
+
create_model_from_path,
|
| 64 |
+
disable_dropout_in_model,
|
| 65 |
+
entropy_from_logits,
|
| 66 |
+
get_config_model_id,
|
| 67 |
+
identity,
|
| 68 |
+
nanmax,
|
| 69 |
+
nanmin,
|
| 70 |
+
nanstd,
|
| 71 |
+
pad,
|
| 72 |
+
print_prompt_completions_sample,
|
| 73 |
+
selective_log_softmax,
|
| 74 |
+
shuffle_sequence_dict,
|
| 75 |
+
shutdown_event_loop_in_daemon,
|
| 76 |
+
split_pixel_values_by_grid,
|
| 77 |
+
split_tensor_dict,
|
| 78 |
+
start_event_loop_in_daemon,
|
| 79 |
+
unsplit_pixel_values_by_grid,
|
| 80 |
+
use_adapter,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
if is_peft_available():
|
| 85 |
+
import peft
|
| 86 |
+
from peft import LoraConfig, PeftConfig, PeftModel, get_peft_model
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
if is_wandb_available():
|
| 90 |
+
import wandb
|
| 91 |
+
|
| 92 |
+
if is_trackio_available():
|
| 93 |
+
import trackio
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
logger = get_logger(__name__)
|
| 97 |
+
|
| 98 |
+
# A reward function can be a string, interpreted as a model ID and loaded as a pretrained model, a pretrained model, or
|
| 99 |
+
# a callable that returns a list of floats (the rewards). The callable receives prompts, completions, and additional
|
| 100 |
+
# arguments from the trainer (refer to the trainer's source for details). To ensure forward compatibility, it should
|
| 101 |
+
# accept **kwargs.
|
| 102 |
+
RewardFunc = str | PreTrainedModel | Callable[..., list[float | None]]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class RLOOTrainer(_BaseTrainer):
|
| 106 |
+
"""
|
| 107 |
+
Trainer for the Reinforce Leave One Out (RLOO) method. This algorithm was initially proposed in the paper [Back to
|
| 108 |
+
Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in
|
| 109 |
+
LLMs](https://huggingface.co/papers/2402.14740).
|
| 110 |
+
|
| 111 |
+
Example:
|
| 112 |
+
|
| 113 |
+
```python
|
| 114 |
+
from trl import RLOOTrainer
|
| 115 |
+
from trl.rewards import accuracy_reward
|
| 116 |
+
from datasets import load_dataset
|
| 117 |
+
|
| 118 |
+
dataset = load_dataset("trl-lib/DeepMath-103K", split="train")
|
| 119 |
+
|
| 120 |
+
trainer = RLOOTrainer(
|
| 121 |
+
model="Qwen/Qwen2.5-0.5B-Instruct",
|
| 122 |
+
reward_funcs=accuracy_reward,
|
| 123 |
+
train_dataset=dataset,
|
| 124 |
+
)
|
| 125 |
+
trainer.train()
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]):
|
| 130 |
+
Model to be trained. Can be either:
|
| 131 |
+
|
| 132 |
+
- A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
|
| 133 |
+
path to a *directory* containing model weights saved using
|
| 134 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
| 135 |
+
using `<ModelArchitecture>.from_pretrained` (where `<ModelArchitecture>` is derived from the model
|
| 136 |
+
config) with the keyword arguments in `args.model_init_kwargs`.
|
| 137 |
+
- A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
|
| 138 |
+
- A [`~peft.PeftModel`] object. Only causal language models are supported.
|
| 139 |
+
reward_funcs (`RewardFunc | list[RewardFunc]`):
|
| 140 |
+
Reward functions to be used for computing the rewards. To compute the rewards, we call all the reward
|
| 141 |
+
functions with the prompts and completions and sum the rewards. Can be either:
|
| 142 |
+
|
| 143 |
+
- A single reward function, such as:
|
| 144 |
+
- A string: The *model ID* of a pretrained model hosted inside a model repo on huggingface.co, or a
|
| 145 |
+
path to a *directory* containing model weights saved using
|
| 146 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
| 147 |
+
using [`~transformers.AutoModelForSequenceClassification.from_pretrained`] with `num_labels=1` and the
|
| 148 |
+
keyword arguments in `args.model_init_kwargs`.
|
| 149 |
+
- A [`~transformers.PreTrainedModel`] object: Only sequence classification models are supported.
|
| 150 |
+
- A custom reward function: The function is provided with the prompts and the generated completions,
|
| 151 |
+
plus any additional columns in the dataset. It should return a list of rewards. Custom reward
|
| 152 |
+
functions can be either synchronous or asynchronous and can also return `None` when the reward is
|
| 153 |
+
not applicable to those samples. This is useful for multi-task training where different reward
|
| 154 |
+
functions apply to different types of samples. When a reward function returns `None` for a sample,
|
| 155 |
+
that reward function is excluded from the reward calculation for that sample. For more details, see
|
| 156 |
+
[Using a custom reward
|
| 157 |
+
function](#using-a-custom-reward-function).
|
| 158 |
+
|
| 159 |
+
The trainer's state is also passed to the reward function. The trainer's state is an instance of
|
| 160 |
+
[`~transformers.TrainerState`] and can be accessed by accessing the `trainer_state` argument to the
|
| 161 |
+
reward function's signature.
|
| 162 |
+
- A list of reward functions, where each item can independently be any of the above types. Mixing different
|
| 163 |
+
types within the list (e.g., a string model ID and a custom reward function) is allowed.
|
| 164 |
+
args ([`RLOOConfig`], *optional*):
|
| 165 |
+
Configuration for this trainer. If `None`, a default configuration is used.
|
| 166 |
+
train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
|
| 167 |
+
Dataset to use for training. It must include a column `"prompt"`. Any additional columns in the dataset is
|
| 168 |
+
ignored. The format of the samples can be either:
|
| 169 |
+
|
| 170 |
+
- [Standard](dataset_formats#standard): Each sample contains plain text.
|
| 171 |
+
- [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
|
| 172 |
+
and content).
|
| 173 |
+
eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
|
| 174 |
+
Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
|
| 175 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*):
|
| 176 |
+
Processing class used to process the data. The padding side must be set to "left". If `None`, the
|
| 177 |
+
processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A
|
| 178 |
+
padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
|
| 179 |
+
`tokenizer.eos_token` will be used as the default.
|
| 180 |
+
reward_processing_classes ([`~transformers.PreTrainedTokenizerBase`] or `list[PreTrainedTokenizerBase]`, *optional*):
|
| 181 |
+
Processing classes corresponding to the reward functions specified in `reward_funcs`. Can be either:
|
| 182 |
+
|
| 183 |
+
- A single processing class: Used when `reward_funcs` contains only one reward function.
|
| 184 |
+
- A list of processing classes: Must match the order and length of the reward functions in `reward_funcs`.
|
| 185 |
+
If set to `None`, or if an element of the list corresponding to a [`~transformers.PreTrainedModel`] is
|
| 186 |
+
`None`, the tokenizer for the model is automatically loaded using
|
| 187 |
+
[`~transformers.AutoTokenizer.from_pretrained`]. For elements in `reward_funcs` that are custom reward
|
| 188 |
+
functions (not [`~transformers.PreTrainedModel`]), the corresponding entries in `reward_processing_classes`
|
| 189 |
+
are ignored.
|
| 190 |
+
callbacks (list of [`~transformers.TrainerCallback`], *optional*):
|
| 191 |
+
List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
|
| 192 |
+
in [here](https://huggingface.co/docs/transformers/main_classes/callback).
|
| 193 |
+
|
| 194 |
+
If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
|
| 195 |
+
method.
|
| 196 |
+
optimizers (`tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None]`, *optional*, defaults to `(None, None)`):
|
| 197 |
+
A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your
|
| 198 |
+
model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`.
|
| 199 |
+
peft_config ([`~peft.PeftConfig`], *optional*):
|
| 200 |
+
PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
_tag_names = ["trl", "rloo"]
|
| 204 |
+
_name = "RLOO"
|
| 205 |
+
_paper = {
|
| 206 |
+
"title": "Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs",
|
| 207 |
+
"id": "2402.14740",
|
| 208 |
+
# docstyle-ignore
|
| 209 |
+
"citation": textwrap.dedent("""\
|
| 210 |
+
@inproceedings{ahmadian2024back,
|
| 211 |
+
title = {{Back to Basics: Revisiting REINFORCE-Style Optimization for Learning from Human Feedback in LLMs}},
|
| 212 |
+
author = {Arash Ahmadian and Chris Cremer and Matthias Gall{\'{e}} and Marzieh Fadaee and Julia Kreutzer and Olivier Pietquin and Ahmet {\"{U}}st{\"{u}}n and Sara Hooker},
|
| 213 |
+
year = 2024,
|
| 214 |
+
booktitle = {Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), {ACL} 2024, Bangkok, Thailand, August 11-16, 2024},
|
| 215 |
+
pages = {12248--12267},
|
| 216 |
+
publisher = {Association for Computational Linguistics},
|
| 217 |
+
editor = {Lun{-}Wei Ku and Andre Martins and Vivek Srikumar},
|
| 218 |
+
}"""),
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
def __init__(
|
| 222 |
+
self,
|
| 223 |
+
model: "str | PreTrainedModel | PeftModel",
|
| 224 |
+
reward_funcs: RewardFunc | list[RewardFunc],
|
| 225 |
+
args: RLOOConfig | None = None,
|
| 226 |
+
train_dataset: Dataset | IterableDataset | None = None,
|
| 227 |
+
eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
|
| 228 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
|
| 229 |
+
reward_processing_classes: PreTrainedTokenizerBase | list[PreTrainedTokenizerBase] | None = None,
|
| 230 |
+
callbacks: list[TrainerCallback] | None = None,
|
| 231 |
+
optimizers: tuple[torch.optim.Optimizer | None, torch.optim.lr_scheduler.LambdaLR | None] = (None, None),
|
| 232 |
+
peft_config: "PeftConfig | None" = None,
|
| 233 |
+
):
|
| 234 |
+
# Args
|
| 235 |
+
if args is None:
|
| 236 |
+
model_name = model if isinstance(model, str) else get_config_model_id(model.config)
|
| 237 |
+
model_name = model_name.split("/")[-1]
|
| 238 |
+
args = RLOOConfig(f"{model_name}-RLOO")
|
| 239 |
+
|
| 240 |
+
# Model
|
| 241 |
+
if isinstance(model, str):
|
| 242 |
+
model_init_kwargs = args.model_init_kwargs or {}
|
| 243 |
+
# Distributed training requires device_map=None ("auto" fails)
|
| 244 |
+
if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
|
| 245 |
+
model_init_kwargs["device_map"] = None
|
| 246 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 247 |
+
model = create_model_from_path(model, **model_init_kwargs)
|
| 248 |
+
else:
|
| 249 |
+
if args.model_init_kwargs is not None:
|
| 250 |
+
logger.warning(
|
| 251 |
+
"You passed `model_init_kwargs` to the `RLOOConfig`, but your model is already instantiated. "
|
| 252 |
+
"The `model_init_kwargs` will be ignored."
|
| 253 |
+
)
|
| 254 |
+
# Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do
|
| 255 |
+
_is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False)
|
| 256 |
+
|
| 257 |
+
# Some models (SmolVLM/Idefics3) don't support `logits_to_keep` argument and error out if we pass it
|
| 258 |
+
# Inspect the forward method before we wrap the model with PEFT
|
| 259 |
+
self.model_kwarg_keys = (
|
| 260 |
+
inspect.signature(model.forward).parameters.keys()
|
| 261 |
+
if not hasattr(model, "get_base_model")
|
| 262 |
+
else inspect.signature(model.get_base_model().forward).parameters.keys()
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
# Processing class
|
| 266 |
+
if processing_class is None:
|
| 267 |
+
processing_class = AutoProcessor.from_pretrained(
|
| 268 |
+
get_config_model_id(model.config),
|
| 269 |
+
truncation_side="left",
|
| 270 |
+
padding_side="left",
|
| 271 |
+
trust_remote_code=args.trust_remote_code,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
if args.use_transformers_continuous_batching and isinstance(processing_class, ProcessorMixin):
|
| 275 |
+
raise ValueError(
|
| 276 |
+
"`use_transformers_continuous_batching` does not support multimodal models. Use `use_vllm` instead."
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
# Handle pad token for processors or tokenizers
|
| 280 |
+
if isinstance(processing_class, ProcessorMixin):
|
| 281 |
+
self._tokenizer = processing_class.tokenizer
|
| 282 |
+
elif isinstance(processing_class, PreTrainedTokenizerBase):
|
| 283 |
+
self._tokenizer = processing_class
|
| 284 |
+
else:
|
| 285 |
+
raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
|
| 286 |
+
|
| 287 |
+
if self._tokenizer.pad_token is None:
|
| 288 |
+
self._tokenizer.pad_token = self._tokenizer.eos_token
|
| 289 |
+
|
| 290 |
+
# PEFT
|
| 291 |
+
if peft_config is not None:
|
| 292 |
+
if not is_peft_available():
|
| 293 |
+
raise ImportError(
|
| 294 |
+
"You passed `peft_config` but the `peft` library is not installed. "
|
| 295 |
+
"Install it with `pip install trl[peft]`."
|
| 296 |
+
)
|
| 297 |
+
if not isinstance(peft_config, PeftConfig):
|
| 298 |
+
raise TypeError(
|
| 299 |
+
f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
|
| 300 |
+
f"got {type(peft_config).__name__}."
|
| 301 |
+
)
|
| 302 |
+
if is_peft_model(model):
|
| 303 |
+
raise ValueError(
|
| 304 |
+
"You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge "
|
| 305 |
+
"and unload the existing adapter, save the resulting base model, and then pass that base model along "
|
| 306 |
+
"with the new `peft_config` to the trainer."
|
| 307 |
+
)
|
| 308 |
+
# Create PEFT model
|
| 309 |
+
# ZeRO-3 + PEFT for non-quantized models:
|
| 310 |
+
# - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16.
|
| 311 |
+
# - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter,
|
| 312 |
+
# so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step.
|
| 313 |
+
# - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch.
|
| 314 |
+
# - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for
|
| 315 |
+
# non-quantized bf16 training.
|
| 316 |
+
# - See:
|
| 317 |
+
# - TRL issue: https://github.com/huggingface/trl/issues/6089
|
| 318 |
+
# - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072
|
| 319 |
+
# - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg
|
| 320 |
+
get_peft_model_kwargs = {}
|
| 321 |
+
if (
|
| 322 |
+
args.deepspeed_plugin is not None
|
| 323 |
+
and args.deepspeed_plugin.zero_stage == 3
|
| 324 |
+
and not _is_quantized_model
|
| 325 |
+
and Version(peft.__version__) >= Version("0.12.0")
|
| 326 |
+
):
|
| 327 |
+
get_peft_model_kwargs["autocast_adapter_dtype"] = False
|
| 328 |
+
model = get_peft_model(model, peft_config, **get_peft_model_kwargs)
|
| 329 |
+
|
| 330 |
+
elif is_peft_model(model):
|
| 331 |
+
# If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy
|
| 332 |
+
# of the "default" adapter, so that we can use it as the reference model during the training. PEFT only
|
| 333 |
+
# supports one adapter per model when the LoRA config uses `target_parameters` (see peft#3340), so in that
|
| 334 |
+
# case we skip the "ref" adapter and compute the reference log probs with adapters disabled, i.e. with the
|
| 335 |
+
# base model.
|
| 336 |
+
default_config = model.peft_config["default"]
|
| 337 |
+
if isinstance(default_config, LoraConfig) and default_config.target_parameters:
|
| 338 |
+
logger.warning(
|
| 339 |
+
"PEFT can't add a frozen reference adapter alongside one that uses `target_parameters` "
|
| 340 |
+
"(peft#3340), so the reference log probs are computed from the base model (adapters disabled). "
|
| 341 |
+
"If you wrapped the model only to apply LoRA, pass a `peft_config` to the trainer instead; if you "
|
| 342 |
+
"wrapped it deliberately (pretrained adapter or custom init), note that the base model matches "
|
| 343 |
+
"your adapter only when it's freshly zero-initialized. If it is, this warning is safe to ignore."
|
| 344 |
+
)
|
| 345 |
+
else:
|
| 346 |
+
model.add_adapter("ref", default_config)
|
| 347 |
+
for name, param in model.named_parameters():
|
| 348 |
+
if ".default." in name:
|
| 349 |
+
ref_name = name.replace(".default.", ".ref.")
|
| 350 |
+
ref_param = model.get_parameter(ref_name)
|
| 351 |
+
ref_param.data.copy_(param.data)
|
| 352 |
+
|
| 353 |
+
# When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally
|
| 354 |
+
# handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489
|
| 355 |
+
if is_peft_model(model) and args.gradient_checkpointing:
|
| 356 |
+
model.enable_input_require_grads()
|
| 357 |
+
|
| 358 |
+
# When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the
|
| 359 |
+
# original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by
|
| 360 |
+
# passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for
|
| 361 |
+
# quantized models. See: https://github.com/huggingface/peft/issues/2889
|
| 362 |
+
if _is_quantized_model:
|
| 363 |
+
for param in model.parameters():
|
| 364 |
+
if param.requires_grad:
|
| 365 |
+
param.data = param.data.to(torch.bfloat16)
|
| 366 |
+
|
| 367 |
+
# Reward functions
|
| 368 |
+
if not isinstance(reward_funcs, list):
|
| 369 |
+
reward_funcs = [reward_funcs]
|
| 370 |
+
self.reward_func_names = []
|
| 371 |
+
for i, reward_func in enumerate(reward_funcs):
|
| 372 |
+
if isinstance(reward_func, str):
|
| 373 |
+
model_init_kwargs = args.model_init_kwargs or {}
|
| 374 |
+
# Distributed training requires device_map=None ("auto" fails)
|
| 375 |
+
if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
|
| 376 |
+
model_init_kwargs["device_map"] = None
|
| 377 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 378 |
+
reward_funcs[i] = AutoModelForSequenceClassification.from_pretrained(
|
| 379 |
+
reward_func, num_labels=1, **model_init_kwargs
|
| 380 |
+
)
|
| 381 |
+
if isinstance(reward_funcs[i], nn.Module): # Use Module over PretrainedModel for compat w/ compiled models
|
| 382 |
+
self.reward_func_names.append(get_config_model_id(reward_funcs[i].config).split("/")[-1])
|
| 383 |
+
else:
|
| 384 |
+
self.reward_func_names.append(reward_funcs[i].__name__)
|
| 385 |
+
self.reward_funcs = reward_funcs
|
| 386 |
+
|
| 387 |
+
self._has_async_funcs = any(inspect.iscoroutinefunction(func) for func in self.reward_funcs)
|
| 388 |
+
if self._has_async_funcs:
|
| 389 |
+
self.async_loop_thread, self.async_loop, self.async_loop_ready_event = start_event_loop_in_daemon(
|
| 390 |
+
name="RLOOTrainer-AsyncRewardLoop"
|
| 391 |
+
)
|
| 392 |
+
# wait until the event loop is running in the daemon thread
|
| 393 |
+
self.async_loop_ready_event.wait()
|
| 394 |
+
atexit.register(shutdown_event_loop_in_daemon, self.async_loop_thread, self.async_loop)
|
| 395 |
+
|
| 396 |
+
# Reward weights
|
| 397 |
+
if args.reward_weights is not None:
|
| 398 |
+
if len(args.reward_weights) != len(reward_funcs):
|
| 399 |
+
raise ValueError(
|
| 400 |
+
f"Number of reward weights ({len(args.reward_weights)}) must match number of reward "
|
| 401 |
+
f"functions ({len(reward_funcs)})"
|
| 402 |
+
)
|
| 403 |
+
self.reward_weights = torch.tensor(args.reward_weights, dtype=torch.float32)
|
| 404 |
+
else:
|
| 405 |
+
self.reward_weights = torch.ones(len(reward_funcs), dtype=torch.float32)
|
| 406 |
+
|
| 407 |
+
# Reward processing class
|
| 408 |
+
if reward_processing_classes is None:
|
| 409 |
+
reward_processing_classes = [None] * len(reward_funcs)
|
| 410 |
+
elif not isinstance(reward_processing_classes, list):
|
| 411 |
+
reward_processing_classes = [reward_processing_classes]
|
| 412 |
+
if len(reward_processing_classes) != len(reward_funcs):
|
| 413 |
+
raise ValueError(
|
| 414 |
+
f"The number of reward processing classes ({len(reward_processing_classes)}) must match the number of "
|
| 415 |
+
f"reward functions ({len(reward_funcs)})."
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
for i, (reward_processing_class, reward_func) in enumerate(
|
| 419 |
+
zip(reward_processing_classes, reward_funcs, strict=True)
|
| 420 |
+
):
|
| 421 |
+
if isinstance(reward_func, PreTrainedModel):
|
| 422 |
+
if reward_processing_class is None:
|
| 423 |
+
reward_processing_class = AutoTokenizer.from_pretrained(
|
| 424 |
+
get_config_model_id(reward_func.config), trust_remote_code=args.trust_remote_code
|
| 425 |
+
)
|
| 426 |
+
if reward_processing_class.pad_token_id is None:
|
| 427 |
+
reward_processing_class.pad_token = reward_processing_class.eos_token
|
| 428 |
+
# The reward model computes the reward for the latest non-padded token in the input sequence.
|
| 429 |
+
# So it's important to set the pad token ID to the padding token ID of the processing class.
|
| 430 |
+
reward_func.config.pad_token_id = reward_processing_class.pad_token_id
|
| 431 |
+
reward_processing_classes[i] = reward_processing_class
|
| 432 |
+
|
| 433 |
+
self.reward_processing_classes = reward_processing_classes
|
| 434 |
+
|
| 435 |
+
# Training arguments
|
| 436 |
+
self.max_completion_length = args.max_completion_length
|
| 437 |
+
self.num_generations = args.num_generations
|
| 438 |
+
self.num_generations_eval = args.num_generations_eval or self.num_generations
|
| 439 |
+
self.chat_template_kwargs = args.chat_template_kwargs or {}
|
| 440 |
+
self.temperature = args.temperature
|
| 441 |
+
self.top_p = args.top_p
|
| 442 |
+
self.top_k = args.top_k
|
| 443 |
+
self.min_p = args.min_p
|
| 444 |
+
self.repetition_penalty = args.repetition_penalty
|
| 445 |
+
self.use_transformers_continuous_batching = args.use_transformers_continuous_batching
|
| 446 |
+
if self.use_transformers_continuous_batching:
|
| 447 |
+
if not Version(transformers.__version__) >= Version("5.8.0"):
|
| 448 |
+
raise ImportError(
|
| 449 |
+
"Using `use_transformers_continuous_batching` requires transformers>=5.8.0. "
|
| 450 |
+
"Please upgrade with `pip install --upgrade transformers`."
|
| 451 |
+
)
|
| 452 |
+
from transformers.generation import ContinuousBatchingConfig
|
| 453 |
+
|
| 454 |
+
cb_kwargs = dict(args.transformers_continuous_batching_config or {})
|
| 455 |
+
# The transformers default (0.9) leaves almost no VRAM for the training backward pass;
|
| 456 |
+
# use a training-aware default unless the user has set it explicitly.
|
| 457 |
+
cb_kwargs.setdefault("max_memory_percent", 0.5)
|
| 458 |
+
self.continuous_batching_config = ContinuousBatchingConfig(**cb_kwargs)
|
| 459 |
+
else:
|
| 460 |
+
self.continuous_batching_config = None
|
| 461 |
+
self.pad_to_multiple_of = args.pad_to_multiple_of
|
| 462 |
+
self.use_vllm = args.use_vllm
|
| 463 |
+
self.vllm_mode = args.vllm_mode
|
| 464 |
+
self.vllm_gpu_memory_utilization = args.vllm_gpu_memory_utilization # only applies to colocation mode
|
| 465 |
+
self.vllm_tensor_parallel_size = args.vllm_tensor_parallel_size # only applies to colocation mode
|
| 466 |
+
self.normalize_advantages = args.normalize_advantages
|
| 467 |
+
self.mask_truncated_completions = args.mask_truncated_completions
|
| 468 |
+
self.reward_clip_range = args.reward_clip_range
|
| 469 |
+
|
| 470 |
+
# Datasets
|
| 471 |
+
self.shuffle_dataset = args.shuffle_dataset
|
| 472 |
+
|
| 473 |
+
if train_dataset is None:
|
| 474 |
+
raise ValueError("`train_dataset` is required")
|
| 475 |
+
elif (
|
| 476 |
+
isinstance(train_dataset, IterableDataset)
|
| 477 |
+
or isinstance(eval_dataset, IterableDataset)
|
| 478 |
+
or (
|
| 479 |
+
isinstance(eval_dataset, dict) and any(isinstance(ds, IterableDataset) for ds in eval_dataset.values())
|
| 480 |
+
)
|
| 481 |
+
):
|
| 482 |
+
# See https://github.com/huggingface/trl/issues/3213
|
| 483 |
+
raise NotImplementedError(
|
| 484 |
+
"Iterable datasets are not yet supported in RLOOTrainer. Please use a standard dataset instead."
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
# Multi-step
|
| 488 |
+
self.num_iterations = args.num_iterations
|
| 489 |
+
self.epsilon_low = args.epsilon
|
| 490 |
+
self.epsilon_high = args.epsilon_high if args.epsilon_high is not None else args.epsilon
|
| 491 |
+
|
| 492 |
+
# MoE load-balancing auxiliary loss, applied to Mixture-of-Experts models (no effect otherwise)
|
| 493 |
+
text_config = model.config.get_text_config()
|
| 494 |
+
is_moe = getattr(text_config, "output_router_logits", None) is not None
|
| 495 |
+
self.aux_loss_enabled = is_moe and args.router_aux_loss_coef != 0.0
|
| 496 |
+
self.router_aux_loss_coef = args.router_aux_loss_coef
|
| 497 |
+
# Tracks the number of iterations (forward + backward passes), including those within a grad accum cycle
|
| 498 |
+
self._step = 0
|
| 499 |
+
# Buffer the batch to reuse generated outputs across multiple updates. For more details, see
|
| 500 |
+
# `_get_train_sampler` and `_prepare_inputs`.
|
| 501 |
+
self._buffered_inputs = None
|
| 502 |
+
|
| 503 |
+
# Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
|
| 504 |
+
# never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
|
| 505 |
+
# (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
|
| 506 |
+
# default to the recommended non-reentrant behavior here, while preserving any user-provided value.
|
| 507 |
+
if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
|
| 508 |
+
args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
|
| 509 |
+
args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
|
| 510 |
+
|
| 511 |
+
super().__init__(
|
| 512 |
+
model=model,
|
| 513 |
+
args=args,
|
| 514 |
+
data_collator=identity, # No data collation is needed in RLOO
|
| 515 |
+
train_dataset=train_dataset,
|
| 516 |
+
eval_dataset=eval_dataset,
|
| 517 |
+
processing_class=processing_class,
|
| 518 |
+
callbacks=callbacks,
|
| 519 |
+
optimizers=optimizers,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
# Reference model
|
| 523 |
+
self.beta = args.beta
|
| 524 |
+
if self.beta == 0.0:
|
| 525 |
+
# If beta is 0.0, the reference model is not needed
|
| 526 |
+
self.ref_model = None
|
| 527 |
+
elif is_peft_model(model):
|
| 528 |
+
# If PEFT is used, the reference model is not needed since the adapter can be disabled
|
| 529 |
+
# to revert to the initial model.
|
| 530 |
+
self.ref_model = None
|
| 531 |
+
else:
|
| 532 |
+
# For deepspeed, fsdp or non-distributed models, create a reference model from scratch
|
| 533 |
+
model_init_kwargs = args.model_init_kwargs or {}
|
| 534 |
+
# Distributed training requires device_map=None ("auto" fails)
|
| 535 |
+
if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
|
| 536 |
+
model_init_kwargs["device_map"] = None
|
| 537 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 538 |
+
self.ref_model = create_model_from_path(get_config_model_id(self.model.config), **model_init_kwargs)
|
| 539 |
+
|
| 540 |
+
# Disable dropout in the models
|
| 541 |
+
if args.disable_dropout:
|
| 542 |
+
disable_dropout_in_model(model)
|
| 543 |
+
if self.ref_model is not None:
|
| 544 |
+
disable_dropout_in_model(self.ref_model)
|
| 545 |
+
|
| 546 |
+
# Initialize the metrics
|
| 547 |
+
self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
|
| 548 |
+
self._total_train_tokens = 0
|
| 549 |
+
self._current_train_step_time = 0.0
|
| 550 |
+
self.log_completions = args.log_completions
|
| 551 |
+
self.log_unique_prompts = args.log_unique_prompts
|
| 552 |
+
self.num_completions_to_print = args.num_completions_to_print
|
| 553 |
+
# Keep logs sized to the generation batch to record only outputs from the latest model update.
|
| 554 |
+
self._logs = {
|
| 555 |
+
"images": deque(maxlen=args.generation_batch_size),
|
| 556 |
+
"prompt": deque(maxlen=args.generation_batch_size),
|
| 557 |
+
"completion": deque(maxlen=args.generation_batch_size),
|
| 558 |
+
"rewards": defaultdict(lambda: deque(maxlen=args.generation_batch_size)),
|
| 559 |
+
"advantages": deque(maxlen=args.generation_batch_size),
|
| 560 |
+
"extra": defaultdict(lambda: deque(maxlen=args.generation_batch_size)),
|
| 561 |
+
}
|
| 562 |
+
# Buffers for user-logged data from reward functions, flushed after gathering
|
| 563 |
+
self._pending_extra_logs = defaultdict(list)
|
| 564 |
+
self._pending_metrics = defaultdict(list)
|
| 565 |
+
|
| 566 |
+
# Ensure each process receives a unique seed to prevent duplicate completions when generating with
|
| 567 |
+
# transformers if num_generations exceeds per_device_train_batch_size. We could skip it if we use vLLM, but
|
| 568 |
+
# it's safer to set it in all cases.
|
| 569 |
+
set_seed(args.seed, device_specific=True)
|
| 570 |
+
|
| 571 |
+
if self.use_vllm:
|
| 572 |
+
# Initialize vLLM generation backend
|
| 573 |
+
self.vllm_generation = VLLMGeneration(
|
| 574 |
+
model=self.model,
|
| 575 |
+
accelerator=self.accelerator,
|
| 576 |
+
processing_class=self.processing_class,
|
| 577 |
+
# vLLM configuration
|
| 578 |
+
mode=args.vllm_mode,
|
| 579 |
+
structured_outputs_regex=args.vllm_structured_outputs_regex,
|
| 580 |
+
# Server mode configuration
|
| 581 |
+
server_base_url=args.vllm_server_base_url,
|
| 582 |
+
server_host=args.vllm_server_host,
|
| 583 |
+
server_port=args.vllm_server_port,
|
| 584 |
+
group_port=args.vllm_group_port,
|
| 585 |
+
server_timeout=args.vllm_server_timeout,
|
| 586 |
+
# Colocate mode configuration
|
| 587 |
+
tensor_parallel_size=args.vllm_tensor_parallel_size,
|
| 588 |
+
gpu_memory_utilization=args.vllm_gpu_memory_utilization,
|
| 589 |
+
max_model_length=args.vllm_max_model_length,
|
| 590 |
+
max_num_seqs=args.per_device_train_batch_size
|
| 591 |
+
* args.vllm_tensor_parallel_size
|
| 592 |
+
* args.steps_per_generation,
|
| 593 |
+
enable_sleep_mode=args.vllm_enable_sleep_mode,
|
| 594 |
+
model_impl=args.vllm_model_impl,
|
| 595 |
+
# Generation configuration
|
| 596 |
+
repetition_penalty=self.repetition_penalty,
|
| 597 |
+
temperature=self.temperature,
|
| 598 |
+
top_p=self.top_p,
|
| 599 |
+
top_k=self.top_k,
|
| 600 |
+
min_p=self.min_p,
|
| 601 |
+
max_completion_length=self.max_completion_length,
|
| 602 |
+
logprobs=None, # we don't need logprobs from vLLM in RLOO
|
| 603 |
+
generation_kwargs=args.generation_kwargs,
|
| 604 |
+
)
|
| 605 |
+
self._last_loaded_step = -1 # tag to avoid useless loading during grad accumulation
|
| 606 |
+
else:
|
| 607 |
+
generation_kwargs = {
|
| 608 |
+
"max_new_tokens": self.max_completion_length,
|
| 609 |
+
"do_sample": True,
|
| 610 |
+
"pad_token_id": self._tokenizer.pad_token_id,
|
| 611 |
+
"bos_token_id": self._tokenizer.bos_token_id,
|
| 612 |
+
"eos_token_id": self._tokenizer.eos_token_id,
|
| 613 |
+
"temperature": self.temperature,
|
| 614 |
+
"top_p": self.top_p,
|
| 615 |
+
"top_k": self.top_k,
|
| 616 |
+
"min_p": self.min_p,
|
| 617 |
+
"repetition_penalty": self.repetition_penalty,
|
| 618 |
+
"cache_implementation": args.cache_implementation,
|
| 619 |
+
}
|
| 620 |
+
if args.generation_kwargs is not None:
|
| 621 |
+
generation_kwargs.update(args.generation_kwargs)
|
| 622 |
+
self.generation_config = GenerationConfig(**generation_kwargs, disable_compile=True)
|
| 623 |
+
# Keep training-specific generation kwargs to overwrite model's original generation config
|
| 624 |
+
self.generation_kwargs = generation_kwargs
|
| 625 |
+
|
| 626 |
+
# Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
|
| 627 |
+
# model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
|
| 628 |
+
# self.model_accepts_loss_kwargs to False to enable scaling.
|
| 629 |
+
self.model_accepts_loss_kwargs = False
|
| 630 |
+
self._dist = DistributedBackend(self.accelerator)
|
| 631 |
+
|
| 632 |
+
# Add tags to the model
|
| 633 |
+
self.model.add_model_tags(self._tag_names)
|
| 634 |
+
|
| 635 |
+
if self.ref_model is not None:
|
| 636 |
+
if self.is_deepspeed_enabled:
|
| 637 |
+
self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
|
| 638 |
+
elif self.is_fsdp_enabled:
|
| 639 |
+
self.ref_model = prepare_fsdp(self.ref_model, self.accelerator)
|
| 640 |
+
else:
|
| 641 |
+
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
|
| 642 |
+
|
| 643 |
+
if args.sync_ref_model:
|
| 644 |
+
if self.beta == 0.0:
|
| 645 |
+
raise ValueError(
|
| 646 |
+
"You passed `sync_ref_model=True` while `beta=0.0`, which means the reference model is not used "
|
| 647 |
+
"during training. Consequently, RLOOTrainer does not create a `ref_model` instance, and there is "
|
| 648 |
+
"nothing to synchronize. Please set `sync_ref_model=False`, or set `beta` to a non-zero value."
|
| 649 |
+
)
|
| 650 |
+
if is_peft_model(model):
|
| 651 |
+
raise NotImplementedError(
|
| 652 |
+
"You passed `sync_ref_model=True` while using a PEFT model, which is currently not supported. "
|
| 653 |
+
"With PEFT, RLOOTrainer does not keep a separate reference model in memory; instead, it recovers "
|
| 654 |
+
"reference behavior by temporarily disabling the adapter. As a result, there is no standalone "
|
| 655 |
+
"`ref_model` instance to synchronize. Use `sync_ref_model=False`, or opt for full fine-tuning if "
|
| 656 |
+
"you need a synced reference model. If you need `sync_ref_model` to work with PEFT, please open a "
|
| 657 |
+
"feature request at https://github.com/huggingface/trl/issues."
|
| 658 |
+
)
|
| 659 |
+
self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator))
|
| 660 |
+
|
| 661 |
+
for i, reward_func in enumerate(self.reward_funcs):
|
| 662 |
+
if isinstance(reward_func, PreTrainedModel):
|
| 663 |
+
if self.is_deepspeed_enabled:
|
| 664 |
+
self.reward_funcs[i] = prepare_deepspeed(reward_func, self.accelerator)
|
| 665 |
+
else:
|
| 666 |
+
# set device placement to True to make `prepare_model` move `reward_func` to device when using fsdp
|
| 667 |
+
self.reward_funcs[i] = self.accelerator.prepare_model(
|
| 668 |
+
reward_func, evaluation_mode=True, device_placement=True
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
def _set_signature_columns_if_needed(self):
|
| 672 |
+
# If `self.args.remove_unused_columns` is True, non-signature columns are removed.
|
| 673 |
+
# By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids"
|
| 674 |
+
# and "attention_mask"). In RLOOTrainer, we preprocess data, so using the model's signature columns doesn't
|
| 675 |
+
# work. Instead, we set them to the columns expected by the `training_step` method, hence the override.
|
| 676 |
+
if self._signature_columns is None:
|
| 677 |
+
self._signature_columns = ["prompt", "image", "images"]
|
| 678 |
+
|
| 679 |
+
# This method overrides `Trainer.get_train_dataloader` to support our custom batching strategy.
|
| 680 |
+
# Instead of returning a standard per-step batch (i.e., `per_device_batch_size), our dataloader loads an
|
| 681 |
+
# *generation* batch (i.e., `per_device_batch_size × steps_per_generation`). This allows us to generate completions
|
| 682 |
+
# once every steps_per_generation step—rather than once per accumulation step—which is significantly more
|
| 683 |
+
# efficient. The only change from the original implementation is multiplying the batch size by
|
| 684 |
+
# `steps_per_generation`. Thus, `_prepare_inputs` is called with this *generation* batch, and it handles the
|
| 685 |
+
# splitting internally.
|
| 686 |
+
# Maintenance note: This method is a copy-paste of the original `Trainer.get_train_dataloader` with only one line
|
| 687 |
+
# modification.
|
| 688 |
+
def get_train_dataloader(self):
|
| 689 |
+
return self._get_dataloader(
|
| 690 |
+
dataset=self.train_dataset,
|
| 691 |
+
description="Training",
|
| 692 |
+
batch_size=self._train_batch_size * self.args.steps_per_generation, # < this is the change
|
| 693 |
+
sampler_fn=self._get_train_sampler,
|
| 694 |
+
is_training=True,
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
def _get_train_sampler(self, dataset: Dataset | None = None) -> Sampler:
|
| 698 |
+
# Returns a sampler that
|
| 699 |
+
# 1. ensures each prompt is repeated across multiple processes. This guarantees that identical prompts are
|
| 700 |
+
# distributed to different GPUs, allowing rewards to be computed and normalized correctly within each prompt
|
| 701 |
+
# group. Using the same seed across processes ensures consistent prompt assignment, preventing discrepancies
|
| 702 |
+
# in group formation.
|
| 703 |
+
# 2. repeats the batch multiple times to allow reusing generations across multiple updates. Refer to
|
| 704 |
+
# _prepare_inputs to see how the generations are stored and reused.
|
| 705 |
+
|
| 706 |
+
# In the following figure, the values are the prompt indices. The first row shows the first sampled batch, the
|
| 707 |
+
# second row shows the second sampled batch, and so on.
|
| 708 |
+
#
|
| 709 |
+
# | GPU 0 | GPU 1 |
|
| 710 |
+
#
|
| 711 |
+
# global_step step <-───> num_generations=2
|
| 712 |
+
# <-───────> per_device_train_batch_size=3
|
| 713 |
+
# grad_accum ▲ ▲ 0 0 0 0 1 1 2 2 <- Generate for the first `steps_per_generation` (prompts 0 to 11); store the completions; use the first slice to compute the loss
|
| 714 |
+
# =2 ▼ | 0 1 3 3 4 4 5 5 <- Take the stored generations and use the second slice to compute the loss
|
| 715 |
+
# |
|
| 716 |
+
# | 1 2 6 6 7 7 8 8 <- Take the stored generations and use the third slice to compute the loss
|
| 717 |
+
# steps_per_gen=4 ▼ 1 3 9 9 10 10 11 11 <- Take the stored generations and use the fourth slice to compute the loss
|
| 718 |
+
#
|
| 719 |
+
# 2 4 12 12 13 13 14 14 <- Generate for the second `steps_per_generation` (prompts 12 to 23); store the completions; use the first slice to compute the loss
|
| 720 |
+
# 2 5 15 15 16 16 17 17 <- Take the stored generations and use the second slice to compute the loss
|
| 721 |
+
# ...
|
| 722 |
+
if dataset is None:
|
| 723 |
+
dataset = self.train_dataset
|
| 724 |
+
return RepeatSampler(
|
| 725 |
+
data_source=dataset,
|
| 726 |
+
mini_repeat_count=self.num_generations,
|
| 727 |
+
batch_size=self.args.generation_batch_size // self.num_generations,
|
| 728 |
+
repeat_count=self.num_iterations * self.args.steps_per_generation,
|
| 729 |
+
shuffle=self.shuffle_dataset,
|
| 730 |
+
seed=self.args.seed,
|
| 731 |
+
)
|
| 732 |
+
|
| 733 |
+
def _get_eval_sampler(self, eval_dataset) -> Sampler:
|
| 734 |
+
# See _get_train_sampler for an explanation of the sampler.
|
| 735 |
+
return RepeatSampler(
|
| 736 |
+
data_source=eval_dataset,
|
| 737 |
+
mini_repeat_count=self.num_generations_eval,
|
| 738 |
+
seed=self.args.seed,
|
| 739 |
+
)
|
| 740 |
+
|
| 741 |
+
@profiling_decorator
|
| 742 |
+
def _get_per_token_logps_and_entropies(
|
| 743 |
+
self,
|
| 744 |
+
model,
|
| 745 |
+
input_ids,
|
| 746 |
+
attention_mask,
|
| 747 |
+
logits_to_keep,
|
| 748 |
+
batch_size=None,
|
| 749 |
+
compute_entropy=False,
|
| 750 |
+
compute_aux_loss=False,
|
| 751 |
+
pixel_values=None,
|
| 752 |
+
image_grid_thw=None,
|
| 753 |
+
num_images=None,
|
| 754 |
+
pixel_attention_mask=None,
|
| 755 |
+
image_sizes=None,
|
| 756 |
+
token_type_ids=None,
|
| 757 |
+
mm_token_type_ids=None,
|
| 758 |
+
image_position_ids=None,
|
| 759 |
+
) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
|
| 760 |
+
"""Compute log-probs, (optionally) entropies, and (optionally) the MoE load-balancing aux loss."""
|
| 761 |
+
batch_size = batch_size or input_ids.size(0) # Chunk inputs into smaller batches to reduce memory peak
|
| 762 |
+
all_logps = []
|
| 763 |
+
all_entropies = []
|
| 764 |
+
all_aux_losses = []
|
| 765 |
+
for start in range(0, input_ids.size(0), batch_size):
|
| 766 |
+
input_ids_batch = input_ids[start : start + batch_size]
|
| 767 |
+
attention_mask_batch = attention_mask[start : start + batch_size]
|
| 768 |
+
|
| 769 |
+
# Build model inputs
|
| 770 |
+
model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch}
|
| 771 |
+
if image_grid_thw is not None and pixel_values is not None:
|
| 772 |
+
rows_per_image = image_grid_thw.prod(dim=-1)
|
| 773 |
+
rows_per_sample = torch.split(rows_per_image, num_images)
|
| 774 |
+
rows_per_sample = torch.stack([s.sum() for s in rows_per_sample])
|
| 775 |
+
cum_rows = torch.cat([torch.tensor([0], device=rows_per_sample.device), rows_per_sample.cumsum(0)])
|
| 776 |
+
row_start, row_end = cum_rows[start].item(), cum_rows[start + batch_size].item()
|
| 777 |
+
model_inputs["pixel_values"] = pixel_values[row_start:row_end]
|
| 778 |
+
cum_imgs = torch.tensor([0] + num_images).cumsum(0)
|
| 779 |
+
img_start, img_end = cum_imgs[start], cum_imgs[start + batch_size]
|
| 780 |
+
model_inputs["image_grid_thw"] = image_grid_thw[img_start:img_end]
|
| 781 |
+
elif image_position_ids is not None and pixel_values is not None:
|
| 782 |
+
cum_imgs = torch.tensor([0] + num_images).cumsum(0)
|
| 783 |
+
img_start, img_end = cum_imgs[start], cum_imgs[start + batch_size]
|
| 784 |
+
model_inputs["pixel_values"] = pixel_values[img_start:img_end]
|
| 785 |
+
model_inputs["image_position_ids"] = image_position_ids[img_start:img_end]
|
| 786 |
+
elif pixel_values is not None:
|
| 787 |
+
model_inputs["pixel_values"] = pixel_values[start : start + batch_size]
|
| 788 |
+
if pixel_attention_mask is not None:
|
| 789 |
+
model_inputs["pixel_attention_mask"] = pixel_attention_mask[start : start + batch_size]
|
| 790 |
+
if image_sizes is not None:
|
| 791 |
+
model_inputs["image_sizes"] = image_sizes[start : start + batch_size]
|
| 792 |
+
if token_type_ids is not None:
|
| 793 |
+
model_inputs["token_type_ids"] = token_type_ids[start : start + batch_size]
|
| 794 |
+
if mm_token_type_ids is not None:
|
| 795 |
+
model_inputs["mm_token_type_ids"] = mm_token_type_ids[start : start + batch_size]
|
| 796 |
+
|
| 797 |
+
# Only add logits_to_keep if the model supports it
|
| 798 |
+
if "logits_to_keep" in self.model_kwarg_keys:
|
| 799 |
+
# We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded
|
| 800 |
+
model_inputs["logits_to_keep"] = logits_to_keep + 1
|
| 801 |
+
|
| 802 |
+
model_inputs["use_cache"] = False # only used in generation; set False to suppress warnings
|
| 803 |
+
|
| 804 |
+
# MoE models: request router logits so the model returns `outputs.aux_loss`. VLM wrappers honor this only
|
| 805 |
+
# as a forward kwarg (not from the model config), so it must be passed here.
|
| 806 |
+
if compute_aux_loss:
|
| 807 |
+
model_inputs["output_router_logits"] = True
|
| 808 |
+
|
| 809 |
+
outputs = model(**model_inputs)
|
| 810 |
+
logits = outputs.logits
|
| 811 |
+
# Exclude the last value: it corresponds to the next token pred
|
| 812 |
+
logits = logits[:, :-1, :] # (B, L-1, H)
|
| 813 |
+
# Only keep the last logits_to_keep. For model that support logits_to_keep, this is a no-op.
|
| 814 |
+
logits = logits[:, -logits_to_keep:, :] # (B, logits_to_keep, H)
|
| 815 |
+
# Divide logits by sampling temperature.
|
| 816 |
+
# See https://huggingface.co/blog/the_n_implementation_details_of_rlhf_with_ppo#policy-training-implementation-details
|
| 817 |
+
logits.div_(self.temperature)
|
| 818 |
+
completion_ids = input_ids_batch[:, -logits_to_keep:]
|
| 819 |
+
logps = selective_log_softmax(logits, completion_ids) # compute logprobs
|
| 820 |
+
all_logps.append(logps)
|
| 821 |
+
|
| 822 |
+
if compute_entropy:
|
| 823 |
+
with torch.no_grad():
|
| 824 |
+
entropies = entropy_from_logits(logits)
|
| 825 |
+
all_entropies.append(entropies)
|
| 826 |
+
|
| 827 |
+
if compute_aux_loss:
|
| 828 |
+
all_aux_losses.append(outputs.aux_loss)
|
| 829 |
+
|
| 830 |
+
logps = torch.cat(all_logps, dim=0)
|
| 831 |
+
entropies = torch.cat(all_entropies, dim=0) if compute_entropy else None
|
| 832 |
+
aux_loss = torch.stack(all_aux_losses).mean() if compute_aux_loss else None
|
| 833 |
+
return logps, entropies, aux_loss
|
| 834 |
+
|
| 835 |
+
def training_step(self, model, inputs, num_items_in_batch):
|
| 836 |
+
time_before = time.perf_counter()
|
| 837 |
+
output = super().training_step(model, inputs, num_items_in_batch)
|
| 838 |
+
self._step += 1
|
| 839 |
+
time_after = time.perf_counter()
|
| 840 |
+
self._current_train_step_time += time_after - time_before
|
| 841 |
+
if self._step % self.current_gradient_accumulation_steps == 0:
|
| 842 |
+
self._metrics["train"]["step_time"].append(self._current_train_step_time)
|
| 843 |
+
self._current_train_step_time = 0.0
|
| 844 |
+
return output
|
| 845 |
+
|
| 846 |
+
@profiling_decorator
|
| 847 |
+
def _prepare_inputs(self, generation_batch: dict[str, torch.Tensor | Any]) -> dict[str, torch.Tensor | Any]:
|
| 848 |
+
# Prepares inputs for model training/evaluation by managing completion generation and batch handling.
|
| 849 |
+
# During training:
|
| 850 |
+
# - Receives the local generation batch (Per-GPU batch size × steps per generation)
|
| 851 |
+
# from the modified training dataloader instead of the standard local batch
|
| 852 |
+
# - Generates completions once for the entire generation batch and splits it into batches of size
|
| 853 |
+
# `per_device_train_batch_size`
|
| 854 |
+
# - Buffers these completions and returns the appropriate slice for the current accumulation step
|
| 855 |
+
# - Optimizes by regenerating completions only periodically (every steps_per_generation * num_iterations)
|
| 856 |
+
# During evaluation:
|
| 857 |
+
# - The input is treated as a standard local batch (no accumulation, no multiple iterations)
|
| 858 |
+
# - Completions are generated for each batch without buffering or reuse
|
| 859 |
+
# Returns a single local batch in both cases.
|
| 860 |
+
|
| 861 |
+
mode = "train" if self.model.training else "eval"
|
| 862 |
+
if mode == "train":
|
| 863 |
+
generate_every = self.args.steps_per_generation * self.num_iterations
|
| 864 |
+
if self._step % generate_every == 0 or self._buffered_inputs is None:
|
| 865 |
+
# self._buffered_inputs=None can occur when resuming from a checkpoint
|
| 866 |
+
generation_batch = self._generate_and_score_completions(generation_batch)
|
| 867 |
+
generation_batch = split_pixel_values_by_grid(generation_batch)
|
| 868 |
+
generation_batch = shuffle_sequence_dict(generation_batch)
|
| 869 |
+
generation_batches = split_tensor_dict(generation_batch, self.args.steps_per_generation)
|
| 870 |
+
self._buffered_inputs = [unsplit_pixel_values_by_grid(batch) for batch in generation_batches]
|
| 871 |
+
inputs = self._buffered_inputs[self._step % self.args.steps_per_generation]
|
| 872 |
+
else:
|
| 873 |
+
# In evaluation, there is neither batch grouping for generation, nor multiple iterations, hence
|
| 874 |
+
# local generation batch == local eval batch
|
| 875 |
+
inputs = self._generate_and_score_completions(generation_batch)
|
| 876 |
+
return inputs
|
| 877 |
+
|
| 878 |
+
def _log_completion_extra(self, column: str, values: list):
|
| 879 |
+
"""
|
| 880 |
+
Log extra columns to the completions table. Called from reward functions via the `log_extra` kwarg.
|
| 881 |
+
|
| 882 |
+
Args:
|
| 883 |
+
column (`str`):
|
| 884 |
+
Name of the column to add.
|
| 885 |
+
values (`list`):
|
| 886 |
+
Values for the column, one per sample in the batch.
|
| 887 |
+
"""
|
| 888 |
+
self._pending_extra_logs[column].extend(values)
|
| 889 |
+
|
| 890 |
+
def _log_metric(self, name: str, value: float):
|
| 891 |
+
"""
|
| 892 |
+
Log a scalar metric from a reward function. Called via the `log_metric` kwarg. Values are averaged over each
|
| 893 |
+
logging step and reported alongside built-in metrics like `kl` and `entropy`.
|
| 894 |
+
|
| 895 |
+
Args:
|
| 896 |
+
name (`str`):
|
| 897 |
+
Name of the metric.
|
| 898 |
+
value (`float`):
|
| 899 |
+
Scalar value for this batch.
|
| 900 |
+
"""
|
| 901 |
+
self._pending_metrics[name].append(value)
|
| 902 |
+
|
| 903 |
+
@profiling_decorator
|
| 904 |
+
def _calculate_rewards(self, inputs, prompts, completions, completion_ids_list):
|
| 905 |
+
device = self.accelerator.device
|
| 906 |
+
rewards_per_func = torch.zeros(len(prompts), len(self.reward_funcs), device=device)
|
| 907 |
+
|
| 908 |
+
# Repeat all input columns (but "prompt", "completion", and "completion_ids") to match the num of generations
|
| 909 |
+
keys = [key for key in inputs[0] if key not in ["prompt", "completion", "completion_ids"]]
|
| 910 |
+
reward_kwargs = {key: [example[key] for example in inputs] for key in keys}
|
| 911 |
+
|
| 912 |
+
# This allows for dynamic reward shaping based on training progress.
|
| 913 |
+
reward_kwargs["trainer_state"] = self.state
|
| 914 |
+
|
| 915 |
+
# Allow reward functions to log extra columns to the completions table.
|
| 916 |
+
reward_kwargs["log_extra"] = self._log_completion_extra
|
| 917 |
+
|
| 918 |
+
# Allow reward functions to log additional scalar metrics.
|
| 919 |
+
reward_kwargs["log_metric"] = self._log_metric
|
| 920 |
+
|
| 921 |
+
async_funcs_info = [] # async custom functions for asyncio.gather
|
| 922 |
+
|
| 923 |
+
for i, (reward_func, reward_processing_class, reward_func_name) in enumerate(
|
| 924 |
+
zip(self.reward_funcs, self.reward_processing_classes, self.reward_func_names, strict=True)
|
| 925 |
+
):
|
| 926 |
+
if isinstance(reward_func, nn.Module): # Module (no PretrainedModel) for compat with compiled models
|
| 927 |
+
with profiling_context(self, reward_func_name):
|
| 928 |
+
if is_conversational(inputs[0]):
|
| 929 |
+
messages = [{"messages": p + c} for p, c in zip(prompts, completions, strict=True)]
|
| 930 |
+
texts = [
|
| 931 |
+
apply_chat_template(x, reward_processing_class, **self.chat_template_kwargs)["text"]
|
| 932 |
+
for x in messages
|
| 933 |
+
]
|
| 934 |
+
else:
|
| 935 |
+
texts = [p + c for p, c in zip(prompts, completions, strict=True)]
|
| 936 |
+
reward_inputs = reward_processing_class(
|
| 937 |
+
text=texts, return_tensors="pt", padding=True, padding_side="right", add_special_tokens=False
|
| 938 |
+
)
|
| 939 |
+
reward_inputs = super()._prepare_inputs(reward_inputs)
|
| 940 |
+
with torch.inference_mode():
|
| 941 |
+
rewards_per_func[:, i] = reward_func(**reward_inputs).logits[:, 0] # Shape (B*G,)
|
| 942 |
+
elif inspect.iscoroutinefunction(reward_func): # Separate async reward funcs to run them in parallel later
|
| 943 |
+
async_funcs_info.append((i, reward_func, reward_func_name))
|
| 944 |
+
else:
|
| 945 |
+
# Run synchronous reward function
|
| 946 |
+
with profiling_context(self, reward_func_name):
|
| 947 |
+
output_reward_func = reward_func(
|
| 948 |
+
prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs
|
| 949 |
+
)
|
| 950 |
+
# Convert None values to NaN
|
| 951 |
+
output_reward_func = [reward if reward is not None else torch.nan for reward in output_reward_func]
|
| 952 |
+
rewards_per_func[:, i] = torch.tensor(output_reward_func, dtype=torch.float32, device=device)
|
| 953 |
+
|
| 954 |
+
# Execute async custom functions in parallel using asyncio.gather
|
| 955 |
+
if async_funcs_info:
|
| 956 |
+
|
| 957 |
+
async def _invoke_async(index, func, func_name):
|
| 958 |
+
with profiling_context(self, func_name):
|
| 959 |
+
output = await func(
|
| 960 |
+
prompts=prompts, completions=completions, completion_ids=completion_ids_list, **reward_kwargs
|
| 961 |
+
)
|
| 962 |
+
output = [r if r is not None else torch.nan for r in output]
|
| 963 |
+
return index, output
|
| 964 |
+
|
| 965 |
+
async def _run_async_funcs():
|
| 966 |
+
coros = [_invoke_async(i, func, func_name) for (i, func, func_name) in async_funcs_info]
|
| 967 |
+
return await asyncio.gather(*coros)
|
| 968 |
+
|
| 969 |
+
async_results = asyncio.run_coroutine_threadsafe(_run_async_funcs(), self.async_loop).result()
|
| 970 |
+
for idx, output_reward_func in async_results:
|
| 971 |
+
rewards_per_func[:, idx] = torch.tensor(output_reward_func, dtype=torch.float32, device=device)
|
| 972 |
+
|
| 973 |
+
# If all reward functions return None for a given row, issue a detailed warning
|
| 974 |
+
if torch.isnan(rewards_per_func).all(dim=1).any():
|
| 975 |
+
nan_row_idx = torch.isnan(rewards_per_func).all(dim=1).nonzero(as_tuple=True)[0][0]
|
| 976 |
+
row_reward_kwargs = {
|
| 977 |
+
key: value[nan_row_idx]
|
| 978 |
+
for key, value in reward_kwargs.items()
|
| 979 |
+
if key not in ("trainer_state", "log_extra", "log_metric")
|
| 980 |
+
}
|
| 981 |
+
row_reward_kwargs["prompt"] = prompts[nan_row_idx]
|
| 982 |
+
row_reward_kwargs["completion"] = completions[nan_row_idx]
|
| 983 |
+
logger.warning(
|
| 984 |
+
f"All reward functions returned None for the following kwargs:\n{row_reward_kwargs}\n"
|
| 985 |
+
"Please ensure that at least one reward function returns a valid reward."
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
# Gather the reward per function: this part is crucial, because the rewards are normalized per group and the
|
| 989 |
+
# completions may be distributed across processes
|
| 990 |
+
rewards_per_func = gather(rewards_per_func)
|
| 991 |
+
return rewards_per_func
|
| 992 |
+
|
| 993 |
+
def _tokenize_prompts(self, prompts: list):
|
| 994 |
+
"""Tokenize prompts and extract images/multimodal fields for generation."""
|
| 995 |
+
if is_conversational({"prompt": prompts[0]}):
|
| 996 |
+
# Extract images from messages for VLM support
|
| 997 |
+
images = []
|
| 998 |
+
has_images = False
|
| 999 |
+
for prompt in prompts:
|
| 1000 |
+
prompt_images = []
|
| 1001 |
+
for message in prompt:
|
| 1002 |
+
if isinstance(message["content"], list):
|
| 1003 |
+
for part in message["content"]:
|
| 1004 |
+
if part["type"] == "image":
|
| 1005 |
+
prompt_images.append(part["image"])
|
| 1006 |
+
has_images = True
|
| 1007 |
+
images.append(prompt_images if prompt_images else None)
|
| 1008 |
+
images = images if has_images else None
|
| 1009 |
+
|
| 1010 |
+
# Workaround for a bug in transformers 5.3.0 where some processors (e.g. Qwen2.5-VL) crash on
|
| 1011 |
+
# batched unpadded input (transformers#44514).
|
| 1012 |
+
# Fixed in transformers 5.4.0 (transformers#44563).
|
| 1013 |
+
needs_padding_workaround = Version("5.3.0") <= Version(transformers.__version__) < Version("5.4.0")
|
| 1014 |
+
tokenized = self.processing_class.apply_chat_template(
|
| 1015 |
+
conversation=prompts,
|
| 1016 |
+
add_generation_prompt=True,
|
| 1017 |
+
tokenize=True,
|
| 1018 |
+
return_dict=True,
|
| 1019 |
+
**({"padding": True} if needs_padding_workaround else {}),
|
| 1020 |
+
**self.chat_template_kwargs,
|
| 1021 |
+
)
|
| 1022 |
+
if needs_padding_workaround:
|
| 1023 |
+
# Unpad input_ids: remove padding tokens using attention_mask to get per-sequence lists
|
| 1024 |
+
prompt_ids = [
|
| 1025 |
+
[tok for tok, m in zip(ids, mask, strict=True) if m]
|
| 1026 |
+
for ids, mask in zip(tokenized["input_ids"], tokenized["attention_mask"], strict=True)
|
| 1027 |
+
]
|
| 1028 |
+
else:
|
| 1029 |
+
prompt_ids = tokenized["input_ids"]
|
| 1030 |
+
# For VLMs, the processor returns extra multimodal fields (pixel_values, image_grid_thw, etc.)
|
| 1031 |
+
multimodal_fields = {k: v for k, v in tokenized.items() if k not in ("input_ids", "attention_mask")}
|
| 1032 |
+
else:
|
| 1033 |
+
prompt_ids = self.processing_class(text=prompts)["input_ids"]
|
| 1034 |
+
images = None
|
| 1035 |
+
multimodal_fields = {}
|
| 1036 |
+
return prompt_ids, images, multimodal_fields
|
| 1037 |
+
|
| 1038 |
+
def _generate_single_turn(self, prompt_ids, images, multimodal_fields):
|
| 1039 |
+
device = self.accelerator.device
|
| 1040 |
+
mode = "train" if self.model.training else "eval"
|
| 1041 |
+
|
| 1042 |
+
# Generate completions using either vLLM or regular generation
|
| 1043 |
+
if self.use_vllm:
|
| 1044 |
+
# Sync weights if training step changed
|
| 1045 |
+
if self.state.global_step != self._last_loaded_step:
|
| 1046 |
+
with profiling_context(self, "sync_weights"):
|
| 1047 |
+
self.vllm_generation.sync_weights()
|
| 1048 |
+
self._last_loaded_step = self.state.global_step
|
| 1049 |
+
|
| 1050 |
+
# Generate using vLLM (note: RLOO doesn't use logprobs from generation, so we ignore them)
|
| 1051 |
+
num_generations = self.num_generations if mode == "train" else self.num_generations_eval
|
| 1052 |
+
_, completion_ids, _, _ = self.vllm_generation.generate(
|
| 1053 |
+
prompts=prompt_ids,
|
| 1054 |
+
images=images,
|
| 1055 |
+
num_generations=num_generations,
|
| 1056 |
+
profiler=profiling_context(self, "vLLM.generate"),
|
| 1057 |
+
)
|
| 1058 |
+
|
| 1059 |
+
elif self.use_transformers_continuous_batching:
|
| 1060 |
+
with (
|
| 1061 |
+
profiling_context(self, "transformers.generate_batch"),
|
| 1062 |
+
unwrap_model_for_generation(
|
| 1063 |
+
self.model_wrapped, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation
|
| 1064 |
+
) as unwrapped_model,
|
| 1065 |
+
torch.no_grad(),
|
| 1066 |
+
self._dist.summon_full_params(self.model_wrapped, recurse=False),
|
| 1067 |
+
):
|
| 1068 |
+
# Cast to the appropriate dtype based on training configuration
|
| 1069 |
+
if self.args.bf16:
|
| 1070 |
+
unwrapped_model.to(torch.bfloat16)
|
| 1071 |
+
elif self.args.fp16:
|
| 1072 |
+
unwrapped_model.to(torch.float16)
|
| 1073 |
+
all_outputs = unwrapped_model.generate_batch(
|
| 1074 |
+
prompt_ids,
|
| 1075 |
+
generation_config=self.generation_config,
|
| 1076 |
+
continuous_batching_config=self.continuous_batching_config,
|
| 1077 |
+
progress_bar=False,
|
| 1078 |
+
)
|
| 1079 |
+
unwrapped_model.train()
|
| 1080 |
+
completion_ids = [output.generated_tokens for output in all_outputs.values()]
|
| 1081 |
+
|
| 1082 |
+
else:
|
| 1083 |
+
# Regular generation path: left-pad token IDs into tensors
|
| 1084 |
+
prompt_tensors = [torch.tensor(ids) for ids in prompt_ids]
|
| 1085 |
+
padded_ids = pad(prompt_tensors, padding_value=self._tokenizer.pad_token_id, padding_side="left")
|
| 1086 |
+
attention_mask = pad([torch.ones_like(t) for t in prompt_tensors], padding_value=0, padding_side="left")
|
| 1087 |
+
generate_inputs = {"input_ids": padded_ids, "attention_mask": attention_mask}
|
| 1088 |
+
# For VLMs, include multimodal fields as tensors (pixel_values, image_grid_thw, etc.)
|
| 1089 |
+
for k, v in multimodal_fields.items():
|
| 1090 |
+
if isinstance(v, torch.Tensor):
|
| 1091 |
+
generate_inputs[k] = v
|
| 1092 |
+
elif isinstance(v, list) and v and isinstance(v[0], list):
|
| 1093 |
+
# Per-token field (e.g., token_type_ids): left-pad like input_ids
|
| 1094 |
+
generate_inputs[k] = pad([torch.tensor(x) for x in v], padding_value=0, padding_side="left")
|
| 1095 |
+
else:
|
| 1096 |
+
generate_inputs[k] = torch.tensor(np.array(v))
|
| 1097 |
+
generate_inputs = super()._prepare_inputs(generate_inputs)
|
| 1098 |
+
|
| 1099 |
+
with (
|
| 1100 |
+
profiling_context(self, "transformers.generate"),
|
| 1101 |
+
unwrap_model_for_generation(
|
| 1102 |
+
self.model_wrapped,
|
| 1103 |
+
self.accelerator,
|
| 1104 |
+
gather_deepspeed3_params=self.args.ds3_gather_for_generation,
|
| 1105 |
+
generation_kwargs=self.generation_kwargs, # Override model.generation_config with generation_kwargs to fix transformers#42762
|
| 1106 |
+
) as unwrapped_model,
|
| 1107 |
+
torch.no_grad(),
|
| 1108 |
+
self._dist.summon_full_params(self.model_wrapped, recurse=False),
|
| 1109 |
+
):
|
| 1110 |
+
prompt_completion_ids = unwrapped_model.generate(
|
| 1111 |
+
**generate_inputs, generation_config=self.generation_config
|
| 1112 |
+
)
|
| 1113 |
+
# Compute prompt length and extract completion ids
|
| 1114 |
+
prompt_length = generate_inputs["input_ids"].size(1)
|
| 1115 |
+
completion_ids = prompt_completion_ids[:, prompt_length:]
|
| 1116 |
+
|
| 1117 |
+
# Mask everything after the first EOS token
|
| 1118 |
+
is_eos = completion_ids == self._tokenizer.eos_token_id
|
| 1119 |
+
eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=device)
|
| 1120 |
+
eos_idx[is_eos.any(dim=1)] = is_eos.int().argmax(dim=1)[is_eos.any(dim=1)]
|
| 1121 |
+
sequence_indices = torch.arange(is_eos.size(1), device=device).expand(is_eos.size(0), -1)
|
| 1122 |
+
completion_mask = (sequence_indices <= eos_idx.unsqueeze(1)).int()
|
| 1123 |
+
completion_ids = [
|
| 1124 |
+
c[m].tolist() for c, m in zip(completion_ids.cpu(), completion_mask.bool().cpu(), strict=True)
|
| 1125 |
+
]
|
| 1126 |
+
|
| 1127 |
+
return completion_ids
|
| 1128 |
+
|
| 1129 |
+
def _generate(self, prompts: list):
|
| 1130 |
+
device = self.accelerator.device
|
| 1131 |
+
mode = "train" if self.model.training else "eval"
|
| 1132 |
+
|
| 1133 |
+
# Copy the prompts to avoid modifying the original list
|
| 1134 |
+
prompts = copy.deepcopy(prompts)
|
| 1135 |
+
|
| 1136 |
+
prompt_ids, images, multimodal_fields = self._tokenize_prompts(prompts)
|
| 1137 |
+
completion_ids = self._generate_single_turn(prompt_ids, images, multimodal_fields)
|
| 1138 |
+
|
| 1139 |
+
# Decode completions. It's important to use `parse_response` when possible, because it handles tool calls.
|
| 1140 |
+
if is_conversational({"prompt": prompts[0]}):
|
| 1141 |
+
contents = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
|
| 1142 |
+
completions = [[{"role": "assistant", "content": content}] for content in contents]
|
| 1143 |
+
else:
|
| 1144 |
+
completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
|
| 1145 |
+
|
| 1146 |
+
# Get completion length per sequence, used for logging
|
| 1147 |
+
prompt_lengths = torch.tensor([len(ids) for ids in prompt_ids], device=device)
|
| 1148 |
+
completion_lengths = torch.tensor([len(ids) for ids in completion_ids], device=device)
|
| 1149 |
+
agg_prompt_lengths = self.accelerator.gather(prompt_lengths)
|
| 1150 |
+
agg_completion_lengths = self.accelerator.gather(completion_lengths)
|
| 1151 |
+
total_prompt_tokens = agg_prompt_lengths.sum()
|
| 1152 |
+
total_completion_tokens = agg_completion_lengths.sum() # = num_items_in_batch, required for the DAPO loss
|
| 1153 |
+
|
| 1154 |
+
# Log the metrics
|
| 1155 |
+
if mode == "train":
|
| 1156 |
+
self.state.num_input_tokens_seen += (total_prompt_tokens + total_completion_tokens).item()
|
| 1157 |
+
self._metrics[mode]["num_tokens"] = [self.state.num_input_tokens_seen]
|
| 1158 |
+
|
| 1159 |
+
# Log completion lengths, mean, min, max
|
| 1160 |
+
self._metrics[mode]["completions/mean_length"].append(agg_completion_lengths.float().mean().item())
|
| 1161 |
+
self._metrics[mode]["completions/min_length"].append(agg_completion_lengths.float().min().item())
|
| 1162 |
+
self._metrics[mode]["completions/max_length"].append(agg_completion_lengths.float().max().item())
|
| 1163 |
+
|
| 1164 |
+
# Identify sequences that terminated with EOS and log their lengths
|
| 1165 |
+
eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id]
|
| 1166 |
+
is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids], device=device)
|
| 1167 |
+
agg_is_truncated = self.accelerator.gather(is_truncated)
|
| 1168 |
+
self._metrics[mode]["completions/clipped_ratio"].append(agg_is_truncated.float().mean().item())
|
| 1169 |
+
term_completion_lengths = agg_completion_lengths[~agg_is_truncated]
|
| 1170 |
+
if len(term_completion_lengths) == 0: # edge case where no terminated sequences are found
|
| 1171 |
+
term_completion_lengths = torch.zeros(1, device=device)
|
| 1172 |
+
self._metrics[mode]["completions/mean_terminated_length"].append(term_completion_lengths.float().mean().item())
|
| 1173 |
+
self._metrics[mode]["completions/min_terminated_length"].append(term_completion_lengths.float().min().item())
|
| 1174 |
+
self._metrics[mode]["completions/max_terminated_length"].append(term_completion_lengths.float().max().item())
|
| 1175 |
+
|
| 1176 |
+
return prompt_ids, completion_ids, completions
|
| 1177 |
+
|
| 1178 |
+
def _generate_and_score_completions(
|
| 1179 |
+
self, inputs: list[dict[str, torch.Tensor | Any]]
|
| 1180 |
+
) -> dict[str, torch.Tensor | Any]:
|
| 1181 |
+
device = self.accelerator.device
|
| 1182 |
+
mode = "train" if self.model.training else "eval"
|
| 1183 |
+
|
| 1184 |
+
prompts = [x["prompt"] for x in inputs]
|
| 1185 |
+
|
| 1186 |
+
if "images" in inputs[0]:
|
| 1187 |
+
images = [example.get("images") for example in inputs]
|
| 1188 |
+
elif "image" in inputs[0]:
|
| 1189 |
+
images = [[example.get("image")] if example.get("image") is not None else None for example in inputs]
|
| 1190 |
+
else:
|
| 1191 |
+
images = None
|
| 1192 |
+
# Transformers requires at least one image in the batch, otherwise it throws an error
|
| 1193 |
+
if images is not None and all(img_list == [] for img_list in images):
|
| 1194 |
+
images = None
|
| 1195 |
+
|
| 1196 |
+
# If the prompts are conversational and the inputs contain images, we need to convert the prompts from
|
| 1197 |
+
# [{"role": "user", "content": "What color is the sky?"}] to
|
| 1198 |
+
# [{"role": "user", "content": [{"type": "image", "image": <Image>}, {"type": "text", "text": "What color is the sky?"}]}]
|
| 1199 |
+
if images is not None:
|
| 1200 |
+
if not is_conversational(inputs[0]):
|
| 1201 |
+
raise ValueError(
|
| 1202 |
+
"Multimodal training requires conversational prompts. It looks like the dataset contains "
|
| 1203 |
+
"non-conversational inputs, likely because a chat template was applied before passing the dataset "
|
| 1204 |
+
"to the trainer. Please provide the raw conversational prompts and let the trainer apply the chat "
|
| 1205 |
+
"template internally."
|
| 1206 |
+
)
|
| 1207 |
+
prompts = [
|
| 1208 |
+
prepare_multimodal_messages(prompt, images=image_list)
|
| 1209 |
+
for prompt, image_list in zip(prompts, images, strict=True)
|
| 1210 |
+
]
|
| 1211 |
+
|
| 1212 |
+
prompt_ids_list, completion_ids_list, completions = self._generate(prompts)
|
| 1213 |
+
|
| 1214 |
+
# Convert lists of token IDs to padded tensors
|
| 1215 |
+
prompt_ids = [torch.tensor(ids) for ids in prompt_ids_list]
|
| 1216 |
+
prompt_mask = [torch.ones_like(ids, dtype=torch.long) for ids in prompt_ids]
|
| 1217 |
+
prompt_ids = pad(
|
| 1218 |
+
prompt_ids,
|
| 1219 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 1220 |
+
padding_side="left",
|
| 1221 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 1222 |
+
).to(device=device)
|
| 1223 |
+
prompt_mask = pad(
|
| 1224 |
+
prompt_mask, padding_value=0, padding_side="left", pad_to_multiple_of=self.pad_to_multiple_of
|
| 1225 |
+
).to(device=device)
|
| 1226 |
+
completion_ids = [torch.tensor(ids) for ids in completion_ids_list]
|
| 1227 |
+
completion_mask = [torch.ones_like(ids, dtype=torch.long) for ids in completion_ids]
|
| 1228 |
+
completion_ids = pad(
|
| 1229 |
+
completion_ids,
|
| 1230 |
+
padding_value=self._tokenizer.pad_token_id,
|
| 1231 |
+
padding_side="right",
|
| 1232 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 1233 |
+
).to(device=device)
|
| 1234 |
+
completion_mask = pad(
|
| 1235 |
+
completion_mask, padding_value=0, padding_side="right", pad_to_multiple_of=self.pad_to_multiple_of
|
| 1236 |
+
).to(device=device)
|
| 1237 |
+
|
| 1238 |
+
# If mask_truncated_completions is enabled, zero out truncated completions in completion_mask
|
| 1239 |
+
if self.mask_truncated_completions:
|
| 1240 |
+
eos_and_pad = [self._tokenizer.eos_token_id, self._tokenizer.pad_token_id]
|
| 1241 |
+
# Mask completion_mask for attention masking
|
| 1242 |
+
is_truncated = torch.tensor([ids[-1] not in eos_and_pad for ids in completion_ids_list], device=device)
|
| 1243 |
+
completion_mask = completion_mask * (~is_truncated).unsqueeze(1).int()
|
| 1244 |
+
|
| 1245 |
+
# Concatenate prompt_mask with completion_mask for logit computation
|
| 1246 |
+
prompt_completion_ids = torch.cat([prompt_ids, completion_ids], dim=1) # (B, P+C)
|
| 1247 |
+
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1) # (B, P+C)
|
| 1248 |
+
|
| 1249 |
+
logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
|
| 1250 |
+
batch_size = self.args.per_device_train_batch_size if mode == "train" else self.args.per_device_eval_batch_size
|
| 1251 |
+
|
| 1252 |
+
num_images = [len(img_list) if img_list else 0 for img_list in images] if images is not None else None
|
| 1253 |
+
|
| 1254 |
+
# Get forward_kwargs for models with multimodal inputs
|
| 1255 |
+
if images is not None:
|
| 1256 |
+
prompts_text = [
|
| 1257 |
+
apply_chat_template({"prompt": prompt}, self.processing_class, **self.chat_template_kwargs)["prompt"]
|
| 1258 |
+
for prompt in prompts
|
| 1259 |
+
]
|
| 1260 |
+
prompt_inputs = self.processing_class(images=images, text=prompts_text, padding=True, return_tensors="pt")
|
| 1261 |
+
prompt_inputs = super()._prepare_inputs(prompt_inputs)
|
| 1262 |
+
forward_kwargs = {k: v for k, v in prompt_inputs.items() if k not in ["input_ids", "attention_mask"]}
|
| 1263 |
+
else:
|
| 1264 |
+
forward_kwargs = {}
|
| 1265 |
+
|
| 1266 |
+
# If token_type_ids are used, extend them with zeros for the completion part
|
| 1267 |
+
if "token_type_ids" in forward_kwargs:
|
| 1268 |
+
token_type_ids = forward_kwargs["token_type_ids"]
|
| 1269 |
+
if self.pad_to_multiple_of is not None:
|
| 1270 |
+
# Needed only with pad_to_multiple_of: otherwise prompt_ids and token_type_ids must have equal len
|
| 1271 |
+
padding_size = prompt_ids.size(1) - token_type_ids.size(1)
|
| 1272 |
+
if padding_size > 0:
|
| 1273 |
+
token_type_ids = torch.cat(
|
| 1274 |
+
[token_type_ids.new_zeros((token_type_ids.size(0), padding_size)), token_type_ids], dim=1
|
| 1275 |
+
)
|
| 1276 |
+
forward_kwargs["token_type_ids"] = torch.cat(
|
| 1277 |
+
[token_type_ids, token_type_ids.new_zeros(completion_ids.shape)], dim=1
|
| 1278 |
+
)
|
| 1279 |
+
# If mm_token_type_ids are used, extend them with zeros for the completion part
|
| 1280 |
+
if "mm_token_type_ids" in forward_kwargs:
|
| 1281 |
+
mm_token_type_ids = forward_kwargs["mm_token_type_ids"]
|
| 1282 |
+
if self.pad_to_multiple_of is not None:
|
| 1283 |
+
# Needed only with pad_to_multiple_of: otherwise prompt_ids and mm_token_type_ids must have equal len
|
| 1284 |
+
padding_size = prompt_ids.size(1) - mm_token_type_ids.size(1)
|
| 1285 |
+
if padding_size > 0:
|
| 1286 |
+
mm_token_type_ids = torch.cat(
|
| 1287 |
+
[mm_token_type_ids.new_zeros((mm_token_type_ids.size(0), padding_size)), mm_token_type_ids],
|
| 1288 |
+
dim=1,
|
| 1289 |
+
)
|
| 1290 |
+
forward_kwargs["mm_token_type_ids"] = torch.cat(
|
| 1291 |
+
[mm_token_type_ids, mm_token_type_ids.new_zeros(completion_ids.shape)], dim=1
|
| 1292 |
+
)
|
| 1293 |
+
|
| 1294 |
+
# When gradient checkpointing is enabled with use_reentrant=True (non default), calling the model inside a
|
| 1295 |
+
# torch.no_grad() block triggers a harmless PyTorch warning ("None of the inputs have requires_grad=True").
|
| 1296 |
+
# Temporarily disable checkpointing to avoid this warning during inference.
|
| 1297 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 1298 |
+
# Compute the per-token log probabilities for the current model
|
| 1299 |
+
old_per_token_logps, _, _ = self._get_per_token_logps_and_entropies(
|
| 1300 |
+
self.model,
|
| 1301 |
+
prompt_completion_ids,
|
| 1302 |
+
attention_mask,
|
| 1303 |
+
logits_to_keep,
|
| 1304 |
+
batch_size,
|
| 1305 |
+
num_images=num_images,
|
| 1306 |
+
**forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, image_sizes, image_position_ids
|
| 1307 |
+
)
|
| 1308 |
+
old_logps = (old_per_token_logps * completion_mask).sum(1) # mask out padding and tokens after EOS
|
| 1309 |
+
|
| 1310 |
+
# Compute the per-token log probabilities for the reference model
|
| 1311 |
+
if self.beta != 0.0:
|
| 1312 |
+
if self.ref_model is not None:
|
| 1313 |
+
ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies(
|
| 1314 |
+
self.ref_model,
|
| 1315 |
+
prompt_completion_ids,
|
| 1316 |
+
attention_mask,
|
| 1317 |
+
logits_to_keep,
|
| 1318 |
+
batch_size=batch_size,
|
| 1319 |
+
num_images=num_images,
|
| 1320 |
+
**forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, image_sizes, image_position_ids
|
| 1321 |
+
)
|
| 1322 |
+
else:
|
| 1323 |
+
# When training a PEFT adapter, how we obtain the reference depends on the setup:
|
| 1324 |
+
# - New adapter: disabling adapters yields the base model.
|
| 1325 |
+
# - Re-training an existing adapter: an initial copy is loaded under the name "ref".
|
| 1326 |
+
model = self.accelerator.unwrap_model(self.model)
|
| 1327 |
+
with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None):
|
| 1328 |
+
ref_per_token_logps, _, _ = self._get_per_token_logps_and_entropies(
|
| 1329 |
+
self.model,
|
| 1330 |
+
prompt_completion_ids,
|
| 1331 |
+
attention_mask,
|
| 1332 |
+
logits_to_keep,
|
| 1333 |
+
batch_size=batch_size,
|
| 1334 |
+
num_images=num_images,
|
| 1335 |
+
**forward_kwargs, # may contain pixel_values, image_grid_thw, pixel_attention_mask, image_sizes, image_position_ids
|
| 1336 |
+
)
|
| 1337 |
+
else:
|
| 1338 |
+
ref_per_token_logps = None
|
| 1339 |
+
|
| 1340 |
+
# Decode
|
| 1341 |
+
prompts_text = self.processing_class.batch_decode(prompt_ids, skip_special_tokens=True)
|
| 1342 |
+
completions_text = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True)
|
| 1343 |
+
|
| 1344 |
+
# Calculate rewards for each reward function. rewards_per_func aggregates rewards across all processes. This is
|
| 1345 |
+
# important because rewards will be normalized per group, and completions are distributed. We will later slice
|
| 1346 |
+
# rewards_per_func to extract each process's subset.
|
| 1347 |
+
rewards_per_func = self._calculate_rewards(inputs, prompts, completions, completion_ids_list)
|
| 1348 |
+
num_generations = self.num_generations if mode == "train" else self.num_generations_eval
|
| 1349 |
+
|
| 1350 |
+
# A completion for which every reward function returned None is unscorable. nansum would collapse it to 0,
|
| 1351 |
+
# which both biases the leave-one-out baseline and hands the completion a spurious advantage. Mark these rows
|
| 1352 |
+
# NaN so they're excluded from the (nan-aware) baseline below; their advantage is forced to 0 afterwards.
|
| 1353 |
+
unscorable_mask = torch.isnan(rewards_per_func).all(dim=1)
|
| 1354 |
+
|
| 1355 |
+
# Apply weights to each reward function's output and sum
|
| 1356 |
+
rewards = (rewards_per_func * self.reward_weights.to(device).unsqueeze(0)).nansum(dim=1)
|
| 1357 |
+
rewards[unscorable_mask] = torch.nan
|
| 1358 |
+
|
| 1359 |
+
# Apply reward clipping if specified
|
| 1360 |
+
if self.reward_clip_range:
|
| 1361 |
+
rewards = rewards.clamp(min=self.reward_clip_range[0], max=self.reward_clip_range[1])
|
| 1362 |
+
|
| 1363 |
+
# Include the KL penalty in the reward
|
| 1364 |
+
if self.beta != 0.0:
|
| 1365 |
+
# RLOO uses the first-order log ratio for the per-token KL estimate, following the original RLOO paper
|
| 1366 |
+
# (Ahmadian et al., 2024, https://huggingface.co/papers/2405.14782). Unlike GRPOTrainer's Schulman
|
| 1367 |
+
# approximation (always >= 0), this can be negative per token. The divergence is intentional: RLOO applies
|
| 1368 |
+
# KL as a reward penalty (summed across tokens per sequence), while GRPO adds it to the per-token loss.
|
| 1369 |
+
per_token_kl = old_per_token_logps - ref_per_token_logps
|
| 1370 |
+
# Apply sequence-level KL penalty to rewards (sum KL across tokens first, then apply to each sequence)
|
| 1371 |
+
kl = (per_token_kl * completion_mask).sum(-1)
|
| 1372 |
+
kl = gather(kl) # rewards are gathered, so kl must be too
|
| 1373 |
+
rewards = rewards - self.beta * kl
|
| 1374 |
+
|
| 1375 |
+
grouped_rewards = rewards.view(-1, num_generations)
|
| 1376 |
+
mean_grouped_rewards = torch.nanmean(grouped_rewards, dim=1)
|
| 1377 |
+
if num_generations > 1:
|
| 1378 |
+
std_rewards = nanstd(grouped_rewards, dim=1)
|
| 1379 |
+
else: # doesn't occur during training, but could occur in eval when num_generations_eval=1
|
| 1380 |
+
std_rewards = torch.zeros_like(mean_grouped_rewards)
|
| 1381 |
+
|
| 1382 |
+
# RLOO advantages computation. The leave-one-out baseline averages over scorable siblings only: nansum drops
|
| 1383 |
+
# unscorable rewards and the divisor is (scorable count − 1). A group with a single scorable completion yields
|
| 1384 |
+
# 0/0 = NaN, and unscorable rows stay NaN; both are zeroed by nan_to_num below.
|
| 1385 |
+
scorable_counts = (~torch.isnan(grouped_rewards)).sum(dim=1, keepdim=True) # (num_prompts, 1)
|
| 1386 |
+
grouped_sum = torch.nansum(grouped_rewards, dim=1, keepdim=True) # (num_prompts, 1)
|
| 1387 |
+
if num_generations > 1:
|
| 1388 |
+
baselines = (grouped_sum - grouped_rewards) / (scorable_counts - 1) # (num_prompts, num_generations)
|
| 1389 |
+
baselines = baselines.view(-1) # Flatten back to match rewards shape
|
| 1390 |
+
advantages = rewards - baselines
|
| 1391 |
+
else: # this case doesn't occur during training, but could in eval when num_generations_eval=1
|
| 1392 |
+
advantages = torch.zeros_like(rewards)
|
| 1393 |
+
|
| 1394 |
+
# Normalize advantages over the scorable subset only (unscorable advantages are still NaN here).
|
| 1395 |
+
if self.normalize_advantages:
|
| 1396 |
+
advantages = (advantages - torch.nanmean(advantages)) / (nanstd(advantages) + 1e-4)
|
| 1397 |
+
|
| 1398 |
+
# Unscorable completions carry no learning signal: zero their advantage to keep them from moving the policy.
|
| 1399 |
+
advantages = torch.nan_to_num(advantages, nan=0.0)
|
| 1400 |
+
|
| 1401 |
+
is_std_zero = torch.isclose(std_rewards, torch.zeros_like(std_rewards)) # for logging
|
| 1402 |
+
|
| 1403 |
+
# Slice to keep only the local part of the data
|
| 1404 |
+
process_slice = slice(
|
| 1405 |
+
self.accelerator.process_index * len(prompts),
|
| 1406 |
+
(self.accelerator.process_index + 1) * len(prompts),
|
| 1407 |
+
)
|
| 1408 |
+
all_process_advantages = advantages.clone() # keep the aggregated advantages for logging
|
| 1409 |
+
advantages = advantages[process_slice]
|
| 1410 |
+
|
| 1411 |
+
# Calculate and log the mean KL divergence between current and reference model
|
| 1412 |
+
if self.beta != 0.0:
|
| 1413 |
+
mean_kl = (per_token_kl * completion_mask).sum() / completion_mask.sum().clamp(min=1.0)
|
| 1414 |
+
self._metrics[mode]["kl"].append(self.accelerator.gather(mean_kl).nanmean().item())
|
| 1415 |
+
|
| 1416 |
+
# Calculate mean reward per function, but only for samples where the function was applied (non-NaN values)
|
| 1417 |
+
for i, reward_func_name in enumerate(self.reward_func_names):
|
| 1418 |
+
mean_rewards = torch.nanmean(rewards_per_func[:, i]).item()
|
| 1419 |
+
self._metrics[mode][f"rewards/{reward_func_name}/mean"].append(mean_rewards)
|
| 1420 |
+
std_func_rewards = nanstd(rewards_per_func[:, i]).item()
|
| 1421 |
+
self._metrics[mode][f"rewards/{reward_func_name}/std"].append(std_func_rewards)
|
| 1422 |
+
rewards = (rewards_per_func * self.reward_weights.to(rewards_per_func.device).unsqueeze(0)).nansum(dim=1)
|
| 1423 |
+
rewards[unscorable_mask] = torch.nan # exclude unscorable rows from the logged reward stats
|
| 1424 |
+
self._metrics[mode]["reward"].append(torch.nanmean(rewards).item())
|
| 1425 |
+
self._metrics[mode]["reward_std"].append(nanstd(rewards).item())
|
| 1426 |
+
self._metrics[mode]["frac_reward_zero_std"].append(is_std_zero.float().mean().item())
|
| 1427 |
+
|
| 1428 |
+
# Log prompt and completion texts
|
| 1429 |
+
self._logs["prompt"].extend(gather_object(prompts_text))
|
| 1430 |
+
self._logs["completion"].extend(gather_object(completions_text))
|
| 1431 |
+
for i, name in enumerate(self.reward_func_names):
|
| 1432 |
+
self._logs["rewards"][name].extend(rewards_per_func[:, i].tolist())
|
| 1433 |
+
self._logs["advantages"].extend(all_process_advantages.tolist())
|
| 1434 |
+
|
| 1435 |
+
# Flush user-logged extra columns (from log_extra), gathering across processes.
|
| 1436 |
+
# Keys must be sorted so that all ranks call gather_object in the same order, otherwise values
|
| 1437 |
+
# get mis-attributed across columns (dict insertion order may differ between processes).
|
| 1438 |
+
for column in sorted(self._pending_extra_logs):
|
| 1439 |
+
self._logs["extra"][column].extend(gather_object(self._pending_extra_logs[column]))
|
| 1440 |
+
self._pending_extra_logs.clear()
|
| 1441 |
+
|
| 1442 |
+
# Flush user-logged metrics (from log_metric), averaging across processes.
|
| 1443 |
+
# Keys must be sorted so that all ranks call accelerator.gather in the same order, otherwise values
|
| 1444 |
+
# get mis-attributed across metrics (dict insertion order may differ between processes).
|
| 1445 |
+
for name in sorted(self._pending_metrics):
|
| 1446 |
+
values = self._pending_metrics[name]
|
| 1447 |
+
local_mean = sum(values) / len(values)
|
| 1448 |
+
global_mean = self.accelerator.gather(torch.tensor(local_mean, device=device)).mean().item()
|
| 1449 |
+
self._metrics[mode][name].append(global_mean)
|
| 1450 |
+
self._pending_metrics.clear()
|
| 1451 |
+
|
| 1452 |
+
if images is not None:
|
| 1453 |
+
self._logs["images"].extend(gather_object(images))
|
| 1454 |
+
|
| 1455 |
+
output = {
|
| 1456 |
+
"prompt_ids": prompt_ids,
|
| 1457 |
+
"prompt_mask": prompt_mask,
|
| 1458 |
+
"completion_ids": completion_ids,
|
| 1459 |
+
"completion_mask": completion_mask,
|
| 1460 |
+
"old_logps": old_logps,
|
| 1461 |
+
"advantages": advantages,
|
| 1462 |
+
}
|
| 1463 |
+
if "pixel_values" in forward_kwargs:
|
| 1464 |
+
output["pixel_values"] = forward_kwargs["pixel_values"]
|
| 1465 |
+
if "image_grid_thw" in forward_kwargs:
|
| 1466 |
+
output["image_grid_thw"] = forward_kwargs["image_grid_thw"]
|
| 1467 |
+
if "pixel_attention_mask" in forward_kwargs:
|
| 1468 |
+
output["pixel_attention_mask"] = forward_kwargs["pixel_attention_mask"]
|
| 1469 |
+
if "image_sizes" in forward_kwargs:
|
| 1470 |
+
output["image_sizes"] = forward_kwargs["image_sizes"]
|
| 1471 |
+
if "token_type_ids" in forward_kwargs:
|
| 1472 |
+
output["token_type_ids"] = forward_kwargs["token_type_ids"]
|
| 1473 |
+
if "mm_token_type_ids" in forward_kwargs:
|
| 1474 |
+
output["mm_token_type_ids"] = forward_kwargs["mm_token_type_ids"]
|
| 1475 |
+
if "image_position_ids" in forward_kwargs:
|
| 1476 |
+
output["image_position_ids"] = forward_kwargs["image_position_ids"]
|
| 1477 |
+
if images is not None:
|
| 1478 |
+
output["num_images"] = num_images
|
| 1479 |
+
return output
|
| 1480 |
+
|
| 1481 |
+
@profiling_decorator
|
| 1482 |
+
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 1483 |
+
if return_outputs:
|
| 1484 |
+
raise ValueError("The RLOOTrainer does not support returning outputs")
|
| 1485 |
+
return self._compute_loss(model, inputs)
|
| 1486 |
+
|
| 1487 |
+
def _compute_loss(self, model, inputs):
|
| 1488 |
+
# Compute the per-token log probabilities for the model
|
| 1489 |
+
prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
|
| 1490 |
+
completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
|
| 1491 |
+
input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
|
| 1492 |
+
attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
|
| 1493 |
+
logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
|
| 1494 |
+
|
| 1495 |
+
# Compute the per_token_logps and the entropy at each position in the completion
|
| 1496 |
+
per_token_logps, entropies, aux_loss = self._get_per_token_logps_and_entropies(
|
| 1497 |
+
model,
|
| 1498 |
+
input_ids,
|
| 1499 |
+
attention_mask,
|
| 1500 |
+
logits_to_keep,
|
| 1501 |
+
compute_entropy=True,
|
| 1502 |
+
compute_aux_loss=self.aux_loss_enabled,
|
| 1503 |
+
pixel_values=inputs.get("pixel_values"),
|
| 1504 |
+
image_grid_thw=inputs.get("image_grid_thw"),
|
| 1505 |
+
num_images=inputs.get("num_images"),
|
| 1506 |
+
pixel_attention_mask=inputs.get("pixel_attention_mask"),
|
| 1507 |
+
image_sizes=inputs.get("image_sizes"),
|
| 1508 |
+
token_type_ids=inputs.get("token_type_ids"),
|
| 1509 |
+
mm_token_type_ids=inputs.get("mm_token_type_ids"),
|
| 1510 |
+
image_position_ids=inputs.get("image_position_ids"),
|
| 1511 |
+
)
|
| 1512 |
+
|
| 1513 |
+
logps = (per_token_logps * completion_mask).sum(1) # mask out padding and tokens after EOS
|
| 1514 |
+
old_logps = inputs["old_logps"]
|
| 1515 |
+
log_ratio = logps - old_logps
|
| 1516 |
+
|
| 1517 |
+
# Compute the loss
|
| 1518 |
+
advantages = inputs["advantages"]
|
| 1519 |
+
coef_1 = torch.exp(log_ratio)
|
| 1520 |
+
coef_2 = torch.clamp(coef_1, 1 - self.epsilon_low, 1 + self.epsilon_high)
|
| 1521 |
+
per_sequence_loss1 = coef_1 * advantages
|
| 1522 |
+
per_sequence_loss2 = coef_2 * advantages
|
| 1523 |
+
per_sequence_loss = -torch.min(per_sequence_loss1, per_sequence_loss2)
|
| 1524 |
+
loss = per_sequence_loss.mean()
|
| 1525 |
+
|
| 1526 |
+
# Log the metrics
|
| 1527 |
+
mode = "train" if self.model.training else "eval"
|
| 1528 |
+
|
| 1529 |
+
# RLOO returns an unscaled loss (the HF Trainer divides by gradient accumulation), so add the aux term unscaled
|
| 1530 |
+
if self.aux_loss_enabled:
|
| 1531 |
+
loss = loss + self.router_aux_loss_coef * aux_loss
|
| 1532 |
+
self._metrics[mode]["aux_loss"].append(self.accelerator.gather_for_metrics(aux_loss).mean().item())
|
| 1533 |
+
|
| 1534 |
+
# Entropy
|
| 1535 |
+
mean_entropy = (entropies * completion_mask).sum() / completion_mask.sum().clamp(min=1.0)
|
| 1536 |
+
self._metrics[mode]["entropy"].append(self.accelerator.gather(mean_entropy).nanmean().item())
|
| 1537 |
+
|
| 1538 |
+
# Compute the clipped probability ratios
|
| 1539 |
+
is_low_clipped = (coef_1 < 1 - self.epsilon_low) & (advantages < 0)
|
| 1540 |
+
is_high_clipped = (coef_1 > 1 + self.epsilon_high) & (advantages > 0)
|
| 1541 |
+
is_region_clipped = is_low_clipped | is_high_clipped
|
| 1542 |
+
gathered_low_clip = self.accelerator.gather(is_low_clipped.float().mean())
|
| 1543 |
+
self._metrics[mode]["clip_ratio/low_mean"].append(gathered_low_clip.nanmean().item())
|
| 1544 |
+
self._metrics[mode]["clip_ratio/low_min"].append(nanmin(gathered_low_clip).item())
|
| 1545 |
+
gathered_high_clip = self.accelerator.gather(is_high_clipped.float().mean())
|
| 1546 |
+
self._metrics[mode]["clip_ratio/high_mean"].append(gathered_high_clip.nanmean().item())
|
| 1547 |
+
self._metrics[mode]["clip_ratio/high_max"].append(nanmax(gathered_high_clip).item())
|
| 1548 |
+
gathered_clip_ratio = self.accelerator.gather(is_region_clipped.float().mean())
|
| 1549 |
+
self._metrics[mode]["clip_ratio/region_mean"].append(gathered_clip_ratio.nanmean().item())
|
| 1550 |
+
return loss
|
| 1551 |
+
|
| 1552 |
+
# During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and
|
| 1553 |
+
# returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels.
|
| 1554 |
+
def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys: list[str] | None = None):
|
| 1555 |
+
inputs = self._prepare_inputs(inputs)
|
| 1556 |
+
with torch.no_grad():
|
| 1557 |
+
with self.compute_loss_context_manager():
|
| 1558 |
+
loss = self.compute_loss(model, inputs)
|
| 1559 |
+
loss = loss.mean().detach()
|
| 1560 |
+
return loss, None, None
|
| 1561 |
+
|
| 1562 |
+
def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
|
| 1563 |
+
mode = "train" if self.model.training else "eval"
|
| 1564 |
+
# Average the metrics
|
| 1565 |
+
metrics = {}
|
| 1566 |
+
for key, val in self._metrics[mode].items():
|
| 1567 |
+
# Filter out NaN values before averaging. A reward function that returns None for all samples
|
| 1568 |
+
# in a batch produces NaN for that batch's metric. With logging_steps > 1, a naive sum()/len()
|
| 1569 |
+
# would let a single NaN contaminate valid data from other batches. Only return None when no
|
| 1570 |
+
# valid values remain (e.g. JSON loggers crash on float NaN).
|
| 1571 |
+
valid = [v for v in val if not math.isnan(v)]
|
| 1572 |
+
metrics[key] = sum(valid) / len(valid) if valid else None
|
| 1573 |
+
|
| 1574 |
+
# This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
|
| 1575 |
+
# start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
|
| 1576 |
+
if mode == "eval":
|
| 1577 |
+
metrics = {f"eval_{key}": val for key, val in metrics.items()}
|
| 1578 |
+
|
| 1579 |
+
logs.update(metrics)
|
| 1580 |
+
super().log(logs, start_time)
|
| 1581 |
+
self._metrics[mode].clear()
|
| 1582 |
+
|
| 1583 |
+
if self.accelerator.is_main_process and self.log_completions:
|
| 1584 |
+
if is_rich_available():
|
| 1585 |
+
print_prompt_completions_sample(
|
| 1586 |
+
self._logs["prompt"],
|
| 1587 |
+
self._logs["completion"],
|
| 1588 |
+
self._logs["rewards"],
|
| 1589 |
+
self._logs["advantages"],
|
| 1590 |
+
self.state.global_step,
|
| 1591 |
+
self.num_completions_to_print,
|
| 1592 |
+
extra=dict(self._logs["extra"]),
|
| 1593 |
+
)
|
| 1594 |
+
|
| 1595 |
+
logging_backends = []
|
| 1596 |
+
if self.args.report_to and "wandb" in self.args.report_to and wandb.run is not None:
|
| 1597 |
+
logging_backends.append(wandb)
|
| 1598 |
+
if self.args.report_to and "trackio" in self.args.report_to:
|
| 1599 |
+
logging_backends.append(trackio)
|
| 1600 |
+
|
| 1601 |
+
table = {
|
| 1602 |
+
"step": [self.state.global_step] * len(self._logs["prompt"]),
|
| 1603 |
+
"prompt": self._logs["prompt"],
|
| 1604 |
+
"completion": self._logs["completion"],
|
| 1605 |
+
**self._logs["rewards"],
|
| 1606 |
+
**self._logs["extra"],
|
| 1607 |
+
"advantage": self._logs["advantages"],
|
| 1608 |
+
}
|
| 1609 |
+
|
| 1610 |
+
df_base = pd.DataFrame(table)
|
| 1611 |
+
images_raw = self._logs["images"] or []
|
| 1612 |
+
|
| 1613 |
+
for logging_backend in logging_backends:
|
| 1614 |
+
if images_raw:
|
| 1615 |
+
images = []
|
| 1616 |
+
for image_list in self._logs["images"]:
|
| 1617 |
+
images.append([logging_backend.Image(image) for image in image_list])
|
| 1618 |
+
df = pd.concat(
|
| 1619 |
+
[df_base, pd.Series(images, name="image")],
|
| 1620 |
+
axis=1,
|
| 1621 |
+
copy=False,
|
| 1622 |
+
)
|
| 1623 |
+
else:
|
| 1624 |
+
df = df_base
|
| 1625 |
+
|
| 1626 |
+
if self.log_unique_prompts:
|
| 1627 |
+
df = df.drop_duplicates(subset=["prompt"])
|
| 1628 |
+
|
| 1629 |
+
logging_backend.log({"completions": logging_backend.Table(dataframe=df)})
|
| 1630 |
+
|
| 1631 |
+
# Ensure the model card is saved along with the checkpoint
|
| 1632 |
+
def _save_checkpoint(self, model, trial):
|
| 1633 |
+
if self.args.hub_model_id is None:
|
| 1634 |
+
model_name = Path(self.args.output_dir).name
|
| 1635 |
+
else:
|
| 1636 |
+
model_name = self.args.hub_model_id.split("/")[-1]
|
| 1637 |
+
self.create_model_card(model_name=model_name)
|
| 1638 |
+
super()._save_checkpoint(model, trial)
|
tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/sft_config.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 .base_config import _BaseConfig
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class SFTConfig(_BaseConfig):
|
| 24 |
+
# docstyle-ignore
|
| 25 |
+
r"""
|
| 26 |
+
Configuration class for the [`SFTTrainer`].
|
| 27 |
+
|
| 28 |
+
This class includes only the parameters that are specific to SFT training. For a full list of training arguments,
|
| 29 |
+
please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
|
| 30 |
+
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 |
+
> Parameters that control the model
|
| 38 |
+
|
| 39 |
+
model_init_kwargs (`dict[str, Any]`, *optional*):
|
| 40 |
+
Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
|
| 41 |
+
argument of the [`SFTTrainer`] is provided as a string.
|
| 42 |
+
trust_remote_code (`bool`, *optional*, defaults to `False`):
|
| 43 |
+
Whether to allow loading models and tokenizers that ship custom Python code from the Hub. Forwarded to
|
| 44 |
+
[`~transformers.AutoModelForCausalLM.from_pretrained`] and
|
| 45 |
+
[`~transformers.AutoProcessor.from_pretrained`].
|
| 46 |
+
router_aux_loss_coef (`float`, *optional*, defaults to `0.001`):
|
| 47 |
+
Coefficient of the load-balancing auxiliary loss. Only has an effect when training a Mixture-of-Experts
|
| 48 |
+
(MoE) model; for other models it does nothing. The auxiliary loss is added to the training loss with this
|
| 49 |
+
weight. Set to `0.0` to disable it.
|
| 50 |
+
chat_template_path (`str`, *optional*):
|
| 51 |
+
If specified, sets the model's chat template. This can either be the path to a tokenizer (local directory
|
| 52 |
+
or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, you must
|
| 53 |
+
ensure that any special tokens referenced in the template are added to the tokenizer and that the model's
|
| 54 |
+
embedding layer is resized accordingly.
|
| 55 |
+
|
| 56 |
+
> Parameters that control the data preprocessing
|
| 57 |
+
|
| 58 |
+
dataset_text_field (`str`, *optional*, defaults to `"text"`):
|
| 59 |
+
Name of the column that contains text data in the dataset.
|
| 60 |
+
dataset_kwargs (`dict[str, Any]`, *optional*):
|
| 61 |
+
Dictionary of optional keyword arguments for the dataset preparation. The only supported key is
|
| 62 |
+
`skip_prepare_dataset`. When the model is a VLM, `skip_prepare_dataset` is automatically treated as `True`
|
| 63 |
+
regardless of the provided value, since preprocessing is done on the fly.
|
| 64 |
+
dataset_num_proc (`int`, *optional*):
|
| 65 |
+
Number of processes to use for processing the dataset.
|
| 66 |
+
eos_token (`str`, *optional*):
|
| 67 |
+
Token used to indicate the end of a turn or sequence. If `None`, it defaults to
|
| 68 |
+
`processing_class.eos_token`.
|
| 69 |
+
max_length (`int` or `None`, *optional*, defaults to `1024`):
|
| 70 |
+
Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the left
|
| 71 |
+
or right depending on `truncation_mode`. If `None`, no truncation is applied. When packing is enabled,
|
| 72 |
+
this value sets the sequence length.
|
| 73 |
+
truncation_mode (`str`, *optional*, defaults to `"keep_start"`):
|
| 74 |
+
Truncation mode to use when the sequence exceeds `max_length`. The only supported value is
|
| 75 |
+
`"keep_start"`. The `"keep_end"` value is deprecated and will be removed in v2.0.0.
|
| 76 |
+
shuffle_dataset (`bool`, *optional*, defaults to `False`):
|
| 77 |
+
Whether to shuffle the dataset.
|
| 78 |
+
packing (`bool`, *optional*, defaults to `False`):
|
| 79 |
+
Whether to group multiple sequences into fixed-length blocks to improve computational efficiency and reduce
|
| 80 |
+
padding. Uses `max_length` to define sequence length.
|
| 81 |
+
packing_strategy (`str`, *optional*, defaults to `"bfd"`):
|
| 82 |
+
Strategy for packing sequences. Can be `"bfd"` (best-fit decreasing, truncates overflow), `"bfd_split"`
|
| 83 |
+
(best-fit decreasing, splits overflow sequences), or `"wrapped"` (aggressive, cuts mid-sequence).
|
| 84 |
+
padding_free (`bool`, *optional*, defaults to `False`):
|
| 85 |
+
Whether to perform forward passes without padding by flattening all sequences in the batch into a single
|
| 86 |
+
continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this is only
|
| 87 |
+
supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch structure. When
|
| 88 |
+
packing is enabled with strategy `"bfd"`, padding-free is enabled, regardless of the value of this
|
| 89 |
+
parameter.
|
| 90 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 91 |
+
If set, the sequences will be padded to a multiple of this value.
|
| 92 |
+
eval_packing (`bool`, *optional*):
|
| 93 |
+
Whether to pack the eval dataset. If `None`, uses the same value as `packing`.
|
| 94 |
+
|
| 95 |
+
> Parameters that control the training
|
| 96 |
+
|
| 97 |
+
completion_only_loss (`bool`, *optional*):
|
| 98 |
+
Whether to compute loss only on the completion part of the sequence. If set to `True`, loss is computed
|
| 99 |
+
only on the completion, which is supported only for [prompt-completion](#prompt-completion) datasets. If
|
| 100 |
+
`False`, loss is computed on the entire sequence. If `None` (default), the behavior depends on the dataset:
|
| 101 |
+
loss is computed on the completion for [prompt-completion](#prompt-completion) datasets, and on the full
|
| 102 |
+
sequence for [language modeling](#language-modeling) datasets.
|
| 103 |
+
assistant_only_loss (`bool`, *optional*, defaults to `False`):
|
| 104 |
+
Whether to compute loss only on the assistant part of the sequence. If set to `True`, loss is computed only
|
| 105 |
+
on the assistant responses, which is supported only for [conversational](#conversational) datasets. If
|
| 106 |
+
`False`, loss is computed on the entire sequence.
|
| 107 |
+
loss_type (`str`, *optional*, defaults to `"chunked_nll"`):
|
| 108 |
+
Type of loss to use. When left unset, it defaults to `"chunked_nll"`, except when `use_liger_kernel=True`,
|
| 109 |
+
in which case it defaults to `"nll"`. Possible values are:
|
| 110 |
+
|
| 111 |
+
- `"nll"`: standard negative log-likelihood.
|
| 112 |
+
- `"dft"`: Dynamic Fine-Tuning, as described in
|
| 113 |
+
[this paper](https://huggingface.co/papers/2508.05629).
|
| 114 |
+
- `"chunked_nll"`: same math as `"nll"`, but the `lm_head` projection is computed on non-ignored tokens
|
| 115 |
+
only (positions with `labels == -100` are dropped before the matmul) and the cross-entropy is processed
|
| 116 |
+
in chunks of tokens to reduce peak activation memory. Not compatible with `use_liger_kernel`.
|
| 117 |
+
|
| 118 |
+
activation_offloading (`bool`, *optional*, defaults to `False`):
|
| 119 |
+
Whether to offload the activations to the CPU.
|
| 120 |
+
|
| 121 |
+
> Deprecated parameters
|
| 122 |
+
|
| 123 |
+
pad_token:
|
| 124 |
+
|
| 125 |
+
<Deprecated version="1.1.0">
|
| 126 |
+
|
| 127 |
+
Parameter `pad_token` is deprecated and will be removed in version v2.0.0. Set `tokenizer.pad_token`
|
| 128 |
+
directly and pass it as `processing_class` to the trainer instead.
|
| 129 |
+
|
| 130 |
+
</Deprecated>
|
| 131 |
+
|
| 132 |
+
> [!NOTE]
|
| 133 |
+
> These parameters have default values different from [`~transformers.TrainingArguments`]:
|
| 134 |
+
> - `logging_steps`: Defaults to `10` instead of `500`.
|
| 135 |
+
> - `gradient_checkpointing`: Defaults to `True` instead of `False`.
|
| 136 |
+
> - `bf16`: Defaults to `True` if `fp16` is not set, instead of `False`.
|
| 137 |
+
> - `learning_rate`: Defaults to `2e-5` instead of `5e-5`.
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
_VALID_DICT_FIELDS = _BaseConfig._VALID_DICT_FIELDS + ["model_init_kwargs"]
|
| 141 |
+
|
| 142 |
+
# Parameters whose default values are overridden from TrainingArguments
|
| 143 |
+
learning_rate: float = field(
|
| 144 |
+
default=2e-5,
|
| 145 |
+
metadata={"help": "The initial learning rate for AdamW."},
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
# Parameters that control the model
|
| 149 |
+
model_init_kwargs: dict[str, Any] | str | None = field(
|
| 150 |
+
default=None,
|
| 151 |
+
metadata={
|
| 152 |
+
"help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of "
|
| 153 |
+
"the `SFTTrainer` is provided as a string."
|
| 154 |
+
},
|
| 155 |
+
)
|
| 156 |
+
router_aux_loss_coef: float = field(
|
| 157 |
+
default=0.001,
|
| 158 |
+
metadata={
|
| 159 |
+
"help": "Coefficient of the load-balancing auxiliary loss. Only has an effect when training a "
|
| 160 |
+
"Mixture-of-Experts (MoE) model; for other models it does nothing. The auxiliary loss is added to the "
|
| 161 |
+
"training loss with this weight. Set to `0.0` to disable it."
|
| 162 |
+
},
|
| 163 |
+
)
|
| 164 |
+
trust_remote_code: bool = field(
|
| 165 |
+
default=False,
|
| 166 |
+
metadata={
|
| 167 |
+
"help": "Whether to allow loading models and tokenizers that ship custom Python code from the Hub. "
|
| 168 |
+
"Forwarded to `AutoModelForCausalLM.from_pretrained` and `AutoProcessor.from_pretrained`."
|
| 169 |
+
},
|
| 170 |
+
)
|
| 171 |
+
chat_template_path: str | None = field(
|
| 172 |
+
default=None,
|
| 173 |
+
metadata={
|
| 174 |
+
"help": "If specified, sets the model's chat template. This can either be the path to a tokenizer (local "
|
| 175 |
+
"directory or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, "
|
| 176 |
+
"you must ensure that any special tokens referenced in the template are added to the tokenizer and "
|
| 177 |
+
"that the model's embedding layer is resized accordingly."
|
| 178 |
+
},
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
# Parameters that control the data preprocessing
|
| 182 |
+
dataset_text_field: str = field(
|
| 183 |
+
default="text",
|
| 184 |
+
metadata={"help": "Name of the column that contains text data in the dataset."},
|
| 185 |
+
)
|
| 186 |
+
dataset_kwargs: dict[str, Any] | None = field(
|
| 187 |
+
default=None,
|
| 188 |
+
metadata={
|
| 189 |
+
"help": "Dictionary of optional keyword arguments for the dataset preparation. The only supported key is "
|
| 190 |
+
"`skip_prepare_dataset`. If the model is a VLM, `skip_prepare_dataset` value is ignored. When the model "
|
| 191 |
+
"is a VLM, `skip_prepare_dataset` is automatically treated as `True` regardless of the provided value, "
|
| 192 |
+
"since preprocessing is done on the fly."
|
| 193 |
+
},
|
| 194 |
+
)
|
| 195 |
+
dataset_num_proc: int | None = field(
|
| 196 |
+
default=None,
|
| 197 |
+
metadata={"help": "Number of processes to use for processing the dataset."},
|
| 198 |
+
)
|
| 199 |
+
eos_token: str | None = field(
|
| 200 |
+
default=None,
|
| 201 |
+
metadata={
|
| 202 |
+
"help": "Token used to indicate the end of a turn or sequence. If `None`, it defaults to `processing_class.eos_token`."
|
| 203 |
+
},
|
| 204 |
+
)
|
| 205 |
+
max_length: int | None = field(
|
| 206 |
+
default=1024,
|
| 207 |
+
metadata={
|
| 208 |
+
"help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from "
|
| 209 |
+
"the left or right depending on the `truncation_mode`. If `None`, no truncation is applied. When packing "
|
| 210 |
+
"is enabled, this value sets the sequence length."
|
| 211 |
+
},
|
| 212 |
+
)
|
| 213 |
+
truncation_mode: str = field(
|
| 214 |
+
default="keep_start",
|
| 215 |
+
metadata={
|
| 216 |
+
"help": "Truncation mode to use when the sequence exceeds `max_length`. The only supported value is "
|
| 217 |
+
"`'keep_start'`. The `'keep_end'` value is deprecated and will be removed in v2.0.0.",
|
| 218 |
+
"choices": ["keep_end", "keep_start"],
|
| 219 |
+
},
|
| 220 |
+
)
|
| 221 |
+
shuffle_dataset: bool = field(
|
| 222 |
+
default=False,
|
| 223 |
+
metadata={"help": "Whether to shuffle the dataset."},
|
| 224 |
+
)
|
| 225 |
+
packing: bool = field(
|
| 226 |
+
default=False,
|
| 227 |
+
metadata={
|
| 228 |
+
"help": "Whether to group multiple sequences into fixed-length blocks to improve computational efficiency "
|
| 229 |
+
"and reduce padding. Uses `max_length` to define sequence length."
|
| 230 |
+
},
|
| 231 |
+
)
|
| 232 |
+
packing_strategy: str = field(
|
| 233 |
+
default="bfd",
|
| 234 |
+
metadata={
|
| 235 |
+
"help": "Strategy for packing sequences. Can be `'bfd'` (best-fit decreasing, truncates overflow), "
|
| 236 |
+
"`'bfd_split'` (best-fit decreasing, splits overflow sequences), or `'wrapped'` (aggressive, cuts "
|
| 237 |
+
"mid-sequence).",
|
| 238 |
+
"choices": ["bfd", "bfd_split", "wrapped"],
|
| 239 |
+
},
|
| 240 |
+
)
|
| 241 |
+
padding_free: bool = field(
|
| 242 |
+
default=False,
|
| 243 |
+
metadata={
|
| 244 |
+
"help": "Whether to perform forward passes without padding by flattening all sequences in the batch into "
|
| 245 |
+
"a single continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this "
|
| 246 |
+
"is only supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch "
|
| 247 |
+
"structure. When packing is enabled with strategy `'bfd'`, padding-free is enabled, regardless of the "
|
| 248 |
+
"value of this parameter."
|
| 249 |
+
},
|
| 250 |
+
)
|
| 251 |
+
pad_to_multiple_of: int | None = field(
|
| 252 |
+
default=None,
|
| 253 |
+
metadata={"help": "If set, the sequences will be padded to a multiple of this value."},
|
| 254 |
+
)
|
| 255 |
+
eval_packing: bool | None = field(
|
| 256 |
+
default=None,
|
| 257 |
+
metadata={"help": "Whether to pack the eval dataset. If `None`, uses the same value as `packing`."},
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
# Parameters that control the training
|
| 261 |
+
completion_only_loss: bool | None = field(
|
| 262 |
+
default=None,
|
| 263 |
+
metadata={
|
| 264 |
+
"help": (
|
| 265 |
+
"Whether to compute loss only on the completion part of the sequence. If set to `True`, loss is "
|
| 266 |
+
"computed only on the completion, which is supported only for prompt-completion datasets. If `False`, "
|
| 267 |
+
"loss is computed on the entire sequence. If `None` (default), the behavior depends on the dataset: "
|
| 268 |
+
"loss is computed on the completion for prompt-completion datasets, and on the full sequence for "
|
| 269 |
+
"language modeling datasets."
|
| 270 |
+
)
|
| 271 |
+
},
|
| 272 |
+
)
|
| 273 |
+
assistant_only_loss: bool = field(
|
| 274 |
+
default=False,
|
| 275 |
+
metadata={
|
| 276 |
+
"help": (
|
| 277 |
+
"Whether to compute loss only on the assistant part of the sequence. If set to `True`, loss is "
|
| 278 |
+
"computed only on the assistant responses, which is supported only for conversational datasets. If `False`, "
|
| 279 |
+
"loss is computed on the entire sequence."
|
| 280 |
+
)
|
| 281 |
+
},
|
| 282 |
+
)
|
| 283 |
+
loss_type: str | None = field(
|
| 284 |
+
default=None,
|
| 285 |
+
metadata={
|
| 286 |
+
"help": "Type of loss to use. When left unset, it defaults to `'chunked_nll'`, except when "
|
| 287 |
+
"`use_liger_kernel=True`, in which case it defaults to `'nll'`. Possible values are `'nll'` (standard "
|
| 288 |
+
"negative log-likelihood), `'dft'` (Dynamic Fine-Tuning, https://huggingface.co/papers/2508.05629), and "
|
| 289 |
+
"`'chunked_nll'` (same math as `'nll'`, but the `lm_head` projection is computed on non-ignored tokens "
|
| 290 |
+
"only — positions with `labels == -100` are dropped before the matmul — and the cross-entropy is "
|
| 291 |
+
"processed in chunks of tokens to reduce peak activation memory; not compatible with `use_liger_kernel`; "
|
| 292 |
+
"the patched `lm_head` path covers standard causal LMs and VLMs whose language model exposes a top-level "
|
| 293 |
+
"`lm_head`, architectures with a non-standard head are not supported)."
|
| 294 |
+
},
|
| 295 |
+
)
|
| 296 |
+
activation_offloading: bool = field(
|
| 297 |
+
default=False,
|
| 298 |
+
metadata={"help": "Whether to offload the activations to the CPU."},
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
# Deprecated parameters
|
| 302 |
+
pad_token: str | None = field(
|
| 303 |
+
default=None,
|
| 304 |
+
metadata={
|
| 305 |
+
"help": "Deprecated. Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead."
|
| 306 |
+
},
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
def __post_init__(self):
|
| 310 |
+
super().__post_init__()
|
| 311 |
+
if self.pad_token is not None:
|
| 312 |
+
warnings.warn(
|
| 313 |
+
"`pad_token` is deprecated and will be removed in v2.0.0. "
|
| 314 |
+
"Set `tokenizer.pad_token` directly and pass it as `processing_class` to the trainer instead.",
|
| 315 |
+
FutureWarning,
|
| 316 |
+
stacklevel=3,
|
| 317 |
+
)
|
| 318 |
+
if self.truncation_mode == "keep_end":
|
| 319 |
+
warnings.warn(
|
| 320 |
+
"The `'keep_end'` truncation mode is deprecated and will be removed in v2.0.0. "
|
| 321 |
+
"Use `truncation_mode='keep_start'` (the default) instead.",
|
| 322 |
+
FutureWarning,
|
| 323 |
+
stacklevel=3,
|
| 324 |
+
)
|
| 325 |
+
if self.packing_strategy == "bfd-requeue":
|
| 326 |
+
warnings.warn(
|
| 327 |
+
"The `bfd-requeue` packing strategy has been renamed to `bfd_split`. Please update your configuration accordingly. "
|
| 328 |
+
"The `bfd-requeue` strategy is deprecated and will be removed in v2.0.0.",
|
| 329 |
+
FutureWarning,
|
| 330 |
+
stacklevel=3,
|
| 331 |
+
)
|
| 332 |
+
self.packing_strategy = "bfd_split"
|
| 333 |
+
|
| 334 |
+
# When unset, default to "chunked_nll" unless `use_liger_kernel=True`, in which case default to "nll".
|
| 335 |
+
if self.loss_type is None:
|
| 336 |
+
self.loss_type = "nll" if self.use_liger_kernel else "chunked_nll"
|
tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/sft_trainer.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-03a6a091b12f/environment/source/trl/trainer/utils.py
ADDED
|
@@ -0,0 +1,1501 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 hashlib
|
| 17 |
+
import importlib.resources as pkg_resources
|
| 18 |
+
import os
|
| 19 |
+
import random
|
| 20 |
+
import socket
|
| 21 |
+
import threading
|
| 22 |
+
import types
|
| 23 |
+
from collections.abc import Mapping, Sequence, Sized
|
| 24 |
+
from contextlib import contextmanager
|
| 25 |
+
from importlib.metadata import version
|
| 26 |
+
from itertools import accumulate
|
| 27 |
+
from typing import TypeVar
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import pandas as pd
|
| 31 |
+
import torch
|
| 32 |
+
import torch.nn.functional as F
|
| 33 |
+
import transformers
|
| 34 |
+
from accelerate import PartialState
|
| 35 |
+
from accelerate.logging import get_logger
|
| 36 |
+
from huggingface_hub import ModelCard, ModelCardData
|
| 37 |
+
from packaging.version import Version
|
| 38 |
+
from torch.utils.data import Sampler
|
| 39 |
+
from transformers import (
|
| 40 |
+
AutoConfig,
|
| 41 |
+
AutoModelForCausalLM,
|
| 42 |
+
AutoModelForImageTextToText,
|
| 43 |
+
BitsAndBytesConfig,
|
| 44 |
+
PretrainedConfig,
|
| 45 |
+
PreTrainedModel,
|
| 46 |
+
is_comet_available,
|
| 47 |
+
is_trackio_available,
|
| 48 |
+
)
|
| 49 |
+
from transformers.models.auto.auto_factory import _BaseAutoModelClass
|
| 50 |
+
from transformers.utils import (
|
| 51 |
+
is_peft_available,
|
| 52 |
+
is_rich_available,
|
| 53 |
+
is_torch_xpu_available,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
from ..trainer.model_config import ModelConfig
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
if is_rich_available():
|
| 60 |
+
from rich.console import Console
|
| 61 |
+
from rich.panel import Panel
|
| 62 |
+
from rich.table import Table
|
| 63 |
+
from rich.text import Text
|
| 64 |
+
|
| 65 |
+
if is_comet_available():
|
| 66 |
+
import comet_ml
|
| 67 |
+
|
| 68 |
+
if is_peft_available():
|
| 69 |
+
from peft import LoraConfig, PeftConfig, PeftModel
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
logger = get_logger(__name__)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _is_port_free(port: int, host: str = "127.0.0.1") -> bool:
|
| 76 |
+
try:
|
| 77 |
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
| 78 |
+
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
| 79 |
+
s.bind((host, port))
|
| 80 |
+
return True
|
| 81 |
+
except OSError:
|
| 82 |
+
return False
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _find_free_port() -> int:
|
| 86 |
+
candidates = (29500, 23456, 12355, 12345)
|
| 87 |
+
for p in candidates:
|
| 88 |
+
if _is_port_free(p):
|
| 89 |
+
return p
|
| 90 |
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
| 91 |
+
s.bind(("", 0))
|
| 92 |
+
return s.getsockname()[1]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def ensure_master_addr_port(addr: str | None = None, port: int | None = None) -> None:
|
| 96 |
+
"""
|
| 97 |
+
Ensure `MASTER_ADDR`/`MASTER_PORT` are set safely.
|
| 98 |
+
|
| 99 |
+
- Respects existing environment variables.
|
| 100 |
+
- Defaults `MASTER_ADDR` to localhost if unset.
|
| 101 |
+
- Chooses a free TCP port if `MASTER_PORT` is unset to avoid collisions.
|
| 102 |
+
- If `MASTER_PORT` is set to `"0"` or `"auto"`, it is resolved to a free port.
|
| 103 |
+
"""
|
| 104 |
+
os.environ["MASTER_ADDR"] = os.environ.get("MASTER_ADDR") or addr or "localhost"
|
| 105 |
+
|
| 106 |
+
env_port = os.environ.get("MASTER_PORT", "").strip().lower()
|
| 107 |
+
if port is None and env_port not in {"", "0", "auto"}:
|
| 108 |
+
try:
|
| 109 |
+
port = int(env_port)
|
| 110 |
+
except ValueError:
|
| 111 |
+
pass
|
| 112 |
+
|
| 113 |
+
os.environ["MASTER_PORT"] = str(_find_free_port() if port in (None, 0) else port)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def pad(
|
| 117 |
+
tensors: list[torch.Tensor],
|
| 118 |
+
padding_value: int = 0,
|
| 119 |
+
padding_side: str = "right",
|
| 120 |
+
pad_to_multiple_of: int | None = None,
|
| 121 |
+
) -> torch.Tensor:
|
| 122 |
+
"""
|
| 123 |
+
Pads a list of tensors to the same shape along the first dimension.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
tensors (`list[torch.Tensor]`):
|
| 127 |
+
List of input tensors to pad.
|
| 128 |
+
padding_value (`int`):
|
| 129 |
+
Value to use for padding. Default is 0.
|
| 130 |
+
padding_side (`str`):
|
| 131 |
+
Side on which to add padding. Must be 'left' or 'right'. Default is 'right'.
|
| 132 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 133 |
+
If set will pad the sequence to a multiple of the provided value.
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
`torch.Tensor`:
|
| 137 |
+
A single tensor containing the padded tensors.
|
| 138 |
+
|
| 139 |
+
Examples:
|
| 140 |
+
```python
|
| 141 |
+
>>> import torch
|
| 142 |
+
|
| 143 |
+
>>> pad([torch.tensor([1, 2, 3]), torch.tensor([4, 5])])
|
| 144 |
+
tensor([[1, 2, 3],
|
| 145 |
+
[4, 5, 0]])
|
| 146 |
+
|
| 147 |
+
>>> pad([torch.tensor([[1, 2], [3, 4]]), torch.tensor([[5, 6]])])
|
| 148 |
+
tensor([[[1, 2],
|
| 149 |
+
[3, 4]],
|
| 150 |
+
[[5, 6],
|
| 151 |
+
[0, 0]]])
|
| 152 |
+
```
|
| 153 |
+
"""
|
| 154 |
+
# Determine the maximum shape for each dimension
|
| 155 |
+
output_shape = np.max([t.shape for t in tensors], 0).tolist()
|
| 156 |
+
|
| 157 |
+
# Apply pad_to_multiple_of to the first (sequence) dimension
|
| 158 |
+
if pad_to_multiple_of is not None:
|
| 159 |
+
remainder = output_shape[0] % pad_to_multiple_of
|
| 160 |
+
if remainder != 0:
|
| 161 |
+
output_shape[0] += pad_to_multiple_of - remainder
|
| 162 |
+
|
| 163 |
+
# Create an output tensor filled with the padding value
|
| 164 |
+
output = torch.full((len(tensors), *output_shape), padding_value, dtype=tensors[0].dtype, device=tensors[0].device)
|
| 165 |
+
|
| 166 |
+
for i, t in enumerate(tensors):
|
| 167 |
+
if padding_side == "left":
|
| 168 |
+
seq_start = output_shape[0] - t.shape[0]
|
| 169 |
+
elif padding_side == "right":
|
| 170 |
+
seq_start = 0
|
| 171 |
+
else:
|
| 172 |
+
raise ValueError("padding_side must be 'left' or 'right'")
|
| 173 |
+
|
| 174 |
+
# Define the slices
|
| 175 |
+
seq_slice = slice(seq_start, seq_start + t.shape[0])
|
| 176 |
+
slices = (seq_slice,) + tuple(slice(0, s) for s in t.shape[1:])
|
| 177 |
+
output[i][slices] = t
|
| 178 |
+
|
| 179 |
+
return output
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def disable_dropout_in_model(model: torch.nn.Module) -> None:
|
| 183 |
+
for module in model.modules():
|
| 184 |
+
if isinstance(module, torch.nn.Dropout):
|
| 185 |
+
module.p = 0
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def get_quantization_config(model_args: ModelConfig) -> BitsAndBytesConfig | None:
|
| 189 |
+
if model_args.load_in_4bit:
|
| 190 |
+
quantization_config = BitsAndBytesConfig(
|
| 191 |
+
load_in_4bit=True,
|
| 192 |
+
bnb_4bit_compute_dtype=model_args.dtype, # For consistency with model weights, we use the same value as `dtype`
|
| 193 |
+
bnb_4bit_quant_type=model_args.bnb_4bit_quant_type,
|
| 194 |
+
bnb_4bit_use_double_quant=model_args.use_bnb_nested_quant,
|
| 195 |
+
bnb_4bit_quant_storage=model_args.bnb_4bit_quant_storage,
|
| 196 |
+
)
|
| 197 |
+
elif model_args.load_in_8bit:
|
| 198 |
+
quantization_config = BitsAndBytesConfig(
|
| 199 |
+
load_in_8bit=True,
|
| 200 |
+
)
|
| 201 |
+
else:
|
| 202 |
+
quantization_config = None
|
| 203 |
+
|
| 204 |
+
return quantization_config
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def get_kbit_device_map() -> dict[str, int] | None:
|
| 208 |
+
if torch.cuda.is_available() or is_torch_xpu_available():
|
| 209 |
+
return {"": PartialState().local_process_index}
|
| 210 |
+
else:
|
| 211 |
+
return None
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def get_peft_config(model_args: ModelConfig) -> "PeftConfig | None":
|
| 215 |
+
if model_args.use_peft is False:
|
| 216 |
+
return None
|
| 217 |
+
|
| 218 |
+
if not is_peft_available():
|
| 219 |
+
raise ValueError(
|
| 220 |
+
"You need to have PEFT library installed in your environment, make sure to install `peft`. "
|
| 221 |
+
"Make sure to run `pip install -U peft`."
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
peft_config = LoraConfig(
|
| 225 |
+
task_type=model_args.lora_task_type,
|
| 226 |
+
r=model_args.lora_r,
|
| 227 |
+
target_modules=model_args.lora_target_modules,
|
| 228 |
+
target_parameters=model_args.lora_target_parameters,
|
| 229 |
+
lora_alpha=model_args.lora_alpha,
|
| 230 |
+
lora_dropout=model_args.lora_dropout,
|
| 231 |
+
bias="none",
|
| 232 |
+
use_rslora=model_args.use_rslora,
|
| 233 |
+
use_dora=model_args.use_dora,
|
| 234 |
+
modules_to_save=model_args.lora_modules_to_save,
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
return peft_config
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def generate_model_card(
|
| 241 |
+
base_model: str | None,
|
| 242 |
+
model_name: str,
|
| 243 |
+
hub_model_id: str,
|
| 244 |
+
dataset_name: str | None,
|
| 245 |
+
tags: list[str],
|
| 246 |
+
wandb_url: str | None,
|
| 247 |
+
trackio_url: str | None,
|
| 248 |
+
trainer_name: str,
|
| 249 |
+
trainer_citation: str | None = None,
|
| 250 |
+
template_file: str | None = None,
|
| 251 |
+
paper_title: str | None = None,
|
| 252 |
+
paper_id: str | None = None,
|
| 253 |
+
comet_url: str | None = None,
|
| 254 |
+
) -> ModelCard:
|
| 255 |
+
"""
|
| 256 |
+
Generate a [`~huggingface_hub.ModelCard`] from a template.
|
| 257 |
+
|
| 258 |
+
Args:
|
| 259 |
+
base_model (`str` or `None`):
|
| 260 |
+
Base model name.
|
| 261 |
+
model_name (`str`):
|
| 262 |
+
Model name.
|
| 263 |
+
hub_model_id (`str`):
|
| 264 |
+
Hub model ID as `username/model_id`.
|
| 265 |
+
dataset_name (`str` or `None`):
|
| 266 |
+
Dataset name.
|
| 267 |
+
tags (`list[str]`):
|
| 268 |
+
Tags.
|
| 269 |
+
wandb_url (`str` or `None`):
|
| 270 |
+
Weights & Biases run URL.
|
| 271 |
+
trackio_url (`str` or `None`):
|
| 272 |
+
Trackio Space URL.
|
| 273 |
+
comet_url (`str` or `None`):
|
| 274 |
+
Comet experiment URL.
|
| 275 |
+
trainer_name (`str`):
|
| 276 |
+
Trainer name.
|
| 277 |
+
trainer_citation (`str` or `None`, defaults to `None`):
|
| 278 |
+
Trainer citation as a BibTeX entry.
|
| 279 |
+
template_file (`str` *optional*):
|
| 280 |
+
Template file name located in the `trl/templates` directory. Defaults to `lm_model_card.md`.
|
| 281 |
+
paper_title (`str` or `None`, defaults to `None`):
|
| 282 |
+
Paper title.
|
| 283 |
+
paper_id (`str` or `None`, defaults to `None`):
|
| 284 |
+
ArXiv paper ID as `YYMM.NNNNN`.
|
| 285 |
+
|
| 286 |
+
Returns:
|
| 287 |
+
[`~huggingface_hub.ModelCard`]:
|
| 288 |
+
A ModelCard object.
|
| 289 |
+
"""
|
| 290 |
+
card_data = ModelCardData(
|
| 291 |
+
base_model=base_model,
|
| 292 |
+
datasets=dataset_name,
|
| 293 |
+
library_name="transformers",
|
| 294 |
+
licence="license",
|
| 295 |
+
model_name=model_name,
|
| 296 |
+
tags=["generated_from_trainer", *tags],
|
| 297 |
+
)
|
| 298 |
+
template_file = template_file or "lm_model_card.md"
|
| 299 |
+
card = ModelCard.from_template(
|
| 300 |
+
card_data,
|
| 301 |
+
template_path=str(pkg_resources.files("trl").joinpath(f"templates/{template_file}")),
|
| 302 |
+
base_model=base_model,
|
| 303 |
+
model_name=model_name,
|
| 304 |
+
hub_model_id=hub_model_id,
|
| 305 |
+
dataset_name=dataset_name,
|
| 306 |
+
wandb_url=wandb_url,
|
| 307 |
+
trackio_url=trackio_url,
|
| 308 |
+
comet_url=comet_url,
|
| 309 |
+
trainer_name=trainer_name,
|
| 310 |
+
trainer_citation=trainer_citation,
|
| 311 |
+
paper_title=paper_title,
|
| 312 |
+
paper_id=paper_id,
|
| 313 |
+
trl_version=version("trl"),
|
| 314 |
+
transformers_version=version("transformers"),
|
| 315 |
+
pytorch_version=version("torch"),
|
| 316 |
+
datasets_version=version("datasets"),
|
| 317 |
+
tokenizers_version=version("tokenizers"),
|
| 318 |
+
)
|
| 319 |
+
return card
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def get_comet_experiment_url() -> str | None:
|
| 323 |
+
"""
|
| 324 |
+
If Comet integration is enabled, return the URL of the current Comet experiment; otherwise, return `None`.
|
| 325 |
+
"""
|
| 326 |
+
if not is_comet_available():
|
| 327 |
+
return None
|
| 328 |
+
|
| 329 |
+
if comet_ml.get_running_experiment() is not None:
|
| 330 |
+
return comet_ml.get_running_experiment().url
|
| 331 |
+
|
| 332 |
+
return None
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def get_trackio_space_url() -> str | None:
|
| 336 |
+
"""
|
| 337 |
+
If Trackio integration is enabled, return the URL of the current Trackio Space; otherwise, return `None`.
|
| 338 |
+
"""
|
| 339 |
+
if not is_trackio_available():
|
| 340 |
+
return None
|
| 341 |
+
|
| 342 |
+
from trackio import context_vars
|
| 343 |
+
|
| 344 |
+
run = context_vars.current_run.get()
|
| 345 |
+
if run is None:
|
| 346 |
+
return None
|
| 347 |
+
space_id = run._space_id
|
| 348 |
+
if space_id is None:
|
| 349 |
+
return None
|
| 350 |
+
space_id = space_id.replace("/", "-")
|
| 351 |
+
project = run.project
|
| 352 |
+
name = run.name
|
| 353 |
+
return f"https://{space_id}.hf.space?project={project}&runs={name}&sidebar=collapsed"
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def log_table_to_comet_experiment(name: str, table: pd.DataFrame) -> None:
|
| 357 |
+
"""
|
| 358 |
+
If Comet integration is enabled logs a table to the Comet experiment if it is currently running.
|
| 359 |
+
|
| 360 |
+
Args:
|
| 361 |
+
name (`str`):
|
| 362 |
+
Table name.
|
| 363 |
+
table (`pandas.DataFrame`):
|
| 364 |
+
The Pandas DataFrame containing the table to log.
|
| 365 |
+
"""
|
| 366 |
+
if not is_comet_available():
|
| 367 |
+
raise ModuleNotFoundError("The comet-ml is not installed. Please install it first: pip install comet-ml")
|
| 368 |
+
|
| 369 |
+
experiment = comet_ml.get_running_experiment()
|
| 370 |
+
if experiment is not None:
|
| 371 |
+
experiment.log_table(tabular_data=table, filename=name)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def flush_left(mask: torch.Tensor, *tensors: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, ...]:
|
| 375 |
+
"""
|
| 376 |
+
Shift non-zero elements in the mask and corresponding tensors to the left.
|
| 377 |
+
|
| 378 |
+
This function operates on a binary mask and any number of additional tensors with the same dimensions as the mask.
|
| 379 |
+
For each row, non-zero values are shifted to the leftmost positions. Then, columns that contain only zeros across
|
| 380 |
+
all rows are truncated from the mask and tensors. Visually, this operation can be represented as follows:
|
| 381 |
+
|
| 382 |
+
```
|
| 383 |
+
[[0, 0, x, x, x, x], -> [[x, x, x, x],
|
| 384 |
+
[0, x, x, x, 0, 0]] [x, x, x, 0]]
|
| 385 |
+
```
|
| 386 |
+
|
| 387 |
+
Args:
|
| 388 |
+
mask (`torch.Tensor`):
|
| 389 |
+
2D tensor (binary mask) with shape `(N, M)`.
|
| 390 |
+
*tensors (`torch.Tensor`):
|
| 391 |
+
One or more 2D tensors with the same shape as `mask`. These tensors will be processed alongside `mask`,
|
| 392 |
+
with non-zero values shifted and excess zero columns truncated in the same manner.
|
| 393 |
+
|
| 394 |
+
Returns:
|
| 395 |
+
`torch.Tensor`:
|
| 396 |
+
Updated binary mask with non-zero values flushed to the left and trailing zero columns removed.
|
| 397 |
+
`*torch.Tensor`
|
| 398 |
+
Updated tensors, processed in the same way as the mask.
|
| 399 |
+
|
| 400 |
+
Example:
|
| 401 |
+
```python
|
| 402 |
+
>>> mask = torch.tensor([[0, 0, 1, 1, 1], [0, 1, 1, 0, 0]])
|
| 403 |
+
>>> tensor = torch.tensor([[9, 9, 2, 3, 4], [9, 5, 6, 9, 9]])
|
| 404 |
+
>>> new_mask, new_tensor = flush_left(mask, tensor)
|
| 405 |
+
>>> print(new_mask)
|
| 406 |
+
tensor([[1, 1, 1],
|
| 407 |
+
[1, 1, 0]])
|
| 408 |
+
|
| 409 |
+
>>> print(new_tensor)
|
| 410 |
+
tensor([[2, 3, 4],
|
| 411 |
+
[5, 6, 0]])
|
| 412 |
+
```
|
| 413 |
+
"""
|
| 414 |
+
_, M = mask.shape
|
| 415 |
+
|
| 416 |
+
# Create copy of mask and tensors
|
| 417 |
+
mask_copy = mask.clone()
|
| 418 |
+
tensors = [t.clone() for t in tensors]
|
| 419 |
+
|
| 420 |
+
# Shift non-zero values to the left
|
| 421 |
+
first_non_zero = mask_copy.argmax(dim=1)
|
| 422 |
+
pos = torch.arange(M, device=mask_copy.device).unsqueeze(0)
|
| 423 |
+
idx_roll = (pos + first_non_zero.unsqueeze(1)) % M
|
| 424 |
+
mask_roll = mask_copy.gather(1, idx_roll)
|
| 425 |
+
rolled_tensors = [t.gather(1, idx_roll) for t in tensors]
|
| 426 |
+
|
| 427 |
+
# Truncate trailing columns that are all zeros in mask_roll
|
| 428 |
+
col_sums = mask_roll.sum(dim=0)
|
| 429 |
+
empty_cols = col_sums == 0
|
| 430 |
+
first_empty_col = int(empty_cols.to(torch.int8).argmax()) if empty_cols.any() else M
|
| 431 |
+
flushed_mask = mask_roll[:, :first_empty_col]
|
| 432 |
+
flushed_tensors = [t[:, :first_empty_col] for t in rolled_tensors]
|
| 433 |
+
|
| 434 |
+
if not flushed_tensors:
|
| 435 |
+
return flushed_mask
|
| 436 |
+
return flushed_mask, *flushed_tensors
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def selective_log_softmax(logits, index) -> torch.Tensor:
|
| 440 |
+
"""
|
| 441 |
+
A memory-efficient implementation of the common `log_softmax -> gather` operation.
|
| 442 |
+
|
| 443 |
+
This function is equivalent to the following naive implementation:
|
| 444 |
+
```python
|
| 445 |
+
# for index with shape (...):
|
| 446 |
+
logps = torch.gather(logits.log_softmax(-1), dim=-1, index=index.unsqueeze(-1)).squeeze(-1)
|
| 447 |
+
# for index with shape (..., K):
|
| 448 |
+
logps = torch.gather(logits.log_softmax(-1), dim=-1, index=index)
|
| 449 |
+
```
|
| 450 |
+
|
| 451 |
+
Args:
|
| 452 |
+
logits (`torch.Tensor`):
|
| 453 |
+
Logits tensor of shape `(..., num_classes)`.
|
| 454 |
+
index (`torch.Tensor`):
|
| 455 |
+
Index tensor of shape `(..., K)` or `(...)`, specifying the positions to gather from the log-softmax
|
| 456 |
+
output. When the last case is used, `K` log-probabilities are gathered per position (e.g. for top-K)
|
| 457 |
+
|
| 458 |
+
Returns:
|
| 459 |
+
`torch.Tensor`:
|
| 460 |
+
Gathered log probabilities with the same shape as `index`.
|
| 461 |
+
"""
|
| 462 |
+
squeeze = index.ndim == logits.ndim - 1
|
| 463 |
+
if squeeze:
|
| 464 |
+
index = index.unsqueeze(-1)
|
| 465 |
+
|
| 466 |
+
if logits.dtype in [torch.float32, torch.float64]:
|
| 467 |
+
selected_logits = torch.gather(logits, dim=-1, index=index)
|
| 468 |
+
# loop to reduce peak mem consumption
|
| 469 |
+
logsumexp_values = torch.stack([torch.logsumexp(lg, dim=-1) for lg in logits])
|
| 470 |
+
per_token_logps = selected_logits - logsumexp_values.unsqueeze(-1) # log_softmax(x_i) = x_i - logsumexp(x)
|
| 471 |
+
else:
|
| 472 |
+
# logsumexp approach is unstable with bfloat16, fall back to slightly less efficient approach
|
| 473 |
+
per_token_logps = []
|
| 474 |
+
for row_logits, row_labels in zip(logits, index, strict=True): # loop to reduce peak mem consumption
|
| 475 |
+
row_logps = F.log_softmax(row_logits, dim=-1)
|
| 476 |
+
row_per_token_logps = row_logps.gather(dim=-1, index=row_labels)
|
| 477 |
+
per_token_logps.append(row_per_token_logps)
|
| 478 |
+
per_token_logps = torch.stack(per_token_logps)
|
| 479 |
+
|
| 480 |
+
if squeeze:
|
| 481 |
+
per_token_logps = per_token_logps.squeeze(-1)
|
| 482 |
+
|
| 483 |
+
return per_token_logps
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def entropy_from_logits(logits: torch.Tensor, chunk_size: int = 128) -> torch.Tensor:
|
| 487 |
+
"""
|
| 488 |
+
Compute the Shannon entropy (in nats) for each row of *logits* in a memory-efficient way.
|
| 489 |
+
|
| 490 |
+
Instead of materializing the full softmax for all rows at once, the logits are flattened to shape (N, num_classes),
|
| 491 |
+
where N is the product of all leading dimensions. Computation is then performed in chunks of size `chunk_size`
|
| 492 |
+
along this flattened dimension, reducing peak memory usage. The result is reshaped back to match the input's
|
| 493 |
+
leading dimensions.
|
| 494 |
+
|
| 495 |
+
Args:
|
| 496 |
+
logits (`torch.Tensor`):
|
| 497 |
+
Logits tensor of shape `(..., num_classes)`. Entropy is taken along the last axis; all leading dimensions
|
| 498 |
+
are preserved in the output.
|
| 499 |
+
chunk_size (`int`, *optional*, defaults to `128`):
|
| 500 |
+
Number of rows from the flattened logits to process per iteration. Smaller values reduce memory usage at
|
| 501 |
+
the cost of more iterations.
|
| 502 |
+
|
| 503 |
+
Returns:
|
| 504 |
+
`torch.Tensor`:
|
| 505 |
+
Entropy values with shape `logits.shape[:-1]`.
|
| 506 |
+
"""
|
| 507 |
+
original_shape = logits.shape[:-1] # all dims except num_classes
|
| 508 |
+
num_classes = logits.shape[-1]
|
| 509 |
+
|
| 510 |
+
# Flatten all leading dimensions into one
|
| 511 |
+
flat_logits = logits.reshape(-1, num_classes)
|
| 512 |
+
|
| 513 |
+
entropies = []
|
| 514 |
+
for chunk in flat_logits.split(chunk_size, dim=0):
|
| 515 |
+
logps = F.log_softmax(chunk, dim=-1)
|
| 516 |
+
chunk_entropy = -(torch.exp(logps) * logps).sum(-1)
|
| 517 |
+
entropies.append(chunk_entropy)
|
| 518 |
+
|
| 519 |
+
entropies = torch.cat(entropies, dim=0)
|
| 520 |
+
return entropies.reshape(original_shape)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def print_prompt_completions_sample(
|
| 524 |
+
prompts: list,
|
| 525 |
+
completions: list,
|
| 526 |
+
rewards: dict[str, list[float]],
|
| 527 |
+
advantages: list[float],
|
| 528 |
+
step: int,
|
| 529 |
+
num_samples: int = None,
|
| 530 |
+
extra: dict[str, list] | None = None,
|
| 531 |
+
) -> None:
|
| 532 |
+
"""
|
| 533 |
+
Print out a sample of model completions to the console with multiple reward metrics.
|
| 534 |
+
|
| 535 |
+
This function creates a nicely formatted table showing prompt-completion pairs, useful for monitoring model outputs
|
| 536 |
+
during training. It requires the `rich` library to be installed.
|
| 537 |
+
|
| 538 |
+
Args:
|
| 539 |
+
prompts (`list`):
|
| 540 |
+
List of prompts. Can be either strings or lists of messages.
|
| 541 |
+
completions (`list`):
|
| 542 |
+
List of completions corresponding to the prompts. Can be either strings or lists of messages.
|
| 543 |
+
rewards (`dict[str, list[float]]`):
|
| 544 |
+
Dictionary where keys are reward names and values are lists of rewards.
|
| 545 |
+
advantages (`list[float]`):
|
| 546 |
+
List of advantages corresponding to the prompts and completions.
|
| 547 |
+
step (`int`):
|
| 548 |
+
Current training step number, used in the output title.
|
| 549 |
+
num_samples (`int`, *optional*):
|
| 550 |
+
Number of random samples to display. If `None` (default), all items will be displayed.
|
| 551 |
+
extra (`dict[str, list]`, *optional*):
|
| 552 |
+
Additional columns to display after the advantage column. Keys are column names and values are lists of
|
| 553 |
+
per-completion data (strings or any value convertible to string). Typically populated via `log_extra` in
|
| 554 |
+
reward functions. If `None` (default), no extra columns are shown.
|
| 555 |
+
|
| 556 |
+
Example:
|
| 557 |
+
```python
|
| 558 |
+
>>> from trl.trainer.utils import print_prompt_completions_sample
|
| 559 |
+
|
| 560 |
+
>>> prompts = ["The sky is", "The sun is"]
|
| 561 |
+
>>> completions = [" blue.", " in the sky."]
|
| 562 |
+
>>> rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]}
|
| 563 |
+
>>> advantages = [0.987, 0.654]
|
| 564 |
+
>>> extra = {"source": ["dataset_A", "dataset_B"]}
|
| 565 |
+
>>> print_prompt_completions_sample(prompts, completions, rewards, advantages, 42, extra=extra)
|
| 566 |
+
╭────────────────────────────────── Step 42 ───────────────────────────────────╮
|
| 567 |
+
│ ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┓ │
|
| 568 |
+
│ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ source ┃ │
|
| 569 |
+
│ ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━┩ │
|
| 570 |
+
│ │ The sky is │ blue. │ 0.12 │ 0.79 │ 0.99 │ dataset_A │ │
|
| 571 |
+
│ ├────────────┼──────────────┼─────────────┼────────┼───────────┼───────────┤ │
|
| 572 |
+
│ │ The sun is │ in the sky. │ 0.46 │ 0.10 │ 0.65 │ dataset_B │ │
|
| 573 |
+
│ └────────────┴──────────────┴─────────────┴────────┴───────────┴───────────┘ │
|
| 574 |
+
╰──────────────────────────────────────────────────────────────────────────────╯
|
| 575 |
+
```
|
| 576 |
+
"""
|
| 577 |
+
if not is_rich_available():
|
| 578 |
+
raise ImportError(
|
| 579 |
+
"The function `print_prompt_completions_sample` requires the `rich` library. Please install it with "
|
| 580 |
+
"`pip install rich`."
|
| 581 |
+
)
|
| 582 |
+
console = Console()
|
| 583 |
+
table = Table(show_header=True, header_style="bold white", expand=True)
|
| 584 |
+
|
| 585 |
+
extra = extra or {}
|
| 586 |
+
|
| 587 |
+
# Add columns
|
| 588 |
+
table.add_column("Prompt", style="bright_yellow")
|
| 589 |
+
table.add_column("Completion", style="bright_green")
|
| 590 |
+
for reward_name in rewards.keys():
|
| 591 |
+
table.add_column(reward_name, style="bold cyan", justify="right")
|
| 592 |
+
table.add_column("Advantage", style="bold magenta", justify="right")
|
| 593 |
+
for extra_name in extra.keys():
|
| 594 |
+
table.add_column(extra_name, style="bright_white")
|
| 595 |
+
|
| 596 |
+
def format_entry(entry) -> Text:
|
| 597 |
+
t = Text()
|
| 598 |
+
if isinstance(entry, list) and all(isinstance(m, dict) for m in entry):
|
| 599 |
+
for j, msg in enumerate(entry):
|
| 600 |
+
role = msg.get("role", "")
|
| 601 |
+
if "content" in msg or "reasoning_content" in msg or "thinking" in msg:
|
| 602 |
+
# Chat message
|
| 603 |
+
t.append(f"{role.upper()}\n", style="bold red")
|
| 604 |
+
reasoning = msg.get("reasoning_content") or msg.get("thinking")
|
| 605 |
+
if reasoning:
|
| 606 |
+
t.append(reasoning, style="italic dim white")
|
| 607 |
+
t.append("\n")
|
| 608 |
+
if "content" in msg:
|
| 609 |
+
t.append(msg["content"])
|
| 610 |
+
elif "name" in msg and "args" in msg:
|
| 611 |
+
# Tool call
|
| 612 |
+
t.append(f"{role.upper()}\n", style="bold red")
|
| 613 |
+
t.append(f"{msg['name']}({msg['args']})")
|
| 614 |
+
else:
|
| 615 |
+
# Fallback
|
| 616 |
+
t.append(str(msg))
|
| 617 |
+
if j < len(entry) - 1:
|
| 618 |
+
t.append("\n\n")
|
| 619 |
+
else:
|
| 620 |
+
t.append(str(entry))
|
| 621 |
+
return t
|
| 622 |
+
|
| 623 |
+
# Some basic input validation
|
| 624 |
+
if num_samples is not None:
|
| 625 |
+
if num_samples >= len(prompts):
|
| 626 |
+
num_samples = None
|
| 627 |
+
elif num_samples <= 0:
|
| 628 |
+
return
|
| 629 |
+
|
| 630 |
+
# Subsample data if num_samples is specified
|
| 631 |
+
if num_samples is not None:
|
| 632 |
+
indices = random.sample(range(len(prompts)), num_samples)
|
| 633 |
+
prompts = [prompts[i] for i in indices]
|
| 634 |
+
completions = [completions[i] for i in indices]
|
| 635 |
+
rewards = {key: [val[i] for i in indices] for key, val in rewards.items()}
|
| 636 |
+
advantages = [advantages[i] for i in indices]
|
| 637 |
+
extra = {key: [val[i] for i in indices] for key, val in extra.items()}
|
| 638 |
+
|
| 639 |
+
for i in range(len(prompts)):
|
| 640 |
+
reward_values = [f"{rewards[key][i]:.2f}" for key in rewards.keys()] # 2 decimals
|
| 641 |
+
extra_values = [format_entry(extra[key][i]) for key in extra.keys()]
|
| 642 |
+
table.add_row(
|
| 643 |
+
format_entry(prompts[i]),
|
| 644 |
+
format_entry(completions[i]),
|
| 645 |
+
*reward_values,
|
| 646 |
+
f"{advantages[i]:.2f}",
|
| 647 |
+
*extra_values,
|
| 648 |
+
)
|
| 649 |
+
table.add_section() # Adds a separator between rows
|
| 650 |
+
|
| 651 |
+
panel = Panel(table, expand=False, title=f"Step {step}", border_style="bold white")
|
| 652 |
+
console.print(panel)
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
class RepeatSampler(Sampler):
|
| 656 |
+
"""
|
| 657 |
+
Sampler that repeats the indices of a dataset in a structured manner.
|
| 658 |
+
|
| 659 |
+
Args:
|
| 660 |
+
data_source (`Sized`):
|
| 661 |
+
Dataset to sample from.
|
| 662 |
+
mini_repeat_count (`int`):
|
| 663 |
+
Number of times to repeat each index per batch.
|
| 664 |
+
batch_size (`int`, *optional*, defaults to `1`):
|
| 665 |
+
Number of unique indices per batch.
|
| 666 |
+
repeat_count (`int`, *optional*, defaults to `1`):
|
| 667 |
+
Number of times to repeat the full sampling process.
|
| 668 |
+
shuffle (`bool`, *optional*, defaults to `True`):
|
| 669 |
+
Whether to shuffle the dataset.
|
| 670 |
+
seed (`int`, *optional*):
|
| 671 |
+
Random seed for reproducibility (only affects this sampler).
|
| 672 |
+
|
| 673 |
+
Example:
|
| 674 |
+
```python
|
| 675 |
+
>>> sampler = RepeatSampler(["a", "b", "c", "d", "e", "f", "g"], mini_repeat_count=2, batch_size=3, repeat_count=4)
|
| 676 |
+
>>> list(sampler)
|
| 677 |
+
[4, 4, 3, 3, 0, 0,
|
| 678 |
+
4, 4, 3, 3, 0, 0,
|
| 679 |
+
4, 4, 3, 3, 0, 0,
|
| 680 |
+
4, 4, 3, 3, 0, 0,
|
| 681 |
+
1, 1, 2, 2, 6, 6,
|
| 682 |
+
1, 1, 2, 2, 6, 6,
|
| 683 |
+
1, 1, 2, 2, 6, 6,
|
| 684 |
+
1, 1, 2, 2, 6, 6]
|
| 685 |
+
```
|
| 686 |
+
|
| 687 |
+
```txt
|
| 688 |
+
mini_repeat_count = 3
|
| 689 |
+
- - -
|
| 690 |
+
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, |
|
| 691 |
+
4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, |
|
| 692 |
+
8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, |
|
| 693 |
+
repeat_count = 2
|
| 694 |
+
0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, |
|
| 695 |
+
4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, |
|
| 696 |
+
8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, ...] |
|
| 697 |
+
--------- --------- --------- ---------
|
| 698 |
+
--------- --------- --------- ---------
|
| 699 |
+
--------- --------- --------- ---------
|
| 700 |
+
batch_size = 12
|
| 701 |
+
```
|
| 702 |
+
"""
|
| 703 |
+
|
| 704 |
+
def __init__(
|
| 705 |
+
self,
|
| 706 |
+
data_source: Sized,
|
| 707 |
+
mini_repeat_count: int,
|
| 708 |
+
batch_size: int = 1,
|
| 709 |
+
repeat_count: int = 1,
|
| 710 |
+
shuffle: bool = True,
|
| 711 |
+
seed: int | None = None,
|
| 712 |
+
):
|
| 713 |
+
self.data_source = data_source
|
| 714 |
+
self.mini_repeat_count = mini_repeat_count
|
| 715 |
+
self.batch_size = batch_size
|
| 716 |
+
self.repeat_count = repeat_count
|
| 717 |
+
self.num_samples = len(data_source)
|
| 718 |
+
self.shuffle = shuffle
|
| 719 |
+
self.seed = seed
|
| 720 |
+
|
| 721 |
+
if shuffle:
|
| 722 |
+
self.generator = torch.Generator() # Create a local random generator
|
| 723 |
+
if seed is not None:
|
| 724 |
+
self.generator.manual_seed(seed)
|
| 725 |
+
|
| 726 |
+
def __iter__(self):
|
| 727 |
+
if self.shuffle:
|
| 728 |
+
# E.g., [2, 4, 3, 1, 0, 6, 5] (num_samples = 7)
|
| 729 |
+
indexes = torch.randperm(self.num_samples, generator=self.generator).tolist()
|
| 730 |
+
else:
|
| 731 |
+
indexes = list(range(self.num_samples))
|
| 732 |
+
|
| 733 |
+
# [2, 4, 3, 1, 0, 6, 5]
|
| 734 |
+
# -> [[2, 4, 3], [1, 0, 6], [5]] (batch_size = 3)
|
| 735 |
+
indexes = [indexes[i : i + self.batch_size] for i in range(0, len(indexes), self.batch_size)]
|
| 736 |
+
|
| 737 |
+
# [[2, 4, 3], [1, 0, 6], [5]]
|
| 738 |
+
# -> [[2, 4, 3], [1, 0, 6]]
|
| 739 |
+
indexes = [chunk for chunk in indexes if len(chunk) == self.batch_size]
|
| 740 |
+
|
| 741 |
+
for chunk in indexes:
|
| 742 |
+
for _ in range(self.repeat_count):
|
| 743 |
+
for index in chunk:
|
| 744 |
+
for _ in range(self.mini_repeat_count):
|
| 745 |
+
yield index
|
| 746 |
+
|
| 747 |
+
def __len__(self) -> int:
|
| 748 |
+
return (self.num_samples // self.batch_size) * self.batch_size * self.mini_repeat_count * self.repeat_count
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
# torch.nanstd doesn't exist, so we define it here
|
| 752 |
+
def nanstd(tensor: torch.Tensor, dim: int | tuple[int, ...] | None = None, keepdim: bool = False) -> torch.Tensor:
|
| 753 |
+
"""
|
| 754 |
+
Compute the standard deviation of a tensor, ignoring NaNs.
|
| 755 |
+
|
| 756 |
+
Args:
|
| 757 |
+
tensor (`torch.Tensor`):
|
| 758 |
+
Input tensor.
|
| 759 |
+
dim (`int` or `tuple[int, ...]`, *optional*):
|
| 760 |
+
Dimension(s) to reduce. Defaults to all dimensions.
|
| 761 |
+
keepdim (`bool`, *optional*, defaults to `False`):
|
| 762 |
+
Whether to keep reduced dimensions.
|
| 763 |
+
|
| 764 |
+
Returns:
|
| 765 |
+
`torch.Tensor`:
|
| 766 |
+
Standard deviation of the tensor, ignoring NaNs.
|
| 767 |
+
"""
|
| 768 |
+
# Compute variance ignoring NaNs
|
| 769 |
+
mean = torch.nanmean(tensor, dim=dim, keepdim=True)
|
| 770 |
+
variance = torch.nanmean((tensor - mean) ** 2, dim=dim, keepdim=True)
|
| 771 |
+
count = torch.sum(~torch.isnan(tensor), dim=dim, keepdim=True) # count of non-NaN values
|
| 772 |
+
correction = count / (count - 1)
|
| 773 |
+
correction = torch.where(count > 1, correction, torch.full_like(correction, float("nan")))
|
| 774 |
+
variance *= correction # Bessel's correction
|
| 775 |
+
std = torch.sqrt(variance)
|
| 776 |
+
if keepdim:
|
| 777 |
+
return std
|
| 778 |
+
if dim is None:
|
| 779 |
+
return std.squeeze()
|
| 780 |
+
if isinstance(dim, int):
|
| 781 |
+
return std.squeeze(dim)
|
| 782 |
+
dims = [(d if d >= 0 else d + std.ndim) for d in dim]
|
| 783 |
+
for d in sorted(dims, reverse=True):
|
| 784 |
+
std = std.squeeze(d)
|
| 785 |
+
return std
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def split_tensor_dict(
|
| 789 |
+
tensor_dict: dict[str, torch.Tensor | None], num_chunks: int
|
| 790 |
+
) -> list[dict[str, torch.Tensor | None]]:
|
| 791 |
+
"""
|
| 792 |
+
Splits a dictionary of tensors along the first dimension into `num_chunks` equal parts.
|
| 793 |
+
|
| 794 |
+
Example:
|
| 795 |
+
```python
|
| 796 |
+
>>> x = torch.arange(12).reshape(6, 2)
|
| 797 |
+
>>> y = torch.arange(6).reshape(6, 1)
|
| 798 |
+
>>> tensor_dict = {"x": x, "y": y}
|
| 799 |
+
>>> split_tensor_dict(tensor_dict, 3)
|
| 800 |
+
[
|
| 801 |
+
{"x": tensor([[0, 1], [2, 3]]), "y": tensor([[0], [1]])},
|
| 802 |
+
{"x": tensor([[4, 5], [6, 7]]), "y": tensor([[2], [3]])},
|
| 803 |
+
{"x": tensor([[ 8, 9], [10, 11]]), "y": tensor([[4], [5]])}
|
| 804 |
+
]
|
| 805 |
+
```
|
| 806 |
+
"""
|
| 807 |
+
first_tensor = next(tensor for tensor in tensor_dict.values() if tensor is not None)
|
| 808 |
+
chunk_size = first_tensor.shape[0] // num_chunks
|
| 809 |
+
chunks = []
|
| 810 |
+
for i in range(num_chunks):
|
| 811 |
+
chunk_dict = {}
|
| 812 |
+
for key, tensor in tensor_dict.items():
|
| 813 |
+
if tensor is not None and (isinstance(tensor, list) or tensor.ndim > 0):
|
| 814 |
+
chunk_dict[key] = tensor[i * chunk_size : (i + 1) * chunk_size]
|
| 815 |
+
elif tensor is not None and tensor.ndim == 0:
|
| 816 |
+
chunk_dict[key] = tensor
|
| 817 |
+
else:
|
| 818 |
+
chunk_dict[key] = None
|
| 819 |
+
chunks.append(chunk_dict)
|
| 820 |
+
return chunks
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
def shuffle_sequence_dict(seq_dict: dict[str, Sequence | None]) -> dict[str, Sequence | None]:
|
| 824 |
+
"""
|
| 825 |
+
Shuffles all sequence-like values in a dictionary along the first dimension in unison.
|
| 826 |
+
|
| 827 |
+
Example:
|
| 828 |
+
```python
|
| 829 |
+
>>> x = torch.arange(6).reshape(3, 2)
|
| 830 |
+
>>> y = ["a", "b", "c"]
|
| 831 |
+
>>> seq_dict = {"x": x, "y": y}
|
| 832 |
+
>>> shuffle_sequence_dict(seq_dict)
|
| 833 |
+
{'x': tensor([[2, 3],
|
| 834 |
+
[0, 1],
|
| 835 |
+
[4, 5]]),
|
| 836 |
+
'y': ['b', 'a', 'c']}
|
| 837 |
+
```
|
| 838 |
+
"""
|
| 839 |
+
# Determine batch size from the first non-None sequence
|
| 840 |
+
batch_size = len(next(v for v in seq_dict.values() if v is not None))
|
| 841 |
+
permutation = torch.randperm(batch_size)
|
| 842 |
+
|
| 843 |
+
def permute(v: Sequence | None) -> Sequence | None:
|
| 844 |
+
if v is None:
|
| 845 |
+
return None
|
| 846 |
+
if isinstance(v, torch.Tensor) and v.ndim == 0:
|
| 847 |
+
return v
|
| 848 |
+
if isinstance(v, torch.Tensor) and v.ndim >= 1:
|
| 849 |
+
return v[permutation]
|
| 850 |
+
return [v[i] for i in permutation]
|
| 851 |
+
|
| 852 |
+
return {key: permute(val) for key, val in seq_dict.items()}
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def nanmin(tensor: torch.Tensor) -> torch.Tensor:
|
| 856 |
+
"""
|
| 857 |
+
Compute the minimum value of a tensor, ignoring NaNs. This function only supports 1D tensors.
|
| 858 |
+
|
| 859 |
+
Args:
|
| 860 |
+
tensor (`torch.Tensor`): Input tensor of shape `(N,)`.
|
| 861 |
+
|
| 862 |
+
Returns:
|
| 863 |
+
`torch.Tensor`: Minimum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN.
|
| 864 |
+
"""
|
| 865 |
+
if torch.isnan(tensor).all():
|
| 866 |
+
return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device)
|
| 867 |
+
return torch.min(tensor[~torch.isnan(tensor)])
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def nanmax(tensor: torch.Tensor) -> torch.Tensor:
|
| 871 |
+
"""
|
| 872 |
+
Compute the maximum value of a tensor, ignoring NaNs. This function only supports 1D tensors.
|
| 873 |
+
|
| 874 |
+
Args:
|
| 875 |
+
tensor (`torch.Tensor`): Input tensor of shape `(N,)`.
|
| 876 |
+
|
| 877 |
+
Returns:
|
| 878 |
+
`torch.Tensor`: Maximum value of the tensor, ignoring NaNs. Returns NaN if all values are NaN.
|
| 879 |
+
"""
|
| 880 |
+
if torch.isnan(tensor).all():
|
| 881 |
+
return torch.tensor(float("nan"), dtype=tensor.dtype, device=tensor.device)
|
| 882 |
+
return torch.max(tensor[~torch.isnan(tensor)])
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
def identity(x):
|
| 886 |
+
"""Do we really need docs for this?"""
|
| 887 |
+
return x
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
def split_pixel_values_by_grid(batch: dict[str, torch.Tensor]) -> dict[str, torch.Tensor | list[torch.Tensor]]:
|
| 891 |
+
"""
|
| 892 |
+
Splits `batch["pixel_values"]` into a list of tensors, one per sample, based on `batch["num_images"]`.
|
| 893 |
+
|
| 894 |
+
For models with `image_grid_thw` (e.g. Qwen), the grid dimensions determine how many rows of `pixel_values` belong
|
| 895 |
+
to each image. For models with `image_position_ids` instead (e.g. Gemma), `pixel_values` is indexed directly by
|
| 896 |
+
image count.
|
| 897 |
+
"""
|
| 898 |
+
if "pixel_values" not in batch or "num_images" not in batch:
|
| 899 |
+
return batch
|
| 900 |
+
|
| 901 |
+
num_images = batch["num_images"]
|
| 902 |
+
pixel_values = batch["pixel_values"] # [total, feature_dim]
|
| 903 |
+
|
| 904 |
+
if "image_grid_thw" in batch:
|
| 905 |
+
lengths = batch["image_grid_thw"].prod(-1).tolist() # [num_images]
|
| 906 |
+
if sum(lengths) != pixel_values.size(0):
|
| 907 |
+
raise ValueError(
|
| 908 |
+
f"Mismatch: sum(lengths) = {sum(lengths)} != pixel_values.size(0) = {pixel_values.size(0)}"
|
| 909 |
+
)
|
| 910 |
+
|
| 911 |
+
boundaries = [0, *accumulate(num_images)]
|
| 912 |
+
image_grid_thw = batch["image_grid_thw"] # [total, 3]
|
| 913 |
+
sections = [sum(lengths[boundaries[i] : boundaries[i + 1]]) for i in range(len(num_images))]
|
| 914 |
+
split_pixel_values = list(torch.split(pixel_values, sections, dim=0))
|
| 915 |
+
split_image_grid_thw = list(torch.split(image_grid_thw, num_images, dim=0))
|
| 916 |
+
return {**batch, "pixel_values": split_pixel_values, "image_grid_thw": split_image_grid_thw}
|
| 917 |
+
|
| 918 |
+
if "image_position_ids" in batch:
|
| 919 |
+
image_position_ids = batch["image_position_ids"] # [total]
|
| 920 |
+
split_pixel_values = list(torch.split(pixel_values, num_images, dim=0))
|
| 921 |
+
split_image_position_ids = list(torch.split(image_position_ids, num_images, dim=0))
|
| 922 |
+
return {**batch, "pixel_values": split_pixel_values, "image_position_ids": split_image_position_ids}
|
| 923 |
+
|
| 924 |
+
return batch
|
| 925 |
+
|
| 926 |
+
|
| 927 |
+
def unsplit_pixel_values_by_grid(batch: dict[str, torch.Tensor | list[torch.Tensor]]) -> dict[str, torch.Tensor]:
|
| 928 |
+
"""
|
| 929 |
+
Opposite of `split_pixel_values_by_grid`. Merges a list of tensors in `batch["pixel_values"]` back into a single
|
| 930 |
+
tensor along the first dimension.
|
| 931 |
+
"""
|
| 932 |
+
pixel_values = batch.get("pixel_values")
|
| 933 |
+
if isinstance(pixel_values, list):
|
| 934 |
+
merged = torch.cat(pixel_values, dim=0)
|
| 935 |
+
batch = {**batch, "pixel_values": merged}
|
| 936 |
+
|
| 937 |
+
image_grid_thw = batch.get("image_grid_thw")
|
| 938 |
+
if isinstance(image_grid_thw, list):
|
| 939 |
+
merged = torch.cat(image_grid_thw, dim=0)
|
| 940 |
+
batch = {**batch, "image_grid_thw": merged}
|
| 941 |
+
|
| 942 |
+
image_position_ids = batch.get("image_position_ids")
|
| 943 |
+
if isinstance(image_position_ids, list):
|
| 944 |
+
merged = torch.cat(image_position_ids, dim=0)
|
| 945 |
+
batch = {**batch, "image_position_ids": merged}
|
| 946 |
+
|
| 947 |
+
return batch
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
TListOrMapping = TypeVar("TListOrMapping", list, Mapping)
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
# This function is intentionally not used internally. It is provided as a utility for users whose datasets contain
|
| 954 |
+
# `None` values inserted by tabular backends (e.g., Arrow/Parquet) for missing keys in nested structures. This
|
| 955 |
+
# situation arises when loading datasets created before `datasets` v4.7.0 (which introduced the Json dtype), or when
|
| 956 |
+
# datasets created after that version were saved without using the Json feature. In both cases, users can apply this
|
| 957 |
+
# function via `dataset = dataset.with_transform(remove_none_values)` before training to strip the spurious `None`
|
| 958 |
+
# values. See the migration guide for more details.
|
| 959 |
+
def remove_none_values(example: TListOrMapping) -> TListOrMapping:
|
| 960 |
+
"""
|
| 961 |
+
Recursively removes entries with `None` values from a nested structure (list or dictionary).
|
| 962 |
+
|
| 963 |
+
Args:
|
| 964 |
+
example (`list` or `Mapping`):
|
| 965 |
+
Input nested structure (list or dictionary) from which to remove `None`.
|
| 966 |
+
|
| 967 |
+
Examples:
|
| 968 |
+
```python
|
| 969 |
+
>>> dataset = dataset.with_transform(remove_none_values)
|
| 970 |
+
```
|
| 971 |
+
```python
|
| 972 |
+
>>> [
|
| 973 |
+
... {
|
| 974 |
+
... "a": {"aa": None, "ab": 1},
|
| 975 |
+
... "b": "my_string",
|
| 976 |
+
... }
|
| 977 |
+
... ]
|
| 978 |
+
>>> remove_none_values(example)
|
| 979 |
+
[{'a': {'ab': 1}, 'b': 'my_string'}]
|
| 980 |
+
```
|
| 981 |
+
"""
|
| 982 |
+
if isinstance(example, list):
|
| 983 |
+
return [remove_none_values(value) if isinstance(value, (dict, list)) else value for value in example]
|
| 984 |
+
elif isinstance(example, Mapping):
|
| 985 |
+
return {
|
| 986 |
+
key: remove_none_values(value) if isinstance(value, (dict, list)) else value
|
| 987 |
+
for key, value in example.items()
|
| 988 |
+
if value is not None
|
| 989 |
+
}
|
| 990 |
+
else:
|
| 991 |
+
raise TypeError("Input must be a list or a dictionary.")
|
| 992 |
+
|
| 993 |
+
|
| 994 |
+
def create_model_from_path(
|
| 995 |
+
model_id: str, architecture: _BaseAutoModelClass | None = None, **kwargs
|
| 996 |
+
) -> PreTrainedModel:
|
| 997 |
+
"""
|
| 998 |
+
Create a model from a given path using the specified initialization arguments.
|
| 999 |
+
|
| 1000 |
+
Args:
|
| 1001 |
+
model_id (`str`):
|
| 1002 |
+
Path to the model. Can be either a local directory or a model identifier from the Hugging Face Hub.
|
| 1003 |
+
architecture (`_BaseAutoModelClass` or `None`, *optional*):
|
| 1004 |
+
Model architecture class to instantiate. The model is initialized using the `from_pretrained` method of
|
| 1005 |
+
this class. If `None`, the architecture will be inferred from the model's configuration.
|
| 1006 |
+
kwargs (`dict`):
|
| 1007 |
+
Initialization keyword arguments to pass to the model's `from_pretrained` method. When `'dtype'` is
|
| 1008 |
+
specified, it can be either a `torch.dtype` or one of the strings: `'bfloat16'`, `'float16'`, `'float32'`,
|
| 1009 |
+
or `'auto'`. If not explicitly set, `dtype` defaults to `'float32'`.
|
| 1010 |
+
|
| 1011 |
+
Returns:
|
| 1012 |
+
[`~transformers.PreTrainedModel`]:
|
| 1013 |
+
The instantiated model.
|
| 1014 |
+
"""
|
| 1015 |
+
dtype = kwargs.get("dtype", "float32")
|
| 1016 |
+
if isinstance(dtype, torch.dtype) or dtype == "auto" or dtype is None:
|
| 1017 |
+
pass # dtype is already a torch.dtype or "auto" or None
|
| 1018 |
+
elif isinstance(dtype, str) and dtype in ["bfloat16", "float16", "float32"]:
|
| 1019 |
+
kwargs["dtype"] = getattr(torch, dtype)
|
| 1020 |
+
else:
|
| 1021 |
+
raise ValueError(
|
| 1022 |
+
"Invalid `dtype` passed to the config. Expected either 'auto' or a string representing "
|
| 1023 |
+
f"a valid `torch.dtype` (e.g., 'float32'), but got {dtype}."
|
| 1024 |
+
)
|
| 1025 |
+
kwargs["device_map"] = kwargs.get("device_map", "auto")
|
| 1026 |
+
if architecture is None:
|
| 1027 |
+
# Best effort to infer architecture from config, but we fall back to AutoModelForCausalLM if we can't find it
|
| 1028 |
+
config = AutoConfig.from_pretrained(model_id, trust_remote_code=kwargs.get("trust_remote_code", False))
|
| 1029 |
+
architecture = getattr(transformers, config.architectures[0], None)
|
| 1030 |
+
if architecture is None:
|
| 1031 |
+
# Remote-code checkpoint: the architecture name lives in the dynamic module, not in
|
| 1032 |
+
# `transformers`. Pick the most specific auto class declared in `config.auto_map`.
|
| 1033 |
+
auto_map = config.auto_map or {}
|
| 1034 |
+
for candidate in (AutoModelForImageTextToText, AutoModelForCausalLM):
|
| 1035 |
+
if candidate.__name__ in auto_map:
|
| 1036 |
+
architecture = candidate
|
| 1037 |
+
break
|
| 1038 |
+
else:
|
| 1039 |
+
architecture = AutoModelForCausalLM
|
| 1040 |
+
model = architecture.from_pretrained(model_id, **kwargs)
|
| 1041 |
+
return model
|
| 1042 |
+
|
| 1043 |
+
|
| 1044 |
+
def hash_module(module: torch.nn.Module) -> str:
|
| 1045 |
+
h = hashlib.sha256()
|
| 1046 |
+
for _, tensor in sorted(module.state_dict().items()):
|
| 1047 |
+
tensor = tensor.cpu()
|
| 1048 |
+
h.update(str(tensor.dtype).encode())
|
| 1049 |
+
if tensor.dtype in [torch.bfloat16, torch.float8_e4m3fn, torch.float8_e5m2]:
|
| 1050 |
+
tensor = tensor.to(torch.float32)
|
| 1051 |
+
h.update(tensor.numpy().tobytes())
|
| 1052 |
+
return h.hexdigest()
|
| 1053 |
+
|
| 1054 |
+
|
| 1055 |
+
def get_config_model_id(config: PretrainedConfig) -> str:
|
| 1056 |
+
"""
|
| 1057 |
+
Retrieve the model identifier from a given model configuration.
|
| 1058 |
+
|
| 1059 |
+
Args:
|
| 1060 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 1061 |
+
Configuration from which to extract the model identifier.
|
| 1062 |
+
|
| 1063 |
+
Returns:
|
| 1064 |
+
`str`:
|
| 1065 |
+
The model identifier associated with the model configuration.
|
| 1066 |
+
"""
|
| 1067 |
+
return getattr(config, "_name_or_path", "")
|
| 1068 |
+
|
| 1069 |
+
|
| 1070 |
+
@contextmanager
|
| 1071 |
+
def use_adapter(model: "PeftModel", adapter_name: str | None):
|
| 1072 |
+
"""
|
| 1073 |
+
Context manager to temporarily set and reset the active adapter in a PEFT model.
|
| 1074 |
+
|
| 1075 |
+
Args:
|
| 1076 |
+
model ([`~peft.PeftModel`]):
|
| 1077 |
+
PEFT model to manage.
|
| 1078 |
+
adapter_name (`str` or `None`):
|
| 1079 |
+
Name of the adapter to set as active. If `None`, the context manager will disable all adapters.
|
| 1080 |
+
|
| 1081 |
+
Example:
|
| 1082 |
+
```python
|
| 1083 |
+
>>> from trl.trainer.utils import use_adapter
|
| 1084 |
+
>>> from peft import AutoPeftModelForCausalLM
|
| 1085 |
+
>>> import torch
|
| 1086 |
+
|
| 1087 |
+
>>> model = AutoPeftModelForCausalLM.from_pretrained("path/to/model")
|
| 1088 |
+
>>> input_ids = torch.tensor([[1, 2, 3]])
|
| 1089 |
+
>>> with use_adapter(model, "adapter_name"):
|
| 1090 |
+
... outputs = model(input_ids)
|
| 1091 |
+
```
|
| 1092 |
+
"""
|
| 1093 |
+
|
| 1094 |
+
if not is_peft_available():
|
| 1095 |
+
raise ImportError(
|
| 1096 |
+
"You're trying to use a PEFT adapter but PEFT is not installed. Please install it with `pip install peft`."
|
| 1097 |
+
)
|
| 1098 |
+
if adapter_name is None:
|
| 1099 |
+
with model.disable_adapter():
|
| 1100 |
+
yield
|
| 1101 |
+
else:
|
| 1102 |
+
previous_adapter = model.active_adapter
|
| 1103 |
+
model.set_adapter(adapter_name)
|
| 1104 |
+
try:
|
| 1105 |
+
yield
|
| 1106 |
+
finally:
|
| 1107 |
+
model.set_adapter(previous_adapter)
|
| 1108 |
+
|
| 1109 |
+
|
| 1110 |
+
def start_event_loop_in_daemon(
|
| 1111 |
+
name: str | None = None,
|
| 1112 |
+
) -> tuple[threading.Thread, asyncio.AbstractEventLoop, threading.Event]:
|
| 1113 |
+
"""
|
| 1114 |
+
This function creates a new daemon thread that runs the provided event loop.
|
| 1115 |
+
|
| 1116 |
+
Args:
|
| 1117 |
+
name (`str`, *optional*):
|
| 1118 |
+
Name of the thread. If `None`, the default thread naming will be used.
|
| 1119 |
+
|
| 1120 |
+
Returns:
|
| 1121 |
+
`threading.Thread`:
|
| 1122 |
+
The thread running the event loop.
|
| 1123 |
+
`asyncio.AbstractEventLoop`:
|
| 1124 |
+
The event loop being run in the thread.
|
| 1125 |
+
`threading.Event`:
|
| 1126 |
+
An event that is set when the loop is ready.
|
| 1127 |
+
"""
|
| 1128 |
+
loop = asyncio.new_event_loop()
|
| 1129 |
+
loop_ready_event = threading.Event()
|
| 1130 |
+
|
| 1131 |
+
def run_loop():
|
| 1132 |
+
asyncio.set_event_loop(loop)
|
| 1133 |
+
loop_ready_event.set()
|
| 1134 |
+
loop.run_forever()
|
| 1135 |
+
|
| 1136 |
+
thread = threading.Thread(target=run_loop, name=name, daemon=True)
|
| 1137 |
+
thread.start()
|
| 1138 |
+
return thread, loop, loop_ready_event
|
| 1139 |
+
|
| 1140 |
+
|
| 1141 |
+
def shutdown_event_loop_in_daemon(
|
| 1142 |
+
thread: threading.Thread | None,
|
| 1143 |
+
loop: asyncio.AbstractEventLoop | None,
|
| 1144 |
+
) -> None:
|
| 1145 |
+
"""
|
| 1146 |
+
Shutdown an asyncio event loop running in a separate thread.
|
| 1147 |
+
|
| 1148 |
+
This function stops the event loop and waits for the associated thread to finish execution.
|
| 1149 |
+
|
| 1150 |
+
Args:
|
| 1151 |
+
thread (`threading.Thread`):
|
| 1152 |
+
The thread running the event loop.
|
| 1153 |
+
loop (`asyncio.AbstractEventLoop`):
|
| 1154 |
+
The asyncio event loop to shut down.
|
| 1155 |
+
"""
|
| 1156 |
+
if loop is None or thread is None:
|
| 1157 |
+
return
|
| 1158 |
+
loop.call_soon_threadsafe(loop.stop)
|
| 1159 |
+
thread.join(timeout=5)
|
| 1160 |
+
|
| 1161 |
+
|
| 1162 |
+
class _ChunkedLogProbFunction(torch.autograd.Function):
|
| 1163 |
+
"""Compute per-token log-probs and entropy without materializing [N, V] logits.
|
| 1164 |
+
|
| 1165 |
+
Processes the lm_head in chunks and uses online logsumexp
|
| 1166 |
+
"""
|
| 1167 |
+
|
| 1168 |
+
@staticmethod
|
| 1169 |
+
def forward(
|
| 1170 |
+
ctx,
|
| 1171 |
+
last_hidden: torch.Tensor, # [N, H]
|
| 1172 |
+
weight: torch.Tensor, # [V, H]
|
| 1173 |
+
targets: torch.Tensor, # [N]
|
| 1174 |
+
temperature: float,
|
| 1175 |
+
chunk_size: int,
|
| 1176 |
+
final_logit_softcapping: float | None = None,
|
| 1177 |
+
logit_scale: float = 1.0,
|
| 1178 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1179 |
+
device = last_hidden.device
|
| 1180 |
+
N, _ = last_hidden.shape
|
| 1181 |
+
vocab, _ = weight.shape
|
| 1182 |
+
inv_t = 1 / temperature
|
| 1183 |
+
|
| 1184 |
+
# NOTE(@aminediro): always acc in fp32 for stability
|
| 1185 |
+
max_old = torch.full((N,), float("-inf"), device=device, dtype=torch.float32)
|
| 1186 |
+
sum_exp = torch.zeros((N,), device=device, dtype=torch.float32)
|
| 1187 |
+
x_sum_exp = torch.zeros((N,), device=device, dtype=torch.float32)
|
| 1188 |
+
target_logit = torch.zeros((N,), device=device, dtype=torch.float32)
|
| 1189 |
+
|
| 1190 |
+
# Pre-allocate reusable buffers to avoid per-chunk allocation
|
| 1191 |
+
mm_buf = torch.empty((N, chunk_size), device=device, dtype=last_hidden.dtype)
|
| 1192 |
+
logits_buf = torch.empty((N, chunk_size), device=device, dtype=torch.float32)
|
| 1193 |
+
|
| 1194 |
+
for start in range(0, vocab, chunk_size):
|
| 1195 |
+
end = min(start + chunk_size, vocab)
|
| 1196 |
+
C = end - start
|
| 1197 |
+
# using fp16=True, the model's hidden states get cast to float16 by autocast, but the mm_buf is allocated
|
| 1198 |
+
# with last_hidden.dtype (float16) while w_chunk (the lm_head weights) is not auto casted
|
| 1199 |
+
w_chunk = weight[start:end].to(last_hidden.dtype) # [C, H]
|
| 1200 |
+
torch.mm(last_hidden, w_chunk.t(), out=mm_buf[:, :C])
|
| 1201 |
+
logits_chunk = logits_buf[:, :C]
|
| 1202 |
+
logits_chunk.copy_(mm_buf[:, :C])
|
| 1203 |
+
|
| 1204 |
+
logits_chunk.mul_(logit_scale)
|
| 1205 |
+
if final_logit_softcapping is not None:
|
| 1206 |
+
logits_chunk.div_(final_logit_softcapping).tanh_().mul_(final_logit_softcapping)
|
| 1207 |
+
|
| 1208 |
+
logits_chunk.mul_(inv_t) # [N, C]
|
| 1209 |
+
|
| 1210 |
+
# Online logsumexp update
|
| 1211 |
+
chunk_max = logits_chunk.amax(dim=-1) # [N]
|
| 1212 |
+
max_new = torch.maximum(max_old, chunk_max)
|
| 1213 |
+
rescale = torch.exp(max_old - max_new)
|
| 1214 |
+
chunk_exp = torch.exp(logits_chunk - max_new.unsqueeze(-1)) # [N, C]
|
| 1215 |
+
|
| 1216 |
+
sum_exp = sum_exp * rescale + chunk_exp.sum(dim=-1)
|
| 1217 |
+
x_sum_exp = x_sum_exp * rescale + (chunk_exp * logits_chunk).sum(dim=-1)
|
| 1218 |
+
max_old = max_new
|
| 1219 |
+
|
| 1220 |
+
# Gather target logits for labels in this chunk
|
| 1221 |
+
in_chunk_cond = (targets >= start) & (targets < end)
|
| 1222 |
+
local_idx = torch.clamp(targets - start, 0, end - start - 1)
|
| 1223 |
+
# take the new logit if target_idx is in this chunk bounds else 0
|
| 1224 |
+
target_logit += logits_chunk[torch.arange(N, device=device), local_idx] * in_chunk_cond
|
| 1225 |
+
|
| 1226 |
+
log_z = max_old + torch.log(sum_exp)
|
| 1227 |
+
logprobs = target_logit - log_z
|
| 1228 |
+
entropy = log_z - x_sum_exp / sum_exp
|
| 1229 |
+
|
| 1230 |
+
ctx.save_for_backward(last_hidden, weight, targets, log_z)
|
| 1231 |
+
ctx.temperature = temperature
|
| 1232 |
+
ctx.chunk_size = chunk_size
|
| 1233 |
+
ctx.logit_scale = logit_scale
|
| 1234 |
+
ctx.final_logit_softcapping = final_logit_softcapping
|
| 1235 |
+
|
| 1236 |
+
return logprobs, entropy
|
| 1237 |
+
|
| 1238 |
+
@staticmethod
|
| 1239 |
+
def backward(ctx, grad_logprobs: torch.Tensor, grad_entropy: torch.Tensor): # type: ignore
|
| 1240 |
+
hidden, weight, labels, log_z = ctx.saved_tensors
|
| 1241 |
+
temperature: float = ctx.temperature
|
| 1242 |
+
chunk_size: int = ctx.chunk_size
|
| 1243 |
+
logit_scale: float = ctx.logit_scale
|
| 1244 |
+
final_logit_softcapping: float = ctx.final_logit_softcapping
|
| 1245 |
+
inv_t = 1 / temperature
|
| 1246 |
+
|
| 1247 |
+
N, _ = hidden.shape
|
| 1248 |
+
vocab = weight.shape[0]
|
| 1249 |
+
|
| 1250 |
+
# NOTE(@aminediro): always acc in fp32 even if input is not
|
| 1251 |
+
grad_hidden = torch.zeros(hidden.shape, device=hidden.device, dtype=torch.float32)
|
| 1252 |
+
grad_weight = torch.zeros(weight.shape, device=weight.device, dtype=torch.float32)
|
| 1253 |
+
|
| 1254 |
+
# Pre-allocate reusable buffers to avoid per-chunk allocation
|
| 1255 |
+
mm_buf = torch.empty((N, chunk_size), device=hidden.device, dtype=hidden.dtype)
|
| 1256 |
+
logits_buf = torch.empty((N, chunk_size), device=hidden.device, dtype=torch.float32)
|
| 1257 |
+
|
| 1258 |
+
g = grad_logprobs.to(torch.float32) # [N]
|
| 1259 |
+
row_idx = torch.arange(N, device=hidden.device)
|
| 1260 |
+
|
| 1261 |
+
for start in range(0, vocab, chunk_size):
|
| 1262 |
+
end = min(start + chunk_size, vocab)
|
| 1263 |
+
C = end - start
|
| 1264 |
+
w_chunk = weight[start:end] # [C, H]
|
| 1265 |
+
|
| 1266 |
+
torch.mm(hidden, w_chunk.t(), out=mm_buf[:, :C])
|
| 1267 |
+
logits_chunk = logits_buf[:, :C]
|
| 1268 |
+
logits_chunk.copy_(mm_buf[:, :C])
|
| 1269 |
+
|
| 1270 |
+
logits_chunk.mul_(logit_scale)
|
| 1271 |
+
if final_logit_softcapping is not None:
|
| 1272 |
+
tanh_scaled = torch.tanh(logits_chunk / final_logit_softcapping)
|
| 1273 |
+
logits_chunk.copy_(tanh_scaled * final_logit_softcapping)
|
| 1274 |
+
|
| 1275 |
+
logits_chunk.mul_(inv_t) # [N, C]
|
| 1276 |
+
probs = torch.exp(logits_chunk - log_z.unsqueeze(-1)) # [N, C]
|
| 1277 |
+
|
| 1278 |
+
# dL/d(logits) = g * (1_[label] - p)
|
| 1279 |
+
grad_logits = (-g).unsqueeze(-1) * probs # [N, C]
|
| 1280 |
+
|
| 1281 |
+
in_chunk_cond = (labels >= start) & (labels < end)
|
| 1282 |
+
local_idx = torch.clamp(labels - start, 0, end - start - 1)
|
| 1283 |
+
# If label in chunk add g to grad else it stays the same
|
| 1284 |
+
grad_logits[row_idx, local_idx] += g * in_chunk_cond
|
| 1285 |
+
|
| 1286 |
+
grad_logits = grad_logits * inv_t
|
| 1287 |
+
if final_logit_softcapping is not None:
|
| 1288 |
+
grad_logits.mul_(1 - tanh_scaled.pow(2))
|
| 1289 |
+
|
| 1290 |
+
grad_logits = grad_logits * logit_scale
|
| 1291 |
+
|
| 1292 |
+
grad_hidden.add_(grad_logits @ w_chunk.float())
|
| 1293 |
+
grad_weight[start:end].add_(grad_logits.t() @ hidden.float())
|
| 1294 |
+
|
| 1295 |
+
return grad_hidden.to(hidden.dtype), grad_weight.to(weight.dtype), None, None, None, None, None
|
| 1296 |
+
|
| 1297 |
+
|
| 1298 |
+
def patch_chunked_lm_head(
|
| 1299 |
+
model: torch.nn.Module, chunk_size: int, temperature: float, output_router_logits: bool = False
|
| 1300 |
+
) -> None:
|
| 1301 |
+
final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None)
|
| 1302 |
+
|
| 1303 |
+
def _chunked_forward(
|
| 1304 |
+
self: torch.nn.Module,
|
| 1305 |
+
input_ids: torch.Tensor | None = None,
|
| 1306 |
+
attention_mask: torch.Tensor | None = None,
|
| 1307 |
+
labels: torch.Tensor | None = None,
|
| 1308 |
+
completion_mask: torch.Tensor | None = None,
|
| 1309 |
+
use_cache: bool = False,
|
| 1310 |
+
**kwargs,
|
| 1311 |
+
) -> dict[str, torch.Tensor]:
|
| 1312 |
+
assert labels is not None, "requires labels to not be None for logprob computation"
|
| 1313 |
+
|
| 1314 |
+
decoder_kwargs = {"output_router_logits": True} if output_router_logits else {}
|
| 1315 |
+
outputs = self.model(
|
| 1316 |
+
input_ids=input_ids, attention_mask=attention_mask, use_cache=use_cache, **decoder_kwargs, **kwargs
|
| 1317 |
+
)
|
| 1318 |
+
# NOTE(@aminediro): supporting Cohere2 models
|
| 1319 |
+
logit_scale = getattr(self.config, "logit_scale", 1.0)
|
| 1320 |
+
hidden_states = outputs.last_hidden_state # [B, S+1, H]
|
| 1321 |
+
|
| 1322 |
+
# Shift: predict next token
|
| 1323 |
+
hidden_states = hidden_states[:, :-1, :] # [B, S-1, H]
|
| 1324 |
+
labels = labels[:, 1:] # [B, S-1]
|
| 1325 |
+
|
| 1326 |
+
b, s, h = hidden_states.shape
|
| 1327 |
+
hidden_flat = hidden_states.reshape(b * s, h)
|
| 1328 |
+
targets_flat = labels.reshape(b * s)
|
| 1329 |
+
|
| 1330 |
+
# Filter to completion tokens only to avoid expensive matmuls on prompt tokens and tool results
|
| 1331 |
+
valid_mask = None
|
| 1332 |
+
if completion_mask is not None:
|
| 1333 |
+
completion_mask = completion_mask[:, 1:] # same shift as labels
|
| 1334 |
+
valid_mask = completion_mask.bool().reshape(b * s)
|
| 1335 |
+
hidden_flat = hidden_flat[valid_mask] # [N_valid, H]
|
| 1336 |
+
targets_flat = targets_flat[valid_mask] # [N_valid]
|
| 1337 |
+
|
| 1338 |
+
logprobs_valid, entropy_valid = _ChunkedLogProbFunction.apply(
|
| 1339 |
+
hidden_flat,
|
| 1340 |
+
self.lm_head.weight,
|
| 1341 |
+
targets_flat,
|
| 1342 |
+
temperature,
|
| 1343 |
+
chunk_size,
|
| 1344 |
+
final_logit_softcapping,
|
| 1345 |
+
logit_scale,
|
| 1346 |
+
)
|
| 1347 |
+
|
| 1348 |
+
if valid_mask is not None:
|
| 1349 |
+
logprobs = torch.zeros(b * s, device=logprobs_valid.device, dtype=logprobs_valid.dtype)
|
| 1350 |
+
entropy = torch.zeros(b * s, device=entropy_valid.device, dtype=entropy_valid.dtype)
|
| 1351 |
+
logprobs[valid_mask] = logprobs_valid
|
| 1352 |
+
entropy[valid_mask] = entropy_valid
|
| 1353 |
+
else:
|
| 1354 |
+
logprobs = logprobs_valid
|
| 1355 |
+
entropy = entropy_valid
|
| 1356 |
+
|
| 1357 |
+
aux_loss = None
|
| 1358 |
+
if output_router_logits:
|
| 1359 |
+
# Mirror the per-family MoE forward: add `router_aux_loss_coef * load_balancing_loss_func(...)` to
|
| 1360 |
+
# the main loss. Mixtral is the source of truth — every MoE family (Qwen3Moe, GptOss, OLMoE,
|
| 1361 |
+
# Qwen2Moe, DBRX, JetMoE, PhiMoE, …) pulls this function from mixtral via the modular system, so a
|
| 1362 |
+
# single import keeps us in lockstep with upstream for every family we test.
|
| 1363 |
+
from transformers.models.mixtral.modeling_mixtral import load_balancing_loss_func
|
| 1364 |
+
|
| 1365 |
+
if Version(transformers.__version__) < Version("5.0.0"):
|
| 1366 |
+
num_experts = self.num_experts
|
| 1367 |
+
num_experts_per_tok = self.num_experts_per_tok
|
| 1368 |
+
else:
|
| 1369 |
+
# Upstream bug AttributeError: 'GptOssConfig' object has no attribute 'num_experts'; see #5754
|
| 1370 |
+
if self.config.model_type == "gpt_oss" and Version("5.0.0") <= Version(
|
| 1371 |
+
transformers.__version__
|
| 1372 |
+
) < Version("5.6.0"):
|
| 1373 |
+
num_experts = self.num_experts
|
| 1374 |
+
else:
|
| 1375 |
+
num_experts = self.config.num_experts
|
| 1376 |
+
num_experts_per_tok = self.config.num_experts_per_tok
|
| 1377 |
+
# Padding-free packs all real tokens into a single row, so `attention_mask` is None and every token counts.
|
| 1378 |
+
aux_loss = load_balancing_loss_func(
|
| 1379 |
+
outputs.router_logits, num_experts, num_experts_per_tok, attention_mask
|
| 1380 |
+
)
|
| 1381 |
+
|
| 1382 |
+
return {
|
| 1383 |
+
"log_probs": logprobs.reshape(b, s),
|
| 1384 |
+
"entropy": entropy.reshape(b, s),
|
| 1385 |
+
"aux_loss": aux_loss,
|
| 1386 |
+
}
|
| 1387 |
+
|
| 1388 |
+
model.forward = types.MethodType(_chunked_forward, model)
|
| 1389 |
+
|
| 1390 |
+
|
| 1391 |
+
def compute_flops_per_token(config: PretrainedConfig, seq_len: int) -> int:
|
| 1392 |
+
"""
|
| 1393 |
+
Estimate training FLOPs per token for a causal language model (forward + backward).
|
| 1394 |
+
|
| 1395 |
+
Supports dense and MoE architectures. Backward is assumed to cost 2× the forward pass, so total training FLOPs = 3
|
| 1396 |
+
× forward FLOPs. The attention-score term uses the non-causal convention (every token attends to the full
|
| 1397 |
+
`seq_len`, matching PaLM / Megatron / nanoGPT); pass the resulting MFU through [`adjusted_mfu`] for the Llama /
|
| 1398 |
+
DeepSpeed Ulysses causal-corrected convention.
|
| 1399 |
+
|
| 1400 |
+
Args:
|
| 1401 |
+
config ([`~transformers.PretrainedConfig`]):
|
| 1402 |
+
The model configuration.
|
| 1403 |
+
seq_len (`int`):
|
| 1404 |
+
The sequence length used for training.
|
| 1405 |
+
|
| 1406 |
+
Returns:
|
| 1407 |
+
`int`: Estimated training FLOPs per token.
|
| 1408 |
+
"""
|
| 1409 |
+
h = config.hidden_size
|
| 1410 |
+
L = config.num_hidden_layers
|
| 1411 |
+
V = config.vocab_size
|
| 1412 |
+
n_heads = config.num_attention_heads
|
| 1413 |
+
n_kv_heads = config.num_key_value_heads
|
| 1414 |
+
head_dim = config.head_dim
|
| 1415 |
+
|
| 1416 |
+
# Attention: Q/K/V/O projections + attention score (Q·Kᵀ and attn·V).
|
| 1417 |
+
qkv_flops = 2 * h * (n_heads * head_dim + 2 * n_kv_heads * head_dim)
|
| 1418 |
+
o_proj_flops = 2 * n_heads * head_dim * h
|
| 1419 |
+
attn_score_flops = 2 * 2 * n_heads * head_dim * seq_len
|
| 1420 |
+
attn_flops = qkv_flops + o_proj_flops + attn_score_flops
|
| 1421 |
+
|
| 1422 |
+
# MoE dispatch: `num_experts_per_tok` is the canonical MoE marker — present on Mixtral,
|
| 1423 |
+
# Qwen3-MoE, DeepSeek-V2, etc.; absent on dense configs.
|
| 1424 |
+
num_experts_per_tok = getattr(config, "num_experts_per_tok", None)
|
| 1425 |
+
if num_experts_per_tok is None:
|
| 1426 |
+
mlp_flops = 2 * 3 * h * config.intermediate_size
|
| 1427 |
+
total_layer_flops = L * (attn_flops + mlp_flops)
|
| 1428 |
+
else:
|
| 1429 |
+
# Routed experts (gate + up + down, 3 matmuls each) + router.
|
| 1430 |
+
if Version(transformers.__version__) >= Version("5.1.0"):
|
| 1431 |
+
num_experts = config.num_local_experts
|
| 1432 |
+
else:
|
| 1433 |
+
num_experts = config.num_experts
|
| 1434 |
+
moe_mlp_flops = num_experts_per_tok * 2 * 3 * h * config.moe_intermediate_size
|
| 1435 |
+
moe_mlp_flops += 2 * h * num_experts
|
| 1436 |
+
dense_mlp_flops = 2 * 3 * h * config.intermediate_size # interspersed dense layers
|
| 1437 |
+
sparse_step = config.decoder_sparse_step
|
| 1438 |
+
total_layer_flops = sum(
|
| 1439 |
+
attn_flops + (moe_mlp_flops if layer_idx % sparse_step == 0 else dense_mlp_flops) for layer_idx in range(L)
|
| 1440 |
+
)
|
| 1441 |
+
|
| 1442 |
+
embed_flops = 2 * V * h
|
| 1443 |
+
lm_head_flops = 0 if config.tie_word_embeddings else 2 * V * h
|
| 1444 |
+
|
| 1445 |
+
forward_flops = total_layer_flops + embed_flops + lm_head_flops
|
| 1446 |
+
return 3 * forward_flops
|
| 1447 |
+
|
| 1448 |
+
|
| 1449 |
+
def compute_mfu(
|
| 1450 |
+
flops_per_token: int,
|
| 1451 |
+
tokens_per_second: float,
|
| 1452 |
+
world_size: int,
|
| 1453 |
+
peak_flops_per_device: float = 989.5e12,
|
| 1454 |
+
) -> float:
|
| 1455 |
+
"""
|
| 1456 |
+
Compute Model FLOPs Utilization (MFU) as a percentage.
|
| 1457 |
+
|
| 1458 |
+
The caller is responsible for correcting `tokens_per_second` for any parallelism dimension that causes the
|
| 1459 |
+
trainer's token counter to over-count (e.g. context parallelism, sequence parallelism, tensor parallelism — every
|
| 1460 |
+
rank in those dims sees the same input tokens).
|
| 1461 |
+
|
| 1462 |
+
Args:
|
| 1463 |
+
flops_per_token (`int`):
|
| 1464 |
+
Training FLOPs per token (from [`compute_flops_per_token`]).
|
| 1465 |
+
tokens_per_second (`float`):
|
| 1466 |
+
Aggregate tokens per second across all devices, after any parallelism corrections.
|
| 1467 |
+
world_size (`int`):
|
| 1468 |
+
Number of devices (GPUs).
|
| 1469 |
+
peak_flops_per_device (`float`, *optional*, defaults to `989.5e12`):
|
| 1470 |
+
Theoretical peak FLOPs per device in bf16. Defaults to H100 SXM5.
|
| 1471 |
+
|
| 1472 |
+
Returns:
|
| 1473 |
+
`float`: MFU as a percentage (0-100).
|
| 1474 |
+
"""
|
| 1475 |
+
return 100 * (flops_per_token * tokens_per_second) / (peak_flops_per_device * world_size)
|
| 1476 |
+
|
| 1477 |
+
|
| 1478 |
+
def adjusted_mfu(mfu: float, config: PretrainedConfig, seq_len: int) -> float:
|
| 1479 |
+
"""
|
| 1480 |
+
Apply a causal-masking correction to an MFU computed with [`compute_flops_per_token`].
|
| 1481 |
+
|
| 1482 |
+
[`compute_flops_per_token`] uses the non-causal attention convention (every token treated as attending to the full
|
| 1483 |
+
`seq_len`, matching PaLM / Megatron / nanoGPT). With causal masking, only half of the attention-score FLOPs (`Q·Kᵀ`
|
| 1484 |
+
and `attn·V`) are actually performed. This function subtracts that half from the per-token total and rescales `mfu`
|
| 1485 |
+
accordingly. Use it to compare against reports that follow the Llama 2/3 / DeepSpeed Ulysses convention.
|
| 1486 |
+
|
| 1487 |
+
Args:
|
| 1488 |
+
mfu (`float`):
|
| 1489 |
+
MFU as a percentage, computed via [`compute_mfu`] (i.e., using the non-causal [`compute_flops_per_token`]).
|
| 1490 |
+
config ([`~transformers.PretrainedConfig`]):
|
| 1491 |
+
The model configuration.
|
| 1492 |
+
seq_len (`int`):
|
| 1493 |
+
The sequence length used for training.
|
| 1494 |
+
|
| 1495 |
+
Returns:
|
| 1496 |
+
`float`: Causal-corrected MFU as a percentage.
|
| 1497 |
+
"""
|
| 1498 |
+
flops_full = compute_flops_per_token(config, seq_len)
|
| 1499 |
+
# Half of the attention-score FLOPs (Q·Kᵀ and attn·V), per layer, ×3 for fwd+bwd.
|
| 1500 |
+
half_attn_score = config.num_hidden_layers * 3 * 2 * config.num_attention_heads * config.head_dim * seq_len
|
| 1501 |
+
return mfu * (flops_full - half_attn_score) / flops_full
|
tasks/tasksmith-03a6a091b12f/instruction.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Add support for periodic reference model synchronization (TR-DPO style) to `KTOConfig` and `KTOTrainer`, matching the existing DPO implementation.
|
| 2 |
+
|
| 3 |
+
**KTOConfig changes**
|
| 4 |
+
|
| 5 |
+
Add three new fields with the following defaults:
|
| 6 |
+
|
| 7 |
+
| Field | Type | Default |
|
| 8 |
+
|---|---|---|
|
| 9 |
+
| `sync_ref_model` | `bool` | `False` |
|
| 10 |
+
| `ref_model_mixup_alpha` | `float` | `0.6` |
|
| 11 |
+
| `ref_model_sync_steps` | `int` | `512` |
|
| 12 |
+
|
| 13 |
+
When `sync_ref_model=True`, the reference model is periodically updated: `π_ref = α · π_θ + (1−α) · π_ref_prev`, where α is `ref_model_mixup_alpha` and the update happens every `ref_model_sync_steps` training steps.
|
| 14 |
+
|
| 15 |
+
**KTOTrainer changes**
|
| 16 |
+
|
| 17 |
+
With `sync_ref_model=True`, KTO training must update the reference model parameters using the interpolation and training-step interval specified above. The reference parameters must remain unchanged between synchronization steps.
|
| 18 |
+
|
| 19 |
+
Trainer construction must reject synchronization with a PEFT active model by raising `NotImplementedError`, and reject synchronization with `precompute_ref_log_probs=True` by raising `ValueError`.
|
| 20 |
+
|
| 21 |
+
When `sync_ref_model=False` (the default), behaviour is unchanged, including support for PEFT and precomputed reference log probabilities.
|
| 22 |
+
|
| 23 |
+
Work in `/workspace`. Submit your fix in the existing Python source files under `trl`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files.
|
tasks/tasksmith-03a6a091b12f/solution/reference/trl/experimental/kto/kto_config.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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=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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, 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 |
+
if is_peft_available():
|
| 75 |
+
import peft
|
| 76 |
+
from peft import LoraConfig, PeftConfig, PeftModel, get_peft_model
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
logger = get_logger(__name__)
|
| 80 |
+
|
| 81 |
+
RUNNING_NAME = "running.pt"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def get_dataset_column_names(dataset: Dataset | IterableDataset) -> list[str]:
|
| 85 |
+
return list(next(iter(dataset)).keys()) if dataset.column_names is None else dataset.column_names
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _get_kl_completion_ids(batch: dict[str, list[Any]]) -> dict[str, list[Any]]:
|
| 89 |
+
"""
|
| 90 |
+
Creates mismatched pairs of prompts and completions for the KL dataset by adding a +1 offset to the order of
|
| 91 |
+
completions. For best results, the mismatched outputs y' used to estimate the KL term for a batch should be the
|
| 92 |
+
same set as the matched outputs y used to estimate the rewards in that batch, just paired with different x.
|
| 93 |
+
"""
|
| 94 |
+
batch["completion_ids"] = [batch["completion_ids"][-1]] + batch["completion_ids"][:-1]
|
| 95 |
+
return batch
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@dataclass
|
| 99 |
+
class DataCollatorForUnpairedPreference(DataCollatorMixin):
|
| 100 |
+
"""
|
| 101 |
+
Data collator for unpaired preference data. Assembles completions from raw token IDs and pads sequences to the
|
| 102 |
+
maximum length of the batch.
|
| 103 |
+
|
| 104 |
+
Each example is expected to contain `"prompt_ids"`, `"completion_ids"` (and optionally `"KL_completion_ids"`) keys.
|
| 105 |
+
The collator returns a dictionary with the following keys for each prefix (`"completion"` and, if present,
|
| 106 |
+
`"KL_completion"`):
|
| 107 |
+
- `"{prefix}_input_ids"`: full prompt + completion token IDs, padded to the batch maximum length.
|
| 108 |
+
- `"{prefix}_attention_mask"`: attention mask, padded with 0s.
|
| 109 |
+
- `"{prefix}_mask"`: binary mask where 1 marks completion tokens and 0 marks prompt or padding tokens.
|
| 110 |
+
|
| 111 |
+
Args:
|
| 112 |
+
pad_token_id (`int`):
|
| 113 |
+
Token ID to use for padding `input_ids` sequences.
|
| 114 |
+
max_length (`int`, *optional*):
|
| 115 |
+
Maximum sequence length after assembly. Sequences longer than `max_length` are truncated from the end.
|
| 116 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 117 |
+
If set, the sequences will be padded to a multiple of this value.
|
| 118 |
+
return_tensors (`str`, *optional*, defaults to `"pt"`):
|
| 119 |
+
The tensor type to return. Currently, only `"pt"` (PyTorch tensors) is supported.
|
| 120 |
+
"""
|
| 121 |
+
|
| 122 |
+
pad_token_id: int
|
| 123 |
+
max_length: int | None = None
|
| 124 |
+
pad_to_multiple_of: int | None = None
|
| 125 |
+
return_tensors: str = "pt"
|
| 126 |
+
|
| 127 |
+
def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
|
| 128 |
+
batch = {}
|
| 129 |
+
for prefix, ids_key in [("completion", "completion_ids"), ("KL_completion", "KL_completion_ids")]:
|
| 130 |
+
if ids_key not in examples[0]:
|
| 131 |
+
continue
|
| 132 |
+
|
| 133 |
+
full_ids_list = []
|
| 134 |
+
completion_mask_list = []
|
| 135 |
+
for ex in examples:
|
| 136 |
+
prompt_ids = ex["prompt_ids"]
|
| 137 |
+
answer_ids = ex[ids_key]
|
| 138 |
+
full_ids = prompt_ids + answer_ids
|
| 139 |
+
completion_mask = [0] * len(prompt_ids) + [1] * len(answer_ids)
|
| 140 |
+
if self.max_length is not None:
|
| 141 |
+
full_ids = full_ids[: self.max_length]
|
| 142 |
+
completion_mask = completion_mask[: self.max_length]
|
| 143 |
+
full_ids_list.append(full_ids)
|
| 144 |
+
completion_mask_list.append(completion_mask)
|
| 145 |
+
|
| 146 |
+
batch[f"{prefix}_input_ids"] = pad(
|
| 147 |
+
[torch.tensor(ids, dtype=torch.int64) for ids in full_ids_list],
|
| 148 |
+
padding_value=self.pad_token_id,
|
| 149 |
+
padding_side="right",
|
| 150 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 151 |
+
)
|
| 152 |
+
batch[f"{prefix}_attention_mask"] = pad(
|
| 153 |
+
[torch.ones(len(ids), dtype=torch.int64) for ids in full_ids_list],
|
| 154 |
+
padding_value=0,
|
| 155 |
+
padding_side="right",
|
| 156 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 157 |
+
)
|
| 158 |
+
batch[f"{prefix}_mask"] = pad(
|
| 159 |
+
[torch.tensor(m, dtype=torch.int64) for m in completion_mask_list],
|
| 160 |
+
padding_value=0,
|
| 161 |
+
padding_side="right",
|
| 162 |
+
pad_to_multiple_of=self.pad_to_multiple_of,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
if "ref_logps" in examples[0]:
|
| 166 |
+
batch["ref_logps"] = torch.tensor([ex["ref_logps"] for ex in examples])
|
| 167 |
+
if "ref_KL_logps" in examples[0]:
|
| 168 |
+
batch["ref_KL_logps"] = torch.tensor([ex["ref_KL_logps"] for ex in examples])
|
| 169 |
+
batch["label"] = [ex["label"] for ex in examples]
|
| 170 |
+
return batch
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
@dataclass
|
| 174 |
+
class DataCollatorForVisionUnpairedPreference(DataCollatorMixin):
|
| 175 |
+
"""
|
| 176 |
+
Data collator for vision unpaired preference data. Performs tokenization and image processing on-the-fly.
|
| 177 |
+
|
| 178 |
+
Unlike the text-only [`DataCollatorForUnpairedPreference`], this collator does not expect pre-tokenized inputs.
|
| 179 |
+
Instead, it takes raw examples with `"prompt"`, `"completion"`, and `"images"` (or `"image"`) keys and processes
|
| 180 |
+
them at collation time. When `calculate_kl` is `True`, the collator also produces KL sequences by cycling
|
| 181 |
+
completions within the batch — the same mismatching strategy as the text-only path, but done here rather than as a
|
| 182 |
+
dataset pre-processing step.
|
| 183 |
+
|
| 184 |
+
Each input example should contain at least:
|
| 185 |
+
- A `"prompt"` key with either a plain text string or a list of message dicts.
|
| 186 |
+
- A `"completion"` key with a plain text string or a list of message dicts.
|
| 187 |
+
- An `"images"` key holding a list of images, or an `"image"` key holding a single image.
|
| 188 |
+
- A `"label"` key (`bool`) indicating whether the completion is desirable.
|
| 189 |
+
|
| 190 |
+
The collator outputs:
|
| 191 |
+
- `"completion_input_ids"`, `"completion_attention_mask"`, `"completion_mask"`: full prompt+completion sequence.
|
| 192 |
+
- `"pixel_values"` and any additional processor outputs (e.g., `"image_grid_thw"`).
|
| 193 |
+
- `"label"`: list of booleans.
|
| 194 |
+
- When `calculate_kl=True`: `"KL_completion_input_ids"`, `"KL_completion_attention_mask"`, `"KL_completion_mask"`
|
| 195 |
+
for the cycled KL sequences.
|
| 196 |
+
|
| 197 |
+
Args:
|
| 198 |
+
processor ([`~transformers.ProcessorMixin`]):
|
| 199 |
+
The processor used to tokenize text and process images.
|
| 200 |
+
max_length (`int`, *optional*):
|
| 201 |
+
Maximum sequence length. Sequences longer than `max_length` are truncated.
|
| 202 |
+
calculate_kl (`bool`, *optional*, defaults to `True`):
|
| 203 |
+
Whether to produce KL sequences by cycling completions within the batch.
|
| 204 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 205 |
+
If set, the sequences will be padded to a multiple of this value.
|
| 206 |
+
return_tensors (`str`, *optional*, defaults to `"pt"`):
|
| 207 |
+
The tensor type to return. Only `"pt"` is supported.
|
| 208 |
+
"""
|
| 209 |
+
|
| 210 |
+
processor: ProcessorMixin
|
| 211 |
+
max_length: int | None = None
|
| 212 |
+
calculate_kl: bool = True
|
| 213 |
+
pad_to_multiple_of: int | None = None
|
| 214 |
+
return_tensors: str = "pt"
|
| 215 |
+
|
| 216 |
+
def torch_call(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
|
| 217 |
+
if self.pad_to_multiple_of is not None:
|
| 218 |
+
raise NotImplementedError(
|
| 219 |
+
"Padding to a multiple of a value is not yet implemented for vision-language modeling and "
|
| 220 |
+
"prompt-completion data."
|
| 221 |
+
)
|
| 222 |
+
if "image" in examples[0]:
|
| 223 |
+
for example in examples:
|
| 224 |
+
example["images"] = [example.pop("image")]
|
| 225 |
+
images = [example["images"] for example in examples]
|
| 226 |
+
# Transformers requires at least one image in the batch, otherwise it throws an error
|
| 227 |
+
if all(img_list == [] for img_list in images):
|
| 228 |
+
images = None
|
| 229 |
+
if is_conversational(examples[0]): # conversational case
|
| 230 |
+
for example in examples:
|
| 231 |
+
example["prompt"] = prepare_multimodal_messages(example["prompt"], images=example["images"])
|
| 232 |
+
example["completion"] = prepare_multimodal_messages(example["completion"])
|
| 233 |
+
examples = [apply_chat_template(example, self.processor) for example in examples]
|
| 234 |
+
|
| 235 |
+
prompts = [example["prompt"] for example in examples]
|
| 236 |
+
completions = [example["completion"] for example in examples]
|
| 237 |
+
|
| 238 |
+
processed_prompts = self.processor(
|
| 239 |
+
images=images,
|
| 240 |
+
text=prompts,
|
| 241 |
+
padding=True,
|
| 242 |
+
padding_side="left",
|
| 243 |
+
return_tensors=self.return_tensors,
|
| 244 |
+
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
|
| 245 |
+
)
|
| 246 |
+
processed_completions = self.processor(
|
| 247 |
+
text=completions,
|
| 248 |
+
padding=True,
|
| 249 |
+
padding_side="right",
|
| 250 |
+
return_tensors=self.return_tensors,
|
| 251 |
+
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
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
# Concatenate prompts and completions
|
| 255 |
+
prompt_ids, prompt_mask = processed_prompts["input_ids"], processed_prompts["attention_mask"]
|
| 256 |
+
completion_ids, completion_mask = processed_completions["input_ids"], processed_completions["attention_mask"]
|
| 257 |
+
input_ids = torch.cat((prompt_ids, completion_ids), dim=1)
|
| 258 |
+
attention_mask = torch.cat((prompt_mask, completion_mask), dim=1)
|
| 259 |
+
completion_mask = torch.cat((torch.zeros_like(prompt_mask), completion_mask), dim=1)
|
| 260 |
+
|
| 261 |
+
has_tti = "token_type_ids" in processed_prompts
|
| 262 |
+
has_mm_tti = "mm_token_type_ids" in processed_prompts
|
| 263 |
+
|
| 264 |
+
if has_tti: # special case for Gemma
|
| 265 |
+
prompt_token_type_ids = processed_prompts["token_type_ids"]
|
| 266 |
+
completion_token_type_ids = processed_completions["token_type_ids"]
|
| 267 |
+
token_type_ids = torch.cat((prompt_token_type_ids, completion_token_type_ids), dim=1)
|
| 268 |
+
if has_mm_tti: # special case for Qwen2.5-VL
|
| 269 |
+
prompt_mm_token_type_ids = processed_prompts["mm_token_type_ids"]
|
| 270 |
+
completion_mm_token_type_ids = processed_completions.get(
|
| 271 |
+
"mm_token_type_ids", torch.zeros_like(completion_ids)
|
| 272 |
+
)
|
| 273 |
+
mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, completion_mm_token_type_ids), dim=1)
|
| 274 |
+
|
| 275 |
+
# Flush left to reduce padding
|
| 276 |
+
if has_tti and has_mm_tti:
|
| 277 |
+
attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids = flush_left(
|
| 278 |
+
attention_mask, input_ids, completion_mask, token_type_ids, mm_token_type_ids
|
| 279 |
+
)
|
| 280 |
+
elif has_tti:
|
| 281 |
+
attention_mask, input_ids, completion_mask, token_type_ids = flush_left(
|
| 282 |
+
attention_mask, input_ids, completion_mask, token_type_ids
|
| 283 |
+
)
|
| 284 |
+
elif has_mm_tti:
|
| 285 |
+
attention_mask, input_ids, completion_mask, mm_token_type_ids = flush_left(
|
| 286 |
+
attention_mask, input_ids, completion_mask, mm_token_type_ids
|
| 287 |
+
)
|
| 288 |
+
else:
|
| 289 |
+
attention_mask, input_ids, completion_mask = flush_left(attention_mask, input_ids, completion_mask)
|
| 290 |
+
|
| 291 |
+
# Truncate if necessary
|
| 292 |
+
if self.max_length is not None:
|
| 293 |
+
input_ids = input_ids[:, : self.max_length]
|
| 294 |
+
attention_mask = attention_mask[:, : self.max_length]
|
| 295 |
+
completion_mask = completion_mask[:, : self.max_length]
|
| 296 |
+
if has_tti:
|
| 297 |
+
token_type_ids = token_type_ids[:, : self.max_length]
|
| 298 |
+
if has_mm_tti:
|
| 299 |
+
mm_token_type_ids = mm_token_type_ids[:, : self.max_length]
|
| 300 |
+
|
| 301 |
+
# Build the output dictionary
|
| 302 |
+
output = processed_prompts # we take processed_prompts because it contains the images
|
| 303 |
+
output.pop("input_ids", None)
|
| 304 |
+
output.pop("attention_mask", None)
|
| 305 |
+
output["completion_input_ids"] = input_ids
|
| 306 |
+
output["completion_attention_mask"] = attention_mask
|
| 307 |
+
output["completion_mask"] = completion_mask
|
| 308 |
+
if has_tti:
|
| 309 |
+
output["token_type_ids"] = token_type_ids
|
| 310 |
+
if has_mm_tti:
|
| 311 |
+
output["mm_token_type_ids"] = mm_token_type_ids
|
| 312 |
+
|
| 313 |
+
if self.calculate_kl:
|
| 314 |
+
# Cycle completions by +1 within the batch to create mismatched KL pairs — same strategy as
|
| 315 |
+
# _get_kl_completion_ids in the text-only path, but done here to keep the VLM dataset fully raw.
|
| 316 |
+
kl_completions = completions[-1:] + completions[:-1]
|
| 317 |
+
processed_kl = self.processor(
|
| 318 |
+
text=kl_completions,
|
| 319 |
+
padding=True,
|
| 320 |
+
padding_side="right",
|
| 321 |
+
return_tensors=self.return_tensors,
|
| 322 |
+
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
|
| 323 |
+
)
|
| 324 |
+
kl_ids = processed_kl["input_ids"]
|
| 325 |
+
kl_mask = processed_kl["attention_mask"]
|
| 326 |
+
|
| 327 |
+
kl_input_ids = torch.cat((prompt_ids, kl_ids), dim=1)
|
| 328 |
+
kl_attention_mask = torch.cat((prompt_mask, kl_mask), dim=1)
|
| 329 |
+
kl_completion_mask = torch.cat((torch.zeros_like(prompt_mask), kl_mask), dim=1)
|
| 330 |
+
|
| 331 |
+
# Build KL token-type tensors using the original (pre-flush) prompt tensors
|
| 332 |
+
if has_tti:
|
| 333 |
+
kl_completion_token_type_ids = processed_kl.get("token_type_ids", torch.zeros_like(kl_ids))
|
| 334 |
+
kl_token_type_ids = torch.cat((prompt_token_type_ids, kl_completion_token_type_ids), dim=1)
|
| 335 |
+
if has_mm_tti:
|
| 336 |
+
kl_completion_mm_token_type_ids = processed_kl.get("mm_token_type_ids", torch.zeros_like(kl_ids))
|
| 337 |
+
kl_mm_token_type_ids = torch.cat((prompt_mm_token_type_ids, kl_completion_mm_token_type_ids), dim=1)
|
| 338 |
+
|
| 339 |
+
if has_tti and has_mm_tti:
|
| 340 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids, kl_mm_token_type_ids = (
|
| 341 |
+
flush_left(
|
| 342 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids, kl_mm_token_type_ids
|
| 343 |
+
)
|
| 344 |
+
)
|
| 345 |
+
elif has_tti:
|
| 346 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids = flush_left(
|
| 347 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_token_type_ids
|
| 348 |
+
)
|
| 349 |
+
elif has_mm_tti:
|
| 350 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_mm_token_type_ids = flush_left(
|
| 351 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask, kl_mm_token_type_ids
|
| 352 |
+
)
|
| 353 |
+
else:
|
| 354 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask = flush_left(
|
| 355 |
+
kl_attention_mask, kl_input_ids, kl_completion_mask
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
# Truncate if necessary
|
| 359 |
+
if self.max_length is not None:
|
| 360 |
+
kl_input_ids = kl_input_ids[:, : self.max_length]
|
| 361 |
+
kl_attention_mask = kl_attention_mask[:, : self.max_length]
|
| 362 |
+
kl_completion_mask = kl_completion_mask[:, : self.max_length]
|
| 363 |
+
if has_tti:
|
| 364 |
+
kl_token_type_ids = kl_token_type_ids[:, : self.max_length]
|
| 365 |
+
if has_mm_tti:
|
| 366 |
+
kl_mm_token_type_ids = kl_mm_token_type_ids[:, : self.max_length]
|
| 367 |
+
|
| 368 |
+
output["KL_completion_input_ids"] = kl_input_ids
|
| 369 |
+
output["KL_completion_attention_mask"] = kl_attention_mask
|
| 370 |
+
output["KL_completion_mask"] = kl_completion_mask
|
| 371 |
+
if has_tti:
|
| 372 |
+
output["KL_completion_token_type_ids"] = kl_token_type_ids
|
| 373 |
+
if has_mm_tti:
|
| 374 |
+
output["KL_completion_mm_token_type_ids"] = kl_mm_token_type_ids
|
| 375 |
+
|
| 376 |
+
output["label"] = [ex["label"] for ex in examples]
|
| 377 |
+
return output
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class KTOTrainer(_BaseTrainer):
|
| 381 |
+
"""
|
| 382 |
+
Initialize KTOTrainer.
|
| 383 |
+
|
| 384 |
+
Args:
|
| 385 |
+
model (`str` or [`~transformers.PreTrainedModel`] or [`~peft.PeftModel`]):
|
| 386 |
+
Model to be trained. Can be either:
|
| 387 |
+
|
| 388 |
+
- A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
|
| 389 |
+
path to a *directory* containing model weights saved using
|
| 390 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
| 391 |
+
using `<ModelArchitecture>.from_pretrained` (where `<ModelArchitecture>` is derived from the model
|
| 392 |
+
config) with the keyword arguments in `args.model_init_kwargs`.
|
| 393 |
+
- A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
|
| 394 |
+
- A [`~peft.PeftModel`] object. Only causal language models are supported.
|
| 395 |
+
ref_model ([`~transformers.PreTrainedModel`], *optional*):
|
| 396 |
+
Reference model used to compute the reference log probabilities.
|
| 397 |
+
|
| 398 |
+
- If provided, this model is used directly as the reference policy.
|
| 399 |
+
- If `None`, the trainer will automatically use the initial policy corresponding to `model`, i.e. the model
|
| 400 |
+
state before KTO training starts.
|
| 401 |
+
args ([`experimental.kto.KTOConfig`], *optional*):
|
| 402 |
+
Configuration for this trainer. If `None`, a default configuration is used.
|
| 403 |
+
train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
|
| 404 |
+
The dataset to use for training.
|
| 405 |
+
eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Dataset | IterableDataset]`):
|
| 406 |
+
The dataset to use for evaluation.
|
| 407 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`], *optional*):
|
| 408 |
+
Processing class used to process the data. The padding side must be set to "left". If `None`, the
|
| 409 |
+
processing class is loaded from the model's name with [`~transformers.AutoProcessor.from_pretrained`]. A
|
| 410 |
+
padding token, `tokenizer.pad_token`, must be set. If the processing class has not set a padding token,
|
| 411 |
+
`tokenizer.eos_token` will be used as the default.
|
| 412 |
+
data_collator ([`~transformers.DataCollator`], *optional*):
|
| 413 |
+
The data collator to use for training. If None is specified, the default data collator
|
| 414 |
+
([`~experimental.kto.kto_trainer.DataCollatorForUnpairedPreference`]) will be used which will pad the
|
| 415 |
+
sequences to the maximum length of the sequences in the batch.
|
| 416 |
+
callbacks (`list[transformers.TrainerCallback]`):
|
| 417 |
+
The callbacks to use for training.
|
| 418 |
+
optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
|
| 419 |
+
The optimizer and scheduler to use for training.
|
| 420 |
+
peft_config ([`~peft.PeftConfig`], *optional*):
|
| 421 |
+
PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
|
| 422 |
+
compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
|
| 423 |
+
The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
|
| 424 |
+
metric values.
|
| 425 |
+
"""
|
| 426 |
+
|
| 427 |
+
_tag_names = ["trl", "kto"]
|
| 428 |
+
_name = "KTO"
|
| 429 |
+
_paper = {
|
| 430 |
+
"title": "KTO: Model Alignment as Prospect Theoretic Optimization",
|
| 431 |
+
"id": "2402.01306",
|
| 432 |
+
# docstyle-ignore
|
| 433 |
+
"citation": textwrap.dedent("""\
|
| 434 |
+
@article{ethayarajh2024kto,
|
| 435 |
+
title = {{KTO: Model Alignment as Prospect Theoretic Optimization}},
|
| 436 |
+
author = {Kawin Ethayarajh and Winnie Xu and Niklas Muennighoff and Dan Jurafsky and Douwe Kiela},
|
| 437 |
+
year = 2024,
|
| 438 |
+
eprint = {arXiv:2402.01306},
|
| 439 |
+
}"""),
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
def __init__(
|
| 443 |
+
self,
|
| 444 |
+
model: "str | PreTrainedModel | PeftModel",
|
| 445 |
+
ref_model: PreTrainedModel | None = None,
|
| 446 |
+
args: KTOConfig | None = None,
|
| 447 |
+
train_dataset: Dataset | IterableDataset | None = None,
|
| 448 |
+
eval_dataset: Dataset | IterableDataset | dict[str, Dataset | IterableDataset] | None = None,
|
| 449 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin | None = None,
|
| 450 |
+
data_collator: DataCollator | None = None,
|
| 451 |
+
callbacks: list[TrainerCallback] | None = None,
|
| 452 |
+
optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
|
| 453 |
+
peft_config: "PeftConfig | None" = None,
|
| 454 |
+
compute_metrics: Callable[[EvalLoopOutput], dict] | None = None,
|
| 455 |
+
):
|
| 456 |
+
# Args
|
| 457 |
+
if args is None:
|
| 458 |
+
model_name = model if isinstance(model, str) else get_config_model_id(model.config)
|
| 459 |
+
model_name = model_name.split("/")[-1]
|
| 460 |
+
args = KTOConfig(f"{model_name}-KTO")
|
| 461 |
+
|
| 462 |
+
if train_dataset is None:
|
| 463 |
+
raise ValueError("`train_dataset` is required")
|
| 464 |
+
elif isinstance(train_dataset, IterableDataset):
|
| 465 |
+
# IterableDataset requires dispatch_batches=False because Accelerate's dispatch mode may try to concatenate
|
| 466 |
+
# batches from multiple processes, leading to mismatch errors.
|
| 467 |
+
if args.accelerator_config.dispatch_batches is True:
|
| 468 |
+
logger.warning(
|
| 469 |
+
"You are using an `IterableDataset` for training with `dispatch_batches=True`. `dispatch_batches` "
|
| 470 |
+
"is forced to `False` when using an `IterableDataset`. To remove this warning, unset "
|
| 471 |
+
"`dispatch_batches` in `KTOConfig` or set it to `False`."
|
| 472 |
+
)
|
| 473 |
+
args.accelerator_config.dispatch_batches = False
|
| 474 |
+
|
| 475 |
+
# Model
|
| 476 |
+
if isinstance(model, str):
|
| 477 |
+
model_init_kwargs = args.model_init_kwargs or {}
|
| 478 |
+
# Distributed training requires device_map=None ("auto" fails)
|
| 479 |
+
if args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
|
| 480 |
+
model_init_kwargs["device_map"] = None
|
| 481 |
+
model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 482 |
+
model = create_model_from_path(model, **model_init_kwargs)
|
| 483 |
+
else:
|
| 484 |
+
if args.model_init_kwargs is not None:
|
| 485 |
+
logger.warning(
|
| 486 |
+
"You passed `model_init_kwargs` to the KTOConfig, but your model is already instantiated. "
|
| 487 |
+
"The `model_init_kwargs` will be ignored."
|
| 488 |
+
)
|
| 489 |
+
# Non-quantized models do not have the `is_loaded_in_{8,4}bit` attributes, whereas quantized models do
|
| 490 |
+
_is_quantized_model = getattr(model, "is_loaded_in_4bit", False) or getattr(model, "is_loaded_in_8bit", False)
|
| 491 |
+
if ref_model is model:
|
| 492 |
+
raise ValueError(
|
| 493 |
+
"`model` and `ref_model` cannot be the same object. In most cases you should omit `ref_model` and "
|
| 494 |
+
"we'll initialize it to a copy of `model` for you."
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
# Processing class
|
| 498 |
+
if processing_class is None:
|
| 499 |
+
processing_class = AutoProcessor.from_pretrained(
|
| 500 |
+
get_config_model_id(model.config), trust_remote_code=args.trust_remote_code
|
| 501 |
+
)
|
| 502 |
+
if isinstance(processing_class, ProcessorMixin):
|
| 503 |
+
self._tokenizer = processing_class.tokenizer
|
| 504 |
+
self._is_vlm = True
|
| 505 |
+
elif isinstance(processing_class, PreTrainedTokenizerBase):
|
| 506 |
+
self._tokenizer = processing_class
|
| 507 |
+
self._is_vlm = False
|
| 508 |
+
else:
|
| 509 |
+
raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
|
| 510 |
+
if self._tokenizer.pad_token is None:
|
| 511 |
+
self._tokenizer.pad_token = self._tokenizer.eos_token
|
| 512 |
+
|
| 513 |
+
# PEFT
|
| 514 |
+
if peft_config is not None:
|
| 515 |
+
if not is_peft_available():
|
| 516 |
+
raise ImportError(
|
| 517 |
+
"You passed `peft_config` but the `peft` library is not installed. "
|
| 518 |
+
"Install it with `pip install trl[peft]`."
|
| 519 |
+
)
|
| 520 |
+
if not isinstance(peft_config, PeftConfig):
|
| 521 |
+
raise TypeError(
|
| 522 |
+
f"`peft_config` must be a `peft.PeftConfig` instance (e.g. `peft.LoraConfig`), "
|
| 523 |
+
f"got {type(peft_config).__name__}."
|
| 524 |
+
)
|
| 525 |
+
if is_peft_model(model):
|
| 526 |
+
raise ValueError(
|
| 527 |
+
"You passed a `PeftModel` instance together with a `peft_config` to the trainer. Please first merge "
|
| 528 |
+
"and unload the existing adapter, save the resulting base model, and then pass that base model along "
|
| 529 |
+
"with the new `peft_config` to the trainer."
|
| 530 |
+
)
|
| 531 |
+
# Create PEFT model
|
| 532 |
+
# ZeRO-3 + PEFT for non-quantized models:
|
| 533 |
+
# - PEFT's default autocast_adapter_dtype=True upcasts LoRA adapter params to fp32 even when the base model is bf16.
|
| 534 |
+
# - ZeRO-3's _allgather_params_coalesced allocates output buffers using the dtype of the first persistent parameter,
|
| 535 |
+
# so mixed-dtype persistent_parameters (bf16 base + fp32 LoRA) cause a TypeError on the first optimizer step.
|
| 536 |
+
# - Passing autocast_adapter_dtype=False keeps adapter params in the base model dtype (bf16), fixing the mismatch.
|
| 537 |
+
# - This is safe: the fp32 upcast is a QLoRA-specific concern (low-bit quantized base models), not needed for
|
| 538 |
+
# non-quantized bf16 training.
|
| 539 |
+
# - See:
|
| 540 |
+
# - TRL issue: https://github.com/huggingface/trl/issues/6089
|
| 541 |
+
# - Upstream issue: https://github.com/deepspeedai/DeepSpeed/issues/8072
|
| 542 |
+
# - autocast_adapter_dtype was introduced in PEFT 0.12.0; before, no upcast existed: no need to pass the kwarg
|
| 543 |
+
get_peft_model_kwargs = {}
|
| 544 |
+
if (
|
| 545 |
+
args.deepspeed_plugin is not None
|
| 546 |
+
and args.deepspeed_plugin.zero_stage == 3
|
| 547 |
+
and not _is_quantized_model
|
| 548 |
+
and Version(peft.__version__) >= Version("0.12.0")
|
| 549 |
+
):
|
| 550 |
+
get_peft_model_kwargs["autocast_adapter_dtype"] = False
|
| 551 |
+
model = get_peft_model(model, peft_config, **get_peft_model_kwargs)
|
| 552 |
+
|
| 553 |
+
elif is_peft_model(model) and ref_model is None:
|
| 554 |
+
# If the model is a PEFT model with a pretrained adapter, we need to create a "ref" adapter that is a copy
|
| 555 |
+
# of the "default" adapter, so that we can use it as the reference model during KTO training. PEFT only
|
| 556 |
+
# supports one adapter per model when the LoRA config uses `target_parameters` (see peft#3340), so in that
|
| 557 |
+
# case we skip the "ref" adapter and compute the reference log probs with adapters disabled, i.e. with the
|
| 558 |
+
# base model.
|
| 559 |
+
default_config = model.peft_config["default"]
|
| 560 |
+
if isinstance(default_config, LoraConfig) and default_config.target_parameters:
|
| 561 |
+
logger.warning(
|
| 562 |
+
"PEFT can't add a frozen reference adapter alongside one that uses `target_parameters` "
|
| 563 |
+
"(peft#3340), so the reference log probs are computed from the base model (adapters disabled). "
|
| 564 |
+
"If you wrapped the model only to apply LoRA, pass a `peft_config` to the trainer instead; if you "
|
| 565 |
+
"wrapped it deliberately (pretrained adapter or custom init), note that the base model matches "
|
| 566 |
+
"your adapter only when it's freshly zero-initialized. If it is, this warning is safe to ignore."
|
| 567 |
+
)
|
| 568 |
+
else:
|
| 569 |
+
model.add_adapter("ref", default_config)
|
| 570 |
+
for name, param in model.named_parameters():
|
| 571 |
+
if ".default." in name:
|
| 572 |
+
ref_name = name.replace(".default.", ".ref.")
|
| 573 |
+
ref_param = model.get_parameter(ref_name)
|
| 574 |
+
ref_param.data.copy_(param.data)
|
| 575 |
+
|
| 576 |
+
# When using gradient checkpointing with PEFT, we need to enable input gradients. transformers.Trainer normally
|
| 577 |
+
# handles this, but a bug currently prevents it; see https://github.com/huggingface/transformers/issues/42489
|
| 578 |
+
if is_peft_model(model) and args.gradient_checkpointing:
|
| 579 |
+
model.enable_input_require_grads()
|
| 580 |
+
|
| 581 |
+
# When using QLoRA, the PEFT adapter weights are converted to bf16 to follow the recommendations from the
|
| 582 |
+
# original paper (see https://huggingface.co/papers/2305.14314, paragraph 3). Normally, this can be done by
|
| 583 |
+
# passing `autocast_adapter_dtype=False` to `get_peft_model`, but this option is not yet supported for
|
| 584 |
+
# quantized models. See: https://github.com/huggingface/peft/issues/2889
|
| 585 |
+
if _is_quantized_model:
|
| 586 |
+
for param in model.parameters():
|
| 587 |
+
if param.requires_grad:
|
| 588 |
+
param.data = param.data.to(torch.bfloat16)
|
| 589 |
+
|
| 590 |
+
# Vision dataset detection
|
| 591 |
+
dataset_sample = next(iter(train_dataset))
|
| 592 |
+
self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample
|
| 593 |
+
if self._is_vision_dataset and not self._is_vlm:
|
| 594 |
+
raise ValueError(
|
| 595 |
+
"The dataset appears to be vision-related (contains 'image' or 'images' keys), but the provided "
|
| 596 |
+
"model does not seem to be a vision-language model. Please check your model and dataset."
|
| 597 |
+
)
|
| 598 |
+
if self._is_vision_dataset and args.precompute_ref_log_probs:
|
| 599 |
+
raise ValueError(
|
| 600 |
+
"`precompute_ref_log_probs=True` is not supported for vision datasets. For vision-language "
|
| 601 |
+
"models, all data processing is performed on the fly rather than upfront. "
|
| 602 |
+
"Set `precompute_ref_log_probs=False`."
|
| 603 |
+
)
|
| 604 |
+
if self._is_vision_dataset and ("chosen" in dataset_sample or "rejected" in dataset_sample):
|
| 605 |
+
raise ValueError(
|
| 606 |
+
"Vision datasets must be in unpaired format with `completion` and `label` columns. "
|
| 607 |
+
"Paired format (`chosen`/`rejected`) is not supported for vision datasets because "
|
| 608 |
+
"iterating over the full dataset to unpair it would be too expensive for large image "
|
| 609 |
+
"collections. Unpair your dataset first: `dataset = unpair_preference_dataset(dataset)`."
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
# Data collator
|
| 613 |
+
calculate_kl = args.loss_type not in ["apo_zero_unpaired"]
|
| 614 |
+
if data_collator is None and not self._is_vision_dataset:
|
| 615 |
+
data_collator = DataCollatorForUnpairedPreference(
|
| 616 |
+
pad_token_id=self._tokenizer.pad_token_id,
|
| 617 |
+
max_length=args.max_length,
|
| 618 |
+
pad_to_multiple_of=args.pad_to_multiple_of,
|
| 619 |
+
)
|
| 620 |
+
elif data_collator is None and self._is_vision_dataset:
|
| 621 |
+
data_collator = DataCollatorForVisionUnpairedPreference(
|
| 622 |
+
processor=processing_class,
|
| 623 |
+
max_length=args.max_length,
|
| 624 |
+
calculate_kl=calculate_kl,
|
| 625 |
+
pad_to_multiple_of=args.pad_to_multiple_of,
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
# Training arguments
|
| 629 |
+
self.beta = args.beta
|
| 630 |
+
self.precompute_ref_logps = args.precompute_ref_log_probs
|
| 631 |
+
self.loss_type = args.loss_type
|
| 632 |
+
self.desirable_weight = args.desirable_weight
|
| 633 |
+
self.undesirable_weight = args.undesirable_weight
|
| 634 |
+
self.aux_loss_enabled = getattr(model.config, "output_router_logits", False)
|
| 635 |
+
self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0)
|
| 636 |
+
self.calculate_KL = calculate_kl
|
| 637 |
+
if self.calculate_KL and args.train_sampling_strategy != "sequential":
|
| 638 |
+
raise ValueError(
|
| 639 |
+
f"Loss type `'{args.loss_type}'` estimates the KL divergence term and requires "
|
| 640 |
+
f"`train_sampling_strategy='sequential'` because the KL completion for each example is precomputed "
|
| 641 |
+
f"against its neighbors in a fixed-order batch; any other strategy breaks that pairing. "
|
| 642 |
+
f"Got `train_sampling_strategy='{args.train_sampling_strategy}'`."
|
| 643 |
+
)
|
| 644 |
+
if self.calculate_KL and args.per_device_train_batch_size <= 1:
|
| 645 |
+
raise ValueError(
|
| 646 |
+
"Actual (not effective) batch size must be > 1. KTO will not work properly because the KL term will be equivalent to the implied reward."
|
| 647 |
+
)
|
| 648 |
+
if self.aux_loss_enabled and self.aux_loss_coef == 0.0:
|
| 649 |
+
logger.warning(
|
| 650 |
+
"You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to "
|
| 651 |
+
"`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value "
|
| 652 |
+
"greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary "
|
| 653 |
+
"loss.",
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
# Dataset
|
| 657 |
+
# Skip dataset preparation for VLMs: tokenization and image processing happen on-the-fly in the collator.
|
| 658 |
+
if not self._is_vision_dataset:
|
| 659 |
+
train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train")
|
| 660 |
+
if eval_dataset is not None:
|
| 661 |
+
if isinstance(eval_dataset, dict):
|
| 662 |
+
eval_dataset = {
|
| 663 |
+
key: self._prepare_dataset(dataset, processing_class, args, key)
|
| 664 |
+
for key, dataset in eval_dataset.items()
|
| 665 |
+
}
|
| 666 |
+
else:
|
| 667 |
+
eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval")
|
| 668 |
+
|
| 669 |
+
# Transformers explicitly set use_reentrant=True in the past to silence a PyTorch warning, but the default was
|
| 670 |
+
# never updated once PyTorch switched to recommending use_reentrant=False. Until that change lands upstream
|
| 671 |
+
# (see https://github.com/huggingface/transformers/pull/43203) and is released (most likely in 5.0.0), we
|
| 672 |
+
# default to the recommended non-reentrant behavior here, while preserving any user-provided value.
|
| 673 |
+
if args.gradient_checkpointing and Version(transformers.__version__) < Version("5.0.0"):
|
| 674 |
+
args.gradient_checkpointing_kwargs = args.gradient_checkpointing_kwargs or {}
|
| 675 |
+
args.gradient_checkpointing_kwargs.setdefault("use_reentrant", False)
|
| 676 |
+
|
| 677 |
+
super().__init__(
|
| 678 |
+
model=model,
|
| 679 |
+
args=args,
|
| 680 |
+
data_collator=data_collator,
|
| 681 |
+
train_dataset=train_dataset,
|
| 682 |
+
eval_dataset=eval_dataset,
|
| 683 |
+
processing_class=processing_class,
|
| 684 |
+
compute_metrics=compute_metrics,
|
| 685 |
+
callbacks=callbacks,
|
| 686 |
+
optimizers=optimizers,
|
| 687 |
+
)
|
| 688 |
+
|
| 689 |
+
# Initialize activation offloading context
|
| 690 |
+
if self.args.activation_offloading:
|
| 691 |
+
self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model)
|
| 692 |
+
else:
|
| 693 |
+
self.maybe_activation_offload_context = contextlib.nullcontext()
|
| 694 |
+
|
| 695 |
+
# Reference model
|
| 696 |
+
if ref_model is None:
|
| 697 |
+
if is_peft_model(self.model) or args.precompute_ref_log_probs:
|
| 698 |
+
# If PEFT is used, the reference model is not needed since the adapter can be disabled to revert to the
|
| 699 |
+
# initial model. If precompute_ref_log_probs is True, the reference model does not need to be kept in
|
| 700 |
+
# memory during training.
|
| 701 |
+
self.ref_model = None
|
| 702 |
+
else:
|
| 703 |
+
ref_model_init_kwargs = args.model_init_kwargs or {}
|
| 704 |
+
# Distributed training requires device_map=None ("auto" fails)
|
| 705 |
+
if self.args.distributed_state.distributed_type in ["MULTI_GPU", "DEEPSPEED"]:
|
| 706 |
+
ref_model_init_kwargs["device_map"] = None
|
| 707 |
+
ref_model_init_kwargs.setdefault("trust_remote_code", args.trust_remote_code)
|
| 708 |
+
ref_model_path = get_config_model_id(self.model.config)
|
| 709 |
+
self.ref_model = create_model_from_path(ref_model_path, **ref_model_init_kwargs)
|
| 710 |
+
else:
|
| 711 |
+
self.ref_model = ref_model
|
| 712 |
+
|
| 713 |
+
# Disable dropout in the model and reference model
|
| 714 |
+
if args.disable_dropout:
|
| 715 |
+
disable_dropout_in_model(model)
|
| 716 |
+
if self.ref_model is not None:
|
| 717 |
+
disable_dropout_in_model(self.ref_model)
|
| 718 |
+
|
| 719 |
+
# Initialize the metrics
|
| 720 |
+
self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
|
| 721 |
+
|
| 722 |
+
# Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
|
| 723 |
+
# model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
|
| 724 |
+
# self.model_accepts_loss_kwargs to False to enable scaling.
|
| 725 |
+
self.model_accepts_loss_kwargs = False
|
| 726 |
+
|
| 727 |
+
# Add tags to the model
|
| 728 |
+
self.model.add_model_tags(self._tag_names)
|
| 729 |
+
|
| 730 |
+
if self.ref_model is not None:
|
| 731 |
+
if self.is_deepspeed_enabled:
|
| 732 |
+
self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
|
| 733 |
+
elif self.is_fsdp_enabled:
|
| 734 |
+
self.ref_model = prepare_fsdp(self.ref_model, self.accelerator)
|
| 735 |
+
else:
|
| 736 |
+
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
|
| 737 |
+
|
| 738 |
+
if args.sync_ref_model:
|
| 739 |
+
if is_peft_model(self.model):
|
| 740 |
+
raise NotImplementedError(
|
| 741 |
+
"You passed `sync_ref_model=True` while using a PEFT model, which is currently not supported. "
|
| 742 |
+
"With PEFT, KTOTrainer does not keep a separate reference model in memory; instead, it recovers "
|
| 743 |
+
"reference behavior by temporarily disabling the adapter. As a result, there is no standalone "
|
| 744 |
+
"`ref_model` instance to synchronize. Use `sync_ref_model=False`, or opt for full fine-tuning if "
|
| 745 |
+
"you need a synced reference model. If you need `sync_ref_model` to work with PEFT, please open a "
|
| 746 |
+
"feature request at https://github.com/huggingface/trl/issues."
|
| 747 |
+
)
|
| 748 |
+
if args.precompute_ref_log_probs:
|
| 749 |
+
raise ValueError(
|
| 750 |
+
"You cannot use `sync_ref_model=True` together with `precompute_ref_log_probs=True`. "
|
| 751 |
+
"`precompute_ref_log_probs=True` assumes a fixed reference model, but with `sync_ref_model=True` "
|
| 752 |
+
"the reference model is periodically updated during training, making any precomputed reference "
|
| 753 |
+
"log-probs stale. Set `precompute_ref_log_probs=False` or disable `sync_ref_model`."
|
| 754 |
+
)
|
| 755 |
+
self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator))
|
| 756 |
+
|
| 757 |
+
self.use_liger_kernel = args.use_liger_kernel
|
| 758 |
+
# Import Liger kernel if enabled
|
| 759 |
+
if self.use_liger_kernel:
|
| 760 |
+
if not is_liger_kernel_available():
|
| 761 |
+
raise ImportError(
|
| 762 |
+
"You set `use_liger_kernel=True` but the liger kernel is not available. "
|
| 763 |
+
"Please install liger-kernel first: `pip install liger-kernel`"
|
| 764 |
+
)
|
| 765 |
+
if self.loss_type in ["apo_zero_unpaired"]:
|
| 766 |
+
raise ValueError(
|
| 767 |
+
"You cannot set `loss_type='apo_zero_unpaired'` with liger-kernel."
|
| 768 |
+
"Only KTO loss is supported with liger-kernel."
|
| 769 |
+
)
|
| 770 |
+
if self.precompute_ref_logps:
|
| 771 |
+
raise ValueError(
|
| 772 |
+
"You cannot use `precompute_ref_log_probs=True` with liger kernel. Please set "
|
| 773 |
+
"`precompute_ref_log_probs=False`."
|
| 774 |
+
)
|
| 775 |
+
if is_peft_model(self.model):
|
| 776 |
+
raise ValueError(
|
| 777 |
+
"You cannot use `use_liger_kernel=True` with Peft models. Please set `use_liger_kernel=False`."
|
| 778 |
+
)
|
| 779 |
+
self.liger_loss_fn = LigerFusedLinearKTOLoss(beta=self.beta, use_ref_model=(self.ref_model is not None))
|
| 780 |
+
|
| 781 |
+
if self.precompute_ref_logps:
|
| 782 |
+
if isinstance(self.train_dataset, IterableDataset) or isinstance(
|
| 783 |
+
self.eval_dataset, (IterableDataset, IterableDatasetDict)
|
| 784 |
+
):
|
| 785 |
+
raise ValueError(
|
| 786 |
+
"`precompute_ref_log_probs=True` is not supported with IterableDataset. Please use a map-style "
|
| 787 |
+
"Dataset or set `precompute_ref_log_probs=False`."
|
| 788 |
+
)
|
| 789 |
+
self.train_dataset = self._precompute_ref_logps(
|
| 790 |
+
self.train_dataset,
|
| 791 |
+
"train",
|
| 792 |
+
self.args.precompute_ref_batch_size or self.args.per_device_train_batch_size,
|
| 793 |
+
)
|
| 794 |
+
if self.eval_dataset is not None:
|
| 795 |
+
if isinstance(self.eval_dataset, dict):
|
| 796 |
+
self.eval_dataset = {
|
| 797 |
+
name: self._precompute_ref_logps(
|
| 798 |
+
dataset, name, self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size
|
| 799 |
+
)
|
| 800 |
+
for name, dataset in self.eval_dataset.items()
|
| 801 |
+
}
|
| 802 |
+
else:
|
| 803 |
+
self.eval_dataset = self._precompute_ref_logps(
|
| 804 |
+
self.eval_dataset,
|
| 805 |
+
"eval",
|
| 806 |
+
self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size,
|
| 807 |
+
)
|
| 808 |
+
|
| 809 |
+
def _tokenize(
|
| 810 |
+
self,
|
| 811 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin,
|
| 812 |
+
input: str | list,
|
| 813 |
+
**kwargs,
|
| 814 |
+
) -> dict[str, list]:
|
| 815 |
+
"""Tokenize a single example for dataset preprocessing.
|
| 816 |
+
|
| 817 |
+
Dispatches to `apply_chat_template` for conversational input (list of message dicts) and to `__call__` for
|
| 818 |
+
non-conversational input (str).
|
| 819 |
+
|
| 820 |
+
Args:
|
| 821 |
+
processing_class ([`~transformers.PreTrainedTokenizerBase`] or [`~transformers.ProcessorMixin`]):
|
| 822 |
+
The tokenizer or processor to use.
|
| 823 |
+
input (`str` or `list`):
|
| 824 |
+
A string for non-conversational input, or a list of message dicts for conversational input.
|
| 825 |
+
**kwargs:
|
| 826 |
+
Forwarded to `apply_chat_template` (e.g. `add_generation_prompt`, `return_assistant_tokens_mask`).
|
| 827 |
+
|
| 828 |
+
Returns:
|
| 829 |
+
`dict` with at least an `"input_ids"` key mapping to a flat `list[int]`.
|
| 830 |
+
"""
|
| 831 |
+
if isinstance(input, list): # conversational: list of message dicts
|
| 832 |
+
if self._is_vlm:
|
| 833 |
+
input = prepare_multimodal_messages(input)
|
| 834 |
+
result = processing_class.apply_chat_template(input, tokenize=True, return_dict=True, **kwargs)
|
| 835 |
+
else: # non-conversational: plain text string
|
| 836 |
+
result = processing_class(text=input)
|
| 837 |
+
# VLMs emit a batch dimension even for single examples; unwrap it
|
| 838 |
+
if self._is_vlm:
|
| 839 |
+
return {k: v[0] for k, v in result.items()}
|
| 840 |
+
return result
|
| 841 |
+
|
| 842 |
+
def _get_kl_dataset(
|
| 843 |
+
self,
|
| 844 |
+
dataset: Dataset | IterableDataset,
|
| 845 |
+
dataset_name: str,
|
| 846 |
+
args: KTOConfig,
|
| 847 |
+
) -> Dataset | IterableDataset:
|
| 848 |
+
"""
|
| 849 |
+
Creates the KL dataset by creating mismatched (prompt, completion) pairs for KL divergence estimation.
|
| 850 |
+
|
| 851 |
+
Args:
|
| 852 |
+
dataset (`Dataset` or `IterableDataset`):
|
| 853 |
+
Tokenized dataset with `prompt_ids` and `completion_ids` columns.
|
| 854 |
+
dataset_name (`str`):
|
| 855 |
+
Name used in progress bar descriptions.
|
| 856 |
+
args ([`KTOConfig`]):
|
| 857 |
+
Training arguments providing `per_device_train_batch_size` and `dataset_num_proc`.
|
| 858 |
+
|
| 859 |
+
Returns:
|
| 860 |
+
`Dataset` or `IterableDataset` with a single `KL_completion_ids` column.
|
| 861 |
+
"""
|
| 862 |
+
map_kwargs = {}
|
| 863 |
+
if isinstance(dataset, Dataset): # IterableDataset does not support num_proc or desc
|
| 864 |
+
map_kwargs["num_proc"] = args.dataset_num_proc
|
| 865 |
+
map_kwargs["desc"] = f"Extracting KL {dataset_name} dataset"
|
| 866 |
+
kl_dataset = dataset.map(
|
| 867 |
+
_get_kl_completion_ids, batched=True, batch_size=args.per_device_train_batch_size, **map_kwargs
|
| 868 |
+
)
|
| 869 |
+
|
| 870 |
+
def rename_kl_fn(example):
|
| 871 |
+
return {"KL_completion_ids": example["completion_ids"]}
|
| 872 |
+
|
| 873 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 874 |
+
map_kwargs["desc"] = f"Assembling KL {dataset_name} dataset"
|
| 875 |
+
column_names = get_dataset_column_names(dataset)
|
| 876 |
+
kl_dataset = kl_dataset.map(
|
| 877 |
+
rename_kl_fn,
|
| 878 |
+
remove_columns=[c for c in get_dataset_column_names(kl_dataset) if c in column_names],
|
| 879 |
+
**map_kwargs,
|
| 880 |
+
)
|
| 881 |
+
return kl_dataset
|
| 882 |
+
|
| 883 |
+
def _prepare_dataset(
|
| 884 |
+
self,
|
| 885 |
+
dataset: Dataset | IterableDataset,
|
| 886 |
+
processing_class: PreTrainedTokenizerBase | ProcessorMixin,
|
| 887 |
+
args: KTOConfig | None,
|
| 888 |
+
dataset_name: str,
|
| 889 |
+
) -> Dataset | IterableDataset:
|
| 890 |
+
# Build the kwargs for the `map` function
|
| 891 |
+
map_kwargs = {}
|
| 892 |
+
if isinstance(dataset, Dataset): # IterableDataset does not support num_proc
|
| 893 |
+
map_kwargs["num_proc"] = args.dataset_num_proc
|
| 894 |
+
|
| 895 |
+
# Compute that only on the main process for faster data processing.
|
| 896 |
+
# see: https://github.com/huggingface/trl/pull/1255
|
| 897 |
+
with PartialState().main_process_first():
|
| 898 |
+
# Extract the prompt if needed
|
| 899 |
+
first_example = next(iter(dataset))
|
| 900 |
+
if "prompt" not in first_example:
|
| 901 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 902 |
+
map_kwargs["desc"] = f"Extracting prompt from {dataset_name} dataset"
|
| 903 |
+
dataset = dataset.map(extract_prompt, **map_kwargs)
|
| 904 |
+
|
| 905 |
+
# Unpair the dataset if needed
|
| 906 |
+
first_example = next(iter(dataset))
|
| 907 |
+
if "chosen" in first_example and "rejected" in first_example:
|
| 908 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 909 |
+
map_kwargs["desc"] = f"Unpairing {dataset_name} dataset"
|
| 910 |
+
dataset = unpair_preference_dataset(dataset, **map_kwargs)
|
| 911 |
+
|
| 912 |
+
# Add EOS token if needed: non-conversational only
|
| 913 |
+
first_example = next(iter(dataset))
|
| 914 |
+
if not is_conversational(first_example):
|
| 915 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 916 |
+
map_kwargs["desc"] = f"Adding EOS to {dataset_name} dataset"
|
| 917 |
+
|
| 918 |
+
def add_eos(example, eos_token):
|
| 919 |
+
if not example["completion"].endswith(eos_token):
|
| 920 |
+
example["completion"] = example["completion"] + eos_token
|
| 921 |
+
return example
|
| 922 |
+
|
| 923 |
+
dataset = dataset.map(add_eos, fn_kwargs={"eos_token": self._tokenizer.eos_token}, **map_kwargs)
|
| 924 |
+
|
| 925 |
+
# Tokenize dataset
|
| 926 |
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
| 927 |
+
map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset"
|
| 928 |
+
|
| 929 |
+
def tokenize_fn(example, processing_class):
|
| 930 |
+
if is_conversational(example):
|
| 931 |
+
chat_template_kwargs = example.get("chat_template_kwargs", {})
|
| 932 |
+
prompt_ids = self._tokenize(
|
| 933 |
+
processing_class,
|
| 934 |
+
example["prompt"],
|
| 935 |
+
add_generation_prompt=True,
|
| 936 |
+
**chat_template_kwargs,
|
| 937 |
+
)["input_ids"]
|
| 938 |
+
prompt_completion_ids = self._tokenize(
|
| 939 |
+
processing_class,
|
| 940 |
+
example["prompt"] + example["completion"],
|
| 941 |
+
**chat_template_kwargs,
|
| 942 |
+
)["input_ids"]
|
| 943 |
+
else:
|
| 944 |
+
prompt_ids = self._tokenize(processing_class, example["prompt"])["input_ids"]
|
| 945 |
+
prompt_completion_ids = self._tokenize(
|
| 946 |
+
processing_class, example["prompt"] + example["completion"]
|
| 947 |
+
)["input_ids"]
|
| 948 |
+
|
| 949 |
+
if not prompt_completion_ids[: len(prompt_ids)] == prompt_ids:
|
| 950 |
+
logger.warning(
|
| 951 |
+
"Mismatch between tokenized prompt and the start of tokenized prompt+completion. "
|
| 952 |
+
"This may be due to unexpected tokenizer behavior, whitespace issues, or special "
|
| 953 |
+
"token handling. Verify that the tokenizer is processing text consistently."
|
| 954 |
+
)
|
| 955 |
+
|
| 956 |
+
return {
|
| 957 |
+
"prompt_ids": prompt_ids,
|
| 958 |
+
"completion_ids": prompt_completion_ids[len(prompt_ids) :],
|
| 959 |
+
}
|
| 960 |
+
|
| 961 |
+
dataset = dataset.map(tokenize_fn, fn_kwargs={"processing_class": processing_class}, **map_kwargs)
|
| 962 |
+
|
| 963 |
+
# Get KL datasets if needed
|
| 964 |
+
if self.calculate_KL:
|
| 965 |
+
# create pairs for estimating the KL term by flipping the matched pairs in each batch of size total_batch_size
|
| 966 |
+
# 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)
|
| 967 |
+
kl_dataset = self._get_kl_dataset(dataset, dataset_name, args)
|
| 968 |
+
dataset = concatenate_datasets([dataset, kl_dataset], axis=1)
|
| 969 |
+
|
| 970 |
+
# Calculate dataset desirability balance
|
| 971 |
+
if dataset_name == "train" and isinstance(dataset, Dataset): # IterableDataset does not support len
|
| 972 |
+
num_desirable = max(sum(dataset["label"]), 1)
|
| 973 |
+
num_undesirable = max(len(dataset["label"]) - num_desirable, 1) # "label" is binary
|
| 974 |
+
|
| 975 |
+
if num_desirable != num_undesirable:
|
| 976 |
+
# The lower and upper bounds come from Eq. (8) of https://huggingface.co/papers/2402.01306
|
| 977 |
+
des_weight_lower_bound = round((num_undesirable * self.undesirable_weight / num_desirable) * 1, 2)
|
| 978 |
+
des_weight_upper_bound = round(
|
| 979 |
+
(num_undesirable * self.undesirable_weight / num_desirable) * 1.33, 2
|
| 980 |
+
)
|
| 981 |
+
und_weight_lower_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1.33, 2)
|
| 982 |
+
und_weight_upper_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1, 2)
|
| 983 |
+
|
| 984 |
+
des_weight_in_range = des_weight_lower_bound <= self.desirable_weight <= des_weight_upper_bound
|
| 985 |
+
und_weight_in_range = und_weight_lower_bound <= self.undesirable_weight <= und_weight_upper_bound
|
| 986 |
+
|
| 987 |
+
if not (des_weight_in_range or und_weight_in_range):
|
| 988 |
+
logger.warning(
|
| 989 |
+
"You have different amounts of desirable/positive and undesirable/negative examples but the "
|
| 990 |
+
"weights on the desirable and undesirable losses don't seem to be in an ideal range. Based "
|
| 991 |
+
f"on your data, we recommend EITHER "
|
| 992 |
+
f"desirable_weight in [{des_weight_lower_bound}, {des_weight_upper_bound}] or "
|
| 993 |
+
f"undesirable_weight in [{und_weight_lower_bound}, {und_weight_upper_bound}] (but NOT BOTH). "
|
| 994 |
+
"See the documentation on how to optimally set these weights.",
|
| 995 |
+
)
|
| 996 |
+
return dataset
|
| 997 |
+
|
| 998 |
+
def _set_signature_columns_if_needed(self):
|
| 999 |
+
# If `self.args.remove_unused_columns` is True, non-signature columns are removed.
|
| 1000 |
+
# By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids"
|
| 1001 |
+
# and "attention_mask").
|
| 1002 |
+
if self._signature_columns is None:
|
| 1003 |
+
if self._is_vision_dataset:
|
| 1004 |
+
self._signature_columns = [
|
| 1005 |
+
"prompt",
|
| 1006 |
+
"completion",
|
| 1007 |
+
"image",
|
| 1008 |
+
"images",
|
| 1009 |
+
"label",
|
| 1010 |
+
"chat_template_kwargs",
|
| 1011 |
+
]
|
| 1012 |
+
else:
|
| 1013 |
+
self._signature_columns = [
|
| 1014 |
+
"prompt_ids",
|
| 1015 |
+
"completion_ids",
|
| 1016 |
+
"KL_completion_ids",
|
| 1017 |
+
"label",
|
| 1018 |
+
"ref_logps",
|
| 1019 |
+
"ref_KL_logps",
|
| 1020 |
+
]
|
| 1021 |
+
|
| 1022 |
+
def _precompute_ref_logps(self, dataset: Dataset, name: str, batch_size: int) -> Dataset:
|
| 1023 |
+
model_hash = hash_module(self.ref_model or self.model)
|
| 1024 |
+
fingerprint = Hasher.hash((dataset._fingerprint, model_hash, self.calculate_KL))
|
| 1025 |
+
cache_file = dataset._get_cache_file_path(fingerprint)
|
| 1026 |
+
if os.path.exists(cache_file):
|
| 1027 |
+
return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1)
|
| 1028 |
+
|
| 1029 |
+
dataloader = DataLoader(
|
| 1030 |
+
dataset,
|
| 1031 |
+
batch_size=batch_size,
|
| 1032 |
+
collate_fn=self.data_collator,
|
| 1033 |
+
num_workers=self.args.dataloader_num_workers,
|
| 1034 |
+
pin_memory=self.args.dataloader_pin_memory,
|
| 1035 |
+
shuffle=False,
|
| 1036 |
+
)
|
| 1037 |
+
data_loader = self.accelerator.prepare(dataloader)
|
| 1038 |
+
ref_logps = []
|
| 1039 |
+
ref_KL_logps = []
|
| 1040 |
+
for padded_batch in tqdm(iterable=data_loader, desc=f"Computing reference log probs for {name} dataset"):
|
| 1041 |
+
ref_logp, ref_KL_logp = self.compute_ref_log_probs(padded_batch)
|
| 1042 |
+
if self.calculate_KL:
|
| 1043 |
+
ref_logp, ref_KL_logp = self.accelerator.gather_for_metrics((ref_logp, ref_KL_logp))
|
| 1044 |
+
ref_KL_logps.append(ref_KL_logp.cpu())
|
| 1045 |
+
else:
|
| 1046 |
+
ref_logp = self.accelerator.gather_for_metrics(ref_logp)
|
| 1047 |
+
ref_logps.append(ref_logp.cpu())
|
| 1048 |
+
|
| 1049 |
+
ref_logps = torch.cat(ref_logps)
|
| 1050 |
+
if self.calculate_KL:
|
| 1051 |
+
ref_KL_logps = torch.cat(ref_KL_logps)
|
| 1052 |
+
|
| 1053 |
+
if self.accelerator.is_main_process:
|
| 1054 |
+
|
| 1055 |
+
def add_ref_logps(batch, indices):
|
| 1056 |
+
result = {"ref_logps": ref_logps[indices]}
|
| 1057 |
+
if self.calculate_KL:
|
| 1058 |
+
result.update({"ref_KL_logps": ref_KL_logps[indices]})
|
| 1059 |
+
return result
|
| 1060 |
+
|
| 1061 |
+
dataset.map(
|
| 1062 |
+
add_ref_logps,
|
| 1063 |
+
with_indices=True,
|
| 1064 |
+
batched=True,
|
| 1065 |
+
remove_columns=dataset.column_names,
|
| 1066 |
+
new_fingerprint=fingerprint,
|
| 1067 |
+
desc=f"Caching reference log probs for {name} dataset",
|
| 1068 |
+
)
|
| 1069 |
+
self.accelerator.wait_for_everyone()
|
| 1070 |
+
|
| 1071 |
+
return concatenate_datasets([dataset, Dataset.from_file(cache_file)], axis=1)
|
| 1072 |
+
|
| 1073 |
+
def compute_ref_log_probs(self, inputs):
|
| 1074 |
+
"""Computes reference log probabilities for a single padded batch."""
|
| 1075 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 1076 |
+
if self.ref_model is None:
|
| 1077 |
+
if is_peft_model(self.model):
|
| 1078 |
+
model = self.accelerator.unwrap_model(self.model)
|
| 1079 |
+
with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None):
|
| 1080 |
+
completion_logits = self.model(
|
| 1081 |
+
inputs["completion_input_ids"],
|
| 1082 |
+
attention_mask=inputs["completion_attention_mask"],
|
| 1083 |
+
).logits
|
| 1084 |
+
|
| 1085 |
+
if self.calculate_KL:
|
| 1086 |
+
KL_logits = self.model(
|
| 1087 |
+
inputs["KL_completion_input_ids"],
|
| 1088 |
+
attention_mask=inputs["KL_completion_attention_mask"],
|
| 1089 |
+
).logits
|
| 1090 |
+
else:
|
| 1091 |
+
completion_logits = self.model(
|
| 1092 |
+
inputs["completion_input_ids"],
|
| 1093 |
+
attention_mask=inputs["completion_attention_mask"],
|
| 1094 |
+
).logits
|
| 1095 |
+
|
| 1096 |
+
if self.calculate_KL:
|
| 1097 |
+
KL_logits = self.model(
|
| 1098 |
+
inputs["KL_completion_input_ids"],
|
| 1099 |
+
attention_mask=inputs["KL_completion_attention_mask"],
|
| 1100 |
+
).logits
|
| 1101 |
+
else:
|
| 1102 |
+
completion_logits = self.ref_model(
|
| 1103 |
+
inputs["completion_input_ids"], attention_mask=inputs["completion_attention_mask"]
|
| 1104 |
+
).logits
|
| 1105 |
+
|
| 1106 |
+
if self.calculate_KL:
|
| 1107 |
+
KL_logits = self.ref_model(
|
| 1108 |
+
inputs["KL_completion_input_ids"],
|
| 1109 |
+
attention_mask=inputs["KL_completion_attention_mask"],
|
| 1110 |
+
).logits
|
| 1111 |
+
|
| 1112 |
+
shift_logits = completion_logits[:, :-1, :]
|
| 1113 |
+
per_token_logps = selective_log_softmax(shift_logits, inputs["completion_input_ids"][:, 1:])
|
| 1114 |
+
per_token_logps[inputs["completion_mask"][:, 1:] == 0] = 0.0
|
| 1115 |
+
completion_logps = per_token_logps.sum(-1)
|
| 1116 |
+
|
| 1117 |
+
if self.calculate_KL:
|
| 1118 |
+
shift_KL_logits = KL_logits[:, :-1, :]
|
| 1119 |
+
KL_per_token_logps = selective_log_softmax(shift_KL_logits, inputs["KL_completion_input_ids"][:, 1:])
|
| 1120 |
+
KL_per_token_logps[inputs["KL_completion_mask"][:, 1:] == 0] = 0.0
|
| 1121 |
+
KL_logps = KL_per_token_logps.sum(-1)
|
| 1122 |
+
else:
|
| 1123 |
+
KL_logps = None
|
| 1124 |
+
|
| 1125 |
+
return completion_logps, KL_logps
|
| 1126 |
+
|
| 1127 |
+
def _compute_kl_logps(self, model, batch):
|
| 1128 |
+
"""Compute KL log probabilities for a given batch."""
|
| 1129 |
+
KL_logps = None
|
| 1130 |
+
if self.calculate_KL:
|
| 1131 |
+
_non_model_keys = {
|
| 1132 |
+
"completion_input_ids",
|
| 1133 |
+
"completion_attention_mask",
|
| 1134 |
+
"completion_mask",
|
| 1135 |
+
"KL_completion_mask",
|
| 1136 |
+
"KL_completion_token_type_ids",
|
| 1137 |
+
"KL_completion_mm_token_type_ids",
|
| 1138 |
+
"label",
|
| 1139 |
+
"ref_logps",
|
| 1140 |
+
"ref_KL_logps",
|
| 1141 |
+
}
|
| 1142 |
+
KL_model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys}
|
| 1143 |
+
KL_model_kwargs["input_ids"] = KL_model_kwargs.pop("KL_completion_input_ids")
|
| 1144 |
+
KL_model_kwargs["attention_mask"] = KL_model_kwargs.pop("KL_completion_attention_mask")
|
| 1145 |
+
# KL sequences have different widths from the main completion after flush_left; override token-type
|
| 1146 |
+
# tensors with the KL-specific ones the collator built for exactly this purpose.
|
| 1147 |
+
if "KL_completion_token_type_ids" in batch:
|
| 1148 |
+
KL_model_kwargs["token_type_ids"] = batch["KL_completion_token_type_ids"]
|
| 1149 |
+
if "KL_completion_mm_token_type_ids" in batch:
|
| 1150 |
+
KL_model_kwargs["mm_token_type_ids"] = batch["KL_completion_mm_token_type_ids"]
|
| 1151 |
+
|
| 1152 |
+
with torch.no_grad():
|
| 1153 |
+
KL_logits = model(**KL_model_kwargs).logits
|
| 1154 |
+
|
| 1155 |
+
shift_KL_logits = KL_logits[:, :-1, :]
|
| 1156 |
+
KL_per_token_logps = selective_log_softmax(shift_KL_logits, batch["KL_completion_input_ids"][:, 1:])
|
| 1157 |
+
KL_per_token_logps[batch["KL_completion_mask"][:, 1:] == 0] = 0.0
|
| 1158 |
+
KL_logps = KL_per_token_logps.sum(-1)
|
| 1159 |
+
return KL_logps
|
| 1160 |
+
|
| 1161 |
+
def _compute_loss_liger(self, model, inputs, return_outputs):
|
| 1162 |
+
if return_outputs:
|
| 1163 |
+
raise RuntimeError(
|
| 1164 |
+
"return_outputs=True is not supported with the Liger KTO loss. The Liger loss computes the loss "
|
| 1165 |
+
"without materializing logits, so outputs cannot be returned."
|
| 1166 |
+
)
|
| 1167 |
+
mode = "train" if self.model.training else "eval"
|
| 1168 |
+
batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()}
|
| 1169 |
+
|
| 1170 |
+
labels = torch.tensor(batch["label"])
|
| 1171 |
+
num_chosen = labels.sum().to(self.accelerator.device)
|
| 1172 |
+
num_rejected = (len(labels) - num_chosen).to(self.accelerator.device)
|
| 1173 |
+
|
| 1174 |
+
policy_KL_logps = self._compute_kl_logps(model, batch)
|
| 1175 |
+
ref_KL_logps = self._compute_kl_logps(self.ref_model, batch)
|
| 1176 |
+
if self.calculate_KL:
|
| 1177 |
+
kl = (policy_KL_logps - ref_KL_logps).mean().detach()
|
| 1178 |
+
kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0)
|
| 1179 |
+
else:
|
| 1180 |
+
kl = torch.zeros(1).to(self.accelerator.device)
|
| 1181 |
+
|
| 1182 |
+
_non_model_keys = {
|
| 1183 |
+
"completion_mask",
|
| 1184 |
+
"KL_completion_input_ids",
|
| 1185 |
+
"KL_completion_attention_mask",
|
| 1186 |
+
"KL_completion_mask",
|
| 1187 |
+
"KL_completion_token_type_ids",
|
| 1188 |
+
"KL_completion_mm_token_type_ids",
|
| 1189 |
+
"label",
|
| 1190 |
+
"ref_logps",
|
| 1191 |
+
"ref_KL_logps",
|
| 1192 |
+
}
|
| 1193 |
+
model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys}
|
| 1194 |
+
model_kwargs["input_ids"] = model_kwargs.pop("completion_input_ids")
|
| 1195 |
+
model_kwargs["attention_mask"] = model_kwargs.pop("completion_attention_mask")
|
| 1196 |
+
model_kwargs["use_cache"] = False
|
| 1197 |
+
if self.aux_loss_enabled:
|
| 1198 |
+
model_kwargs["output_router_logits"] = True
|
| 1199 |
+
|
| 1200 |
+
# `base_model` gives the inner module (skipping `lm_head`) — text decoder for LMs, multimodal wrapper for
|
| 1201 |
+
# VLMs (so vision-token injection runs before the text decoder). `get_decoder()` won't do: on VLMs it
|
| 1202 |
+
# returns just the text stack and feeds image-placeholder IDs through it.
|
| 1203 |
+
# Pre-5.0 transformers VLMs set `base_model_prefix = ""` so `base_model is self` (re-runs `lm_head`).
|
| 1204 |
+
# Fall back to `.model` there.
|
| 1205 |
+
if self._is_vlm and Version(transformers.__version__) < Version("5.0.0"):
|
| 1206 |
+
backbone, ref_backbone = model.model, self.ref_model.model
|
| 1207 |
+
else:
|
| 1208 |
+
backbone, ref_backbone = model.base_model, self.ref_model.base_model
|
| 1209 |
+
|
| 1210 |
+
outputs = backbone(**model_kwargs)
|
| 1211 |
+
|
| 1212 |
+
# reference model
|
| 1213 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 1214 |
+
ref_outputs = ref_backbone(**{k: v for k, v in model_kwargs.items() if k != "output_router_logits"})
|
| 1215 |
+
lm_head = model.get_output_embeddings()
|
| 1216 |
+
ref_lm_head = self.ref_model.get_output_embeddings()
|
| 1217 |
+
|
| 1218 |
+
shift_completion_mask = batch["completion_mask"][:, 1:]
|
| 1219 |
+
target = batch["completion_input_ids"][:, 1:].clone()
|
| 1220 |
+
target[shift_completion_mask == 0] = -100
|
| 1221 |
+
|
| 1222 |
+
(
|
| 1223 |
+
loss,
|
| 1224 |
+
(
|
| 1225 |
+
chosen_logps_sum,
|
| 1226 |
+
rejected_logps_sum,
|
| 1227 |
+
chosen_logits_sum,
|
| 1228 |
+
rejected_logits_sum,
|
| 1229 |
+
chosen_rewards_sum,
|
| 1230 |
+
rejected_rewards_sum,
|
| 1231 |
+
),
|
| 1232 |
+
) = self.liger_loss_fn(
|
| 1233 |
+
_input=outputs.last_hidden_state[:, :-1],
|
| 1234 |
+
lin_weight=lm_head.weight,
|
| 1235 |
+
target=target,
|
| 1236 |
+
bias=lm_head.bias if hasattr(lm_head, "bias") else None,
|
| 1237 |
+
preference_labels=torch.tensor(batch["label"], dtype=torch.bool).to(self.accelerator.device),
|
| 1238 |
+
ref_input=ref_outputs.last_hidden_state[:, :-1],
|
| 1239 |
+
ref_weight=ref_lm_head.weight,
|
| 1240 |
+
ref_bias=ref_lm_head.bias if hasattr(lm_head, "bias") else None,
|
| 1241 |
+
kl=kl,
|
| 1242 |
+
)
|
| 1243 |
+
if self.aux_loss_enabled:
|
| 1244 |
+
loss += self.aux_loss_coef * outputs.aux_loss
|
| 1245 |
+
|
| 1246 |
+
self._metrics[mode]["kl"].append(kl.item())
|
| 1247 |
+
|
| 1248 |
+
all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item()
|
| 1249 |
+
all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item()
|
| 1250 |
+
|
| 1251 |
+
if all_num_chosen > 0:
|
| 1252 |
+
self._metrics[mode]["rewards/chosen"].append(
|
| 1253 |
+
self.accelerator.gather_for_metrics(chosen_rewards_sum.nansum()).nansum().item() / all_num_chosen
|
| 1254 |
+
)
|
| 1255 |
+
self._metrics[mode]["logps/chosen"].append(
|
| 1256 |
+
self.accelerator.gather_for_metrics(chosen_logps_sum.nansum()).nansum().item() / all_num_chosen
|
| 1257 |
+
)
|
| 1258 |
+
self._metrics[mode]["logits/chosen"].append(
|
| 1259 |
+
self.accelerator.gather_for_metrics(chosen_logits_sum.nansum()).nansum().item() / all_num_chosen
|
| 1260 |
+
)
|
| 1261 |
+
|
| 1262 |
+
if all_num_rejected > 0:
|
| 1263 |
+
self._metrics[mode]["rewards/rejected"].append(
|
| 1264 |
+
self.accelerator.gather_for_metrics(rejected_rewards_sum.nansum()).nansum().item() / all_num_rejected
|
| 1265 |
+
)
|
| 1266 |
+
self._metrics[mode]["logps/rejected"].append(
|
| 1267 |
+
self.accelerator.gather_for_metrics(rejected_logps_sum.nansum()).nansum().item() / all_num_rejected
|
| 1268 |
+
)
|
| 1269 |
+
self._metrics[mode]["logits/rejected"].append(
|
| 1270 |
+
self.accelerator.gather_for_metrics(rejected_logits_sum.nansum()).nansum().item() / all_num_rejected
|
| 1271 |
+
)
|
| 1272 |
+
|
| 1273 |
+
return loss
|
| 1274 |
+
|
| 1275 |
+
def _compute_loss(self, model, inputs, return_outputs):
|
| 1276 |
+
"""Compute the KTO loss and other metrics for the given batch of inputs for train or test."""
|
| 1277 |
+
mode = "train" if self.model.training else "eval"
|
| 1278 |
+
batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()}
|
| 1279 |
+
|
| 1280 |
+
labels = torch.tensor(batch["label"])
|
| 1281 |
+
num_chosen = labels.sum().to(self.accelerator.device)
|
| 1282 |
+
num_rejected = (len(labels) - num_chosen).to(self.accelerator.device)
|
| 1283 |
+
|
| 1284 |
+
policy_KL_logps = self._compute_kl_logps(model, batch)
|
| 1285 |
+
|
| 1286 |
+
_non_model_keys = {
|
| 1287 |
+
"completion_mask",
|
| 1288 |
+
"KL_completion_input_ids",
|
| 1289 |
+
"KL_completion_attention_mask",
|
| 1290 |
+
"KL_completion_mask",
|
| 1291 |
+
"KL_completion_token_type_ids",
|
| 1292 |
+
"KL_completion_mm_token_type_ids",
|
| 1293 |
+
"label",
|
| 1294 |
+
"ref_logps",
|
| 1295 |
+
"ref_KL_logps",
|
| 1296 |
+
}
|
| 1297 |
+
model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys}
|
| 1298 |
+
model_kwargs["input_ids"] = model_kwargs.pop("completion_input_ids")
|
| 1299 |
+
model_kwargs["attention_mask"] = model_kwargs.pop("completion_attention_mask")
|
| 1300 |
+
if self.aux_loss_enabled:
|
| 1301 |
+
model_kwargs["output_router_logits"] = True
|
| 1302 |
+
|
| 1303 |
+
outputs = model(**model_kwargs)
|
| 1304 |
+
if self.aux_loss_enabled:
|
| 1305 |
+
aux_loss = outputs.aux_loss
|
| 1306 |
+
|
| 1307 |
+
shift_logits = outputs.logits[:, :-1, :]
|
| 1308 |
+
per_token_logps = selective_log_softmax(shift_logits, batch["completion_input_ids"][:, 1:])
|
| 1309 |
+
per_token_logps[batch["completion_mask"][:, 1:] == 0] = 0.0
|
| 1310 |
+
completion_logps = per_token_logps.sum(-1)
|
| 1311 |
+
|
| 1312 |
+
if completion_logps.shape[0] != len(batch["label"]):
|
| 1313 |
+
raise ValueError(
|
| 1314 |
+
"There is a mismatch between the number of examples in this batch and the number of "
|
| 1315 |
+
"examples for which an output sequence was predicted."
|
| 1316 |
+
)
|
| 1317 |
+
|
| 1318 |
+
device = outputs.logits.device
|
| 1319 |
+
bool_labels = torch.as_tensor(batch["label"], dtype=torch.bool, device=device)
|
| 1320 |
+
chosen_idx = torch.nonzero(bool_labels, as_tuple=False).view(-1)
|
| 1321 |
+
rejected_idx = torch.nonzero(~bool_labels, as_tuple=False).view(-1)
|
| 1322 |
+
|
| 1323 |
+
policy_chosen_logps = completion_logps.index_select(0, chosen_idx)
|
| 1324 |
+
policy_rejected_logps = completion_logps.index_select(0, rejected_idx)
|
| 1325 |
+
policy_chosen_logits = outputs.logits.index_select(0, chosen_idx)
|
| 1326 |
+
policy_rejected_logits = outputs.logits.index_select(0, rejected_idx)
|
| 1327 |
+
|
| 1328 |
+
if self.precompute_ref_logps:
|
| 1329 |
+
ref_chosen_logps = batch["ref_logps"].index_select(0, chosen_idx)
|
| 1330 |
+
ref_rejected_logps = batch["ref_logps"].index_select(0, rejected_idx)
|
| 1331 |
+
if self.calculate_KL:
|
| 1332 |
+
ref_KL_logps = batch["ref_KL_logps"]
|
| 1333 |
+
else:
|
| 1334 |
+
ref_KL_logps = None
|
| 1335 |
+
else:
|
| 1336 |
+
ref_model_kwargs = {k: v for k, v in model_kwargs.items() if k != "output_router_logits"}
|
| 1337 |
+
with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):
|
| 1338 |
+
if is_peft_model(self.model) and self.ref_model is None:
|
| 1339 |
+
ref_model_unwrapped = self.accelerator.unwrap_model(self.model)
|
| 1340 |
+
with use_adapter(
|
| 1341 |
+
ref_model_unwrapped, adapter_name="ref" if "ref" in ref_model_unwrapped.peft_config else None
|
| 1342 |
+
):
|
| 1343 |
+
ref_KL_logps = self._compute_kl_logps(self.model, batch)
|
| 1344 |
+
ref_outputs = self.model(**ref_model_kwargs)
|
| 1345 |
+
else:
|
| 1346 |
+
ref_KL_logps = self._compute_kl_logps(self.ref_model, batch)
|
| 1347 |
+
ref_outputs = self.ref_model(**ref_model_kwargs)
|
| 1348 |
+
ref_shift_logits = ref_outputs.logits[:, :-1, :]
|
| 1349 |
+
ref_per_token_logps = selective_log_softmax(ref_shift_logits, batch["completion_input_ids"][:, 1:])
|
| 1350 |
+
ref_per_token_logps[batch["completion_mask"][:, 1:] == 0] = 0.0
|
| 1351 |
+
ref_completion_logps = ref_per_token_logps.sum(-1)
|
| 1352 |
+
ref_chosen_logps = ref_completion_logps.index_select(0, chosen_idx)
|
| 1353 |
+
ref_rejected_logps = ref_completion_logps.index_select(0, rejected_idx)
|
| 1354 |
+
|
| 1355 |
+
if self.calculate_KL:
|
| 1356 |
+
kl = (policy_KL_logps - ref_KL_logps).mean().detach()
|
| 1357 |
+
kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0)
|
| 1358 |
+
else:
|
| 1359 |
+
kl = torch.zeros(1).to(policy_chosen_logps.device)
|
| 1360 |
+
# Chosen losses
|
| 1361 |
+
if policy_chosen_logps.shape[0] != 0 or ref_chosen_logps.shape[0] != 0:
|
| 1362 |
+
chosen_logratios = policy_chosen_logps - ref_chosen_logps
|
| 1363 |
+
|
| 1364 |
+
if self.loss_type == "kto":
|
| 1365 |
+
# Eqn (7) of the KTO paper (https://huggingface.co/papers/2402.01306)
|
| 1366 |
+
chosen_losses = 1 - F.sigmoid(self.beta * (chosen_logratios - kl))
|
| 1367 |
+
elif self.loss_type == "apo_zero_unpaired":
|
| 1368 |
+
# Unpaired variant of Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266)
|
| 1369 |
+
# Use this loss when you believe the chosen outputs are better than your model's default output
|
| 1370 |
+
chosen_losses = 1 - F.sigmoid(self.beta * chosen_logratios)
|
| 1371 |
+
|
| 1372 |
+
chosen_rewards = self.beta * chosen_logratios.detach()
|
| 1373 |
+
|
| 1374 |
+
else:
|
| 1375 |
+
# lists can't be empty -- if they are, then accelerate.gather will hang
|
| 1376 |
+
chosen_losses = torch.Tensor([]).to(self.accelerator.device)
|
| 1377 |
+
chosen_rewards = torch.Tensor([]).to(self.accelerator.device)
|
| 1378 |
+
# Rejected losses
|
| 1379 |
+
if policy_rejected_logps.shape[0] != 0 or ref_rejected_logps.shape[0] != 0:
|
| 1380 |
+
rejected_logratios = policy_rejected_logps - ref_rejected_logps
|
| 1381 |
+
|
| 1382 |
+
if self.loss_type == "kto":
|
| 1383 |
+
rejected_losses = 1 - F.sigmoid(self.beta * (kl - rejected_logratios))
|
| 1384 |
+
elif self.loss_type == "apo_zero_unpaired":
|
| 1385 |
+
rejected_losses = F.sigmoid(self.beta * rejected_logratios)
|
| 1386 |
+
|
| 1387 |
+
rejected_rewards = self.beta * rejected_logratios.detach()
|
| 1388 |
+
else:
|
| 1389 |
+
# lists can't be empty -- if they are, then accelerate.gather will hang
|
| 1390 |
+
rejected_losses = torch.Tensor([]).to(self.accelerator.device)
|
| 1391 |
+
rejected_rewards = torch.Tensor([]).to(self.accelerator.device)
|
| 1392 |
+
losses = torch.cat(
|
| 1393 |
+
(self.desirable_weight * chosen_losses, self.undesirable_weight * rejected_losses),
|
| 1394 |
+
0,
|
| 1395 |
+
)
|
| 1396 |
+
|
| 1397 |
+
self._metrics[mode]["kl"].append(kl.item())
|
| 1398 |
+
|
| 1399 |
+
all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item()
|
| 1400 |
+
all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item()
|
| 1401 |
+
|
| 1402 |
+
if all_num_chosen > 0:
|
| 1403 |
+
self._metrics[mode]["rewards/chosen"].append(
|
| 1404 |
+
self.accelerator.gather_for_metrics(chosen_rewards.nansum()).nansum().item() / all_num_chosen
|
| 1405 |
+
)
|
| 1406 |
+
self._metrics[mode]["logps/chosen"].append(
|
| 1407 |
+
self.accelerator.gather_for_metrics(policy_chosen_logps.nansum()).nansum().item() / all_num_chosen
|
| 1408 |
+
)
|
| 1409 |
+
self._metrics[mode]["logits/chosen"].append(
|
| 1410 |
+
self.accelerator.gather_for_metrics(policy_chosen_logits.nansum()).nansum().item() / all_num_chosen
|
| 1411 |
+
)
|
| 1412 |
+
|
| 1413 |
+
if all_num_rejected > 0:
|
| 1414 |
+
self._metrics[mode]["rewards/rejected"].append(
|
| 1415 |
+
self.accelerator.gather_for_metrics(rejected_rewards.nansum()).nansum().item() / all_num_rejected
|
| 1416 |
+
)
|
| 1417 |
+
self._metrics[mode]["logps/rejected"].append(
|
| 1418 |
+
self.accelerator.gather_for_metrics(policy_rejected_logps.nansum()).nansum().item() / all_num_rejected
|
| 1419 |
+
)
|
| 1420 |
+
self._metrics[mode]["logits/rejected"].append(
|
| 1421 |
+
self.accelerator.gather_for_metrics(policy_rejected_logits.nansum()).nansum().item() / all_num_rejected
|
| 1422 |
+
)
|
| 1423 |
+
|
| 1424 |
+
loss = losses.nanmean()
|
| 1425 |
+
if self.aux_loss_enabled:
|
| 1426 |
+
loss += self.aux_loss_coef * aux_loss
|
| 1427 |
+
|
| 1428 |
+
return (loss, outputs) if return_outputs else loss
|
| 1429 |
+
|
| 1430 |
+
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
|
| 1431 |
+
try:
|
| 1432 |
+
if self.use_liger_kernel:
|
| 1433 |
+
return self._compute_loss_liger(model, inputs, return_outputs)
|
| 1434 |
+
return self._compute_loss(model, inputs, return_outputs)
|
| 1435 |
+
except ValueError as e:
|
| 1436 |
+
if "Image features and image tokens do not match" in str(e) and self.args.max_length is not None:
|
| 1437 |
+
raise ValueError(
|
| 1438 |
+
f"The current `max_length` ({self.args.max_length}) is too short and causes image placeholder "
|
| 1439 |
+
f"tokens in `input_ids` to be truncated, while the corresponding image features remain intact. "
|
| 1440 |
+
f"Please increase `max_length` or set it to `None` to disable truncation."
|
| 1441 |
+
) from e
|
| 1442 |
+
raise
|
| 1443 |
+
|
| 1444 |
+
def _get_train_sampler(self, train_dataset: Dataset | None = None) -> torch.utils.data.Sampler | None:
|
| 1445 |
+
if self.calculate_KL and Version(transformers.__version__) < Version("5.2.0"):
|
| 1446 |
+
if train_dataset is None:
|
| 1447 |
+
train_dataset = self.train_dataset
|
| 1448 |
+
if train_dataset is None or not has_length(train_dataset):
|
| 1449 |
+
return None
|
| 1450 |
+
return SequentialSampler(train_dataset)
|
| 1451 |
+
return super()._get_train_sampler(train_dataset)
|
| 1452 |
+
|
| 1453 |
+
# During eval, Trainer calls prediction_step. If no labels are present in the inputs, it only runs forward and
|
| 1454 |
+
# returns logits. We override prediction_step to force compute_loss, because this trainer doesn't involve labels.
|
| 1455 |
+
def prediction_step(self, model, inputs, prediction_loss_only, ignore_keys=None):
|
| 1456 |
+
inputs = self._prepare_inputs(inputs)
|
| 1457 |
+
with torch.no_grad(), self.compute_loss_context_manager():
|
| 1458 |
+
if prediction_loss_only:
|
| 1459 |
+
loss = self.compute_loss(model, inputs, return_outputs=False) # logits aren't materialized with liger
|
| 1460 |
+
logits, labels = None, None
|
| 1461 |
+
else:
|
| 1462 |
+
loss, outputs = self.compute_loss(model, inputs, return_outputs=True)
|
| 1463 |
+
logits, labels = outputs.logits, inputs["completion_input_ids"]
|
| 1464 |
+
return loss, logits, labels
|
| 1465 |
+
|
| 1466 |
+
# Override training step to add activation offloading context.
|
| 1467 |
+
def training_step(self, *args, **kwargs):
|
| 1468 |
+
with self.maybe_activation_offload_context:
|
| 1469 |
+
return super().training_step(*args, **kwargs)
|
| 1470 |
+
|
| 1471 |
+
def log(self, logs: dict[str, float], start_time: float | None = None) -> None:
|
| 1472 |
+
mode = "train" if self.model.training else "eval"
|
| 1473 |
+
metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics
|
| 1474 |
+
if "rewards/chosen" in metrics and "rewards/rejected" in metrics:
|
| 1475 |
+
metrics["rewards/margins"] = metrics["rewards/chosen"] - metrics["rewards/rejected"]
|
| 1476 |
+
# This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
|
| 1477 |
+
# start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
|
| 1478 |
+
if mode == "eval":
|
| 1479 |
+
metrics = {f"eval_{key}": val for key, val in metrics.items()}
|
| 1480 |
+
logs.update(metrics)
|
| 1481 |
+
super().log(logs, start_time)
|
| 1482 |
+
self._metrics[mode].clear()
|
| 1483 |
+
|
| 1484 |
+
# Ensure the model card is saved along with the checkpoint
|
| 1485 |
+
def _save_checkpoint(self, model, trial):
|
| 1486 |
+
if self.args.hub_model_id is None:
|
| 1487 |
+
model_name = Path(self.args.output_dir).name
|
| 1488 |
+
else:
|
| 1489 |
+
model_name = self.args.hub_model_id.split("/")[-1]
|
| 1490 |
+
self.create_model_card(model_name=model_name)
|
| 1491 |
+
super()._save_checkpoint(model, trial)
|
tasks/tasksmith-03a6a091b12f/solution/solve.sh
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
set -eu
|
| 3 |
+
mkdir -p -- /workspace/trl/experimental/kto
|
| 4 |
+
cp /solution/reference/trl/experimental/kto/kto_config.py /workspace/trl/experimental/kto/kto_config.py
|
| 5 |
+
mkdir -p -- /workspace/trl/experimental/kto
|
| 6 |
+
cp /solution/reference/trl/experimental/kto/kto_trainer.py /workspace/trl/experimental/kto/kto_trainer.py
|
tasks/tasksmith-03a6a091b12f/task.toml
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.3"
|
| 2 |
+
|
| 3 |
+
[task]
|
| 4 |
+
name = "repo2rlenv/tasksmith-03a6a091b12f"
|
| 5 |
+
|
| 6 |
+
[metadata.repo2env]
|
| 7 |
+
recipe = "tasksmith"
|
| 8 |
+
recipe_version = "1"
|
| 9 |
+
source_url = "https://github.com/huggingface/trl/pull/6152"
|
| 10 |
+
source_head = "472c7f9c924674c0ced18bc608a737191466334f"
|
| 11 |
+
source_base = "f9aeb5902855e60a006d3b6a56487ab01c54eba8"
|
| 12 |
+
workspace_strategy = "head_minus_source_patch"
|
| 13 |
+
source_diff_sha256 = "018c7f48e9e0867070b3ed577ea5c96b1bd14ab148b4472c76648033084faa74"
|
| 14 |
+
acceptance_profile = "practical-generation-v1"
|
| 15 |
+
upstream_test_policy = "retain"
|
| 16 |
+
reward_kinds = [
|
| 17 |
+
"test_execution",
|
| 18 |
+
]
|
| 19 |
+
quality_status = "exported"
|
| 20 |
+
fail_to_pass_count = 2
|
| 21 |
+
pass_to_pass_count = 7
|
| 22 |
+
bundle_hash = "sha256:51fc3cd2d5e9662a4bee9b3d0bb873b8177c4486f766bd3fe832591e302ad122"
|
| 23 |
+
|
| 24 |
+
[metadata.repo2env.evaluation]
|
| 25 |
+
schema_version = "1"
|
| 26 |
+
status = "verified"
|
| 27 |
+
stage = "complete"
|
| 28 |
+
reason_codes = [
|
| 29 |
+
"quality_verified",
|
| 30 |
+
]
|
| 31 |
+
detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile."
|
| 32 |
+
checked_at = "2026-09-14T05:39:25.898491Z"
|
| 33 |
+
provenance = "assisted"
|
| 34 |
+
subject_bundle_hash = "sha256:51fc3cd2d5e9662a4bee9b3d0bb873b8177c4486f766bd3fe832591e302ad122"
|
| 35 |
+
profile = "practical-generation-v1"
|
| 36 |
+
source_task_path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale30/cpu-pair-repair-v1/candidates/03a6a091b12f/quality/revisions/r0/tasksmith-03a6a091b12f"
|
| 37 |
+
source_task_toml_sha256 = "f89210bc678e905939608dcafdc63bd16ef01afa552a04157312b7c03661b65c"
|
| 38 |
+
|
| 39 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 40 |
+
kind = "quality_result"
|
| 41 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale30/cpu-pair-repair-v1/candidates/03a6a091b12f/quality/result.json"
|
| 42 |
+
sha256 = "9c91f4dc993e4ea155b6813f9ab8d3c8c592a44e93528a70b742fdfc4940b5be"
|
| 43 |
+
subject_bundle_hash = "sha256:51fc3cd2d5e9662a4bee9b3d0bb873b8177c4486f766bd3fe832591e302ad122"
|
| 44 |
+
|
| 45 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 46 |
+
kind = "baseline"
|
| 47 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale30/cpu-pair-repair-v1/candidates/03a6a091b12f/quality/trials/r0-baseline/scale30-cpu-pair-repair-v1-03a6a091b12f-r0-baseline/tasksmith-03a6a091b12f__WURjpE3/result.json"
|
| 48 |
+
sha256 = "0a7855a976bb5013c98b3236e4b5ec48a3aec3903a3d594957bb111c1d524edc"
|
| 49 |
+
subject_bundle_hash = "sha256:51fc3cd2d5e9662a4bee9b3d0bb873b8177c4486f766bd3fe832591e302ad122"
|
| 50 |
+
harbor_task_checksum = "43e41f8ce4ec8dd90e986bc312c5cfa0c69366ccd03680de6d697b0f4059a5d9"
|
| 51 |
+
|
| 52 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 53 |
+
kind = "oracle"
|
| 54 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale30/cpu-pair-repair-v1/candidates/03a6a091b12f/quality/trials/r0-oracle/scale30-cpu-pair-repair-v1-03a6a091b12f-r0-oracle/tasksmith-03a6a091b12f__AZpdZuC/result.json"
|
| 55 |
+
sha256 = "36d2d2d702e891247ee6693820f1709a6438c730d93eff13f4d2b2761ddfc86f"
|
| 56 |
+
subject_bundle_hash = "sha256:51fc3cd2d5e9662a4bee9b3d0bb873b8177c4486f766bd3fe832591e302ad122"
|
| 57 |
+
harbor_task_checksum = "43e41f8ce4ec8dd90e986bc312c5cfa0c69366ccd03680de6d697b0f4059a5d9"
|
| 58 |
+
|
| 59 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 60 |
+
kind = "probe"
|
| 61 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale30/cpu-pair-repair-v1/candidates/03a6a091b12f/quality/trials/r0-probe0/scale30-cpu-pair-repair-v1-03a6a091b12f-r0-probe0/tasksmith-03a6a091b12f__PTMCLHh/result.json"
|
| 62 |
+
sha256 = "adc5dc357c55982f90b705248ed1001c6fea8bb2a2affe8dcf562e62b9ecf48c"
|
| 63 |
+
subject_bundle_hash = "sha256:494577c1bafe920981624c0075a6bc072d5f127a0a6e291d9627122017f21e48"
|
| 64 |
+
harbor_task_checksum = "34126692e7a9be44d10ce9447a19dea1c4148966fef179b27f62456edbc1a611"
|
| 65 |
+
|
| 66 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 67 |
+
kind = "probe"
|
| 68 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale30/cpu-pair-repair-v1/candidates/03a6a091b12f/quality/trials/r0-probe1/scale30-cpu-pair-repair-v1-03a6a091b12f-r0-probe1/tasksmith-03a6a091b12f__GCQ7TaT/result.json"
|
| 69 |
+
sha256 = "fdb19e6fffc032cc8194e939d9c5feeaaf05a109f8d6238708283c93e12050d6"
|
| 70 |
+
subject_bundle_hash = "sha256:754cf8a0b6fafe8d2b86616ba1088adac4abdd38f1398c305f8d5ae0eec5f193"
|
| 71 |
+
harbor_task_checksum = "4b28f2a42f69f1db898283f48d5a069a8bccb6affe77f2f04e62db17bbfa6773"
|
| 72 |
+
|
| 73 |
+
[[metadata.repo2env.evaluation.evidence]]
|
| 74 |
+
kind = "rollout"
|
| 75 |
+
path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale30/cpu-pair-repair-v1/candidates/03a6a091b12f/quality/trials/r0-rollout/scale30-cpu-pair-repair-v1-03a6a091b12f-r0-rollout/tasksmith-03a6a091b12f__jKsfLHe/result.json"
|
| 76 |
+
sha256 = "f8868b64c662d8e76186120004274e2e9b63e0503e475253e7e620e06bb05316"
|
| 77 |
+
subject_bundle_hash = "sha256:51fc3cd2d5e9662a4bee9b3d0bb873b8177c4486f766bd3fe832591e302ad122"
|
| 78 |
+
harbor_task_checksum = "43e41f8ce4ec8dd90e986bc312c5cfa0c69366ccd03680de6d697b0f4059a5d9"
|
| 79 |
+
|
| 80 |
+
[environment]
|
| 81 |
+
cpus = 1
|
| 82 |
+
memory_mb = 2048
|
| 83 |
+
build_timeout_sec = 600
|
| 84 |
+
network_mode = "no-network"
|
| 85 |
+
|
| 86 |
+
[agent]
|
| 87 |
+
timeout_sec = 600
|
| 88 |
+
user = "learner"
|
| 89 |
+
network_mode = "no-network"
|
| 90 |
+
|
| 91 |
+
[verifier]
|
| 92 |
+
timeout_sec = 90
|
| 93 |
+
user = "root"
|
| 94 |
+
network_mode = "no-network"
|
| 95 |
+
environment_mode = "separate"
|
| 96 |
+
|
| 97 |
+
[verifier.environment]
|
| 98 |
+
network_mode = "no-network"
|
| 99 |
+
cpus = 1
|
| 100 |
+
memory_mb = 2048
|
| 101 |
+
|
| 102 |
+
[[artifacts]]
|
| 103 |
+
source = "/workspace/trl/__init__.py"
|
| 104 |
+
|
| 105 |
+
[[artifacts]]
|
| 106 |
+
source = "/workspace/trl/_compat.py"
|
| 107 |
+
|
| 108 |
+
[[artifacts]]
|
| 109 |
+
source = "/workspace/trl/_lazy_module.py"
|
| 110 |
+
|
| 111 |
+
[[artifacts]]
|
| 112 |
+
source = "/workspace/trl/chat_template_utils.py"
|
| 113 |
+
|
| 114 |
+
[[artifacts]]
|
| 115 |
+
source = "/workspace/trl/cli/__init__.py"
|
| 116 |
+
|
| 117 |
+
[[artifacts]]
|
| 118 |
+
source = "/workspace/trl/cli/accelerate_config.py"
|
| 119 |
+
|
| 120 |
+
[[artifacts]]
|
| 121 |
+
source = "/workspace/trl/cli/accelerate_launcher.py"
|
| 122 |
+
|
| 123 |
+
[[artifacts]]
|
| 124 |
+
source = "/workspace/trl/cli/commands/__init__.py"
|
| 125 |
+
|
| 126 |
+
[[artifacts]]
|
| 127 |
+
source = "/workspace/trl/cli/commands/base.py"
|
| 128 |
+
|
| 129 |
+
[[artifacts]]
|
| 130 |
+
source = "/workspace/trl/cli/commands/env.py"
|
| 131 |
+
|
| 132 |
+
[[artifacts]]
|
| 133 |
+
source = "/workspace/trl/cli/commands/skills.py"
|
| 134 |
+
|
| 135 |
+
[[artifacts]]
|
| 136 |
+
source = "/workspace/trl/cli/commands/training.py"
|
| 137 |
+
|
| 138 |
+
[[artifacts]]
|
| 139 |
+
source = "/workspace/trl/cli/commands/vllm_serve.py"
|
| 140 |
+
|
| 141 |
+
[[artifacts]]
|
| 142 |
+
source = "/workspace/trl/cli/main.py"
|
| 143 |
+
|
| 144 |
+
[[artifacts]]
|
| 145 |
+
source = "/workspace/trl/data_utils.py"
|
| 146 |
+
|
| 147 |
+
[[artifacts]]
|
| 148 |
+
source = "/workspace/trl/distributed.py"
|
| 149 |
+
|
| 150 |
+
[[artifacts]]
|
| 151 |
+
source = "/workspace/trl/experimental/__init__.py"
|
| 152 |
+
|
| 153 |
+
[[artifacts]]
|
| 154 |
+
source = "/workspace/trl/experimental/a2po/__init__.py"
|
| 155 |
+
|
| 156 |
+
[[artifacts]]
|
| 157 |
+
source = "/workspace/trl/experimental/a2po/a2po_config.py"
|
| 158 |
+
|
| 159 |
+
[[artifacts]]
|
| 160 |
+
source = "/workspace/trl/experimental/a2po/a2po_trainer.py"
|
| 161 |
+
|
| 162 |
+
[[artifacts]]
|
| 163 |
+
source = "/workspace/trl/experimental/async_grpo/__init__.py"
|
| 164 |
+
|
| 165 |
+
[[artifacts]]
|
| 166 |
+
source = "/workspace/trl/experimental/async_grpo/async_grpo_config.py"
|
| 167 |
+
|
| 168 |
+
[[artifacts]]
|
| 169 |
+
source = "/workspace/trl/experimental/async_grpo/async_grpo_trainer.py"
|
| 170 |
+
|
| 171 |
+
[[artifacts]]
|
| 172 |
+
source = "/workspace/trl/experimental/async_grpo/async_rollout_worker.py"
|
| 173 |
+
|
| 174 |
+
[[artifacts]]
|
| 175 |
+
source = "/workspace/trl/experimental/async_grpo/weight_transfer.py"
|
| 176 |
+
|
| 177 |
+
[[artifacts]]
|
| 178 |
+
source = "/workspace/trl/experimental/bco/__init__.py"
|
| 179 |
+
|
| 180 |
+
[[artifacts]]
|
| 181 |
+
source = "/workspace/trl/experimental/bco/bco_config.py"
|
| 182 |
+
|
| 183 |
+
[[artifacts]]
|
| 184 |
+
source = "/workspace/trl/experimental/bco/bco_trainer.py"
|
| 185 |
+
|
| 186 |
+
[[artifacts]]
|
| 187 |
+
source = "/workspace/trl/experimental/bema_for_ref_model/__init__.py"
|
| 188 |
+
|
| 189 |
+
[[artifacts]]
|
| 190 |
+
source = "/workspace/trl/experimental/bema_for_ref_model/callback.py"
|
| 191 |
+
|
| 192 |
+
[[artifacts]]
|
| 193 |
+
source = "/workspace/trl/experimental/bema_for_ref_model/dpo_trainer.py"
|
| 194 |
+
|
| 195 |
+
[[artifacts]]
|
| 196 |
+
source = "/workspace/trl/experimental/cpo/__init__.py"
|
| 197 |
+
|
| 198 |
+
[[artifacts]]
|
| 199 |
+
source = "/workspace/trl/experimental/cpo/cpo_config.py"
|
| 200 |
+
|
| 201 |
+
[[artifacts]]
|
| 202 |
+
source = "/workspace/trl/experimental/cpo/cpo_trainer.py"
|
| 203 |
+
|
| 204 |
+
[[artifacts]]
|
| 205 |
+
source = "/workspace/trl/experimental/distillation/__init__.py"
|
| 206 |
+
|
| 207 |
+
[[artifacts]]
|
| 208 |
+
source = "/workspace/trl/experimental/distillation/distillation_config.py"
|
| 209 |
+
|
| 210 |
+
[[artifacts]]
|
| 211 |
+
source = "/workspace/trl/experimental/distillation/distillation_trainer.py"
|
| 212 |
+
|
| 213 |
+
[[artifacts]]
|
| 214 |
+
source = "/workspace/trl/experimental/dppo/__init__.py"
|
| 215 |
+
|
| 216 |
+
[[artifacts]]
|
| 217 |
+
source = "/workspace/trl/experimental/dppo/dppo_config.py"
|
| 218 |
+
|
| 219 |
+
[[artifacts]]
|
| 220 |
+
source = "/workspace/trl/experimental/dppo/dppo_trainer.py"
|
| 221 |
+
|
| 222 |
+
[[artifacts]]
|
| 223 |
+
source = "/workspace/trl/experimental/gfpo/__init__.py"
|
| 224 |
+
|
| 225 |
+
[[artifacts]]
|
| 226 |
+
source = "/workspace/trl/experimental/gfpo/gfpo_config.py"
|
| 227 |
+
|
| 228 |
+
[[artifacts]]
|
| 229 |
+
source = "/workspace/trl/experimental/gfpo/gfpo_trainer.py"
|
| 230 |
+
|
| 231 |
+
[[artifacts]]
|
| 232 |
+
source = "/workspace/trl/experimental/gkd/__init__.py"
|
| 233 |
+
|
| 234 |
+
[[artifacts]]
|
| 235 |
+
source = "/workspace/trl/experimental/gkd/gkd_config.py"
|
| 236 |
+
|
| 237 |
+
[[artifacts]]
|
| 238 |
+
source = "/workspace/trl/experimental/gkd/gkd_trainer.py"
|
| 239 |
+
|
| 240 |
+
[[artifacts]]
|
| 241 |
+
source = "/workspace/trl/experimental/gmpo/__init__.py"
|
| 242 |
+
|
| 243 |
+
[[artifacts]]
|
| 244 |
+
source = "/workspace/trl/experimental/gmpo/gmpo_config.py"
|
| 245 |
+
|
| 246 |
+
[[artifacts]]
|
| 247 |
+
source = "/workspace/trl/experimental/gmpo/gmpo_trainer.py"
|
| 248 |
+
|
| 249 |
+
[[artifacts]]
|
| 250 |
+
source = "/workspace/trl/experimental/gold/__init__.py"
|
| 251 |
+
|
| 252 |
+
[[artifacts]]
|
| 253 |
+
source = "/workspace/trl/experimental/gold/gold_config.py"
|
| 254 |
+
|
| 255 |
+
[[artifacts]]
|
| 256 |
+
source = "/workspace/trl/experimental/gold/gold_trainer.py"
|
| 257 |
+
|
| 258 |
+
[[artifacts]]
|
| 259 |
+
source = "/workspace/trl/experimental/grpo_with_replay_buffer/__init__.py"
|
| 260 |
+
|
| 261 |
+
[[artifacts]]
|
| 262 |
+
source = "/workspace/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py"
|
| 263 |
+
|
| 264 |
+
[[artifacts]]
|
| 265 |
+
source = "/workspace/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py"
|
| 266 |
+
|
| 267 |
+
[[artifacts]]
|
| 268 |
+
source = "/workspace/trl/experimental/gspo_token/__init__.py"
|
| 269 |
+
|
| 270 |
+
[[artifacts]]
|
| 271 |
+
source = "/workspace/trl/experimental/gspo_token/grpo_trainer.py"
|
| 272 |
+
|
| 273 |
+
[[artifacts]]
|
| 274 |
+
source = "/workspace/trl/experimental/harbor/__init__.py"
|
| 275 |
+
|
| 276 |
+
[[artifacts]]
|
| 277 |
+
source = "/workspace/trl/experimental/harbor/_env.py"
|
| 278 |
+
|
| 279 |
+
[[artifacts]]
|
| 280 |
+
source = "/workspace/trl/experimental/harbor/_spec.py"
|
| 281 |
+
|
| 282 |
+
[[artifacts]]
|
| 283 |
+
source = "/workspace/trl/experimental/kto/__init__.py"
|
| 284 |
+
|
| 285 |
+
[[artifacts]]
|
| 286 |
+
source = "/workspace/trl/experimental/kto/kto_config.py"
|
| 287 |
+
|
| 288 |
+
[[artifacts]]
|
| 289 |
+
source = "/workspace/trl/experimental/kto/kto_trainer.py"
|
| 290 |
+
|
| 291 |
+
[[artifacts]]
|
| 292 |
+
source = "/workspace/trl/experimental/merge_model_callback.py"
|
| 293 |
+
|
| 294 |
+
[[artifacts]]
|
| 295 |
+
source = "/workspace/trl/experimental/minillm/__init__.py"
|
| 296 |
+
|
| 297 |
+
[[artifacts]]
|
| 298 |
+
source = "/workspace/trl/experimental/minillm/minillm_config.py"
|
| 299 |
+
|
| 300 |
+
[[artifacts]]
|
| 301 |
+
source = "/workspace/trl/experimental/minillm/minillm_trainer.py"
|
| 302 |
+
|
| 303 |
+
[[artifacts]]
|
| 304 |
+
source = "/workspace/trl/experimental/nash_md/__init__.py"
|
| 305 |
+
|
| 306 |
+
[[artifacts]]
|
| 307 |
+
source = "/workspace/trl/experimental/nash_md/nash_md_config.py"
|
| 308 |
+
|
| 309 |
+
[[artifacts]]
|
| 310 |
+
source = "/workspace/trl/experimental/nash_md/nash_md_trainer.py"
|
| 311 |
+
|
| 312 |
+
[[artifacts]]
|
| 313 |
+
source = "/workspace/trl/experimental/online_dpo/__init__.py"
|
| 314 |
+
|
| 315 |
+
[[artifacts]]
|
| 316 |
+
source = "/workspace/trl/experimental/online_dpo/online_dpo_config.py"
|
| 317 |
+
|
| 318 |
+
[[artifacts]]
|
| 319 |
+
source = "/workspace/trl/experimental/online_dpo/online_dpo_trainer.py"
|
| 320 |
+
|
| 321 |
+
[[artifacts]]
|
| 322 |
+
source = "/workspace/trl/experimental/openenv/__init__.py"
|
| 323 |
+
|
| 324 |
+
[[artifacts]]
|
| 325 |
+
source = "/workspace/trl/experimental/openenv/utils.py"
|
| 326 |
+
|
| 327 |
+
[[artifacts]]
|
| 328 |
+
source = "/workspace/trl/experimental/openreward/__init__.py"
|
| 329 |
+
|
| 330 |
+
[[artifacts]]
|
| 331 |
+
source = "/workspace/trl/experimental/openreward/_spec.py"
|
| 332 |
+
|
| 333 |
+
[[artifacts]]
|
| 334 |
+
source = "/workspace/trl/experimental/openreward/environment.py"
|
| 335 |
+
|
| 336 |
+
[[artifacts]]
|
| 337 |
+
source = "/workspace/trl/experimental/orpo/__init__.py"
|
| 338 |
+
|
| 339 |
+
[[artifacts]]
|
| 340 |
+
source = "/workspace/trl/experimental/orpo/orpo_config.py"
|
| 341 |
+
|
| 342 |
+
[[artifacts]]
|
| 343 |
+
source = "/workspace/trl/experimental/orpo/orpo_trainer.py"
|
| 344 |
+
|
| 345 |
+
[[artifacts]]
|
| 346 |
+
source = "/workspace/trl/experimental/papo/__init__.py"
|
| 347 |
+
|
| 348 |
+
[[artifacts]]
|
| 349 |
+
source = "/workspace/trl/experimental/papo/papo_config.py"
|
| 350 |
+
|
| 351 |
+
[[artifacts]]
|
| 352 |
+
source = "/workspace/trl/experimental/papo/papo_trainer.py"
|
| 353 |
+
|
| 354 |
+
[[artifacts]]
|
| 355 |
+
source = "/workspace/trl/experimental/ppo/__init__.py"
|
| 356 |
+
|
| 357 |
+
[[artifacts]]
|
| 358 |
+
source = "/workspace/trl/experimental/ppo/modeling_value_head.py"
|
| 359 |
+
|
| 360 |
+
[[artifacts]]
|
| 361 |
+
source = "/workspace/trl/experimental/ppo/ppo_config.py"
|
| 362 |
+
|
| 363 |
+
[[artifacts]]
|
| 364 |
+
source = "/workspace/trl/experimental/ppo/ppo_trainer.py"
|
| 365 |
+
|
| 366 |
+
[[artifacts]]
|
| 367 |
+
source = "/workspace/trl/experimental/prm/__init__.py"
|
| 368 |
+
|
| 369 |
+
[[artifacts]]
|
| 370 |
+
source = "/workspace/trl/experimental/prm/prm_config.py"
|
| 371 |
+
|
| 372 |
+
[[artifacts]]
|
| 373 |
+
source = "/workspace/trl/experimental/prm/prm_trainer.py"
|
| 374 |
+
|
| 375 |
+
[[artifacts]]
|
| 376 |
+
source = "/workspace/trl/experimental/sdft/__init__.py"
|
| 377 |
+
|
| 378 |
+
[[artifacts]]
|
| 379 |
+
source = "/workspace/trl/experimental/sdft/loss_utils.py"
|
| 380 |
+
|
| 381 |
+
[[artifacts]]
|
| 382 |
+
source = "/workspace/trl/experimental/sdft/sdft_config.py"
|
| 383 |
+
|
| 384 |
+
[[artifacts]]
|
| 385 |
+
source = "/workspace/trl/experimental/sdft/sdft_trainer.py"
|
| 386 |
+
|
| 387 |
+
[[artifacts]]
|
| 388 |
+
source = "/workspace/trl/experimental/sdft/teacher_sync.py"
|
| 389 |
+
|
| 390 |
+
[[artifacts]]
|
| 391 |
+
source = "/workspace/trl/experimental/sdpo/__init__.py"
|
| 392 |
+
|
| 393 |
+
[[artifacts]]
|
| 394 |
+
source = "/workspace/trl/experimental/sdpo/loss_utils.py"
|
| 395 |
+
|
| 396 |
+
[[artifacts]]
|
| 397 |
+
source = "/workspace/trl/experimental/sdpo/sdpo_config.py"
|
| 398 |
+
|
| 399 |
+
[[artifacts]]
|
| 400 |
+
source = "/workspace/trl/experimental/sdpo/sdpo_trainer.py"
|
| 401 |
+
|
| 402 |
+
[[artifacts]]
|
| 403 |
+
source = "/workspace/trl/experimental/sdpo/teacher_sync.py"
|
| 404 |
+
|
| 405 |
+
[[artifacts]]
|
| 406 |
+
source = "/workspace/trl/experimental/ssd/__init__.py"
|
| 407 |
+
|
| 408 |
+
[[artifacts]]
|
| 409 |
+
source = "/workspace/trl/experimental/ssd/ssd_config.py"
|
| 410 |
+
|
| 411 |
+
[[artifacts]]
|
| 412 |
+
source = "/workspace/trl/experimental/ssd/ssd_trainer.py"
|
| 413 |
+
|
| 414 |
+
[[artifacts]]
|
| 415 |
+
source = "/workspace/trl/experimental/tpo/__init__.py"
|
| 416 |
+
|
| 417 |
+
[[artifacts]]
|
| 418 |
+
source = "/workspace/trl/experimental/tpo/tpo_config.py"
|
| 419 |
+
|
| 420 |
+
[[artifacts]]
|
| 421 |
+
source = "/workspace/trl/experimental/tpo/tpo_trainer.py"
|
| 422 |
+
|
| 423 |
+
[[artifacts]]
|
| 424 |
+
source = "/workspace/trl/experimental/utils.py"
|
| 425 |
+
|
| 426 |
+
[[artifacts]]
|
| 427 |
+
source = "/workspace/trl/experimental/xpo/__init__.py"
|
| 428 |
+
|
| 429 |
+
[[artifacts]]
|
| 430 |
+
source = "/workspace/trl/experimental/xpo/xpo_config.py"
|
| 431 |
+
|
| 432 |
+
[[artifacts]]
|
| 433 |
+
source = "/workspace/trl/experimental/xpo/xpo_trainer.py"
|
| 434 |
+
|
| 435 |
+
[[artifacts]]
|
| 436 |
+
source = "/workspace/trl/extras/__init__.py"
|
| 437 |
+
|
| 438 |
+
[[artifacts]]
|
| 439 |
+
source = "/workspace/trl/extras/dataset_formatting.py"
|
| 440 |
+
|
| 441 |
+
[[artifacts]]
|
| 442 |
+
source = "/workspace/trl/extras/profiling.py"
|
| 443 |
+
|
| 444 |
+
[[artifacts]]
|
| 445 |
+
source = "/workspace/trl/generation/__init__.py"
|
| 446 |
+
|
| 447 |
+
[[artifacts]]
|
| 448 |
+
source = "/workspace/trl/generation/vllm_client.py"
|
| 449 |
+
|
| 450 |
+
[[artifacts]]
|
| 451 |
+
source = "/workspace/trl/generation/vllm_generation.py"
|
| 452 |
+
|
| 453 |
+
[[artifacts]]
|
| 454 |
+
source = "/workspace/trl/import_utils.py"
|
| 455 |
+
|
| 456 |
+
[[artifacts]]
|
| 457 |
+
source = "/workspace/trl/models/__init__.py"
|
| 458 |
+
|
| 459 |
+
[[artifacts]]
|
| 460 |
+
source = "/workspace/trl/models/activation_offloading.py"
|
| 461 |
+
|
| 462 |
+
[[artifacts]]
|
| 463 |
+
source = "/workspace/trl/models/utils.py"
|
| 464 |
+
|
| 465 |
+
[[artifacts]]
|
| 466 |
+
source = "/workspace/trl/rewards/__init__.py"
|
| 467 |
+
|
| 468 |
+
[[artifacts]]
|
| 469 |
+
source = "/workspace/trl/rewards/accuracy_rewards.py"
|
| 470 |
+
|
| 471 |
+
[[artifacts]]
|
| 472 |
+
source = "/workspace/trl/rewards/format_rewards.py"
|
| 473 |
+
|
| 474 |
+
[[artifacts]]
|
| 475 |
+
source = "/workspace/trl/rewards/other_rewards.py"
|
| 476 |
+
|
| 477 |
+
[[artifacts]]
|
| 478 |
+
source = "/workspace/trl/scripts/__init__.py"
|
| 479 |
+
|
| 480 |
+
[[artifacts]]
|
| 481 |
+
source = "/workspace/trl/scripts/_hf_argparser.py"
|
| 482 |
+
|
| 483 |
+
[[artifacts]]
|
| 484 |
+
source = "/workspace/trl/scripts/dpo.py"
|
| 485 |
+
|
| 486 |
+
[[artifacts]]
|
| 487 |
+
source = "/workspace/trl/scripts/env.py"
|
| 488 |
+
|
| 489 |
+
[[artifacts]]
|
| 490 |
+
source = "/workspace/trl/scripts/grpo.py"
|
| 491 |
+
|
| 492 |
+
[[artifacts]]
|
| 493 |
+
source = "/workspace/trl/scripts/kto.py"
|
| 494 |
+
|
| 495 |
+
[[artifacts]]
|
| 496 |
+
source = "/workspace/trl/scripts/reward.py"
|
| 497 |
+
|
| 498 |
+
[[artifacts]]
|
| 499 |
+
source = "/workspace/trl/scripts/rloo.py"
|
| 500 |
+
|
| 501 |
+
[[artifacts]]
|
| 502 |
+
source = "/workspace/trl/scripts/sft.py"
|
| 503 |
+
|
| 504 |
+
[[artifacts]]
|
| 505 |
+
source = "/workspace/trl/scripts/utils.py"
|
| 506 |
+
|
| 507 |
+
[[artifacts]]
|
| 508 |
+
source = "/workspace/trl/scripts/vllm_serve.py"
|
| 509 |
+
|
| 510 |
+
[[artifacts]]
|
| 511 |
+
source = "/workspace/trl/skills/__init__.py"
|
| 512 |
+
|
| 513 |
+
[[artifacts]]
|
| 514 |
+
source = "/workspace/trl/skills/cli.py"
|
| 515 |
+
|
| 516 |
+
[[artifacts]]
|
| 517 |
+
source = "/workspace/trl/skills/skills.py"
|
| 518 |
+
|
| 519 |
+
[[artifacts]]
|
| 520 |
+
source = "/workspace/trl/trainer/__init__.py"
|
| 521 |
+
|
| 522 |
+
[[artifacts]]
|
| 523 |
+
source = "/workspace/trl/trainer/base_config.py"
|
| 524 |
+
|
| 525 |
+
[[artifacts]]
|
| 526 |
+
source = "/workspace/trl/trainer/base_trainer.py"
|
| 527 |
+
|
| 528 |
+
[[artifacts]]
|
| 529 |
+
source = "/workspace/trl/trainer/callbacks.py"
|
| 530 |
+
|
| 531 |
+
[[artifacts]]
|
| 532 |
+
source = "/workspace/trl/trainer/dpo_config.py"
|
| 533 |
+
|
| 534 |
+
[[artifacts]]
|
| 535 |
+
source = "/workspace/trl/trainer/dpo_trainer.py"
|
| 536 |
+
|
| 537 |
+
[[artifacts]]
|
| 538 |
+
source = "/workspace/trl/trainer/grpo_config.py"
|
| 539 |
+
|
| 540 |
+
[[artifacts]]
|
| 541 |
+
source = "/workspace/trl/trainer/grpo_trainer.py"
|
| 542 |
+
|
| 543 |
+
[[artifacts]]
|
| 544 |
+
source = "/workspace/trl/trainer/kto_config.py"
|
| 545 |
+
|
| 546 |
+
[[artifacts]]
|
| 547 |
+
source = "/workspace/trl/trainer/kto_trainer.py"
|
| 548 |
+
|
| 549 |
+
[[artifacts]]
|
| 550 |
+
source = "/workspace/trl/trainer/model_config.py"
|
| 551 |
+
|
| 552 |
+
[[artifacts]]
|
| 553 |
+
source = "/workspace/trl/trainer/reward_config.py"
|
| 554 |
+
|
| 555 |
+
[[artifacts]]
|
| 556 |
+
source = "/workspace/trl/trainer/reward_trainer.py"
|
| 557 |
+
|
| 558 |
+
[[artifacts]]
|
| 559 |
+
source = "/workspace/trl/trainer/rloo_config.py"
|
| 560 |
+
|
| 561 |
+
[[artifacts]]
|
| 562 |
+
source = "/workspace/trl/trainer/rloo_trainer.py"
|
| 563 |
+
|
| 564 |
+
[[artifacts]]
|
| 565 |
+
source = "/workspace/trl/trainer/sft_config.py"
|
| 566 |
+
|
| 567 |
+
[[artifacts]]
|
| 568 |
+
source = "/workspace/trl/trainer/sft_trainer.py"
|
| 569 |
+
|
| 570 |
+
[[artifacts]]
|
| 571 |
+
source = "/workspace/trl/trainer/utils.py"
|
tasks/tasksmith-03a6a091b12f/tests/Dockerfile
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
WORKDIR /workspace
|
| 3 |
+
RUN python -m pip install --no-cache-dir --extra-index-url https://download.pytorch.org/whl/cpu torch==2.11.0+cpu numpy==2.5.3 packaging==26.3 parameterized==0.9.0 psutil==7.2.2 pytest==8.4.2 setuptools==78.1.0 wheel==0.48.0 'accelerate>=1.4.0' 'transformers>=4.56.2' 'datasets>=4.7.0' multiprocess huggingface-hub tokenizers safetensors tqdm requests filelock pyyaml regex
|
| 4 |
+
RUN python -m pip install --no-cache-dir 'peft>=0.17.0'
|
| 5 |
+
COPY source /workspace
|
| 6 |
+
RUN python -m pip install --no-cache-dir -e .
|
| 7 |
+
ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
|
| 8 |
+
RUN useradd -m -u 1001 grader
|
| 9 |
+
COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/
|
| 10 |
+
RUN chmod 755 /tests && chmod 644 /tests/*
|
tasks/tasksmith-03a6a091b12f/tests/contract.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"expected_passes": ["tests.test_kto_sync_integration::test_training_synchronizes_at_configured_interval", "tests.test_kto_sync_integration::test_training_keeps_default_reference_fixed", "tests.test_kto_sync_integration::test_precompute_incompatibility", "tests.test_kto_sync_integration::test_peft_incompatibility", "tests.tasksmith_behavior.TestKTOConfigSyncRefModelFields::test_custom_values_stored", "tests.tasksmith_behavior.TestKTOConfigSyncRefModelFields::test_defaults", "tests.experimental.test_kto_trainer.TestDataCollatorForUnpairedPreference::test_optional_reference_logps", "tests.experimental.test_kto_trainer.TestDataCollatorForUnpairedPreference::test_padding_and_masks", "tests.experimental.test_kto_trainer.TestDataCollatorForUnpairedPreference::test_with_pad_to_multiple_of", "tests.tasksmith_behavior.TestKTOConfigSyncRefModelFields::test_existing_beta_field_still_works", "tests.tasksmith_behavior.TestSyncRefModelCallbackWithKTOConfig::test_no_sync_at_non_multiple_step", "tests.tasksmith_behavior.TestSyncRefModelCallbackWithKTOConfig::test_sync_applies_correct_interpolation", "tests.tasksmith_behavior.TestSyncRefModelCallbackWithKTOConfig::test_sync_uses_correct_alpha_ratio"], "submitted_files": ["trl/__init__.py", "trl/_compat.py", "trl/_lazy_module.py", "trl/chat_template_utils.py", "trl/cli/__init__.py", "trl/cli/accelerate_config.py", "trl/cli/accelerate_launcher.py", "trl/cli/commands/__init__.py", "trl/cli/commands/base.py", "trl/cli/commands/env.py", "trl/cli/commands/skills.py", "trl/cli/commands/training.py", "trl/cli/commands/vllm_serve.py", "trl/cli/main.py", "trl/data_utils.py", "trl/distributed.py", "trl/experimental/__init__.py", "trl/experimental/a2po/__init__.py", "trl/experimental/a2po/a2po_config.py", "trl/experimental/a2po/a2po_trainer.py", "trl/experimental/async_grpo/__init__.py", "trl/experimental/async_grpo/async_grpo_config.py", "trl/experimental/async_grpo/async_grpo_trainer.py", "trl/experimental/async_grpo/async_rollout_worker.py", "trl/experimental/async_grpo/weight_transfer.py", "trl/experimental/bco/__init__.py", "trl/experimental/bco/bco_config.py", "trl/experimental/bco/bco_trainer.py", "trl/experimental/bema_for_ref_model/__init__.py", "trl/experimental/bema_for_ref_model/callback.py", "trl/experimental/bema_for_ref_model/dpo_trainer.py", "trl/experimental/cpo/__init__.py", "trl/experimental/cpo/cpo_config.py", "trl/experimental/cpo/cpo_trainer.py", "trl/experimental/distillation/__init__.py", "trl/experimental/distillation/distillation_config.py", "trl/experimental/distillation/distillation_trainer.py", "trl/experimental/dppo/__init__.py", "trl/experimental/dppo/dppo_config.py", "trl/experimental/dppo/dppo_trainer.py", "trl/experimental/gfpo/__init__.py", "trl/experimental/gfpo/gfpo_config.py", "trl/experimental/gfpo/gfpo_trainer.py", "trl/experimental/gkd/__init__.py", "trl/experimental/gkd/gkd_config.py", "trl/experimental/gkd/gkd_trainer.py", "trl/experimental/gmpo/__init__.py", "trl/experimental/gmpo/gmpo_config.py", "trl/experimental/gmpo/gmpo_trainer.py", "trl/experimental/gold/__init__.py", "trl/experimental/gold/gold_config.py", "trl/experimental/gold/gold_trainer.py", "trl/experimental/grpo_with_replay_buffer/__init__.py", "trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_config.py", "trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py", "trl/experimental/gspo_token/__init__.py", "trl/experimental/gspo_token/grpo_trainer.py", "trl/experimental/harbor/__init__.py", "trl/experimental/harbor/_env.py", "trl/experimental/harbor/_spec.py", "trl/experimental/kto/__init__.py", "trl/experimental/kto/kto_config.py", "trl/experimental/kto/kto_trainer.py", "trl/experimental/merge_model_callback.py", "trl/experimental/minillm/__init__.py", "trl/experimental/minillm/minillm_config.py", "trl/experimental/minillm/minillm_trainer.py", "trl/experimental/nash_md/__init__.py", "trl/experimental/nash_md/nash_md_config.py", "trl/experimental/nash_md/nash_md_trainer.py", "trl/experimental/online_dpo/__init__.py", "trl/experimental/online_dpo/online_dpo_config.py", "trl/experimental/online_dpo/online_dpo_trainer.py", "trl/experimental/openenv/__init__.py", "trl/experimental/openenv/utils.py", "trl/experimental/openreward/__init__.py", "trl/experimental/openreward/_spec.py", "trl/experimental/openreward/environment.py", "trl/experimental/orpo/__init__.py", "trl/experimental/orpo/orpo_config.py", "trl/experimental/orpo/orpo_trainer.py", "trl/experimental/papo/__init__.py", "trl/experimental/papo/papo_config.py", "trl/experimental/papo/papo_trainer.py", "trl/experimental/ppo/__init__.py", "trl/experimental/ppo/modeling_value_head.py", "trl/experimental/ppo/ppo_config.py", "trl/experimental/ppo/ppo_trainer.py", "trl/experimental/prm/__init__.py", "trl/experimental/prm/prm_config.py", "trl/experimental/prm/prm_trainer.py", "trl/experimental/sdft/__init__.py", "trl/experimental/sdft/loss_utils.py", "trl/experimental/sdft/sdft_config.py", "trl/experimental/sdft/sdft_trainer.py", "trl/experimental/sdft/teacher_sync.py", "trl/experimental/sdpo/__init__.py", "trl/experimental/sdpo/loss_utils.py", "trl/experimental/sdpo/sdpo_config.py", "trl/experimental/sdpo/sdpo_trainer.py", "trl/experimental/sdpo/teacher_sync.py", "trl/experimental/ssd/__init__.py", "trl/experimental/ssd/ssd_config.py", "trl/experimental/ssd/ssd_trainer.py", "trl/experimental/tpo/__init__.py", "trl/experimental/tpo/tpo_config.py", "trl/experimental/tpo/tpo_trainer.py", "trl/experimental/utils.py", "trl/experimental/xpo/__init__.py", "trl/experimental/xpo/xpo_config.py", "trl/experimental/xpo/xpo_trainer.py", "trl/extras/__init__.py", "trl/extras/dataset_formatting.py", "trl/extras/profiling.py", "trl/generation/__init__.py", "trl/generation/vllm_client.py", "trl/generation/vllm_generation.py", "trl/import_utils.py", "trl/models/__init__.py", "trl/models/activation_offloading.py", "trl/models/utils.py", "trl/rewards/__init__.py", "trl/rewards/accuracy_rewards.py", "trl/rewards/format_rewards.py", "trl/rewards/other_rewards.py", "trl/scripts/__init__.py", "trl/scripts/_hf_argparser.py", "trl/scripts/dpo.py", "trl/scripts/env.py", "trl/scripts/grpo.py", "trl/scripts/kto.py", "trl/scripts/reward.py", "trl/scripts/rloo.py", "trl/scripts/sft.py", "trl/scripts/utils.py", "trl/scripts/vllm_serve.py", "trl/skills/__init__.py", "trl/skills/cli.py", "trl/skills/skills.py", "trl/trainer/__init__.py", "trl/trainer/base_config.py", "trl/trainer/base_trainer.py", "trl/trainer/callbacks.py", "trl/trainer/dpo_config.py", "trl/trainer/dpo_trainer.py", "trl/trainer/grpo_config.py", "trl/trainer/grpo_trainer.py", "trl/trainer/kto_config.py", "trl/trainer/kto_trainer.py", "trl/trainer/model_config.py", "trl/trainer/reward_config.py", "trl/trainer/reward_trainer.py", "trl/trainer/rloo_config.py", "trl/trainer/rloo_trainer.py", "trl/trainer/sft_config.py", "trl/trainer/sft_trainer.py", "trl/trainer/utils.py"], "test_paths": ["tests/experimental/test_kto_trainer.py::TestDataCollatorForUnpairedPreference::test_padding_and_masks", "tests/experimental/test_kto_trainer.py::TestDataCollatorForUnpairedPreference::test_optional_reference_logps", "tests/experimental/test_kto_trainer.py::TestDataCollatorForUnpairedPreference::test_with_pad_to_multiple_of", "tests/tasksmith_behavior.py", "tests/test_kto_sync_integration.py"], "timeout_sec": 60}
|
tasks/tasksmith-03a6a091b12f/tests/grade.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Standalone trusted entry point; copied into each separate verifier image.
|
| 2 |
+
|
| 3 |
+
No Repo2RLEnv installation is needed to grade an exported task. Submitted Python
|
| 4 |
+
runs as an unprivileged user; this parent owns the result parser and reward file.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import hashlib
|
| 10 |
+
import importlib.util
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import signal
|
| 14 |
+
import stat
|
| 15 |
+
import subprocess
|
| 16 |
+
import sys
|
| 17 |
+
import tempfile
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def validate_submission(workspace: Path, contract: dict) -> None:
|
| 22 |
+
"""Validate collected data before any learner-controlled Python is imported."""
|
| 23 |
+
paths = set(contract["submitted_files"]) - set(contract.get("optional_files", []))
|
| 24 |
+
roots = contract.get("submitted_roots", [])
|
| 25 |
+
immutable = contract.get("immutable_assets", {})
|
| 26 |
+
paths.update(immutable)
|
| 27 |
+
for relative in roots:
|
| 28 |
+
root = workspace / relative
|
| 29 |
+
if root.is_symlink() or not root.is_dir():
|
| 30 |
+
raise ValueError("Submitted source root is missing or linked")
|
| 31 |
+
for path in root.rglob("*"):
|
| 32 |
+
if path.is_symlink():
|
| 33 |
+
raise ValueError("Submitted source contains a symlink")
|
| 34 |
+
if path.is_dir():
|
| 35 |
+
continue
|
| 36 |
+
name = path.relative_to(workspace).as_posix()
|
| 37 |
+
if path.suffix != ".py" and name not in immutable:
|
| 38 |
+
raise ValueError("Only Python source files may be added")
|
| 39 |
+
paths.add(name)
|
| 40 |
+
for relative in sorted(paths):
|
| 41 |
+
path = workspace / relative
|
| 42 |
+
for component in (path, *path.parents):
|
| 43 |
+
if component.is_symlink():
|
| 44 |
+
raise ValueError("Submitted source contains a symlink")
|
| 45 |
+
if (
|
| 46 |
+
not path.is_file()
|
| 47 |
+
or not stat.S_ISREG(path.stat().st_mode)
|
| 48 |
+
or path.stat().st_size > 8 * 1024 * 1024
|
| 49 |
+
):
|
| 50 |
+
raise ValueError("Submitted source is not a bounded regular file")
|
| 51 |
+
if (
|
| 52 |
+
relative in immutable
|
| 53 |
+
and hashlib.sha256(path.read_bytes()).hexdigest() != immutable[relative]
|
| 54 |
+
):
|
| 55 |
+
raise ValueError("Non-Python source assets must remain unchanged")
|
| 56 |
+
os.chown(path, 0, 0)
|
| 57 |
+
path.chmod(0o644)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def main() -> None:
|
| 61 |
+
directory = Path("/tests")
|
| 62 |
+
parser_spec = importlib.util.spec_from_file_location(
|
| 63 |
+
"test_results", directory / "test_results.py"
|
| 64 |
+
)
|
| 65 |
+
parser = importlib.util.module_from_spec(parser_spec)
|
| 66 |
+
sys.modules[parser_spec.name] = parser
|
| 67 |
+
parser_spec.loader.exec_module(parser)
|
| 68 |
+
contract = json.loads((directory / "contract.json").read_text())
|
| 69 |
+
logs = Path("/logs/verifier")
|
| 70 |
+
logs.mkdir(parents=True, exist_ok=True)
|
| 71 |
+
logs.chmod(0o755)
|
| 72 |
+
reward = logs / "reward.txt"
|
| 73 |
+
reward.write_text("0\n")
|
| 74 |
+
reward.chmod(0o644)
|
| 75 |
+
try:
|
| 76 |
+
validate_submission(Path("/workspace"), contract)
|
| 77 |
+
except (ValueError, OSError) as exc:
|
| 78 |
+
(logs / "result.json").write_text(json.dumps({"passed": False, "reason": str(exc)}))
|
| 79 |
+
return
|
| 80 |
+
with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary:
|
| 81 |
+
working = Path(temporary)
|
| 82 |
+
os.chown(working, 1001, 1001)
|
| 83 |
+
working.chmod(0o700)
|
| 84 |
+
report = working / "results.xml"
|
| 85 |
+
command = [
|
| 86 |
+
sys.executable,
|
| 87 |
+
"-I",
|
| 88 |
+
"/tests/test_driver.py",
|
| 89 |
+
*contract["test_paths"],
|
| 90 |
+
"-q",
|
| 91 |
+
"--tb=short",
|
| 92 |
+
"-p",
|
| 93 |
+
"no:cacheprovider",
|
| 94 |
+
f"--junitxml={report}",
|
| 95 |
+
]
|
| 96 |
+
with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr:
|
| 97 |
+
process = subprocess.Popen(
|
| 98 |
+
command,
|
| 99 |
+
cwd="/workspace",
|
| 100 |
+
stdout=stdout,
|
| 101 |
+
stderr=stderr,
|
| 102 |
+
user=1001,
|
| 103 |
+
group=1001,
|
| 104 |
+
extra_groups=[],
|
| 105 |
+
start_new_session=True,
|
| 106 |
+
env={
|
| 107 |
+
**{
|
| 108 |
+
key: os.environ[key]
|
| 109 |
+
for key in (
|
| 110 |
+
"LD_LIBRARY_PATH",
|
| 111 |
+
"CUDA_VISIBLE_DEVICES",
|
| 112 |
+
"NVIDIA_VISIBLE_DEVICES",
|
| 113 |
+
"NVIDIA_DRIVER_CAPABILITIES",
|
| 114 |
+
"NCCL_SOCKET_IFNAME",
|
| 115 |
+
"GLOO_SOCKET_IFNAME",
|
| 116 |
+
)
|
| 117 |
+
if key in os.environ
|
| 118 |
+
},
|
| 119 |
+
"PATH": str(Path(sys.executable).parent) + ":/usr/local/bin:/usr/bin:/bin",
|
| 120 |
+
"HOME": temporary,
|
| 121 |
+
"PYTHONDONTWRITEBYTECODE": "1",
|
| 122 |
+
"PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
|
| 123 |
+
},
|
| 124 |
+
)
|
| 125 |
+
try:
|
| 126 |
+
code = process.wait(timeout=contract["timeout_sec"])
|
| 127 |
+
finally:
|
| 128 |
+
# Terminate descendants too: they must not keep modifying the
|
| 129 |
+
# child-owned report while the trusted parent checks it.
|
| 130 |
+
try:
|
| 131 |
+
os.killpg(process.pid, signal.SIGKILL)
|
| 132 |
+
except ProcessLookupError:
|
| 133 |
+
pass
|
| 134 |
+
process.wait()
|
| 135 |
+
if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024:
|
| 136 |
+
(logs / "result.json").write_text(
|
| 137 |
+
json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"})
|
| 138 |
+
)
|
| 139 |
+
return
|
| 140 |
+
text = report.read_text()
|
| 141 |
+
(logs / "results.xml").write_text(text)
|
| 142 |
+
try:
|
| 143 |
+
parsed = parser.parse_junit(text, returncode=code)
|
| 144 |
+
except ValueError as exc:
|
| 145 |
+
(logs / "result.json").write_text(
|
| 146 |
+
json.dumps({"passed": False, "returncode": code, "reason": str(exc)})
|
| 147 |
+
)
|
| 148 |
+
return
|
| 149 |
+
expected = set(contract["expected_passes"])
|
| 150 |
+
passed = code == 0 and bool(expected) and parsed.passed == expected
|
| 151 |
+
(logs / "result.json").write_text(
|
| 152 |
+
json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses})
|
| 153 |
+
)
|
| 154 |
+
reward.write_text("1\n" if passed else "0\n")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
if __name__ == "__main__":
|
| 158 |
+
main()
|
tasks/tasksmith-03a6a091b12f/tests/source/.ai/AGENTS.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AGENTS.md
|
| 2 |
+
|
| 3 |
+
## Repository-specific guidance
|
| 4 |
+
|
| 5 |
+
### Main code vs experimental code
|
| 6 |
+
|
| 7 |
+
The repository is separated into **main code** and **experimental code**.
|
| 8 |
+
|
| 9 |
+
* **Main code** should remain stable, consistent, and well-tested.
|
| 10 |
+
* **Experimental code** may be less stable and may contain inconsistent patterns or limited testing.
|
| 11 |
+
|
| 12 |
+
Small non-invasive improvements that make experimental code more consistent with the main codebase are encouraged, but avoid large refactors.
|
| 13 |
+
|
| 14 |
+
### Paper implementations
|
| 15 |
+
|
| 16 |
+
If a PR implements a method, algorithm, or training approach from a research paper, it must also add a corresponding subsection to `paper_index.md`.
|
| 17 |
+
|
| 18 |
+
When reviewing such PRs, ensure that `paper_index.md` was updated.
|
| 19 |
+
|
| 20 |
+
### Code duplication and consistency
|
| 21 |
+
|
| 22 |
+
Trainers in this repository are **self-contained by design**. Shared logic (generation, reward computation, metric logging, weight syncing, etc.) is deliberately duplicated across trainers rather than abstracted into a shared base class.
|
| 23 |
+
|
| 24 |
+
This is intentional: each trainer must be readable, modifiable, and evolvable in isolation. The base class (`_BaseTrainer`) provides only minimal utilities (model card generation). Everything else — vLLM generation paths, `_get_per_token_logps_and_entropies`, `_calculate_rewards`, `_prepare_inputs`, metric logging — is copied in full.
|
| 25 |
+
|
| 26 |
+
**The tradeoff**: duplication is accepted, but **consistency is mandatory**. When the same logic appears in multiple trainers, the duplicated blocks must stay aligned:
|
| 27 |
+
|
| 28 |
+
- Same variable names (`self._last_loaded_step`, `self._metrics[mode]`, …)
|
| 29 |
+
- Same control flow structure (if/elif/else branches in the same order)
|
| 30 |
+
- Same comments (word-for-word when the logic is identical)
|
| 31 |
+
- Divergences only where the trainer's semantics require it (e.g., GRPO extracts logprobs from vLLM, RLOO discards them)
|
| 32 |
+
|
| 33 |
+
**Consistency over correctness**: this is a strong requirement. When duplicating code, reproduce it exactly — even if you believe the original has a bug. Do not silently fix the issue in your copy. Instead, keep your copy consistent with the source and report the problem so it can be fixed across all trainers in a dedicated PR. A correct-but-inconsistent codebase is harder to maintain than a consistently-wrong one that can be fixed in a single sweep.
|
| 34 |
+
|
| 35 |
+
**When modifying duplicated code**: if you change a pattern that exists in multiple trainers (e.g., the vLLM generation path in `_generate_single_turn`), apply the same change to all other trainers. A fix in GRPO often implies the same fix in RLOO, and vice versa. Not propagating a change is a bug.
|
| 36 |
+
|
| 37 |
+
**When reviewing**: if a PR touches duplicated logic, verify that all copies are updated consistently. A common mistake is fixing one trainer and forgetting the others.
|
| 38 |
+
|
| 39 |
+
### Simplicity
|
| 40 |
+
|
| 41 |
+
This codebase values **leanness and simplicity above all**. Prefer straightforward, inline code over abstractions, helpers, or utilities — even at the cost of some robustness or generality.
|
| 42 |
+
|
| 43 |
+
Concretely:
|
| 44 |
+
|
| 45 |
+
- Do not add layers of indirection (registries, factory patterns, plugin systems). A contributor should be able to read a trainer top to bottom and understand the full flow.
|
| 46 |
+
- Prefer a simple implementation that covers 90% of cases over a complex one that covers 100%. A function that handles the common path in 20 lines is better than a catch-all that handles every edge case in 80.
|
| 47 |
+
- Do not add defensive code, fallback paths, or configuration options "just in case". Only handle cases that actually exist today.
|
| 48 |
+
- Avoid `hasattr` and `getattr`. Their use is almost always a symptom of overly defensive programming or a disguised version check (e.g., "this attribute was added in version X"). Instead, either drop the conditional entirely or express the version check explicitly with a version comparison. There is nearly always a cleaner alternative.
|
| 49 |
+
- When in doubt, prefer less code. Every new function, parameter, or branch is maintenance burden. The best abstraction is often no abstraction.
|
| 50 |
+
|
| 51 |
+
## Documentation
|
| 52 |
+
|
| 53 |
+
### Docstrings
|
| 54 |
+
|
| 55 |
+
Docstrings must follow the repository format below. Do **not** convert docstrings to other styles (Google, NumPy, etc.).
|
| 56 |
+
|
| 57 |
+
Rules:
|
| 58 |
+
|
| 59 |
+
* Types appear in backticks inside parentheses: (`str`)
|
| 60 |
+
* Optional parameters are marked with `*optional*`
|
| 61 |
+
* Defaults are written as: `defaults to <value>`
|
| 62 |
+
* When the default is `None`, prefer ```(`str`, *optional*)``` instead of ```(`str` or `None`, *optional*, defaults to `None`)```
|
| 63 |
+
* Union types use `or`: `str` or `None`
|
| 64 |
+
* References to classes use the format: [`~transformers.PreTrainedModel`]
|
| 65 |
+
* Class docstrings may group parameters using headers such as: `> Parameters for X:`
|
| 66 |
+
|
| 67 |
+
Example:
|
| 68 |
+
|
| 69 |
+
````python
|
| 70 |
+
def method(self, param1: str, param2: int = 1, param3: float | None = None):
|
| 71 |
+
"""
|
| 72 |
+
Brief one-line description of what this does.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
param1 (`str`):
|
| 76 |
+
Description of required param.
|
| 77 |
+
param2 (`int`, *optional*, defaults to `1`):
|
| 78 |
+
Description of optional param with default.
|
| 79 |
+
param3 (`float`, *optional*):
|
| 80 |
+
Description of optional param without explicit default.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
`dict` with keys:
|
| 84 |
+
- `key1` (`list[int]`):
|
| 85 |
+
Description of this key.
|
| 86 |
+
|
| 87 |
+
Examples:
|
| 88 |
+
|
| 89 |
+
```python
|
| 90 |
+
>>> my_func("hello")
|
| 91 |
+
```
|
| 92 |
+
"""
|
| 93 |
+
````
|
| 94 |
+
|
| 95 |
+
### Links to papers
|
| 96 |
+
|
| 97 |
+
When linking to papers, use `https://huggingface.co/papers/<id>` instead of `https://arxiv.org/abs/<id>` (same ID suffix system).
|
tasks/tasksmith-03a6a091b12f/tests/source/.cursor/BUGBOT.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AGENTS.md
|
| 2 |
+
|
| 3 |
+
## Repository-specific guidance
|
| 4 |
+
|
| 5 |
+
### Main code vs experimental code
|
| 6 |
+
|
| 7 |
+
The repository is separated into **main code** and **experimental code**.
|
| 8 |
+
|
| 9 |
+
* **Main code** should remain stable, consistent, and well-tested.
|
| 10 |
+
* **Experimental code** may be less stable and may contain inconsistent patterns or limited testing.
|
| 11 |
+
|
| 12 |
+
Small non-invasive improvements that make experimental code more consistent with the main codebase are encouraged, but avoid large refactors.
|
| 13 |
+
|
| 14 |
+
### Paper implementations
|
| 15 |
+
|
| 16 |
+
If a PR implements a method, algorithm, or training approach from a research paper, it must also add a corresponding subsection to `paper_index.md`.
|
| 17 |
+
|
| 18 |
+
When reviewing such PRs, ensure that `paper_index.md` was updated.
|
| 19 |
+
|
| 20 |
+
### Code duplication and consistency
|
| 21 |
+
|
| 22 |
+
Trainers in this repository are **self-contained by design**. Shared logic (generation, reward computation, metric logging, weight syncing, etc.) is deliberately duplicated across trainers rather than abstracted into a shared base class.
|
| 23 |
+
|
| 24 |
+
This is intentional: each trainer must be readable, modifiable, and evolvable in isolation. The base class (`_BaseTrainer`) provides only minimal utilities (model card generation). Everything else — vLLM generation paths, `_get_per_token_logps_and_entropies`, `_calculate_rewards`, `_prepare_inputs`, metric logging — is copied in full.
|
| 25 |
+
|
| 26 |
+
**The tradeoff**: duplication is accepted, but **consistency is mandatory**. When the same logic appears in multiple trainers, the duplicated blocks must stay aligned:
|
| 27 |
+
|
| 28 |
+
- Same variable names (`self._last_loaded_step`, `self._metrics[mode]`, …)
|
| 29 |
+
- Same control flow structure (if/elif/else branches in the same order)
|
| 30 |
+
- Same comments (word-for-word when the logic is identical)
|
| 31 |
+
- Divergences only where the trainer's semantics require it (e.g., GRPO extracts logprobs from vLLM, RLOO discards them)
|
| 32 |
+
|
| 33 |
+
**Consistency over correctness**: this is a strong requirement. When duplicating code, reproduce it exactly — even if you believe the original has a bug. Do not silently fix the issue in your copy. Instead, keep your copy consistent with the source and report the problem so it can be fixed across all trainers in a dedicated PR. A correct-but-inconsistent codebase is harder to maintain than a consistently-wrong one that can be fixed in a single sweep.
|
| 34 |
+
|
| 35 |
+
**When modifying duplicated code**: if you change a pattern that exists in multiple trainers (e.g., the vLLM generation path in `_generate_single_turn`), apply the same change to all other trainers. A fix in GRPO often implies the same fix in RLOO, and vice versa. Not propagating a change is a bug.
|
| 36 |
+
|
| 37 |
+
**When reviewing**: if a PR touches duplicated logic, verify that all copies are updated consistently. A common mistake is fixing one trainer and forgetting the others.
|
| 38 |
+
|
| 39 |
+
### Simplicity
|
| 40 |
+
|
| 41 |
+
This codebase values **leanness and simplicity above all**. Prefer straightforward, inline code over abstractions, helpers, or utilities — even at the cost of some robustness or generality.
|
| 42 |
+
|
| 43 |
+
Concretely:
|
| 44 |
+
|
| 45 |
+
- Do not add layers of indirection (registries, factory patterns, plugin systems). A contributor should be able to read a trainer top to bottom and understand the full flow.
|
| 46 |
+
- Prefer a simple implementation that covers 90% of cases over a complex one that covers 100%. A function that handles the common path in 20 lines is better than a catch-all that handles every edge case in 80.
|
| 47 |
+
- Do not add defensive code, fallback paths, or configuration options "just in case". Only handle cases that actually exist today.
|
| 48 |
+
- Avoid `hasattr` and `getattr`. Their use is almost always a symptom of overly defensive programming or a disguised version check (e.g., "this attribute was added in version X"). Instead, either drop the conditional entirely or express the version check explicitly with a version comparison. There is nearly always a cleaner alternative.
|
| 49 |
+
- When in doubt, prefer less code. Every new function, parameter, or branch is maintenance burden. The best abstraction is often no abstraction.
|
| 50 |
+
|
| 51 |
+
## Documentation
|
| 52 |
+
|
| 53 |
+
### Docstrings
|
| 54 |
+
|
| 55 |
+
Docstrings must follow the repository format below. Do **not** convert docstrings to other styles (Google, NumPy, etc.).
|
| 56 |
+
|
| 57 |
+
Rules:
|
| 58 |
+
|
| 59 |
+
* Types appear in backticks inside parentheses: (`str`)
|
| 60 |
+
* Optional parameters are marked with `*optional*`
|
| 61 |
+
* Defaults are written as: `defaults to <value>`
|
| 62 |
+
* When the default is `None`, prefer ```(`str`, *optional*)``` instead of ```(`str` or `None`, *optional*, defaults to `None`)```
|
| 63 |
+
* Union types use `or`: `str` or `None`
|
| 64 |
+
* References to classes use the format: [`~transformers.PreTrainedModel`]
|
| 65 |
+
* Class docstrings may group parameters using headers such as: `> Parameters for X:`
|
| 66 |
+
|
| 67 |
+
Example:
|
| 68 |
+
|
| 69 |
+
````python
|
| 70 |
+
def method(self, param1: str, param2: int = 1, param3: float | None = None):
|
| 71 |
+
"""
|
| 72 |
+
Brief one-line description of what this does.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
param1 (`str`):
|
| 76 |
+
Description of required param.
|
| 77 |
+
param2 (`int`, *optional*, defaults to `1`):
|
| 78 |
+
Description of optional param with default.
|
| 79 |
+
param3 (`float`, *optional*):
|
| 80 |
+
Description of optional param without explicit default.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
`dict` with keys:
|
| 84 |
+
- `key1` (`list[int]`):
|
| 85 |
+
Description of this key.
|
| 86 |
+
|
| 87 |
+
Examples:
|
| 88 |
+
|
| 89 |
+
```python
|
| 90 |
+
>>> my_func("hello")
|
| 91 |
+
```
|
| 92 |
+
"""
|
| 93 |
+
````
|
| 94 |
+
|
| 95 |
+
### Links to papers
|
| 96 |
+
|
| 97 |
+
When linking to papers, use `https://huggingface.co/papers/<id>` instead of `https://arxiv.org/abs/<id>` (same ID suffix system).
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: "\U0001F41B Bug Report"
|
| 2 |
+
description: Submit a bug report to help us improve TRL
|
| 3 |
+
labels: [ "bug" ]
|
| 4 |
+
body:
|
| 5 |
+
- type: markdown
|
| 6 |
+
attributes:
|
| 7 |
+
value: |
|
| 8 |
+
Thanks for taking the time to fill out this bug report! 🤗
|
| 9 |
+
|
| 10 |
+
🚩 If it is your first time submitting, be sure to check our [bug report guidelines](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md#did-you-find-a-bug)
|
| 11 |
+
|
| 12 |
+
- type: textarea
|
| 13 |
+
id: reproduction
|
| 14 |
+
validations:
|
| 15 |
+
required: true
|
| 16 |
+
attributes:
|
| 17 |
+
label: Reproduction
|
| 18 |
+
description: |
|
| 19 |
+
Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet.
|
| 20 |
+
If you have code snippets, error messages, stack traces please provide them here as well.
|
| 21 |
+
Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting
|
| 22 |
+
Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.
|
| 23 |
+
|
| 24 |
+
value: |
|
| 25 |
+
```python
|
| 26 |
+
from trl import ...
|
| 27 |
+
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
outputs:
|
| 31 |
+
|
| 32 |
+
```
|
| 33 |
+
Traceback (most recent call last):
|
| 34 |
+
File "example.py", line 42, in <module>
|
| 35 |
+
...
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
- type: textarea
|
| 39 |
+
id: system-info
|
| 40 |
+
attributes:
|
| 41 |
+
label: System Info
|
| 42 |
+
description: |
|
| 43 |
+
Please provide information about your system: platform, Python version, PyTorch version, Transformers version, devices, TRL version, ...
|
| 44 |
+
You can get this information by running `trl env` in your terminal.
|
| 45 |
+
|
| 46 |
+
placeholder: Copy-paste the output of `trl env`
|
| 47 |
+
validations:
|
| 48 |
+
required: true
|
| 49 |
+
|
| 50 |
+
- type: checkboxes
|
| 51 |
+
id: terms
|
| 52 |
+
attributes:
|
| 53 |
+
label: Checklist
|
| 54 |
+
description: |
|
| 55 |
+
Before submitting, please confirm that you've completed each of the following.
|
| 56 |
+
If an item doesn't apply to your issue, check it anyway to show you've reviewed it.
|
| 57 |
+
options:
|
| 58 |
+
- label: "I have checked that my issue isn't already filed (see [open issues](https://github.com/huggingface/trl/issues?q=is%3Aissue))"
|
| 59 |
+
required: true
|
| 60 |
+
- label: "I have included my system information"
|
| 61 |
+
required: true
|
| 62 |
+
- label: "Any code provided is minimal, complete, and reproducible ([more on MREs](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks))"
|
| 63 |
+
required: true
|
| 64 |
+
- label: "Any code provided is properly formatted in code blocks, (no screenshot, [more on code blocks](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/creating-and-highlighting-code-blocks))"
|
| 65 |
+
required: true
|
| 66 |
+
- label: "Any traceback provided is complete"
|
| 67 |
+
required: true
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: "\U0001F680 Feature request"
|
| 2 |
+
description: Submit a proposal/request for a new TRL feature
|
| 3 |
+
labels: [ "Feature request" ]
|
| 4 |
+
body:
|
| 5 |
+
- type: textarea
|
| 6 |
+
id: feature-request
|
| 7 |
+
validations:
|
| 8 |
+
required: true
|
| 9 |
+
attributes:
|
| 10 |
+
label: Feature request
|
| 11 |
+
description: |
|
| 12 |
+
A clear and concise description of the feature proposal. Please provide a link to the paper and code in case they exist.
|
| 13 |
+
|
| 14 |
+
- type: textarea
|
| 15 |
+
id: motivation
|
| 16 |
+
validations:
|
| 17 |
+
required: true
|
| 18 |
+
attributes:
|
| 19 |
+
label: Motivation
|
| 20 |
+
description: |
|
| 21 |
+
Please outline the motivation for the proposal. Is your feature request related to a problem? e.g., I'm always frustrated when [...]. If this is related to another GitHub issue, please link here too.
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
- type: textarea
|
| 25 |
+
id: contribution
|
| 26 |
+
validations:
|
| 27 |
+
required: true
|
| 28 |
+
attributes:
|
| 29 |
+
label: Your contribution
|
| 30 |
+
description: |
|
| 31 |
+
Is there any way that you could help, e.g. by submitting a PR? Make sure to read the CONTRIBUTING.MD [readme](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md)
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/ISSUE_TEMPLATE/new-trainer-addition.yml
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: "\U0001F31F New trainer addition"
|
| 2 |
+
description: Submit a proposal/request to implement a new trainer for a post-training method
|
| 3 |
+
labels: [ "New trainer" ]
|
| 4 |
+
|
| 5 |
+
body:
|
| 6 |
+
- type: textarea
|
| 7 |
+
id: description-request
|
| 8 |
+
validations:
|
| 9 |
+
required: true
|
| 10 |
+
attributes:
|
| 11 |
+
label: Method description
|
| 12 |
+
description: |
|
| 13 |
+
Put any and all important information relative to the method
|
| 14 |
+
|
| 15 |
+
- type: checkboxes
|
| 16 |
+
id: information-tasks
|
| 17 |
+
attributes:
|
| 18 |
+
label: Open source status
|
| 19 |
+
description: |
|
| 20 |
+
Please note that if the method implementation isn't available or model weights with training datasets aren't available, we are less likely to implement it in `trl`.
|
| 21 |
+
options:
|
| 22 |
+
- label: "The method implementation is available"
|
| 23 |
+
- label: "The model weights are available"
|
| 24 |
+
- label: "The training datasets are available"
|
| 25 |
+
|
| 26 |
+
- type: textarea
|
| 27 |
+
id: additional-info
|
| 28 |
+
attributes:
|
| 29 |
+
label: Provide useful links for the implementation
|
| 30 |
+
description: |
|
| 31 |
+
Please provide information regarding the implementation, the weights, and the authors.
|
| 32 |
+
Please mention the authors by @gh-username if you're aware of their usernames.
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/PULL_REQUEST_TEMPLATE.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# What does this PR do?
|
| 2 |
+
|
| 3 |
+
<!--
|
| 4 |
+
Congratulations! You've made it this far! You're not quite done yet though.
|
| 5 |
+
|
| 6 |
+
Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.
|
| 7 |
+
|
| 8 |
+
Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.
|
| 9 |
+
|
| 10 |
+
Once you're done, someone will review your PR shortly. They may suggest changes to make the code even better.
|
| 11 |
+
-->
|
| 12 |
+
|
| 13 |
+
<!-- Remove if not applicable -->
|
| 14 |
+
|
| 15 |
+
Fixes # (issue)
|
| 16 |
+
|
| 17 |
+
## Before submitting
|
| 18 |
+
|
| 19 |
+
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
|
| 20 |
+
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md#create-a-pull-request), Pull Request section?
|
| 21 |
+
- [ ] Was this discussed/approved via a GitHub issue? Please add a link to it if that's the case.
|
| 22 |
+
- [ ] Did you make sure to update the documentation with your changes?
|
| 23 |
+
- [ ] Did you write any new necessary tests?
|
| 24 |
+
|
| 25 |
+
## AI writing disclosure
|
| 26 |
+
|
| 27 |
+
We welcome the use of AI tools to help with contributions. For transparency and to help us improve our review process, please indicate the level of AI involvement in this PR.
|
| 28 |
+
|
| 29 |
+
- [ ] No AI usage: the PR was written entirely by a human.
|
| 30 |
+
- [ ] AI-assisted: some parts were suggested or improved by AI, but the PR was written and reviewed by a human.
|
| 31 |
+
- [ ] AI-generated: the PR was mostly or fully generated by an AI tool.
|
| 32 |
+
|
| 33 |
+
## Who can review?
|
| 34 |
+
|
| 35 |
+
Anyone in the community is free to review the PR once the tests have passed. Feel free to tag members/contributors who may be interested in your PR.
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/codeql/custom-queries.qls
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import codeql
|
| 2 |
+
|
| 3 |
+
from WorkflowString interpolation, Workflow workflow
|
| 4 |
+
where
|
| 5 |
+
interpolation.getStringValue().matches("${{ github.event.issue.title }}") or
|
| 6 |
+
interpolation.getStringValue().matches("${{ github.event.issue.body }}") or
|
| 7 |
+
interpolation.getStringValue().matches("${{ github.event.pull_request.title }}") or
|
| 8 |
+
interpolation.getStringValue().matches("${{ github.event.pull_request.body }}") or
|
| 9 |
+
interpolation.getStringValue().matches("${{ github.event.review.body }}") or
|
| 10 |
+
interpolation.getStringValue().matches("${{ github.event.comment.body }}") or
|
| 11 |
+
interpolation.getStringValue().matches("${{ github.event.inputs.* }}") or
|
| 12 |
+
interpolation.getStringValue().matches("${{ github.event.head_commit.message }}")
|
| 13 |
+
interpolation.getStringValue().matches("${{ github.event.* }}") and
|
| 14 |
+
(
|
| 15 |
+
step.getKey() = "run" or // Injection in run
|
| 16 |
+
step.getKey() = "env" or // Injection via env
|
| 17 |
+
step.getKey() = "with" // Injection via with
|
| 18 |
+
)
|
| 19 |
+
select workflow, "🚨 Do not use directly as input of action"
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/dependabot.yml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version: 2
|
| 2 |
+
updates:
|
| 3 |
+
- package-ecosystem: "github-actions"
|
| 4 |
+
directory: "/"
|
| 5 |
+
schedule:
|
| 6 |
+
interval: "weekly"
|
| 7 |
+
cooldown:
|
| 8 |
+
default-days: 7
|
| 9 |
+
groups:
|
| 10 |
+
actions:
|
| 11 |
+
patterns: ["*"]
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/build_documentation.yml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Build documentation
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- main
|
| 7 |
+
- doc-builder*
|
| 8 |
+
- v*-release
|
| 9 |
+
|
| 10 |
+
env:
|
| 11 |
+
TRL_EXPERIMENTAL_SILENCE: 1
|
| 12 |
+
|
| 13 |
+
jobs:
|
| 14 |
+
build:
|
| 15 |
+
uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@bcff59fca682130d2e7271ca8589911b7ac0b8bf # main
|
| 16 |
+
with:
|
| 17 |
+
commit_sha: ${{ github.sha }}
|
| 18 |
+
package: trl
|
| 19 |
+
version_tag_suffix: ""
|
| 20 |
+
secrets:
|
| 21 |
+
hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/build_pr_documentation.yml
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Build PR Documentation
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
pull_request:
|
| 5 |
+
|
| 6 |
+
env:
|
| 7 |
+
TRL_EXPERIMENTAL_SILENCE: 1
|
| 8 |
+
|
| 9 |
+
concurrency:
|
| 10 |
+
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
|
| 11 |
+
cancel-in-progress: true
|
| 12 |
+
|
| 13 |
+
jobs:
|
| 14 |
+
build:
|
| 15 |
+
if: github.event.pull_request.draft == false
|
| 16 |
+
uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@bcff59fca682130d2e7271ca8589911b7ac0b8bf # main
|
| 17 |
+
with:
|
| 18 |
+
commit_sha: ${{ github.event.pull_request.head.sha }}
|
| 19 |
+
pr_number: ${{ github.event.number }}
|
| 20 |
+
package: trl
|
| 21 |
+
version_tag_suffix: ""
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/clear_cache.yml
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: "Cleanup Cache"
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
workflow_dispatch:
|
| 5 |
+
schedule:
|
| 6 |
+
- cron: "0 0 * * *"
|
| 7 |
+
|
| 8 |
+
jobs:
|
| 9 |
+
cleanup:
|
| 10 |
+
runs-on: ubuntu-latest
|
| 11 |
+
steps:
|
| 12 |
+
- name: Check out code
|
| 13 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 14 |
+
|
| 15 |
+
- name: Cleanup
|
| 16 |
+
run: |
|
| 17 |
+
gh extension install actions/gh-actions-cache
|
| 18 |
+
|
| 19 |
+
echo "Fetching list of cache key"
|
| 20 |
+
cacheKeysForPR=$(gh actions-cache list -R $REPO | cut -f 1 )
|
| 21 |
+
|
| 22 |
+
## Setting this to not fail the workflow while deleting cache keys.
|
| 23 |
+
set +e
|
| 24 |
+
echo "Deleting caches..."
|
| 25 |
+
for cacheKey in $cacheKeysForPR
|
| 26 |
+
do
|
| 27 |
+
gh actions-cache delete $cacheKey -R $REPO --confirm
|
| 28 |
+
done
|
| 29 |
+
echo "Done"
|
| 30 |
+
env:
|
| 31 |
+
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
| 32 |
+
REPO: ${{ github.repository }}
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/codeQL.yml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: "CodeQL Analysis - Workflows"
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
workflow_dispatch:
|
| 5 |
+
|
| 6 |
+
jobs:
|
| 7 |
+
analyze:
|
| 8 |
+
name: "Analyze GitHub Workflows"
|
| 9 |
+
runs-on: ubuntu-latest
|
| 10 |
+
permissions:
|
| 11 |
+
security-events: write
|
| 12 |
+
actions: read
|
| 13 |
+
contents: read
|
| 14 |
+
|
| 15 |
+
steps:
|
| 16 |
+
- name: "Checkout repository"
|
| 17 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 18 |
+
|
| 19 |
+
- name: "Initialize CodeQL"
|
| 20 |
+
uses: github/codeql-action/init@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
|
| 21 |
+
with:
|
| 22 |
+
languages: "actions"
|
| 23 |
+
queries: +security-and-quality, ./.github/codeql/custom-queries.qls
|
| 24 |
+
|
| 25 |
+
- name: "Perform CodeQL Analysis"
|
| 26 |
+
uses: github/codeql-action/analyze@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/docker-build.yml
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Build TRL Docker image
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- main
|
| 7 |
+
workflow_dispatch:
|
| 8 |
+
|
| 9 |
+
concurrency:
|
| 10 |
+
group: docker-image-builds
|
| 11 |
+
cancel-in-progress: false
|
| 12 |
+
|
| 13 |
+
jobs:
|
| 14 |
+
trl:
|
| 15 |
+
name: "Build and push TRL Docker image"
|
| 16 |
+
runs-on:
|
| 17 |
+
group: aws-general-8-plus
|
| 18 |
+
steps:
|
| 19 |
+
- name: Checkout code
|
| 20 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 21 |
+
|
| 22 |
+
- name: Get TRL version from PyPI
|
| 23 |
+
run: |
|
| 24 |
+
VERSION=$(curl -s https://pypi.org/pypi/trl/json | jq -r .info.version)
|
| 25 |
+
if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+([a-zA-Z0-9._-]*)?$ ]]; then
|
| 26 |
+
echo "Invalid version format: $VERSION"
|
| 27 |
+
exit 1
|
| 28 |
+
fi
|
| 29 |
+
if [[ ${#VERSION} -gt 50 ]]; then
|
| 30 |
+
echo "Version string too long: $VERSION"
|
| 31 |
+
exit 1
|
| 32 |
+
fi
|
| 33 |
+
echo "VERSION=$VERSION" >> $GITHUB_ENV
|
| 34 |
+
|
| 35 |
+
- name: Set up Docker Buildx
|
| 36 |
+
uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0
|
| 37 |
+
|
| 38 |
+
- name: Login to DockerHub
|
| 39 |
+
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
|
| 40 |
+
with:
|
| 41 |
+
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
| 42 |
+
password: ${{ secrets.DOCKERHUB_PASSWORD }}
|
| 43 |
+
|
| 44 |
+
- name: Build and Push
|
| 45 |
+
uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0
|
| 46 |
+
env:
|
| 47 |
+
VERSION: ${{ env.VERSION }}
|
| 48 |
+
with:
|
| 49 |
+
context: docker/trl
|
| 50 |
+
push: true
|
| 51 |
+
tags: |
|
| 52 |
+
huggingface/trl:${{ env.VERSION }}
|
| 53 |
+
huggingface/trl
|
| 54 |
+
|
| 55 |
+
- name: Post to Slack
|
| 56 |
+
if: always()
|
| 57 |
+
uses: huggingface/hf-workflows/.github/actions/post-slack@a88e7fa2eaee28de5a4d6142381b1fb792349b67 # main
|
| 58 |
+
with:
|
| 59 |
+
slack_channel: ${{ secrets.CI_DOCKER_CHANNEL }}
|
| 60 |
+
title: 🤗 Results of the TRL Dev Docker Image build
|
| 61 |
+
status: ${{ job.status }}
|
| 62 |
+
slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
|
| 63 |
+
|
| 64 |
+
trl-dev:
|
| 65 |
+
name: "Build and push TRL Dev Docker image"
|
| 66 |
+
runs-on:
|
| 67 |
+
group: aws-general-8-plus
|
| 68 |
+
steps:
|
| 69 |
+
- name: Checkout code
|
| 70 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 71 |
+
|
| 72 |
+
- name: Set up Docker Buildx
|
| 73 |
+
uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0
|
| 74 |
+
|
| 75 |
+
- name: Login to DockerHub
|
| 76 |
+
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
|
| 77 |
+
with:
|
| 78 |
+
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
| 79 |
+
password: ${{ secrets.DOCKERHUB_PASSWORD }}
|
| 80 |
+
|
| 81 |
+
- name: Build and Push
|
| 82 |
+
uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0
|
| 83 |
+
with:
|
| 84 |
+
context: docker/trl-dev
|
| 85 |
+
push: true
|
| 86 |
+
tags: |
|
| 87 |
+
huggingface/trl:dev
|
| 88 |
+
|
| 89 |
+
- name: Post to Slack
|
| 90 |
+
if: always()
|
| 91 |
+
uses: huggingface/hf-workflows/.github/actions/post-slack@a88e7fa2eaee28de5a4d6142381b1fb792349b67 # main
|
| 92 |
+
with:
|
| 93 |
+
slack_channel: ${{ secrets.CI_DOCKER_CHANNEL }}
|
| 94 |
+
title: 🤗 Results of the TRL Dev Docker Image build
|
| 95 |
+
status: ${{ job.status }}
|
| 96 |
+
slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/pr_template_check.yml
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This workflow runs when a PR is first opened by an external contributor
|
| 2 |
+
# (author_association is FIRST_TIME_CONTRIBUTOR, FIRST_TIMER, or NONE).
|
| 3 |
+
# Org members with public membership are skipped (author_association = MEMBER).
|
| 4 |
+
# It checks that the PR body:
|
| 5 |
+
# 1. Contains a non-empty description (not just the template placeholder)
|
| 6 |
+
# 2. Includes the "## Before submitting" checklist
|
| 7 |
+
# 3. Has at least one checkbox checked
|
| 8 |
+
# If any check fails, the workflow posts a comment and closes the PR.
|
| 9 |
+
|
| 10 |
+
name: PR Template Check
|
| 11 |
+
|
| 12 |
+
on:
|
| 13 |
+
pull_request_target:
|
| 14 |
+
types: [opened]
|
| 15 |
+
|
| 16 |
+
permissions:
|
| 17 |
+
pull-requests: write
|
| 18 |
+
issues: write
|
| 19 |
+
statuses: write
|
| 20 |
+
|
| 21 |
+
jobs:
|
| 22 |
+
check-pr-template:
|
| 23 |
+
runs-on: ubuntu-latest
|
| 24 |
+
if: >
|
| 25 |
+
github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' ||
|
| 26 |
+
github.event.pull_request.author_association == 'FIRST_TIMER' ||
|
| 27 |
+
github.event.pull_request.author_association == 'NONE'
|
| 28 |
+
steps:
|
| 29 |
+
- name: Check PR body follows template
|
| 30 |
+
id: check
|
| 31 |
+
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
| 32 |
+
env:
|
| 33 |
+
PR_BODY: ${{ github.event.pull_request.body }}
|
| 34 |
+
with:
|
| 35 |
+
script: |
|
| 36 |
+
const body = process.env.PR_BODY || "";
|
| 37 |
+
|
| 38 |
+
const errors = [];
|
| 39 |
+
|
| 40 |
+
// 1. Must have a non-placeholder description (the "What does this PR do?" section)
|
| 41 |
+
const descriptionSection = body.split("## Before submitting")[0] || "";
|
| 42 |
+
const strippedDescription = descriptionSection
|
| 43 |
+
.replace(/<!--[\s\S]*?-->/g, "") // remove HTML comments
|
| 44 |
+
.replace(/Fixes\s*#\s*\(issue\)/gi, "") // remove placeholder issue line
|
| 45 |
+
.trim();
|
| 46 |
+
|
| 47 |
+
if (strippedDescription.length < 20) {
|
| 48 |
+
errors.push("- Missing PR description: please explain what this PR does and why.");
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
// 2. Must have the "Before submitting" checklist
|
| 52 |
+
if (!body.includes("## Before submitting")) {
|
| 53 |
+
errors.push("- Missing '## Before submitting' checklist section.");
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// 3. At least one checkbox must be checked
|
| 57 |
+
const checkedBoxes = (body.match(/- \[x\]/gi) || []).length;
|
| 58 |
+
if (checkedBoxes === 0) {
|
| 59 |
+
errors.push("- No checkboxes are checked in the 'Before submitting' section. Please review and check the relevant items.");
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
if (errors.length > 0) {
|
| 63 |
+
const comment = "Your PR has been closed because it does not follow the required [PR template](https://github.com/huggingface/trl/blob/main/.github/PULL_REQUEST_TEMPLATE.md). Please open a new PR following the template. See [CONTRIBUTING.md](https://github.com/huggingface/trl/blob/main/CONTRIBUTING.md#submitting-a-pull-request-pr) for guidance.";
|
| 64 |
+
|
| 65 |
+
await github.rest.issues.createComment({
|
| 66 |
+
owner: context.repo.owner,
|
| 67 |
+
repo: context.repo.repo,
|
| 68 |
+
issue_number: context.payload.pull_request.number,
|
| 69 |
+
body: comment,
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
await github.rest.pulls.update({
|
| 73 |
+
owner: context.repo.owner,
|
| 74 |
+
repo: context.repo.repo,
|
| 75 |
+
pull_number: context.payload.pull_request.number,
|
| 76 |
+
state: "closed",
|
| 77 |
+
});
|
| 78 |
+
|
| 79 |
+
core.setFailed("PR does not follow the required template.");
|
| 80 |
+
} else {
|
| 81 |
+
console.log("PR template check passed.");
|
| 82 |
+
}
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/publish.yml
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Publish to PyPI
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- main
|
| 7 |
+
- v*-release
|
| 8 |
+
paths:
|
| 9 |
+
- "VERSION"
|
| 10 |
+
|
| 11 |
+
jobs:
|
| 12 |
+
publish:
|
| 13 |
+
runs-on: ubuntu-latest
|
| 14 |
+
steps:
|
| 15 |
+
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 16 |
+
|
| 17 |
+
- name: Read version
|
| 18 |
+
id: get_version
|
| 19 |
+
run: echo "version=$(cat VERSION)" >> $GITHUB_OUTPUT
|
| 20 |
+
|
| 21 |
+
- name: Debug - Show version.txt content
|
| 22 |
+
run: echo "Version is ${{ steps.get_version.outputs.version }}"
|
| 23 |
+
|
| 24 |
+
- name: Set up Python
|
| 25 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 #v6.2.0
|
| 26 |
+
with:
|
| 27 |
+
python-version: "3.x"
|
| 28 |
+
|
| 29 |
+
- name: Install dependencies
|
| 30 |
+
run: |
|
| 31 |
+
python -m pip install --upgrade pip
|
| 32 |
+
pip install build twine
|
| 33 |
+
|
| 34 |
+
- name: Build package
|
| 35 |
+
run: python -m build
|
| 36 |
+
|
| 37 |
+
- name: Publish to PyPI
|
| 38 |
+
if: ${{ !contains(steps.get_version.outputs.version, 'dev') }}
|
| 39 |
+
env:
|
| 40 |
+
TWINE_USERNAME: __token__
|
| 41 |
+
TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
|
| 42 |
+
run: |
|
| 43 |
+
python -m twine upload dist/*
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/slow-tests.yml
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Slow tests (on push)
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: [main]
|
| 6 |
+
paths:
|
| 7 |
+
# Run only when python files are modified
|
| 8 |
+
- "trl/**.py"
|
| 9 |
+
- "examples/**.py"
|
| 10 |
+
env:
|
| 11 |
+
RUN_SLOW: "yes"
|
| 12 |
+
IS_GITHUB_CI: "1"
|
| 13 |
+
SLACK_API_TOKEN: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
|
| 14 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 15 |
+
TRL_EXPERIMENTAL_SILENCE: 1
|
| 16 |
+
|
| 17 |
+
jobs:
|
| 18 |
+
run_all_tests_single_gpu:
|
| 19 |
+
runs-on:
|
| 20 |
+
group: aws-g4dn-2xlarge
|
| 21 |
+
env:
|
| 22 |
+
CUDA_VISIBLE_DEVICES: "0"
|
| 23 |
+
TEST_TYPE: "single_gpu"
|
| 24 |
+
container:
|
| 25 |
+
image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
|
| 26 |
+
options: --gpus all --shm-size "16gb"
|
| 27 |
+
defaults:
|
| 28 |
+
run:
|
| 29 |
+
shell: bash
|
| 30 |
+
steps:
|
| 31 |
+
- name: Git checkout
|
| 32 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 33 |
+
|
| 34 |
+
- name: Install system dependencies
|
| 35 |
+
run: |
|
| 36 |
+
apt-get update && apt-get install -y make git curl
|
| 37 |
+
|
| 38 |
+
- name: Install uv
|
| 39 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 40 |
+
|
| 41 |
+
- name: Create Python virtual environment
|
| 42 |
+
run: |
|
| 43 |
+
uv venv
|
| 44 |
+
uv pip install --upgrade setuptools wheel
|
| 45 |
+
|
| 46 |
+
- name: Install dependencies
|
| 47 |
+
run: |
|
| 48 |
+
source .venv/bin/activate
|
| 49 |
+
uv pip install ".[dev]"
|
| 50 |
+
uv pip install pytest-reportlog
|
| 51 |
+
|
| 52 |
+
- name: Run slow SFT tests on single GPU
|
| 53 |
+
if: always()
|
| 54 |
+
run: |
|
| 55 |
+
source .venv/bin/activate
|
| 56 |
+
make slow_tests
|
| 57 |
+
|
| 58 |
+
- name: Generate Report
|
| 59 |
+
if: always()
|
| 60 |
+
run: |
|
| 61 |
+
source .venv/bin/activate
|
| 62 |
+
uv pip install slack_sdk tabulate
|
| 63 |
+
python scripts/log_reports.py >> $GITHUB_STEP_SUMMARY
|
| 64 |
+
|
| 65 |
+
run_all_tests_multi_gpu:
|
| 66 |
+
runs-on:
|
| 67 |
+
group: aws-g4dn-2xlarge
|
| 68 |
+
env:
|
| 69 |
+
CUDA_VISIBLE_DEVICES: "0,1"
|
| 70 |
+
TEST_TYPE: "multi_gpu"
|
| 71 |
+
container:
|
| 72 |
+
image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
|
| 73 |
+
options: --gpus all --shm-size "16gb"
|
| 74 |
+
defaults:
|
| 75 |
+
run:
|
| 76 |
+
shell: bash
|
| 77 |
+
steps:
|
| 78 |
+
- name: Git checkout
|
| 79 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 80 |
+
|
| 81 |
+
- name: Install system dependencies
|
| 82 |
+
run: |
|
| 83 |
+
apt-get update && apt-get install -y make git curl
|
| 84 |
+
|
| 85 |
+
- name: Install uv
|
| 86 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 87 |
+
|
| 88 |
+
- name: Create Python virtual environment
|
| 89 |
+
run: |
|
| 90 |
+
uv venv
|
| 91 |
+
uv pip install --upgrade setuptools wheel
|
| 92 |
+
|
| 93 |
+
- name: Install dependencies
|
| 94 |
+
run: |
|
| 95 |
+
source .venv/bin/activate
|
| 96 |
+
uv pip install ".[dev]"
|
| 97 |
+
uv pip install pytest-reportlog
|
| 98 |
+
|
| 99 |
+
- name: Run slow SFT tests on Multi GPU
|
| 100 |
+
if: always()
|
| 101 |
+
run: |
|
| 102 |
+
source .venv/bin/activate
|
| 103 |
+
make slow_tests
|
| 104 |
+
|
| 105 |
+
- name: Generate Reports
|
| 106 |
+
if: always()
|
| 107 |
+
run: |
|
| 108 |
+
source .venv/bin/activate
|
| 109 |
+
uv pip install slack_sdk tabulate
|
| 110 |
+
python scripts/log_reports.py >> $GITHUB_STEP_SUMMARY
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/sync-huggingface-skills.yml
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Sync TRL skill with huggingface/skills
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
tags:
|
| 6 |
+
- 'v*'
|
| 7 |
+
- '!v*rc*'
|
| 8 |
+
workflow_dispatch:
|
| 9 |
+
|
| 10 |
+
jobs:
|
| 11 |
+
sync-skills:
|
| 12 |
+
runs-on: ubuntu-latest
|
| 13 |
+
permissions:
|
| 14 |
+
contents: read
|
| 15 |
+
steps:
|
| 16 |
+
- name: Checkout trl repo
|
| 17 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 18 |
+
|
| 19 |
+
- name: Set up Python
|
| 20 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 21 |
+
with:
|
| 22 |
+
python-version: '3.12'
|
| 23 |
+
|
| 24 |
+
- name: Determine PR title
|
| 25 |
+
id: pr_title
|
| 26 |
+
run: |
|
| 27 |
+
if [[ "${{ github.event_name }}" == "push" && "${{ github.ref_type }}" == "tag" ]]; then
|
| 28 |
+
echo "title=Sync TRL Skill (${{ github.ref_name }})" >> $GITHUB_OUTPUT
|
| 29 |
+
else
|
| 30 |
+
echo "title=Sync TRL Skill (manual trigger)" >> $GITHUB_OUTPUT
|
| 31 |
+
fi
|
| 32 |
+
|
| 33 |
+
- name: Create GitHub App token
|
| 34 |
+
id: app_token
|
| 35 |
+
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
|
| 36 |
+
with:
|
| 37 |
+
app-id: ${{ secrets.APP_ID_HUB_SKILLS_REPO }}
|
| 38 |
+
private-key: ${{ secrets.APP_SECRET_PREM_HUB_SKILLS_REPO }}
|
| 39 |
+
repositories: skills
|
| 40 |
+
|
| 41 |
+
- name: Checkout huggingface/skills repo
|
| 42 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 43 |
+
with:
|
| 44 |
+
repository: huggingface/skills
|
| 45 |
+
token: ${{ steps.app_token.outputs.token }}
|
| 46 |
+
path: skills-repo
|
| 47 |
+
|
| 48 |
+
- name: Set up uv
|
| 49 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 50 |
+
|
| 51 |
+
- name: Copy generated files
|
| 52 |
+
run: cp trl/skills/trl-training/SKILL.md skills-repo/skills/trl-training/
|
| 53 |
+
|
| 54 |
+
- name: Check for TRL skill changes
|
| 55 |
+
id: check_changes
|
| 56 |
+
working-directory: skills-repo
|
| 57 |
+
# git diff returns zero if there is no diff
|
| 58 |
+
run: |
|
| 59 |
+
if git diff --quiet -- skills/trl-training/SKILL.md; then
|
| 60 |
+
echo "changed=false" >> "$GITHUB_OUTPUT"
|
| 61 |
+
echo "No trl skill changes; skipping PR"
|
| 62 |
+
else
|
| 63 |
+
echo "changed=true" >> "$GITHUB_OUTPUT"
|
| 64 |
+
fi
|
| 65 |
+
|
| 66 |
+
- name: Regenerate skills repo artifacts
|
| 67 |
+
if: steps.check_changes.outputs.changed == 'true'
|
| 68 |
+
working-directory: skills-repo
|
| 69 |
+
run: |
|
| 70 |
+
./scripts/publish.sh
|
| 71 |
+
|
| 72 |
+
- name: Create Pull Request
|
| 73 |
+
if: steps.check_changes.outputs.changed == 'true'
|
| 74 |
+
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
|
| 75 |
+
with:
|
| 76 |
+
token: ${{ steps.app_token.outputs.token }}
|
| 77 |
+
path: skills-repo
|
| 78 |
+
branch: sync/hf-cli-${{ github.run_id }}
|
| 79 |
+
delete-branch: true
|
| 80 |
+
title: ${{ steps.pr_title.outputs.title }}
|
| 81 |
+
body: |
|
| 82 |
+
Auto-generated from [trl@${{ github.sha }}](https://github.com/huggingface/trl/commit/${{ github.sha }})
|
| 83 |
+
|
| 84 |
+
Triggered by changes to `trl/skills/trl-training`
|
| 85 |
+
|
| 86 |
+
---
|
| 87 |
+
This PR was created automatically by the [sync-huggingface-skills](https://github.com/huggingface/trl/blob/main/.github/workflows/sync-huggingface-skills.yml) workflow.
|
| 88 |
+
commit-message: "Sync TRL skill from trl@${{ github.sha }}"
|
| 89 |
+
labels: |
|
| 90 |
+
automated
|
| 91 |
+
cli-sync
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/tests-experimental.yml
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Tests (experimental)
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
pull_request:
|
| 5 |
+
paths:
|
| 6 |
+
# Run only when relevant files are modified
|
| 7 |
+
- "trl/experimental/**"
|
| 8 |
+
- "tests/experimental/**"
|
| 9 |
+
|
| 10 |
+
env:
|
| 11 |
+
TQDM_DISABLE: 1
|
| 12 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 13 |
+
PYTORCH_CUDA_ALLOC_CONF: "expandable_segments:True"
|
| 14 |
+
PYTORCH_ALLOC_CONF: "expandable_segments:True"
|
| 15 |
+
TRL_EXPERIMENTAL_SILENCE: 1
|
| 16 |
+
|
| 17 |
+
jobs:
|
| 18 |
+
check_code_quality:
|
| 19 |
+
name: Check code quality
|
| 20 |
+
runs-on: ubuntu-latest
|
| 21 |
+
if: github.event.pull_request.draft == false
|
| 22 |
+
steps:
|
| 23 |
+
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 24 |
+
- name: Set up Python 3.13
|
| 25 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 26 |
+
with:
|
| 27 |
+
python-version: 3.13
|
| 28 |
+
- uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
|
| 29 |
+
with:
|
| 30 |
+
extra_args: --all-files
|
| 31 |
+
|
| 32 |
+
tests:
|
| 33 |
+
name: Tests (experimental)
|
| 34 |
+
runs-on:
|
| 35 |
+
group: aws-g4dn-2xlarge
|
| 36 |
+
container:
|
| 37 |
+
image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
|
| 38 |
+
options: --gpus all
|
| 39 |
+
defaults:
|
| 40 |
+
run:
|
| 41 |
+
shell: bash
|
| 42 |
+
steps:
|
| 43 |
+
- name: Git checkout
|
| 44 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 45 |
+
|
| 46 |
+
- name: Set up Python 3.13
|
| 47 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 48 |
+
with:
|
| 49 |
+
python-version: 3.13
|
| 50 |
+
|
| 51 |
+
- name: Install Make and Git
|
| 52 |
+
run: |
|
| 53 |
+
apt-get update && apt-get install -y make git curl
|
| 54 |
+
|
| 55 |
+
- name: Install uv
|
| 56 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 57 |
+
|
| 58 |
+
- name: Create Python virtual environment
|
| 59 |
+
run: |
|
| 60 |
+
uv venv
|
| 61 |
+
uv pip install --upgrade setuptools wheel
|
| 62 |
+
|
| 63 |
+
- name: Install dependencies
|
| 64 |
+
run: |
|
| 65 |
+
source .venv/bin/activate
|
| 66 |
+
uv pip install ".[dev]"
|
| 67 |
+
|
| 68 |
+
- name: Test with pytest
|
| 69 |
+
run: |
|
| 70 |
+
source .venv/bin/activate
|
| 71 |
+
make test_experimental
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/tests.yml
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Tests
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- main
|
| 7 |
+
- ci-*
|
| 8 |
+
pull_request:
|
| 9 |
+
paths:
|
| 10 |
+
# Run only when relevant files are modified
|
| 11 |
+
- ".github/**.yml"
|
| 12 |
+
- "examples/**.py"
|
| 13 |
+
- "scripts/**.py"
|
| 14 |
+
- "tests/**.py"
|
| 15 |
+
- "trl/**.py"
|
| 16 |
+
- "pyproject.toml"
|
| 17 |
+
# Exclude if only experimental code/tests
|
| 18 |
+
- "!trl/experimental/**"
|
| 19 |
+
- "!tests/experimental/**"
|
| 20 |
+
|
| 21 |
+
env:
|
| 22 |
+
TQDM_DISABLE: 1
|
| 23 |
+
CI_SLACK_CHANNEL: ${{ secrets.CI_PUSH_MAIN_CHANNEL }}
|
| 24 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 25 |
+
PYTORCH_CUDA_ALLOC_CONF: "expandable_segments:True"
|
| 26 |
+
PYTORCH_ALLOC_CONF: "expandable_segments:True"
|
| 27 |
+
|
| 28 |
+
jobs:
|
| 29 |
+
check_code_quality:
|
| 30 |
+
name: Check code quality
|
| 31 |
+
runs-on: ubuntu-latest
|
| 32 |
+
if: github.event.pull_request.draft == false
|
| 33 |
+
steps:
|
| 34 |
+
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 35 |
+
- name: Set up Python 3.12
|
| 36 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 37 |
+
with:
|
| 38 |
+
python-version: 3.12
|
| 39 |
+
- uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
|
| 40 |
+
with:
|
| 41 |
+
extra_args: --all-files
|
| 42 |
+
|
| 43 |
+
tests:
|
| 44 |
+
name: Tests
|
| 45 |
+
strategy:
|
| 46 |
+
matrix:
|
| 47 |
+
python-version: ['3.10', '3.11', '3.12', '3.13', '3.14']
|
| 48 |
+
fail-fast: false
|
| 49 |
+
runs-on:
|
| 50 |
+
group: aws-g4dn-2xlarge
|
| 51 |
+
container:
|
| 52 |
+
image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
|
| 53 |
+
options: --gpus all
|
| 54 |
+
defaults:
|
| 55 |
+
run:
|
| 56 |
+
shell: bash
|
| 57 |
+
if: github.event.pull_request.draft == false
|
| 58 |
+
steps:
|
| 59 |
+
- name: Git checkout
|
| 60 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 61 |
+
|
| 62 |
+
- name: Set up Python ${{ matrix.python-version }}
|
| 63 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 64 |
+
with:
|
| 65 |
+
python-version: ${{ matrix.python-version }}
|
| 66 |
+
|
| 67 |
+
- name: Install Make and Git
|
| 68 |
+
run: |
|
| 69 |
+
apt-get update && apt-get install -y make git curl
|
| 70 |
+
|
| 71 |
+
- name: Install uv
|
| 72 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 73 |
+
|
| 74 |
+
- name: Create Python virtual environment
|
| 75 |
+
run: |
|
| 76 |
+
uv venv
|
| 77 |
+
uv pip install --upgrade setuptools wheel
|
| 78 |
+
|
| 79 |
+
- name: Install dependencies
|
| 80 |
+
run: |
|
| 81 |
+
source .venv/bin/activate
|
| 82 |
+
uv pip install ".[dev]"
|
| 83 |
+
|
| 84 |
+
- name: Test with pytest
|
| 85 |
+
run: |
|
| 86 |
+
source .venv/bin/activate
|
| 87 |
+
make test
|
| 88 |
+
|
| 89 |
+
- name: Post to Slack
|
| 90 |
+
if: github.ref == 'refs/heads/main' && always() # Check if the branch is main
|
| 91 |
+
uses: huggingface/hf-workflows/.github/actions/post-slack@main
|
| 92 |
+
with:
|
| 93 |
+
slack_channel: ${{ env.CI_SLACK_CHANNEL }}
|
| 94 |
+
title: Results with Python ${{ matrix.python-version }} and latest dependencies
|
| 95 |
+
status: ${{ job.status }}
|
| 96 |
+
slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
|
| 97 |
+
|
| 98 |
+
tests_dev:
|
| 99 |
+
name: Tests with dev dependencies
|
| 100 |
+
runs-on:
|
| 101 |
+
group: aws-g4dn-2xlarge
|
| 102 |
+
container:
|
| 103 |
+
image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
|
| 104 |
+
options: --gpus all
|
| 105 |
+
defaults:
|
| 106 |
+
run:
|
| 107 |
+
shell: bash
|
| 108 |
+
if: github.event.pull_request.draft == false
|
| 109 |
+
steps:
|
| 110 |
+
- name: Git checkout
|
| 111 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 112 |
+
|
| 113 |
+
- name: Set up Python 3.12
|
| 114 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 115 |
+
with:
|
| 116 |
+
python-version: '3.12'
|
| 117 |
+
|
| 118 |
+
- name: Install Make and Git
|
| 119 |
+
run: |
|
| 120 |
+
apt-get update && apt-get install -y make git curl
|
| 121 |
+
|
| 122 |
+
- name: Install uv
|
| 123 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 124 |
+
|
| 125 |
+
- name: Create Python virtual environment
|
| 126 |
+
run: |
|
| 127 |
+
uv venv
|
| 128 |
+
uv pip install --upgrade setuptools wheel
|
| 129 |
+
|
| 130 |
+
- name: Install dependencies
|
| 131 |
+
run: |
|
| 132 |
+
source .venv/bin/activate
|
| 133 |
+
uv pip install -U \
|
| 134 |
+
".[dev]" \
|
| 135 |
+
"accelerate @ git+https://github.com/huggingface/accelerate.git" \
|
| 136 |
+
"datasets @ git+https://github.com/huggingface/datasets.git" \
|
| 137 |
+
"transformers @ git+https://github.com/huggingface/transformers.git" \
|
| 138 |
+
"peft @ git+https://github.com/huggingface/peft.git"
|
| 139 |
+
|
| 140 |
+
- name: Test with pytest
|
| 141 |
+
run: |
|
| 142 |
+
source .venv/bin/activate
|
| 143 |
+
make test
|
| 144 |
+
|
| 145 |
+
- name: Post to Slack
|
| 146 |
+
if: github.ref == 'refs/heads/main' && always() # Check if the branch is main
|
| 147 |
+
uses: huggingface/hf-workflows/.github/actions/post-slack@main
|
| 148 |
+
with:
|
| 149 |
+
slack_channel: ${{ env.CI_SLACK_CHANNEL }}
|
| 150 |
+
title: Results with Python 3.12 and dev dependencies
|
| 151 |
+
status: ${{ job.status }}
|
| 152 |
+
slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
|
| 153 |
+
|
| 154 |
+
tests_wo_optional_deps:
|
| 155 |
+
name: Tests without optional dependencies
|
| 156 |
+
runs-on:
|
| 157 |
+
group: aws-g4dn-2xlarge
|
| 158 |
+
container:
|
| 159 |
+
image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
|
| 160 |
+
options: --gpus all
|
| 161 |
+
defaults:
|
| 162 |
+
run:
|
| 163 |
+
shell: bash
|
| 164 |
+
if: github.event.pull_request.draft == false
|
| 165 |
+
steps:
|
| 166 |
+
- name: Git checkout
|
| 167 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 168 |
+
|
| 169 |
+
- name: Set up Python 3.12
|
| 170 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 171 |
+
with:
|
| 172 |
+
python-version: '3.12'
|
| 173 |
+
|
| 174 |
+
- name: Install Make and Git
|
| 175 |
+
run: |
|
| 176 |
+
apt-get update && apt-get install -y make git curl
|
| 177 |
+
|
| 178 |
+
- name: Install uv
|
| 179 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 180 |
+
|
| 181 |
+
- name: Create Python virtual environment
|
| 182 |
+
run: |
|
| 183 |
+
uv venv
|
| 184 |
+
uv pip install --upgrade setuptools wheel
|
| 185 |
+
|
| 186 |
+
- name: Install dependencies
|
| 187 |
+
run: |
|
| 188 |
+
source .venv/bin/activate
|
| 189 |
+
uv pip install ".[test]"
|
| 190 |
+
|
| 191 |
+
- name: Test with pytest
|
| 192 |
+
run: |
|
| 193 |
+
source .venv/bin/activate
|
| 194 |
+
make test
|
| 195 |
+
|
| 196 |
+
- name: Post to Slack
|
| 197 |
+
if: github.ref == 'refs/heads/main' && always() # Check if the branch is main
|
| 198 |
+
uses: huggingface/hf-workflows/.github/actions/post-slack@main
|
| 199 |
+
with:
|
| 200 |
+
slack_channel: ${{ env.CI_SLACK_CHANNEL }}
|
| 201 |
+
title: Results with Python 3.12 without optional dependencies
|
| 202 |
+
status: ${{ job.status }}
|
| 203 |
+
slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
|
| 204 |
+
|
| 205 |
+
tests_min_versions:
|
| 206 |
+
name: Tests with minimum versions
|
| 207 |
+
runs-on:
|
| 208 |
+
group: aws-g4dn-2xlarge
|
| 209 |
+
container:
|
| 210 |
+
image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
|
| 211 |
+
options: --gpus all
|
| 212 |
+
defaults:
|
| 213 |
+
run:
|
| 214 |
+
shell: bash
|
| 215 |
+
if: github.event.pull_request.draft == false
|
| 216 |
+
steps:
|
| 217 |
+
- name: Git checkout
|
| 218 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 219 |
+
|
| 220 |
+
- name: Set up Python 3.12
|
| 221 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 222 |
+
with:
|
| 223 |
+
python-version: '3.12'
|
| 224 |
+
|
| 225 |
+
- name: Install Make and Git
|
| 226 |
+
run: |
|
| 227 |
+
apt-get update && apt-get install -y make git curl
|
| 228 |
+
|
| 229 |
+
- name: Install uv
|
| 230 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 231 |
+
|
| 232 |
+
- name: Create Python virtual environment
|
| 233 |
+
run: |
|
| 234 |
+
uv venv
|
| 235 |
+
uv pip install --upgrade setuptools wheel
|
| 236 |
+
|
| 237 |
+
- name: Install dependencies
|
| 238 |
+
run: |
|
| 239 |
+
source .venv/bin/activate
|
| 240 |
+
uv pip install \
|
| 241 |
+
".[dev]" \
|
| 242 |
+
"accelerate==1.4.0" \
|
| 243 |
+
"datasets==4.7.0" \
|
| 244 |
+
"transformers==4.56.2"
|
| 245 |
+
|
| 246 |
+
- name: Test with pytest
|
| 247 |
+
run: |
|
| 248 |
+
source .venv/bin/activate
|
| 249 |
+
make test
|
| 250 |
+
|
| 251 |
+
- name: Post to Slack
|
| 252 |
+
if: github.ref == 'refs/heads/main' && always() # Check if the branch is main
|
| 253 |
+
uses: huggingface/hf-workflows/.github/actions/post-slack@main
|
| 254 |
+
with:
|
| 255 |
+
slack_channel: ${{ env.CI_SLACK_CHANNEL }}
|
| 256 |
+
title: Results with Python 3.12 and minimum dependencies versions
|
| 257 |
+
status: ${{ job.status }}
|
| 258 |
+
slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
|
| 259 |
+
|
| 260 |
+
distributed_smoke:
|
| 261 |
+
name: Distributed smoke tests
|
| 262 |
+
runs-on:
|
| 263 |
+
group: aws-g5-12xlarge-cache
|
| 264 |
+
container:
|
| 265 |
+
image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
|
| 266 |
+
options: --gpus all
|
| 267 |
+
defaults:
|
| 268 |
+
run:
|
| 269 |
+
shell: bash
|
| 270 |
+
if: github.event.pull_request.draft == false
|
| 271 |
+
env:
|
| 272 |
+
CUDA_VISIBLE_DEVICES: "0,1"
|
| 273 |
+
steps:
|
| 274 |
+
- name: Git checkout
|
| 275 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 276 |
+
|
| 277 |
+
- name: Set up Python 3.12
|
| 278 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 279 |
+
with:
|
| 280 |
+
python-version: '3.12'
|
| 281 |
+
|
| 282 |
+
- name: Install Make and Git
|
| 283 |
+
run: |
|
| 284 |
+
apt-get update && apt-get install -y make git curl
|
| 285 |
+
|
| 286 |
+
- name: Install uv
|
| 287 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 288 |
+
|
| 289 |
+
- name: Create Python virtual environment
|
| 290 |
+
run: |
|
| 291 |
+
uv venv
|
| 292 |
+
uv pip install --upgrade setuptools wheel
|
| 293 |
+
|
| 294 |
+
- name: Install dependencies
|
| 295 |
+
run: |
|
| 296 |
+
source .venv/bin/activate
|
| 297 |
+
uv pip install ".[dev]"
|
| 298 |
+
|
| 299 |
+
- name: Run distributed smoke tests
|
| 300 |
+
run: |
|
| 301 |
+
source .venv/bin/activate
|
| 302 |
+
pytest -v tests/distributed/test_distributed.py
|
| 303 |
+
|
| 304 |
+
- name: Post to Slack
|
| 305 |
+
if: github.ref == 'refs/heads/main' && always() # Check if the branch is main
|
| 306 |
+
uses: huggingface/hf-workflows/.github/actions/post-slack@main
|
| 307 |
+
with:
|
| 308 |
+
slack_channel: ${{ env.CI_SLACK_CHANNEL }}
|
| 309 |
+
title: Results of distributed smoke tests
|
| 310 |
+
status: ${{ job.status }}
|
| 311 |
+
slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/tests_latest.yml
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Tests latest TRL release with dev dependencies
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
schedule:
|
| 5 |
+
- cron: '0 0 * * *' # Runs daily at midnight UTC
|
| 6 |
+
|
| 7 |
+
workflow_dispatch:
|
| 8 |
+
|
| 9 |
+
env:
|
| 10 |
+
TQDM_DISABLE: 1
|
| 11 |
+
CI_SLACK_CHANNEL: ${{ secrets.CI_PUSH_MAIN_CHANNEL }}
|
| 12 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 13 |
+
TRL_EXPERIMENTAL_SILENCE: 1
|
| 14 |
+
|
| 15 |
+
jobs:
|
| 16 |
+
tests:
|
| 17 |
+
name: Tests latest TRL release with dev dependencies
|
| 18 |
+
runs-on:
|
| 19 |
+
group: aws-g4dn-2xlarge
|
| 20 |
+
container:
|
| 21 |
+
image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
|
| 22 |
+
options: --gpus all
|
| 23 |
+
defaults:
|
| 24 |
+
run:
|
| 25 |
+
shell: bash
|
| 26 |
+
steps:
|
| 27 |
+
- name: Git checkout
|
| 28 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 29 |
+
with: { ref: v1.6-release }
|
| 30 |
+
|
| 31 |
+
- name: Set up Python 3.12
|
| 32 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 33 |
+
with:
|
| 34 |
+
python-version: '3.12'
|
| 35 |
+
|
| 36 |
+
- name: Install Make and Git
|
| 37 |
+
run: |
|
| 38 |
+
apt-get update && apt-get install -y make git curl
|
| 39 |
+
|
| 40 |
+
- name: Install uv
|
| 41 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 42 |
+
|
| 43 |
+
- name: Create Python virtual environment
|
| 44 |
+
run: |
|
| 45 |
+
uv venv
|
| 46 |
+
uv pip install --upgrade setuptools wheel
|
| 47 |
+
|
| 48 |
+
- name: Install dependencies
|
| 49 |
+
run: |
|
| 50 |
+
source .venv/bin/activate
|
| 51 |
+
uv pip install -U \
|
| 52 |
+
".[dev]" \
|
| 53 |
+
"accelerate @ git+https://github.com/huggingface/accelerate.git" \
|
| 54 |
+
"datasets @ git+https://github.com/huggingface/datasets.git" \
|
| 55 |
+
"transformers @ git+https://github.com/huggingface/transformers.git"
|
| 56 |
+
|
| 57 |
+
- name: Test with pytest
|
| 58 |
+
run: |
|
| 59 |
+
source .venv/bin/activate
|
| 60 |
+
make test
|
| 61 |
+
|
| 62 |
+
- name: Post to Slack
|
| 63 |
+
uses: huggingface/hf-workflows/.github/actions/post-slack@main
|
| 64 |
+
with:
|
| 65 |
+
slack_channel: ${{ env.CI_SLACK_CHANNEL }}
|
| 66 |
+
title: Results of latest TRL with Python 3.12 and dev dependencies
|
| 67 |
+
status: ${{ job.status }}
|
| 68 |
+
slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/tests_transformers_branch.yml
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Tests against Transformers branch
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
workflow_dispatch:
|
| 5 |
+
inputs:
|
| 6 |
+
transformers_ref:
|
| 7 |
+
description: "Transformers git ref (branch, tag, or commit SHA)"
|
| 8 |
+
required: true
|
| 9 |
+
default: "main"
|
| 10 |
+
|
| 11 |
+
env:
|
| 12 |
+
TQDM_DISABLE: 1
|
| 13 |
+
CI_SLACK_CHANNEL: ${{ secrets.CI_PUSH_MAIN_CHANNEL }}
|
| 14 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 15 |
+
PYTORCH_CUDA_ALLOC_CONF: "expandable_segments:True"
|
| 16 |
+
PYTORCH_ALLOC_CONF: "expandable_segments:True"
|
| 17 |
+
|
| 18 |
+
jobs:
|
| 19 |
+
tests_transformers_branch:
|
| 20 |
+
name: Tests with Transformers ${{ inputs.transformers_ref }}
|
| 21 |
+
runs-on:
|
| 22 |
+
group: aws-g4dn-2xlarge
|
| 23 |
+
container:
|
| 24 |
+
image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
|
| 25 |
+
options: --gpus all
|
| 26 |
+
defaults:
|
| 27 |
+
run:
|
| 28 |
+
shell: bash
|
| 29 |
+
steps:
|
| 30 |
+
- name: Git checkout
|
| 31 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 32 |
+
|
| 33 |
+
- name: Set up Python 3.12
|
| 34 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 35 |
+
with:
|
| 36 |
+
python-version: '3.12'
|
| 37 |
+
|
| 38 |
+
- name: Install Make and Git
|
| 39 |
+
run: |
|
| 40 |
+
apt-get update && apt-get install -y make git curl
|
| 41 |
+
|
| 42 |
+
- name: Install uv
|
| 43 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 44 |
+
|
| 45 |
+
- name: Create Python virtual environment
|
| 46 |
+
run: |
|
| 47 |
+
uv venv
|
| 48 |
+
uv pip install --upgrade setuptools wheel
|
| 49 |
+
|
| 50 |
+
- name: Install dependencies
|
| 51 |
+
env:
|
| 52 |
+
TRANSFORMERS_REF: ${{ inputs.transformers_ref }}
|
| 53 |
+
run: |
|
| 54 |
+
source .venv/bin/activate
|
| 55 |
+
uv pip install -U \
|
| 56 |
+
".[dev]" \
|
| 57 |
+
"transformers @ git+https://github.com/huggingface/transformers.git@${TRANSFORMERS_REF}"
|
| 58 |
+
|
| 59 |
+
- name: Test with pytest
|
| 60 |
+
run: |
|
| 61 |
+
source .venv/bin/activate
|
| 62 |
+
make test
|
| 63 |
+
|
| 64 |
+
- name: Post to Slack
|
| 65 |
+
if: github.ref == 'refs/heads/main' && always()
|
| 66 |
+
uses: huggingface/hf-workflows/.github/actions/post-slack@main
|
| 67 |
+
with:
|
| 68 |
+
slack_channel: ${{ env.CI_SLACK_CHANNEL }}
|
| 69 |
+
title: Results with Transformers ${{ inputs.transformers_ref }}
|
| 70 |
+
status: ${{ job.status }}
|
| 71 |
+
slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
|
| 72 |
+
|
| 73 |
+
distributed_smoke:
|
| 74 |
+
name: Distributed smoke tests with Transformers ${{ inputs.transformers_ref }}
|
| 75 |
+
runs-on:
|
| 76 |
+
group: aws-g5-12xlarge-cache
|
| 77 |
+
container:
|
| 78 |
+
image: pytorch/pytorch:2.8.0-cuda12.8-cudnn9-devel
|
| 79 |
+
options: --gpus all
|
| 80 |
+
defaults:
|
| 81 |
+
run:
|
| 82 |
+
shell: bash
|
| 83 |
+
env:
|
| 84 |
+
CUDA_VISIBLE_DEVICES: "0,1"
|
| 85 |
+
steps:
|
| 86 |
+
- name: Git checkout
|
| 87 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 88 |
+
|
| 89 |
+
- name: Set up Python 3.12
|
| 90 |
+
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
| 91 |
+
with:
|
| 92 |
+
python-version: '3.12'
|
| 93 |
+
|
| 94 |
+
- name: Install Make and Git
|
| 95 |
+
run: |
|
| 96 |
+
apt-get update && apt-get install -y make git curl
|
| 97 |
+
|
| 98 |
+
- name: Install uv
|
| 99 |
+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
|
| 100 |
+
|
| 101 |
+
- name: Create Python virtual environment
|
| 102 |
+
run: |
|
| 103 |
+
uv venv
|
| 104 |
+
uv pip install --upgrade setuptools wheel
|
| 105 |
+
|
| 106 |
+
- name: Install dependencies
|
| 107 |
+
env:
|
| 108 |
+
TRANSFORMERS_REF: ${{ inputs.transformers_ref }}
|
| 109 |
+
run: |
|
| 110 |
+
source .venv/bin/activate
|
| 111 |
+
uv pip install -U \
|
| 112 |
+
".[dev]" \
|
| 113 |
+
"transformers @ git+https://github.com/huggingface/transformers.git@${TRANSFORMERS_REF}"
|
| 114 |
+
|
| 115 |
+
- name: Run distributed smoke tests
|
| 116 |
+
run: |
|
| 117 |
+
source .venv/bin/activate
|
| 118 |
+
pytest -v tests/distributed/test_distributed.py
|
| 119 |
+
|
| 120 |
+
- name: Post to Slack
|
| 121 |
+
if: github.ref == 'refs/heads/main' && always()
|
| 122 |
+
uses: huggingface/hf-workflows/.github/actions/post-slack@main
|
| 123 |
+
with:
|
| 124 |
+
slack_channel: ${{ env.CI_SLACK_CHANNEL }}
|
| 125 |
+
title: Results of distributed smoke tests with Transformers ${{ inputs.transformers_ref }}
|
| 126 |
+
status: ${{ job.status }}
|
| 127 |
+
slack_token: ${{ secrets.SLACK_CIFEEDBACK_BOT_TOKEN }}
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/trufflehog.yml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
on:
|
| 2 |
+
push:
|
| 3 |
+
|
| 4 |
+
name: Secret Leaks
|
| 5 |
+
|
| 6 |
+
jobs:
|
| 7 |
+
trufflehog:
|
| 8 |
+
runs-on: ubuntu-latest
|
| 9 |
+
steps:
|
| 10 |
+
- name: Checkout code
|
| 11 |
+
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
| 12 |
+
with:
|
| 13 |
+
fetch-depth: 0
|
| 14 |
+
- name: Secret Scanning
|
| 15 |
+
uses: trufflesecurity/trufflehog@d411fff7b8879a62509f3fa98c07f247ac089a51 # v3.95.5
|
| 16 |
+
with:
|
| 17 |
+
# exclude buggy postgres detector that is causing false positives and not relevant to our codebase
|
| 18 |
+
extra_args: --results=verified,unknown --exclude-detectors=postgres
|
tasks/tasksmith-03a6a091b12f/tests/source/.github/workflows/upload_pr_documentation.yml
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Upload PR Documentation
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
workflow_run:
|
| 5 |
+
workflows: ["Build PR Documentation"]
|
| 6 |
+
types:
|
| 7 |
+
- completed
|
| 8 |
+
|
| 9 |
+
jobs:
|
| 10 |
+
build:
|
| 11 |
+
uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@bcff59fca682130d2e7271ca8589911b7ac0b8bf # main
|
| 12 |
+
with:
|
| 13 |
+
package_name: trl
|
| 14 |
+
secrets:
|
| 15 |
+
hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }}
|
| 16 |
+
comment_bot_app_id: ${{ secrets.COMMENT_BOT_APP_ID }}
|
| 17 |
+
comment_bot_secret_pem: ${{ secrets.COMMENT_BOT_SECRET_PEM }}
|
tasks/tasksmith-03a6a091b12f/tests/source/.gitignore
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.bak
|
| 2 |
+
.gitattributes
|
| 3 |
+
.last_checked
|
| 4 |
+
.gitconfig
|
| 5 |
+
*.bak
|
| 6 |
+
*.log
|
| 7 |
+
*~
|
| 8 |
+
~*
|
| 9 |
+
_tmp*
|
| 10 |
+
tmp*
|
| 11 |
+
tags
|
| 12 |
+
|
| 13 |
+
# Byte-compiled / optimized / DLL files
|
| 14 |
+
__pycache__/
|
| 15 |
+
*.py[cod]
|
| 16 |
+
*$py.class
|
| 17 |
+
|
| 18 |
+
# C extensions
|
| 19 |
+
*.so
|
| 20 |
+
|
| 21 |
+
# Distribution / packaging
|
| 22 |
+
.Python
|
| 23 |
+
env/
|
| 24 |
+
build/
|
| 25 |
+
develop-eggs/
|
| 26 |
+
dist/
|
| 27 |
+
downloads/
|
| 28 |
+
eggs/
|
| 29 |
+
.eggs/
|
| 30 |
+
lib/
|
| 31 |
+
lib64/
|
| 32 |
+
parts/
|
| 33 |
+
sdist/
|
| 34 |
+
var/
|
| 35 |
+
wheels/
|
| 36 |
+
*.egg-info/
|
| 37 |
+
.installed.cfg
|
| 38 |
+
*.egg
|
| 39 |
+
|
| 40 |
+
# PyInstaller
|
| 41 |
+
# Usually these files are written by a python script from a template
|
| 42 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 43 |
+
*.manifest
|
| 44 |
+
*.spec
|
| 45 |
+
|
| 46 |
+
# Installer logs
|
| 47 |
+
pip-log.txt
|
| 48 |
+
pip-delete-this-directory.txt
|
| 49 |
+
|
| 50 |
+
# Unit test / coverage reports
|
| 51 |
+
htmlcov/
|
| 52 |
+
.tox/
|
| 53 |
+
.coverage
|
| 54 |
+
.coverage.*
|
| 55 |
+
.cache
|
| 56 |
+
nosetests.xml
|
| 57 |
+
coverage.xml
|
| 58 |
+
*.cover
|
| 59 |
+
.hypothesis/
|
| 60 |
+
|
| 61 |
+
# Translations
|
| 62 |
+
*.mo
|
| 63 |
+
*.pot
|
| 64 |
+
|
| 65 |
+
# Django stuff:
|
| 66 |
+
*.log
|
| 67 |
+
local_settings.py
|
| 68 |
+
|
| 69 |
+
# Flask stuff:
|
| 70 |
+
instance/
|
| 71 |
+
.webassets-cache
|
| 72 |
+
|
| 73 |
+
# Scrapy stuff:
|
| 74 |
+
.scrapy
|
| 75 |
+
|
| 76 |
+
# Sphinx documentation
|
| 77 |
+
docs/_build/
|
| 78 |
+
|
| 79 |
+
# PyBuilder
|
| 80 |
+
target/
|
| 81 |
+
|
| 82 |
+
# Jupyter Notebook
|
| 83 |
+
.ipynb_checkpoints
|
| 84 |
+
|
| 85 |
+
# pyenv
|
| 86 |
+
.python-version
|
| 87 |
+
|
| 88 |
+
# celery beat schedule file
|
| 89 |
+
celerybeat-schedule
|
| 90 |
+
|
| 91 |
+
# SageMath parsed files
|
| 92 |
+
*.sage.py
|
| 93 |
+
|
| 94 |
+
# dotenv
|
| 95 |
+
.env
|
| 96 |
+
|
| 97 |
+
# virtualenv
|
| 98 |
+
.venv
|
| 99 |
+
venv/
|
| 100 |
+
ENV/
|
| 101 |
+
|
| 102 |
+
# Spyder project settings
|
| 103 |
+
.spyderproject
|
| 104 |
+
.spyproject
|
| 105 |
+
|
| 106 |
+
# Rope project settings
|
| 107 |
+
.ropeproject
|
| 108 |
+
|
| 109 |
+
# mkdocs documentation
|
| 110 |
+
/site
|
| 111 |
+
|
| 112 |
+
# mypy
|
| 113 |
+
.mypy_cache/
|
| 114 |
+
|
| 115 |
+
.vscode
|
| 116 |
+
*.swp
|
| 117 |
+
|
| 118 |
+
# osx generated files
|
| 119 |
+
.DS_Store
|
| 120 |
+
.DS_Store?
|
| 121 |
+
.Trashes
|
| 122 |
+
ehthumbs.db
|
| 123 |
+
Thumbs.db
|
| 124 |
+
.idea
|
| 125 |
+
|
| 126 |
+
# pytest
|
| 127 |
+
.pytest_cache
|
| 128 |
+
|
| 129 |
+
# tools/trust-doc-nbs
|
| 130 |
+
docs_src/.last_checked
|
| 131 |
+
|
| 132 |
+
# symlinks to fastai
|
| 133 |
+
docs_src/fastai
|
| 134 |
+
tools/fastai
|
| 135 |
+
|
| 136 |
+
# link checker
|
| 137 |
+
checklink/cookies.txt
|
| 138 |
+
|
| 139 |
+
# .gitconfig is now autogenerated
|
| 140 |
+
.gitconfig
|
| 141 |
+
|
| 142 |
+
# wandb files
|
| 143 |
+
nbs/wandb/
|
| 144 |
+
examples/notebooks/wandb/
|
| 145 |
+
wandb/
|
| 146 |
+
|
| 147 |
+
# uv
|
| 148 |
+
uv.lock
|
| 149 |
+
|
| 150 |
+
# AI agent generated artifacts
|
| 151 |
+
/.agents/skills
|
| 152 |
+
/.claude/skills
|
tasks/tasksmith-03a6a091b12f/tests/source/.pre-commit-config.yaml
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
repos:
|
| 2 |
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
| 3 |
+
rev: v0.13.3
|
| 4 |
+
hooks:
|
| 5 |
+
- id: ruff-check
|
| 6 |
+
types_or: [ python, pyi ]
|
| 7 |
+
args: [ --fix ]
|
| 8 |
+
- id: ruff-format
|
| 9 |
+
types_or: [ python, pyi ]
|
| 10 |
+
|
| 11 |
+
- repo: local
|
| 12 |
+
hooks:
|
| 13 |
+
- id: doc-builder-style
|
| 14 |
+
name: Check style with doc-builder
|
| 15 |
+
language: python
|
| 16 |
+
entry: doc-builder style trl tests docs/source --max_len 119
|
| 17 |
+
additional_dependencies: ["git+https://github.com/huggingface/doc-builder@2430c1ec91d04667414e2fa31ecfc36c153ea391", ruff] # See GH-5633
|
| 18 |
+
pass_filenames: false
|
| 19 |
+
types_or: [python, markdown, rst]
|
tasks/tasksmith-03a6a091b12f/tests/source/AGENTS.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AGENTS.md
|
| 2 |
+
|
| 3 |
+
## Repository-specific guidance
|
| 4 |
+
|
| 5 |
+
### Main code vs experimental code
|
| 6 |
+
|
| 7 |
+
The repository is separated into **main code** and **experimental code**.
|
| 8 |
+
|
| 9 |
+
* **Main code** should remain stable, consistent, and well-tested.
|
| 10 |
+
* **Experimental code** may be less stable and may contain inconsistent patterns or limited testing.
|
| 11 |
+
|
| 12 |
+
Small non-invasive improvements that make experimental code more consistent with the main codebase are encouraged, but avoid large refactors.
|
| 13 |
+
|
| 14 |
+
### Paper implementations
|
| 15 |
+
|
| 16 |
+
If a PR implements a method, algorithm, or training approach from a research paper, it must also add a corresponding subsection to `paper_index.md`.
|
| 17 |
+
|
| 18 |
+
When reviewing such PRs, ensure that `paper_index.md` was updated.
|
| 19 |
+
|
| 20 |
+
### Code duplication and consistency
|
| 21 |
+
|
| 22 |
+
Trainers in this repository are **self-contained by design**. Shared logic (generation, reward computation, metric logging, weight syncing, etc.) is deliberately duplicated across trainers rather than abstracted into a shared base class.
|
| 23 |
+
|
| 24 |
+
This is intentional: each trainer must be readable, modifiable, and evolvable in isolation. The base class (`_BaseTrainer`) provides only minimal utilities (model card generation). Everything else — vLLM generation paths, `_get_per_token_logps_and_entropies`, `_calculate_rewards`, `_prepare_inputs`, metric logging — is copied in full.
|
| 25 |
+
|
| 26 |
+
**The tradeoff**: duplication is accepted, but **consistency is mandatory**. When the same logic appears in multiple trainers, the duplicated blocks must stay aligned:
|
| 27 |
+
|
| 28 |
+
- Same variable names (`self._last_loaded_step`, `self._metrics[mode]`, …)
|
| 29 |
+
- Same control flow structure (if/elif/else branches in the same order)
|
| 30 |
+
- Same comments (word-for-word when the logic is identical)
|
| 31 |
+
- Divergences only where the trainer's semantics require it (e.g., GRPO extracts logprobs from vLLM, RLOO discards them)
|
| 32 |
+
|
| 33 |
+
**Consistency over correctness**: this is a strong requirement. When duplicating code, reproduce it exactly — even if you believe the original has a bug. Do not silently fix the issue in your copy. Instead, keep your copy consistent with the source and report the problem so it can be fixed across all trainers in a dedicated PR. A correct-but-inconsistent codebase is harder to maintain than a consistently-wrong one that can be fixed in a single sweep.
|
| 34 |
+
|
| 35 |
+
**When modifying duplicated code**: if you change a pattern that exists in multiple trainers (e.g., the vLLM generation path in `_generate_single_turn`), apply the same change to all other trainers. A fix in GRPO often implies the same fix in RLOO, and vice versa. Not propagating a change is a bug.
|
| 36 |
+
|
| 37 |
+
**When reviewing**: if a PR touches duplicated logic, verify that all copies are updated consistently. A common mistake is fixing one trainer and forgetting the others.
|
| 38 |
+
|
| 39 |
+
### Simplicity
|
| 40 |
+
|
| 41 |
+
This codebase values **leanness and simplicity above all**. Prefer straightforward, inline code over abstractions, helpers, or utilities — even at the cost of some robustness or generality.
|
| 42 |
+
|
| 43 |
+
Concretely:
|
| 44 |
+
|
| 45 |
+
- Do not add layers of indirection (registries, factory patterns, plugin systems). A contributor should be able to read a trainer top to bottom and understand the full flow.
|
| 46 |
+
- Prefer a simple implementation that covers 90% of cases over a complex one that covers 100%. A function that handles the common path in 20 lines is better than a catch-all that handles every edge case in 80.
|
| 47 |
+
- Do not add defensive code, fallback paths, or configuration options "just in case". Only handle cases that actually exist today.
|
| 48 |
+
- Avoid `hasattr` and `getattr`. Their use is almost always a symptom of overly defensive programming or a disguised version check (e.g., "this attribute was added in version X"). Instead, either drop the conditional entirely or express the version check explicitly with a version comparison. There is nearly always a cleaner alternative.
|
| 49 |
+
- When in doubt, prefer less code. Every new function, parameter, or branch is maintenance burden. The best abstraction is often no abstraction.
|
| 50 |
+
|
| 51 |
+
## Documentation
|
| 52 |
+
|
| 53 |
+
### Docstrings
|
| 54 |
+
|
| 55 |
+
Docstrings must follow the repository format below. Do **not** convert docstrings to other styles (Google, NumPy, etc.).
|
| 56 |
+
|
| 57 |
+
Rules:
|
| 58 |
+
|
| 59 |
+
* Types appear in backticks inside parentheses: (`str`)
|
| 60 |
+
* Optional parameters are marked with `*optional*`
|
| 61 |
+
* Defaults are written as: `defaults to <value>`
|
| 62 |
+
* When the default is `None`, prefer ```(`str`, *optional*)``` instead of ```(`str` or `None`, *optional*, defaults to `None`)```
|
| 63 |
+
* Union types use `or`: `str` or `None`
|
| 64 |
+
* References to classes use the format: [`~transformers.PreTrainedModel`]
|
| 65 |
+
* Class docstrings may group parameters using headers such as: `> Parameters for X:`
|
| 66 |
+
|
| 67 |
+
Example:
|
| 68 |
+
|
| 69 |
+
````python
|
| 70 |
+
def method(self, param1: str, param2: int = 1, param3: float | None = None):
|
| 71 |
+
"""
|
| 72 |
+
Brief one-line description of what this does.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
param1 (`str`):
|
| 76 |
+
Description of required param.
|
| 77 |
+
param2 (`int`, *optional*, defaults to `1`):
|
| 78 |
+
Description of optional param with default.
|
| 79 |
+
param3 (`float`, *optional*):
|
| 80 |
+
Description of optional param without explicit default.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
`dict` with keys:
|
| 84 |
+
- `key1` (`list[int]`):
|
| 85 |
+
Description of this key.
|
| 86 |
+
|
| 87 |
+
Examples:
|
| 88 |
+
|
| 89 |
+
```python
|
| 90 |
+
>>> my_func("hello")
|
| 91 |
+
```
|
| 92 |
+
"""
|
| 93 |
+
````
|
| 94 |
+
|
| 95 |
+
### Links to papers
|
| 96 |
+
|
| 97 |
+
When linking to papers, use `https://huggingface.co/papers/<id>` instead of `https://arxiv.org/abs/<id>` (same ID suffix system).
|
tasks/tasksmith-03a6a091b12f/tests/source/CITATION.cff
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cff-version: 1.2.0
|
| 2 |
+
title: 'TRL: Transformers Reinforcement Learning'
|
| 3 |
+
message: >-
|
| 4 |
+
If you use this software, please cite it using the
|
| 5 |
+
metadata from this file.
|
| 6 |
+
type: software
|
| 7 |
+
authors:
|
| 8 |
+
- given-names: Leandro
|
| 9 |
+
family-names: von Werra
|
| 10 |
+
- given-names: Younes
|
| 11 |
+
family-names: Belkada
|
| 12 |
+
- given-names: Lewis
|
| 13 |
+
family-names: Tunstall
|
| 14 |
+
- given-names: Edward
|
| 15 |
+
family-names: Beeching
|
| 16 |
+
- given-names: Tristan
|
| 17 |
+
family-names: Thrush
|
| 18 |
+
- given-names: Nathan
|
| 19 |
+
family-names: Lambert
|
| 20 |
+
- given-names: Shengyi
|
| 21 |
+
family-names: Huang
|
| 22 |
+
- given-names: Kashif
|
| 23 |
+
family-names: Rasul
|
| 24 |
+
- given-names: Quentin
|
| 25 |
+
family-names: Gallouédec
|
| 26 |
+
repository-code: 'https://github.com/huggingface/trl'
|
| 27 |
+
abstract: >-
|
| 28 |
+
TRL (Transformers Reinforcement Learning) is an
|
| 29 |
+
open-source toolkit for aligning transformer models via
|
| 30 |
+
post-training. It provides practical, scalable
|
| 31 |
+
implementations of SFT, reward modeling, DPO, and GRPO
|
| 32 |
+
within the Hugging Face ecosystem.
|
| 33 |
+
keywords:
|
| 34 |
+
- transformers
|
| 35 |
+
- reinforcement learning
|
| 36 |
+
- preference optimization
|
| 37 |
+
- language model alignment
|
| 38 |
+
- post-training
|
| 39 |
+
license: Apache-2.0
|
| 40 |
+
version: '1.6'
|
| 41 |
+
date-released: '2020-03-27'
|
tasks/tasksmith-03a6a091b12f/tests/source/CLAUDE.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# AGENTS.md
|
| 2 |
+
|
| 3 |
+
## Repository-specific guidance
|
| 4 |
+
|
| 5 |
+
### Main code vs experimental code
|
| 6 |
+
|
| 7 |
+
The repository is separated into **main code** and **experimental code**.
|
| 8 |
+
|
| 9 |
+
* **Main code** should remain stable, consistent, and well-tested.
|
| 10 |
+
* **Experimental code** may be less stable and may contain inconsistent patterns or limited testing.
|
| 11 |
+
|
| 12 |
+
Small non-invasive improvements that make experimental code more consistent with the main codebase are encouraged, but avoid large refactors.
|
| 13 |
+
|
| 14 |
+
### Paper implementations
|
| 15 |
+
|
| 16 |
+
If a PR implements a method, algorithm, or training approach from a research paper, it must also add a corresponding subsection to `paper_index.md`.
|
| 17 |
+
|
| 18 |
+
When reviewing such PRs, ensure that `paper_index.md` was updated.
|
| 19 |
+
|
| 20 |
+
### Code duplication and consistency
|
| 21 |
+
|
| 22 |
+
Trainers in this repository are **self-contained by design**. Shared logic (generation, reward computation, metric logging, weight syncing, etc.) is deliberately duplicated across trainers rather than abstracted into a shared base class.
|
| 23 |
+
|
| 24 |
+
This is intentional: each trainer must be readable, modifiable, and evolvable in isolation. The base class (`_BaseTrainer`) provides only minimal utilities (model card generation). Everything else — vLLM generation paths, `_get_per_token_logps_and_entropies`, `_calculate_rewards`, `_prepare_inputs`, metric logging — is copied in full.
|
| 25 |
+
|
| 26 |
+
**The tradeoff**: duplication is accepted, but **consistency is mandatory**. When the same logic appears in multiple trainers, the duplicated blocks must stay aligned:
|
| 27 |
+
|
| 28 |
+
- Same variable names (`self._last_loaded_step`, `self._metrics[mode]`, …)
|
| 29 |
+
- Same control flow structure (if/elif/else branches in the same order)
|
| 30 |
+
- Same comments (word-for-word when the logic is identical)
|
| 31 |
+
- Divergences only where the trainer's semantics require it (e.g., GRPO extracts logprobs from vLLM, RLOO discards them)
|
| 32 |
+
|
| 33 |
+
**Consistency over correctness**: this is a strong requirement. When duplicating code, reproduce it exactly — even if you believe the original has a bug. Do not silently fix the issue in your copy. Instead, keep your copy consistent with the source and report the problem so it can be fixed across all trainers in a dedicated PR. A correct-but-inconsistent codebase is harder to maintain than a consistently-wrong one that can be fixed in a single sweep.
|
| 34 |
+
|
| 35 |
+
**When modifying duplicated code**: if you change a pattern that exists in multiple trainers (e.g., the vLLM generation path in `_generate_single_turn`), apply the same change to all other trainers. A fix in GRPO often implies the same fix in RLOO, and vice versa. Not propagating a change is a bug.
|
| 36 |
+
|
| 37 |
+
**When reviewing**: if a PR touches duplicated logic, verify that all copies are updated consistently. A common mistake is fixing one trainer and forgetting the others.
|
| 38 |
+
|
| 39 |
+
### Simplicity
|
| 40 |
+
|
| 41 |
+
This codebase values **leanness and simplicity above all**. Prefer straightforward, inline code over abstractions, helpers, or utilities — even at the cost of some robustness or generality.
|
| 42 |
+
|
| 43 |
+
Concretely:
|
| 44 |
+
|
| 45 |
+
- Do not add layers of indirection (registries, factory patterns, plugin systems). A contributor should be able to read a trainer top to bottom and understand the full flow.
|
| 46 |
+
- Prefer a simple implementation that covers 90% of cases over a complex one that covers 100%. A function that handles the common path in 20 lines is better than a catch-all that handles every edge case in 80.
|
| 47 |
+
- Do not add defensive code, fallback paths, or configuration options "just in case". Only handle cases that actually exist today.
|
| 48 |
+
- Avoid `hasattr` and `getattr`. Their use is almost always a symptom of overly defensive programming or a disguised version check (e.g., "this attribute was added in version X"). Instead, either drop the conditional entirely or express the version check explicitly with a version comparison. There is nearly always a cleaner alternative.
|
| 49 |
+
- When in doubt, prefer less code. Every new function, parameter, or branch is maintenance burden. The best abstraction is often no abstraction.
|
| 50 |
+
|
| 51 |
+
## Documentation
|
| 52 |
+
|
| 53 |
+
### Docstrings
|
| 54 |
+
|
| 55 |
+
Docstrings must follow the repository format below. Do **not** convert docstrings to other styles (Google, NumPy, etc.).
|
| 56 |
+
|
| 57 |
+
Rules:
|
| 58 |
+
|
| 59 |
+
* Types appear in backticks inside parentheses: (`str`)
|
| 60 |
+
* Optional parameters are marked with `*optional*`
|
| 61 |
+
* Defaults are written as: `defaults to <value>`
|
| 62 |
+
* When the default is `None`, prefer ```(`str`, *optional*)``` instead of ```(`str` or `None`, *optional*, defaults to `None`)```
|
| 63 |
+
* Union types use `or`: `str` or `None`
|
| 64 |
+
* References to classes use the format: [`~transformers.PreTrainedModel`]
|
| 65 |
+
* Class docstrings may group parameters using headers such as: `> Parameters for X:`
|
| 66 |
+
|
| 67 |
+
Example:
|
| 68 |
+
|
| 69 |
+
````python
|
| 70 |
+
def method(self, param1: str, param2: int = 1, param3: float | None = None):
|
| 71 |
+
"""
|
| 72 |
+
Brief one-line description of what this does.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
param1 (`str`):
|
| 76 |
+
Description of required param.
|
| 77 |
+
param2 (`int`, *optional*, defaults to `1`):
|
| 78 |
+
Description of optional param with default.
|
| 79 |
+
param3 (`float`, *optional*):
|
| 80 |
+
Description of optional param without explicit default.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
`dict` with keys:
|
| 84 |
+
- `key1` (`list[int]`):
|
| 85 |
+
Description of this key.
|
| 86 |
+
|
| 87 |
+
Examples:
|
| 88 |
+
|
| 89 |
+
```python
|
| 90 |
+
>>> my_func("hello")
|
| 91 |
+
```
|
| 92 |
+
"""
|
| 93 |
+
````
|
| 94 |
+
|
| 95 |
+
### Links to papers
|
| 96 |
+
|
| 97 |
+
When linking to papers, use `https://huggingface.co/papers/<id>` instead of `https://arxiv.org/abs/<id>` (same ID suffix system).
|
tasks/tasksmith-03a6a091b12f/tests/source/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Contributor Covenant Code of Conduct
|
| 3 |
+
|
| 4 |
+
## Our Pledge
|
| 5 |
+
|
| 6 |
+
We as members, contributors, and leaders pledge to make participation in our
|
| 7 |
+
community a harassment-free experience for everyone, regardless of age, body
|
| 8 |
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
| 9 |
+
identity and expression, level of experience, education, socio-economic status,
|
| 10 |
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
| 11 |
+
identity and orientation.
|
| 12 |
+
|
| 13 |
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
| 14 |
+
diverse, inclusive, and healthy community.
|
| 15 |
+
|
| 16 |
+
## Our Standards
|
| 17 |
+
|
| 18 |
+
Examples of behavior that contributes to a positive environment for our
|
| 19 |
+
community include:
|
| 20 |
+
|
| 21 |
+
* Demonstrating empathy and kindness toward other people
|
| 22 |
+
* Being respectful of differing opinions, viewpoints, and experiences
|
| 23 |
+
* Giving and gracefully accepting constructive feedback
|
| 24 |
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
| 25 |
+
and learning from the experience
|
| 26 |
+
* Focusing on what is best not just for us as individuals, but for the overall
|
| 27 |
+
community
|
| 28 |
+
|
| 29 |
+
Examples of unacceptable behavior include:
|
| 30 |
+
|
| 31 |
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
| 32 |
+
any kind
|
| 33 |
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
| 34 |
+
* Public or private harassment
|
| 35 |
+
* Publishing others' private information, such as a physical or email address,
|
| 36 |
+
without their explicit permission
|
| 37 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
| 38 |
+
professional setting
|
| 39 |
+
|
| 40 |
+
## Enforcement Responsibilities
|
| 41 |
+
|
| 42 |
+
Community leaders are responsible for clarifying and enforcing our standards of
|
| 43 |
+
acceptable behavior and will take appropriate and fair corrective action in
|
| 44 |
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
| 45 |
+
or harmful.
|
| 46 |
+
|
| 47 |
+
Community leaders have the right and responsibility to remove, edit, or reject
|
| 48 |
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
| 49 |
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
| 50 |
+
decisions when appropriate.
|
| 51 |
+
|
| 52 |
+
## Scope
|
| 53 |
+
|
| 54 |
+
This Code of Conduct applies within all community spaces, and also applies when
|
| 55 |
+
an individual is officially representing the community in public spaces.
|
| 56 |
+
Examples of representing our community include using an official e-mail address,
|
| 57 |
+
posting via an official social media account, or acting as an appointed
|
| 58 |
+
representative at an online or offline event.
|
| 59 |
+
|
| 60 |
+
## Enforcement
|
| 61 |
+
|
| 62 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
| 63 |
+
reported to the community leaders responsible for enforcement at
|
| 64 |
+
feedback@huggingface.co.
|
| 65 |
+
All complaints will be reviewed and investigated promptly and fairly.
|
| 66 |
+
|
| 67 |
+
All community leaders are obligated to respect the privacy and security of the
|
| 68 |
+
reporter of any incident.
|
| 69 |
+
|
| 70 |
+
## Enforcement Guidelines
|
| 71 |
+
|
| 72 |
+
Community leaders will follow these Community Impact Guidelines in determining
|
| 73 |
+
the consequences for any action they deem in violation of this Code of Conduct:
|
| 74 |
+
|
| 75 |
+
### 1. Correction
|
| 76 |
+
|
| 77 |
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
| 78 |
+
unprofessional or unwelcome in the community.
|
| 79 |
+
|
| 80 |
+
**Consequence**: A private, written warning from community leaders, providing
|
| 81 |
+
clarity around the nature of the violation and an explanation of why the
|
| 82 |
+
behavior was inappropriate. A public apology may be requested.
|
| 83 |
+
|
| 84 |
+
### 2. Warning
|
| 85 |
+
|
| 86 |
+
**Community Impact**: A violation through a single incident or series of
|
| 87 |
+
actions.
|
| 88 |
+
|
| 89 |
+
**Consequence**: A warning with consequences for continued behavior. No
|
| 90 |
+
interaction with the people involved, including unsolicited interaction with
|
| 91 |
+
those enforcing the Code of Conduct, for a specified period of time. This
|
| 92 |
+
includes avoiding interactions in community spaces as well as external channels
|
| 93 |
+
like social media. Violating these terms may lead to a temporary or permanent
|
| 94 |
+
ban.
|
| 95 |
+
|
| 96 |
+
### 3. Temporary Ban
|
| 97 |
+
|
| 98 |
+
**Community Impact**: A serious violation of community standards, including
|
| 99 |
+
sustained inappropriate behavior.
|
| 100 |
+
|
| 101 |
+
**Consequence**: A temporary ban from any sort of interaction or public
|
| 102 |
+
communication with the community for a specified period of time. No public or
|
| 103 |
+
private interaction with the people involved, including unsolicited interaction
|
| 104 |
+
with those enforcing the Code of Conduct, is allowed during this period.
|
| 105 |
+
Violating these terms may lead to a permanent ban.
|
| 106 |
+
|
| 107 |
+
### 4. Permanent Ban
|
| 108 |
+
|
| 109 |
+
**Community Impact**: Demonstrating a pattern of violation of community
|
| 110 |
+
standards, including sustained inappropriate behavior, harassment of an
|
| 111 |
+
individual, or aggression toward or disparagement of classes of individuals.
|
| 112 |
+
|
| 113 |
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
| 114 |
+
community.
|
| 115 |
+
|
| 116 |
+
## Attribution
|
| 117 |
+
|
| 118 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
| 119 |
+
version 2.1, available at
|
| 120 |
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
| 121 |
+
|
| 122 |
+
Community Impact Guidelines were inspired by
|
| 123 |
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
| 124 |
+
|
| 125 |
+
For answers to common questions about this code of conduct, see the FAQ at
|
| 126 |
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
| 127 |
+
[https://www.contributor-covenant.org/translations][translations].
|
| 128 |
+
|
| 129 |
+
[homepage]: https://www.contributor-covenant.org
|
| 130 |
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
| 131 |
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
| 132 |
+
[FAQ]: https://www.contributor-covenant.org/faq
|
| 133 |
+
[translations]: https://www.contributor-covenant.org/translations
|