cciwon-code-review-cli 2.0.1 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/code-review.js +1 -1
- package/lib/chat-mode.js +7 -2
- package/package.json +1 -1
- package/unsloth_compiled_cache/.locks/.lock.AqlmLoraLinear_peft_forward.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.AwqLoraLinear_peft_forward.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.BatchNorm1d.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.BatchNorm2d.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.BatchNorm3d.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.Conv1d.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.Conv2d.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.Conv3d.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.ConvTranspose1d.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.ConvTranspose2d.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.ConvTranspose3d.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.GPTQLoraLinear_peft_forward.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.GroupNorm.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.LayerNorm.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.Linear4bit_peft_forward.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.Linear8bitLt_peft_forward.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.Linear_peft_forward.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.LoraParallelLinear_peft_forward.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.RMSNorm.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothBCOTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothCPOTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothDPOTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothGKDTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothGRPOTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothKTOTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothNashMDTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothORPOTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothOnlineDPOTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothPPOTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothPRMTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothRLOOTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothRewardTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothSFTTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.UnslothXPOTrainer.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.unsloth_compiled_module_qwen3_moe.py +0 -0
- package/unsloth_compiled_cache/.locks/.lock.unsloth_compiled_module_siglip.py +0 -0
- package/unsloth_compiled_cache/AqlmLoraLinear_peft_forward.py +88 -0
- package/unsloth_compiled_cache/AwqLoraLinear_peft_forward.py +87 -0
- package/unsloth_compiled_cache/BatchNorm1d.py +117 -0
- package/unsloth_compiled_cache/BatchNorm2d.py +117 -0
- package/unsloth_compiled_cache/BatchNorm3d.py +117 -0
- package/unsloth_compiled_cache/Conv1d.py +70 -0
- package/unsloth_compiled_cache/Conv2d.py +70 -0
- package/unsloth_compiled_cache/Conv3d.py +70 -0
- package/unsloth_compiled_cache/ConvTranspose1d.py +97 -0
- package/unsloth_compiled_cache/ConvTranspose2d.py +106 -0
- package/unsloth_compiled_cache/ConvTranspose3d.py +98 -0
- package/unsloth_compiled_cache/GPTQLoraLinear_peft_forward.py +95 -0
- package/unsloth_compiled_cache/GroupNorm.py +70 -0
- package/unsloth_compiled_cache/LayerNorm.py +72 -0
- package/unsloth_compiled_cache/Linear4bit_peft_forward.py +115 -0
- package/unsloth_compiled_cache/Linear8bitLt_peft_forward.py +113 -0
- package/unsloth_compiled_cache/Linear_peft_forward.py +104 -0
- package/unsloth_compiled_cache/LoraParallelLinear_peft_forward.py +91 -0
- package/unsloth_compiled_cache/RMSNorm.py +73 -0
- package/unsloth_compiled_cache/UnslothBCOTrainer.py +2026 -0
- package/unsloth_compiled_cache/UnslothCPOTrainer.py +1806 -0
- package/unsloth_compiled_cache/UnslothDPOTrainer.py +2750 -0
- package/unsloth_compiled_cache/UnslothGKDTrainer.py +1157 -0
- package/unsloth_compiled_cache/UnslothGRPOTrainer.py +3607 -0
- package/unsloth_compiled_cache/UnslothKTOTrainer.py +2220 -0
- package/unsloth_compiled_cache/UnslothNashMDTrainer.py +1210 -0
- package/unsloth_compiled_cache/UnslothORPOTrainer.py +1730 -0
- package/unsloth_compiled_cache/UnslothOnlineDPOTrainer.py +2313 -0
- package/unsloth_compiled_cache/UnslothPPOTrainer.py +1504 -0
- package/unsloth_compiled_cache/UnslothPRMTrainer.py +979 -0
- package/unsloth_compiled_cache/UnslothRLOOTrainer.py +2674 -0
- package/unsloth_compiled_cache/UnslothRewardTrainer.py +1197 -0
- package/unsloth_compiled_cache/UnslothSFTTrainer.py +1416 -0
- package/unsloth_compiled_cache/UnslothXPOTrainer.py +1255 -0
- package/unsloth_compiled_cache/__pycache__/AqlmLoraLinear_peft_forward.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/AwqLoraLinear_peft_forward.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/BatchNorm1d.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/BatchNorm2d.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/BatchNorm3d.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/Conv1d.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/Conv2d.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/Conv3d.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/ConvTranspose1d.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/ConvTranspose2d.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/ConvTranspose3d.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/GPTQLoraLinear_peft_forward.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/GroupNorm.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/LayerNorm.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/Linear4bit_peft_forward.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/Linear8bitLt_peft_forward.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/Linear_peft_forward.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/LoraParallelLinear_peft_forward.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/RMSNorm.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothBCOTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothCPOTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothDPOTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothGKDTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothGRPOTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothKTOTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothNashMDTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothORPOTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothOnlineDPOTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothPPOTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothPRMTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothRLOOTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothRewardTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothSFTTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/UnslothXPOTrainer.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/unsloth_compiled_module_qwen3_moe.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/__pycache__/unsloth_compiled_module_siglip.cpython-312.pyc +0 -0
- package/unsloth_compiled_cache/unsloth_compiled_module_qwen3_moe.py +726 -0
- package/unsloth_compiled_cache/unsloth_compiled_module_siglip.py +534 -0
|
@@ -0,0 +1,2750 @@
|
|
|
1
|
+
"""
|
|
2
|
+
2025.12.6
|
|
3
|
+
2025.12.7
|
|
4
|
+
4.57.1
|
|
5
|
+
0.24.0
|
|
6
|
+
__UNSLOTH_VERSIONING__
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
# Unsloth auto generated code
|
|
10
|
+
# Copyright 2023-present Daniel Han-Chen, Michael Han-Chen & the Unsloth team. All rights reserved.
|
|
11
|
+
#
|
|
12
|
+
# This program is free software: you can redistribute it and/or modify
|
|
13
|
+
# it under the terms of the GNU Lesser General Public License as published by
|
|
14
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
15
|
+
# (at your option) any later version.
|
|
16
|
+
#
|
|
17
|
+
# This program is distributed in the hope that it will be useful,
|
|
18
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
19
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
20
|
+
# GNU General Public License for more details.
|
|
21
|
+
#
|
|
22
|
+
# You should have received a copy of the GNU Lesser General Public License
|
|
23
|
+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
24
|
+
|
|
25
|
+
from torch import Tensor
|
|
26
|
+
import torch
|
|
27
|
+
import torch.nn as nn
|
|
28
|
+
from torch.nn import functional as F
|
|
29
|
+
from typing import Any, List, Optional, Tuple, Union, Dict, Set, Callable
|
|
30
|
+
from trl.trainer.dpo_trainer import (Any, AutoProcessor, BaseImageProcessor, BaseTrainer, Callable, DPOConfig, DPOTrainer, DataCollator, DataCollatorForPreference, DataLoader, Dataset, EvalLoopOutput, F, FDivergenceConstants, FDivergenceType, FeatureExtractionMixin, IterableDataset, Literal, MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, Optional, PartialState, Path, PeftConfig, PeftModel, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, RunningMoments, SyncRefModelCallback, TrainerCallback, Union, autocast, cap_exp, contextmanager, create_model_from_path, create_reference_model, dataclass, defaultdict, disable_dropout_in_model, empty_cache, flush_left, flush_right, get_peft_model, inspect, is_comet_available, is_liger_kernel_available, is_mlflow_available, is_peft_available, is_wandb_available, log_table_to_comet_experiment, logger, logging, maybe_apply_chat_template, maybe_extract_prompt, nn, nullcontext, pad, pad_to_length, pd, peft_module_casting_to_bf16, prepare_deepspeed, prepare_fsdp, prepare_model_for_kbit_training, random, selective_log_softmax, shift_tokens_right, textwrap, torch, tqdm, warnings, F, Optional, PeftModel, PreTrainedModel, is_peft_available, logger, torch)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
import os
|
|
34
|
+
from typing import *
|
|
35
|
+
from dataclasses import dataclass, field
|
|
36
|
+
from packaging.version import Version
|
|
37
|
+
import torch
|
|
38
|
+
import numpy as np
|
|
39
|
+
from contextlib import nullcontext
|
|
40
|
+
from torch.nn import functional as F
|
|
41
|
+
import inspect
|
|
42
|
+
from transformers import DataCollatorForSeq2Seq, DataCollatorForLanguageModeling as TransformersDataCollatorForLanguageModeling
|
|
43
|
+
from transformers.training_args import ParallelMode
|
|
44
|
+
|
|
45
|
+
# Wrap trainer with padding to right and enable training mode
|
|
46
|
+
# Also patches W&B since multiple runs must use wandb.finish()
|
|
47
|
+
import functools
|
|
48
|
+
from types import MethodType
|
|
49
|
+
def prepare_for_training_mode(f):
|
|
50
|
+
@functools.wraps(f)
|
|
51
|
+
def wrapper(self, *args, **kwargs):
|
|
52
|
+
# Enable training mode
|
|
53
|
+
if hasattr(self, 'model') and hasattr(self.model, "for_training"):
|
|
54
|
+
self.model.for_training()
|
|
55
|
+
output = f(self, *args, **kwargs)
|
|
56
|
+
# Return inference mode
|
|
57
|
+
if hasattr(self, 'model') and hasattr(self.model, "for_inference"):
|
|
58
|
+
self.model.for_inference()
|
|
59
|
+
# Patch W&B to enable logging on future runs, otherwise it'll overwrite the first run
|
|
60
|
+
try:
|
|
61
|
+
import wandb
|
|
62
|
+
wandb.finish()
|
|
63
|
+
except:
|
|
64
|
+
pass
|
|
65
|
+
return output
|
|
66
|
+
return wrapper
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
torch_compile_options = {
|
|
70
|
+
"epilogue_fusion" : True,
|
|
71
|
+
"max_autotune" : False,
|
|
72
|
+
"shape_padding" : True,
|
|
73
|
+
"trace.enabled" : False,
|
|
74
|
+
"triton.cudagraphs" : False,
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
@torch.compile(dynamic = True, fullgraph = True, options = torch_compile_options,)
|
|
78
|
+
def chunked_selective_log_softmax(logits, index):
|
|
79
|
+
# Split into 4 chunks only
|
|
80
|
+
chunked_logits = torch.chunk(logits.reshape(-1, logits.shape[-1]), chunks = 4, dim = 0)
|
|
81
|
+
chunked_index = torch.chunk(index.reshape(-1), chunks = 4, dim = 0)
|
|
82
|
+
all_per_token_logps = []
|
|
83
|
+
# Below loop does the same as selective_log_softmax(chunk_logits, chunk_index)
|
|
84
|
+
for chunk_logits, chunk_index in zip(chunked_logits, chunked_index):
|
|
85
|
+
chunk_logits = chunk_logits.to(torch.float32)
|
|
86
|
+
selected_logits = torch.gather(chunk_logits, dim = -1, index = chunk_index.unsqueeze(-1)).squeeze(-1)
|
|
87
|
+
logsumexp_values = torch.logsumexp(chunk_logits, dim = -1)
|
|
88
|
+
per_token_logps = selected_logits - logsumexp_values
|
|
89
|
+
all_per_token_logps.append(per_token_logps)
|
|
90
|
+
pass
|
|
91
|
+
all_per_token_logps = torch.concat(all_per_token_logps)
|
|
92
|
+
all_per_token_logps = all_per_token_logps.reshape((logits.shape[0], logits.shape[1]))
|
|
93
|
+
return all_per_token_logps
|
|
94
|
+
|
|
95
|
+
def calculate_pad_tokens_in_prompt(
|
|
96
|
+
input_ids: torch.Tensor,
|
|
97
|
+
logits_to_keep: int,
|
|
98
|
+
pad_token_id: int
|
|
99
|
+
) -> torch.Tensor:
|
|
100
|
+
"""
|
|
101
|
+
Given prompt tensor, it returns all the left padded tokens in that sequence. so [pad, pad, pad, cat] = 3 tokens
|
|
102
|
+
"""
|
|
103
|
+
if logits_to_keep >= input_ids.shape[1]:
|
|
104
|
+
raise ValueError("logits_to_keep must be smaller than the sequence length.")
|
|
105
|
+
|
|
106
|
+
prompt_section = input_ids[:, :-logits_to_keep]
|
|
107
|
+
|
|
108
|
+
padding_mask = (prompt_section == pad_token_id)
|
|
109
|
+
|
|
110
|
+
pad_token_counts = padding_mask.sum(dim=1)
|
|
111
|
+
|
|
112
|
+
return pad_token_counts
|
|
113
|
+
|
|
114
|
+
def create_completion_attention_mask(
|
|
115
|
+
completion_input_ids: torch.Tensor,
|
|
116
|
+
left_pad_tokens_per_prompt: torch.Tensor,
|
|
117
|
+
max_left_pad: int,
|
|
118
|
+
pad_token_id: int
|
|
119
|
+
) -> torch.Tensor:
|
|
120
|
+
"""
|
|
121
|
+
Given that we have a sequence, [p,p,p,c,c,c,pad,pad,pad]
|
|
122
|
+
|
|
123
|
+
Where p are extra prompt tokens we got from slicing the torch tensor, c is completion tokens
|
|
124
|
+
and pad are pad tokens, this function would make a completion mask that would 0 out the pad
|
|
125
|
+
and p tokens. so in this example [0,0,0,1,1,1,0,0,0]
|
|
126
|
+
"""
|
|
127
|
+
batch_size, completion_len = completion_input_ids.shape
|
|
128
|
+
device = completion_input_ids.device
|
|
129
|
+
|
|
130
|
+
num_tokens_to_mask = max_left_pad - left_pad_tokens_per_prompt
|
|
131
|
+
|
|
132
|
+
indices = torch.arange(completion_len, device=device).unsqueeze(0)
|
|
133
|
+
shift_mask = indices >= num_tokens_to_mask.unsqueeze(1)
|
|
134
|
+
|
|
135
|
+
non_padding_mask = (completion_input_ids != pad_token_id)
|
|
136
|
+
|
|
137
|
+
final_mask = shift_mask & non_padding_mask
|
|
138
|
+
|
|
139
|
+
return final_mask
|
|
140
|
+
|
|
141
|
+
def left_pack_padding(tensor: torch.Tensor, pad_id: int) -> torch.Tensor:
|
|
142
|
+
"""
|
|
143
|
+
Moves all padding tokens in each sequence of a batch to the right.
|
|
144
|
+
"""
|
|
145
|
+
mask = (tensor != pad_id)
|
|
146
|
+
# Must do stable=True since binary mark is unordered
|
|
147
|
+
sorted_indices = torch.argsort(mask, dim=1, descending=True, stable=True)
|
|
148
|
+
packed_tensor = torch.gather(tensor, 1, sorted_indices)
|
|
149
|
+
return packed_tensor
|
|
150
|
+
|
|
151
|
+
def align_logprobs_with_mask(
|
|
152
|
+
logprob_tensor: torch.Tensor,
|
|
153
|
+
attention_mask: torch.Tensor,
|
|
154
|
+
pad_value: float = 0.0
|
|
155
|
+
) -> torch.Tensor:
|
|
156
|
+
"""
|
|
157
|
+
Aligns a log probability tensor with a given attention mask.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
device = logprob_tensor.device
|
|
161
|
+
batch_size, logprob_seq_len = logprob_tensor.shape
|
|
162
|
+
mask_seq_len = attention_mask.shape[1]
|
|
163
|
+
|
|
164
|
+
padded_logprobs = torch.full(
|
|
165
|
+
attention_mask.shape,
|
|
166
|
+
fill_value=pad_value,
|
|
167
|
+
dtype=logprob_tensor.dtype,
|
|
168
|
+
device=device
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
left_pad_counts = torch.argmax(attention_mask, dim=1)
|
|
172
|
+
|
|
173
|
+
cols = torch.arange(logprob_seq_len, device=device)
|
|
174
|
+
dest_indices = left_pad_counts.unsqueeze(1) + cols
|
|
175
|
+
|
|
176
|
+
# Create destination row indices
|
|
177
|
+
# Shape: [batch_size, logprob_seq_len]
|
|
178
|
+
row_indices = torch.arange(batch_size, device=device).unsqueeze(1).expand_as(dest_indices)
|
|
179
|
+
|
|
180
|
+
# --- 4. Filter out-of-bounds indices and perform assignment ---
|
|
181
|
+
# Create a mask to identify only the indices that are within the bounds
|
|
182
|
+
# of the target tensor's sequence length.
|
|
183
|
+
valid_mask = dest_indices < mask_seq_len
|
|
184
|
+
|
|
185
|
+
# Use this mask to select only the valid row indices, column indices,
|
|
186
|
+
# and the corresponding values from the logprob tensor.
|
|
187
|
+
# This flattens the selected elements into 1D tensors.
|
|
188
|
+
valid_rows = row_indices[valid_mask]
|
|
189
|
+
valid_cols = dest_indices[valid_mask]
|
|
190
|
+
valid_vals = logprob_tensor[valid_mask]
|
|
191
|
+
|
|
192
|
+
# Place the valid values into their correct positions in the padded tensor
|
|
193
|
+
# using a single, efficient advanced indexing operation.
|
|
194
|
+
padded_logprobs[valid_rows, valid_cols] = valid_vals
|
|
195
|
+
|
|
196
|
+
return padded_logprobs
|
|
197
|
+
@dataclass
|
|
198
|
+
class UnslothDPOConfig(DPOConfig):
|
|
199
|
+
"""
|
|
200
|
+
|
|
201
|
+
Configuration class for the [`DPOTrainer`].
|
|
202
|
+
|
|
203
|
+
This class includes only the parameters that are specific to DPO training. For a full list of training arguments,
|
|
204
|
+
please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
|
|
205
|
+
differ from those in [`~transformers.TrainingArguments`].
|
|
206
|
+
|
|
207
|
+
Using [`~transformers.HfArgumentParser`] we can turn this class into
|
|
208
|
+
[argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
|
|
209
|
+
command line.
|
|
210
|
+
|
|
211
|
+
Parameters:
|
|
212
|
+
> Parameters that control the model and reference model
|
|
213
|
+
|
|
214
|
+
model_init_kwargs (`dict[str, Any]`, *optional*):
|
|
215
|
+
Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of the
|
|
216
|
+
[`DPOTrainer`] is provided as a string.
|
|
217
|
+
ref_model_init_kwargs (`dict[str, Any]`, *optional*):
|
|
218
|
+
Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `ref_model` argument of the
|
|
219
|
+
[`DPOTrainer`] is provided as a string.
|
|
220
|
+
model_adapter_name (`str`, *optional*):
|
|
221
|
+
Name of the train target PEFT adapter, when using LoRA with multiple adapters.
|
|
222
|
+
ref_adapter_name (`str`, *optional*):
|
|
223
|
+
Name of the reference PEFT adapter, when using LoRA with multiple adapters.
|
|
224
|
+
force_use_ref_model (`bool`, *optional*, defaults to `False`):
|
|
225
|
+
If you provide a PEFT model as the active model and wish to use a different model for the `ref_model`, set
|
|
226
|
+
this flag to `True`.
|
|
227
|
+
disable_dropout (`bool`, *optional*, defaults to `True`):
|
|
228
|
+
Whether to disable dropout in the model and reference model.
|
|
229
|
+
use_logits_to_keep (`bool`, *optional*, defaults to `False`):
|
|
230
|
+
If `True`, only a specified number of logits are computed in the forward pass. This can be useful for
|
|
231
|
+
saving memory and speeding up training by not computing the logits for all tokens, especially in scenarios
|
|
232
|
+
when working with very long prompts where labels are ignored (-100).
|
|
233
|
+
|
|
234
|
+
> Parameters that control the data preprocessing
|
|
235
|
+
|
|
236
|
+
dataset_num_proc (`int`, *optional*):
|
|
237
|
+
Number of processes to use for processing the dataset.
|
|
238
|
+
pad_token (`str`, *optional*):
|
|
239
|
+
Token used for padding. If `None`, it defaults to `processing_class.pad_token`, or if that is also `None`,
|
|
240
|
+
it falls back to `processing_class.eos_token`.
|
|
241
|
+
label_pad_token_id (`int`, *optional*, defaults to `-100`):
|
|
242
|
+
Padding value to use for labels.
|
|
243
|
+
max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
|
|
244
|
+
Maximum length of the prompt.
|
|
245
|
+
max_completion_length (`int`, *optional*):
|
|
246
|
+
Maximum length of the completion.
|
|
247
|
+
max_length (`int` or `None`, *optional*, defaults to `1024`):
|
|
248
|
+
Maximum length of the full sequence (prompt + completion).
|
|
249
|
+
truncation_mode (`str`, *optional*, defaults to `"keep_end"`):
|
|
250
|
+
Truncation mode to use when the sequence exceeds `max_length`. Possible values are `"keep_end"` and
|
|
251
|
+
`"keep_start"`.
|
|
252
|
+
padding_free (`bool`, *optional*, defaults to `False`):
|
|
253
|
+
Whether to perform forward passes without padding by flattening all sequences in the batch into a single
|
|
254
|
+
continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this is only
|
|
255
|
+
supported with the `flash_attention_2` attention implementation, which can efficiently handle the flattened
|
|
256
|
+
batch structure.
|
|
257
|
+
precompute_ref_log_probs (`bool`, *optional*, defaults to `False`):
|
|
258
|
+
Whether to precompute the log probabilities from the reference model. Setting this to `True` allows
|
|
259
|
+
training without needing the reference model during training, which can help reduce GPU memory usage. If
|
|
260
|
+
set to `False` (default), the reference model will be used during training to compute log probabilities
|
|
261
|
+
on-the-fly.
|
|
262
|
+
precompute_ref_batch_size (`int`, *optional*):
|
|
263
|
+
Batch size to use when precomputing reference model log probabilities. This can be set higher than the
|
|
264
|
+
training batch size to speed up preprocessing. If `None`, defaults to `per_device_train_batch_size` for
|
|
265
|
+
training and `per_device_eval_batch_size` for evaluation.
|
|
266
|
+
tools (`Optional[list[Union[dict, Callable]]]`, *optional*):
|
|
267
|
+
List of tools (callable functions) that will be accessible to the model. If the template does not support
|
|
268
|
+
function calling, this argument will have no effect.
|
|
269
|
+
|
|
270
|
+
> Parameters that control the training
|
|
271
|
+
|
|
272
|
+
loss_type (`str` or `list[str]`, *optional*, defaults to `"sigmoid"`):
|
|
273
|
+
Type of loss to use. Possible values are:
|
|
274
|
+
|
|
275
|
+
- `"sigmoid"`: sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper.
|
|
276
|
+
- `"hinge"`: hinge loss on the normalized likelihood from the
|
|
277
|
+
[SLiC](https://huggingface.co/papers/2305.10425) paper.
|
|
278
|
+
- `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper.
|
|
279
|
+
- `"exo_pair"`: pairwise EXO loss from the [EXO](https://huggingface.co/papers/2402.00856) paper.
|
|
280
|
+
- `"nca_pair"`: pairwise NCA loss from the [NCA](https://huggingface.co/papers/2402.05369) paper.
|
|
281
|
+
- `"robust"`: unbiased estimate of the DPO loss that is robust to preference noise from the [Robust
|
|
282
|
+
DPO](https://huggingface.co/papers/2403.00409) paper.
|
|
283
|
+
- `"bco_pair"`: pairwise BCO loss from the [BCO](https://huggingface.co/papers/2404.04656) paper.
|
|
284
|
+
- `"sppo_hard"`: SPPO loss with hard label from the [SPPO](https://huggingface.co/papers/2405.00675)
|
|
285
|
+
paper.
|
|
286
|
+
- `"aot"`: AOT loss for paired datasets from the [AOT](https://huggingface.co/papers/2406.05882) paper.
|
|
287
|
+
- `"aot_pair"`: AOT loss for unpaired datasets from the [AOT](https://huggingface.co/papers/2406.05882)
|
|
288
|
+
paper.
|
|
289
|
+
- `"discopop"`: DiscoPOP (a.k.a Log-Ratio Modulated Loss, LRML) loss from the
|
|
290
|
+
[DiscoPOP](https://huggingface.co/papers/2406.08414) paper.
|
|
291
|
+
- `"apo_zero"`: APO-zero loss from the [APO](https://huggingface.co/papers/2408.06266) paper.
|
|
292
|
+
- `"apo_down"`: APO-down loss from the [APO](https://huggingface.co/papers/2408.06266) paper.
|
|
293
|
+
- `"sft"`: Negative log-likelihood loss (standard supervised fine-tuning loss).
|
|
294
|
+
|
|
295
|
+
Multiple loss types can be combined using comma separation (e.g., `["sigmoid", "bco_pair", "sft"]` for
|
|
296
|
+
[MPO](https://huggingface.co/papers/2411.10442)). The `loss_weights` parameter can be used to specify
|
|
297
|
+
corresponding weights for each loss type.
|
|
298
|
+
|
|
299
|
+
use_liger_loss (`bool`, *optional*, defaults to `False`):
|
|
300
|
+
Whether to use Liger loss.
|
|
301
|
+
base_model_attribute_name (`str`, *optional*, defaults to `"model"`):
|
|
302
|
+
Name of the attribute in the model that contains the base model. This is used to get the base model from
|
|
303
|
+
the model when the model does not have a `get_decoder` method in the case when `use_liger_loss` is `True`.
|
|
304
|
+
beta (`float`, *optional*, defaults to `0.1`):
|
|
305
|
+
Parameter controlling the deviation from the reference model. Higher β means less deviation from the
|
|
306
|
+
reference model. For the IPO loss (`loss_type="ipo"`), β is the regularization parameter denoted by τ in
|
|
307
|
+
the [paper](https://huggingface.co/papers/2310.12036).
|
|
308
|
+
f_divergence_type ([`FDivergenceType`] or `str`, *optional*, defaults to `FDivergenceType.REVERSE_KL`):
|
|
309
|
+
Type of f-divergence regularization function to compute divergence between policy and reference model.
|
|
310
|
+
f_alpha_divergence_coef (`float`, *optional*, defaults to `1.0`):
|
|
311
|
+
α coefficient in the α-divergence u^-α regularization function for DPO loss.
|
|
312
|
+
reference_free (`bool`, *optional*, defaults to `False`):
|
|
313
|
+
Whether to ignore the provided reference model and implicitly use a reference model that assigns equal
|
|
314
|
+
probability to all responses.
|
|
315
|
+
label_smoothing (`float`, *optional*, defaults to `0.0`):
|
|
316
|
+
Robust DPO label smoothing parameter from the [cDPO report](https://ericmitchell.ai/cdpo.pdf) and [Robust
|
|
317
|
+
DPO](https://huggingface.co/papers/2403.00409) paper that should be between `0.0` and `0.5`.
|
|
318
|
+
use_weighting (`bool`, *optional*, defaults to `False`):
|
|
319
|
+
Whether to weight the loss as done in the [WPO paper](https://huggingface.co/papers/2406.11827).
|
|
320
|
+
rpo_alpha (`float`, *optional*):
|
|
321
|
+
α parameter from the [RPO paper](https://huggingface.co/papers/2404.19733) (v3), which controls the
|
|
322
|
+
weighting of the NLL term in the loss. If `None`, no weighting is applied and the loss is the same as the
|
|
323
|
+
DPO loss. The paper recommends `rpo_alpha=1.0`.
|
|
324
|
+
ld_alpha (`float`, *optional*):
|
|
325
|
+
α parameter from the [LD-DPO paper](https://huggingface.co/papers/2409.06411), which controls the weighting
|
|
326
|
+
of the verbose token log-probabilities in responses. If `None`, no weighting is applied to the verbose
|
|
327
|
+
part, and the loss is equivalent to the standard DPO loss. The paper recommends setting `ld_alpha` between
|
|
328
|
+
`0.0` and `1.0`.
|
|
329
|
+
discopop_tau (`float`, *optional*, defaults to `0.05`):
|
|
330
|
+
τ/temperature parameter from the [DiscoPOP](https://huggingface.co/papers/2406.08414) paper, which controls
|
|
331
|
+
the shape of log ratio modulated loss. The paper recommends the default value `discopop_tau=0.05`.
|
|
332
|
+
loss_weights (`list[float]`, *optional*):
|
|
333
|
+
List of loss weights for multi-loss combinations. Used when combining multiple loss types. Example: `[0.8,
|
|
334
|
+
0.2, 1.0]` for [MPO](https://huggingface.co/papers/2411.10442). If not provided, defaults to equal weights
|
|
335
|
+
(`1.0`) for all loss types.
|
|
336
|
+
sync_ref_model (`bool`, *optional*, defaults to `False`):
|
|
337
|
+
Whether to synchronize the reference model with the active model every `ref_model_sync_steps` steps, using
|
|
338
|
+
the `ref_model_mixup_alpha` parameter. This synchronization originates from the
|
|
339
|
+
[TR-DPO](https://huggingface.co/papers/2404.09656) paper.
|
|
340
|
+
ref_model_mixup_alpha (`float`, *optional*, defaults to `0.6`):
|
|
341
|
+
α parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which controls the mix
|
|
342
|
+
between the current policy and the previous reference policy during updates. The reference policy is
|
|
343
|
+
updated according to the equation: `π_ref = α * π_θ + (1 - α) * π_ref_prev`. To use this parameter, you
|
|
344
|
+
must set `sync_ref_model=True`.
|
|
345
|
+
ref_model_sync_steps (`int`, *optional*, defaults to `512`):
|
|
346
|
+
τ parameter from the [TR-DPO](https://huggingface.co/papers/2404.09656) paper, which determines how
|
|
347
|
+
frequently the current policy is synchronized with the reference policy. To use this parameter, you must
|
|
348
|
+
set `sync_ref_model=True`.
|
|
349
|
+
|
|
350
|
+
> Parameters that control the logging
|
|
351
|
+
|
|
352
|
+
generate_during_eval (`bool`, *optional*, defaults to `False`):
|
|
353
|
+
Whether to generate and log completions from both the model and the reference model to W&B or Comet during
|
|
354
|
+
evaluation.
|
|
355
|
+
|
|
356
|
+
> Deprecated parameters
|
|
357
|
+
|
|
358
|
+
padding_value:
|
|
359
|
+
|
|
360
|
+
<Deprecated version="0.24.0">
|
|
361
|
+
|
|
362
|
+
This parameter is deprecated and will be removed in version 0.25.0. Use `pad_token` (`str`) instead.
|
|
363
|
+
|
|
364
|
+
</Deprecated>
|
|
365
|
+
|
|
366
|
+
"""
|
|
367
|
+
vllm_sampling_params: Optional[Any] = field(
|
|
368
|
+
default = None,
|
|
369
|
+
metadata = {'help': 'vLLM SamplingParams'},
|
|
370
|
+
)
|
|
371
|
+
unsloth_num_chunks : Optional[int] = field(
|
|
372
|
+
default = -1,
|
|
373
|
+
metadata = {'help': 'Chunk size to reduce memory usage. -1 is most efficient.'},
|
|
374
|
+
)
|
|
375
|
+
max_seq_length : Optional[int] = field(
|
|
376
|
+
default = None,
|
|
377
|
+
metadata = {'help': 'Maximum sequence length to truncate to.'},
|
|
378
|
+
)
|
|
379
|
+
def __init__(
|
|
380
|
+
self,
|
|
381
|
+
output_dir = None,
|
|
382
|
+
overwrite_output_dir = None,
|
|
383
|
+
do_train = False,
|
|
384
|
+
do_eval = False,
|
|
385
|
+
do_predict = False,
|
|
386
|
+
eval_strategy = 'no',
|
|
387
|
+
prediction_loss_only = False,
|
|
388
|
+
per_device_train_batch_size = 4,
|
|
389
|
+
per_device_eval_batch_size = 4,
|
|
390
|
+
per_gpu_train_batch_size = None,
|
|
391
|
+
per_gpu_eval_batch_size = None,
|
|
392
|
+
gradient_accumulation_steps = 2,
|
|
393
|
+
eval_accumulation_steps = 2,
|
|
394
|
+
eval_delay = 0,
|
|
395
|
+
torch_empty_cache_steps = 250,
|
|
396
|
+
learning_rate = 5e-05,
|
|
397
|
+
weight_decay = 0.01,
|
|
398
|
+
adam_beta1 = 0.9,
|
|
399
|
+
adam_beta2 = 0.999,
|
|
400
|
+
adam_epsilon = 1e-08,
|
|
401
|
+
max_grad_norm = 1.0,
|
|
402
|
+
num_train_epochs = 3.0,
|
|
403
|
+
max_steps = -1,
|
|
404
|
+
lr_scheduler_type = 'linear',
|
|
405
|
+
warmup_ratio = 0.1,
|
|
406
|
+
warmup_steps = 0,
|
|
407
|
+
log_level = 'passive',
|
|
408
|
+
log_level_replica = 'warning',
|
|
409
|
+
log_on_each_node = True,
|
|
410
|
+
logging_dir = None,
|
|
411
|
+
logging_strategy = 'steps',
|
|
412
|
+
logging_first_step = False,
|
|
413
|
+
logging_steps = 1,
|
|
414
|
+
logging_nan_inf_filter = False,
|
|
415
|
+
save_strategy = 'steps',
|
|
416
|
+
save_steps = 500,
|
|
417
|
+
save_total_limit = None,
|
|
418
|
+
save_safetensors = True,
|
|
419
|
+
save_on_each_node = False,
|
|
420
|
+
save_only_model = False,
|
|
421
|
+
restore_callback_states_from_checkpoint = False,
|
|
422
|
+
no_cuda = False,
|
|
423
|
+
use_cpu = False,
|
|
424
|
+
use_mps_device = False,
|
|
425
|
+
seed = 3407,
|
|
426
|
+
data_seed = 3407,
|
|
427
|
+
jit_mode_eval = False,
|
|
428
|
+
bf16 = False,
|
|
429
|
+
fp16 = False,
|
|
430
|
+
fp16_opt_level = 'O1',
|
|
431
|
+
half_precision_backend = 'auto',
|
|
432
|
+
bf16_full_eval = False,
|
|
433
|
+
fp16_full_eval = False,
|
|
434
|
+
tf32 = None,
|
|
435
|
+
local_rank = -1,
|
|
436
|
+
ddp_backend = None,
|
|
437
|
+
tpu_num_cores = None,
|
|
438
|
+
tpu_metrics_debug = False,
|
|
439
|
+
debug = '',
|
|
440
|
+
dataloader_drop_last = False,
|
|
441
|
+
eval_steps = None,
|
|
442
|
+
dataloader_num_workers = 0,
|
|
443
|
+
dataloader_prefetch_factor = None,
|
|
444
|
+
past_index = -1,
|
|
445
|
+
run_name = None,
|
|
446
|
+
disable_tqdm = None,
|
|
447
|
+
remove_unused_columns = True,
|
|
448
|
+
label_names = None,
|
|
449
|
+
load_best_model_at_end = False,
|
|
450
|
+
metric_for_best_model = None,
|
|
451
|
+
greater_is_better = None,
|
|
452
|
+
ignore_data_skip = False,
|
|
453
|
+
fsdp = None,
|
|
454
|
+
fsdp_min_num_params = 0,
|
|
455
|
+
fsdp_config = None,
|
|
456
|
+
fsdp_transformer_layer_cls_to_wrap = None,
|
|
457
|
+
accelerator_config = None,
|
|
458
|
+
parallelism_config = None,
|
|
459
|
+
deepspeed = None,
|
|
460
|
+
label_smoothing_factor = 0.0,
|
|
461
|
+
optim = 'adamw_8bit',
|
|
462
|
+
optim_args = None,
|
|
463
|
+
adafactor = False,
|
|
464
|
+
group_by_length = False,
|
|
465
|
+
length_column_name = 'length',
|
|
466
|
+
report_to = 'none',
|
|
467
|
+
project = 'huggingface',
|
|
468
|
+
trackio_space_id = 'trackio',
|
|
469
|
+
ddp_find_unused_parameters = None,
|
|
470
|
+
ddp_bucket_cap_mb = None,
|
|
471
|
+
ddp_broadcast_buffers = None,
|
|
472
|
+
dataloader_pin_memory = True,
|
|
473
|
+
dataloader_persistent_workers = False,
|
|
474
|
+
skip_memory_metrics = True,
|
|
475
|
+
use_legacy_prediction_loop = False,
|
|
476
|
+
push_to_hub = False,
|
|
477
|
+
resume_from_checkpoint = None,
|
|
478
|
+
hub_model_id = None,
|
|
479
|
+
hub_strategy = 'every_save',
|
|
480
|
+
hub_token = None,
|
|
481
|
+
hub_private_repo = None,
|
|
482
|
+
hub_always_push = False,
|
|
483
|
+
hub_revision = None,
|
|
484
|
+
gradient_checkpointing = True,
|
|
485
|
+
gradient_checkpointing_kwargs = None,
|
|
486
|
+
include_inputs_for_metrics = False,
|
|
487
|
+
eval_do_concat_batches = True,
|
|
488
|
+
fp16_backend = 'auto',
|
|
489
|
+
push_to_hub_model_id = None,
|
|
490
|
+
push_to_hub_organization = None,
|
|
491
|
+
push_to_hub_token = None,
|
|
492
|
+
mp_parameters = '',
|
|
493
|
+
auto_find_batch_size = False,
|
|
494
|
+
full_determinism = False,
|
|
495
|
+
torchdynamo = None,
|
|
496
|
+
ray_scope = 'last',
|
|
497
|
+
ddp_timeout = 1800,
|
|
498
|
+
torch_compile = False,
|
|
499
|
+
torch_compile_backend = None,
|
|
500
|
+
torch_compile_mode = None,
|
|
501
|
+
include_tokens_per_second = False,
|
|
502
|
+
include_num_input_tokens_seen = False,
|
|
503
|
+
neftune_noise_alpha = None,
|
|
504
|
+
optim_target_modules = None,
|
|
505
|
+
batch_eval_metrics = False,
|
|
506
|
+
eval_on_start = False,
|
|
507
|
+
use_liger_kernel = False,
|
|
508
|
+
liger_kernel_config = None,
|
|
509
|
+
eval_use_gather_object = False,
|
|
510
|
+
average_tokens_across_devices = True,
|
|
511
|
+
model_init_kwargs = None,
|
|
512
|
+
ref_model_init_kwargs = None,
|
|
513
|
+
model_adapter_name = None,
|
|
514
|
+
ref_adapter_name = None,
|
|
515
|
+
force_use_ref_model = False,
|
|
516
|
+
disable_dropout = True,
|
|
517
|
+
use_logits_to_keep = False,
|
|
518
|
+
dataset_num_proc = None,
|
|
519
|
+
pad_token = None,
|
|
520
|
+
label_pad_token_id = -100,
|
|
521
|
+
max_prompt_length = 512,
|
|
522
|
+
max_completion_length = None,
|
|
523
|
+
max_length = 1024,
|
|
524
|
+
truncation_mode = 'keep_end',
|
|
525
|
+
padding_free = False,
|
|
526
|
+
precompute_ref_log_probs = False,
|
|
527
|
+
precompute_ref_batch_size = None,
|
|
528
|
+
tools = None,
|
|
529
|
+
use_liger_loss = False,
|
|
530
|
+
base_model_attribute_name = 'model',
|
|
531
|
+
beta = 0.1,
|
|
532
|
+
f_alpha_divergence_coef = 1.0,
|
|
533
|
+
reference_free = False,
|
|
534
|
+
label_smoothing = 0.0,
|
|
535
|
+
use_weighting = False,
|
|
536
|
+
rpo_alpha = None,
|
|
537
|
+
ld_alpha = None,
|
|
538
|
+
discopop_tau = 0.05,
|
|
539
|
+
loss_weights = None,
|
|
540
|
+
sync_ref_model = False,
|
|
541
|
+
ref_model_mixup_alpha = 0.6,
|
|
542
|
+
ref_model_sync_steps = 512,
|
|
543
|
+
generate_during_eval = False,
|
|
544
|
+
padding_value = None,
|
|
545
|
+
vllm_sampling_params = None,
|
|
546
|
+
unsloth_num_chunks = -1,
|
|
547
|
+
max_seq_length = None,
|
|
548
|
+
**kwargs,
|
|
549
|
+
):
|
|
550
|
+
if learning_rate < 1e-7: print(f'Unsloth: Your learning rate of `{learning_rate}` is too small and less than 1e-7! Consider increasing it, otherwise gradient updates will be close to 0!')
|
|
551
|
+
if learning_rate > 1: print(f'Unsloth: Your learning rate of `{learning_rate}` is way too larger > 1! Consider decreasing it to 1e-1, otherwise gradient updates will explode!')
|
|
552
|
+
if output_dir is None and save_strategy == 'steps' and save_steps == 500:
|
|
553
|
+
output_dir = 'unsloth_training_checkpoints'
|
|
554
|
+
save_strategy = 'no'
|
|
555
|
+
if dataset_num_proc is None:
|
|
556
|
+
from multiprocessing import cpu_count
|
|
557
|
+
dataset_num_proc = min(max(cpu_count()+4, 2), 64)
|
|
558
|
+
|
|
559
|
+
super().__init__(
|
|
560
|
+
output_dir = output_dir,
|
|
561
|
+
overwrite_output_dir = overwrite_output_dir,
|
|
562
|
+
do_train = do_train,
|
|
563
|
+
do_eval = do_eval,
|
|
564
|
+
do_predict = do_predict,
|
|
565
|
+
eval_strategy = eval_strategy,
|
|
566
|
+
prediction_loss_only = prediction_loss_only,
|
|
567
|
+
per_device_train_batch_size = per_device_train_batch_size,
|
|
568
|
+
per_device_eval_batch_size = per_device_eval_batch_size,
|
|
569
|
+
per_gpu_train_batch_size = per_gpu_train_batch_size,
|
|
570
|
+
per_gpu_eval_batch_size = per_gpu_eval_batch_size,
|
|
571
|
+
gradient_accumulation_steps = gradient_accumulation_steps,
|
|
572
|
+
eval_accumulation_steps = eval_accumulation_steps,
|
|
573
|
+
eval_delay = eval_delay,
|
|
574
|
+
torch_empty_cache_steps = torch_empty_cache_steps,
|
|
575
|
+
learning_rate = learning_rate,
|
|
576
|
+
weight_decay = weight_decay,
|
|
577
|
+
adam_beta1 = adam_beta1,
|
|
578
|
+
adam_beta2 = adam_beta2,
|
|
579
|
+
adam_epsilon = adam_epsilon,
|
|
580
|
+
max_grad_norm = max_grad_norm,
|
|
581
|
+
num_train_epochs = num_train_epochs,
|
|
582
|
+
max_steps = max_steps,
|
|
583
|
+
lr_scheduler_type = lr_scheduler_type,
|
|
584
|
+
warmup_ratio = warmup_ratio,
|
|
585
|
+
warmup_steps = warmup_steps,
|
|
586
|
+
log_level = log_level,
|
|
587
|
+
log_level_replica = log_level_replica,
|
|
588
|
+
log_on_each_node = log_on_each_node,
|
|
589
|
+
logging_dir = logging_dir,
|
|
590
|
+
logging_strategy = logging_strategy,
|
|
591
|
+
logging_first_step = logging_first_step,
|
|
592
|
+
logging_steps = logging_steps,
|
|
593
|
+
logging_nan_inf_filter = logging_nan_inf_filter,
|
|
594
|
+
save_strategy = save_strategy,
|
|
595
|
+
save_steps = save_steps,
|
|
596
|
+
save_total_limit = save_total_limit,
|
|
597
|
+
save_safetensors = save_safetensors,
|
|
598
|
+
save_on_each_node = save_on_each_node,
|
|
599
|
+
save_only_model = save_only_model,
|
|
600
|
+
restore_callback_states_from_checkpoint = restore_callback_states_from_checkpoint,
|
|
601
|
+
no_cuda = no_cuda,
|
|
602
|
+
use_cpu = use_cpu,
|
|
603
|
+
use_mps_device = use_mps_device,
|
|
604
|
+
seed = seed,
|
|
605
|
+
data_seed = data_seed,
|
|
606
|
+
jit_mode_eval = jit_mode_eval,
|
|
607
|
+
bf16 = bf16,
|
|
608
|
+
fp16 = fp16,
|
|
609
|
+
fp16_opt_level = fp16_opt_level,
|
|
610
|
+
half_precision_backend = half_precision_backend,
|
|
611
|
+
bf16_full_eval = bf16_full_eval,
|
|
612
|
+
fp16_full_eval = fp16_full_eval,
|
|
613
|
+
tf32 = tf32,
|
|
614
|
+
local_rank = local_rank,
|
|
615
|
+
ddp_backend = ddp_backend,
|
|
616
|
+
tpu_num_cores = tpu_num_cores,
|
|
617
|
+
tpu_metrics_debug = tpu_metrics_debug,
|
|
618
|
+
debug = debug,
|
|
619
|
+
dataloader_drop_last = dataloader_drop_last,
|
|
620
|
+
eval_steps = eval_steps,
|
|
621
|
+
dataloader_num_workers = dataloader_num_workers,
|
|
622
|
+
dataloader_prefetch_factor = dataloader_prefetch_factor,
|
|
623
|
+
past_index = past_index,
|
|
624
|
+
run_name = run_name,
|
|
625
|
+
disable_tqdm = disable_tqdm,
|
|
626
|
+
remove_unused_columns = remove_unused_columns,
|
|
627
|
+
label_names = label_names,
|
|
628
|
+
load_best_model_at_end = load_best_model_at_end,
|
|
629
|
+
metric_for_best_model = metric_for_best_model,
|
|
630
|
+
greater_is_better = greater_is_better,
|
|
631
|
+
ignore_data_skip = ignore_data_skip,
|
|
632
|
+
fsdp = fsdp,
|
|
633
|
+
fsdp_min_num_params = fsdp_min_num_params,
|
|
634
|
+
fsdp_config = fsdp_config,
|
|
635
|
+
fsdp_transformer_layer_cls_to_wrap = fsdp_transformer_layer_cls_to_wrap,
|
|
636
|
+
accelerator_config = accelerator_config,
|
|
637
|
+
parallelism_config = parallelism_config,
|
|
638
|
+
deepspeed = deepspeed,
|
|
639
|
+
label_smoothing_factor = label_smoothing_factor,
|
|
640
|
+
optim = optim,
|
|
641
|
+
optim_args = optim_args,
|
|
642
|
+
adafactor = adafactor,
|
|
643
|
+
group_by_length = group_by_length,
|
|
644
|
+
length_column_name = length_column_name,
|
|
645
|
+
report_to = report_to,
|
|
646
|
+
project = project,
|
|
647
|
+
trackio_space_id = trackio_space_id,
|
|
648
|
+
ddp_find_unused_parameters = ddp_find_unused_parameters,
|
|
649
|
+
ddp_bucket_cap_mb = ddp_bucket_cap_mb,
|
|
650
|
+
ddp_broadcast_buffers = ddp_broadcast_buffers,
|
|
651
|
+
dataloader_pin_memory = dataloader_pin_memory,
|
|
652
|
+
dataloader_persistent_workers = dataloader_persistent_workers,
|
|
653
|
+
skip_memory_metrics = skip_memory_metrics,
|
|
654
|
+
use_legacy_prediction_loop = use_legacy_prediction_loop,
|
|
655
|
+
push_to_hub = push_to_hub,
|
|
656
|
+
resume_from_checkpoint = resume_from_checkpoint,
|
|
657
|
+
hub_model_id = hub_model_id,
|
|
658
|
+
hub_strategy = hub_strategy,
|
|
659
|
+
hub_token = hub_token,
|
|
660
|
+
hub_private_repo = hub_private_repo,
|
|
661
|
+
hub_always_push = hub_always_push,
|
|
662
|
+
hub_revision = hub_revision,
|
|
663
|
+
gradient_checkpointing = gradient_checkpointing,
|
|
664
|
+
gradient_checkpointing_kwargs = gradient_checkpointing_kwargs,
|
|
665
|
+
include_inputs_for_metrics = include_inputs_for_metrics,
|
|
666
|
+
eval_do_concat_batches = eval_do_concat_batches,
|
|
667
|
+
fp16_backend = fp16_backend,
|
|
668
|
+
push_to_hub_model_id = push_to_hub_model_id,
|
|
669
|
+
push_to_hub_organization = push_to_hub_organization,
|
|
670
|
+
push_to_hub_token = push_to_hub_token,
|
|
671
|
+
mp_parameters = mp_parameters,
|
|
672
|
+
auto_find_batch_size = auto_find_batch_size,
|
|
673
|
+
full_determinism = full_determinism,
|
|
674
|
+
torchdynamo = torchdynamo,
|
|
675
|
+
ray_scope = ray_scope,
|
|
676
|
+
ddp_timeout = ddp_timeout,
|
|
677
|
+
torch_compile = torch_compile,
|
|
678
|
+
torch_compile_backend = torch_compile_backend,
|
|
679
|
+
torch_compile_mode = torch_compile_mode,
|
|
680
|
+
include_tokens_per_second = include_tokens_per_second,
|
|
681
|
+
include_num_input_tokens_seen = include_num_input_tokens_seen,
|
|
682
|
+
neftune_noise_alpha = neftune_noise_alpha,
|
|
683
|
+
optim_target_modules = optim_target_modules,
|
|
684
|
+
batch_eval_metrics = batch_eval_metrics,
|
|
685
|
+
eval_on_start = eval_on_start,
|
|
686
|
+
use_liger_kernel = use_liger_kernel,
|
|
687
|
+
liger_kernel_config = liger_kernel_config,
|
|
688
|
+
eval_use_gather_object = eval_use_gather_object,
|
|
689
|
+
average_tokens_across_devices = average_tokens_across_devices,
|
|
690
|
+
model_init_kwargs = model_init_kwargs,
|
|
691
|
+
ref_model_init_kwargs = ref_model_init_kwargs,
|
|
692
|
+
model_adapter_name = model_adapter_name,
|
|
693
|
+
ref_adapter_name = ref_adapter_name,
|
|
694
|
+
force_use_ref_model = force_use_ref_model,
|
|
695
|
+
disable_dropout = disable_dropout,
|
|
696
|
+
use_logits_to_keep = use_logits_to_keep,
|
|
697
|
+
dataset_num_proc = dataset_num_proc,
|
|
698
|
+
pad_token = pad_token,
|
|
699
|
+
label_pad_token_id = label_pad_token_id,
|
|
700
|
+
max_prompt_length = max_prompt_length,
|
|
701
|
+
max_completion_length = max_completion_length,
|
|
702
|
+
max_length = max_length,
|
|
703
|
+
truncation_mode = truncation_mode,
|
|
704
|
+
padding_free = padding_free,
|
|
705
|
+
precompute_ref_log_probs = precompute_ref_log_probs,
|
|
706
|
+
precompute_ref_batch_size = precompute_ref_batch_size,
|
|
707
|
+
tools = tools,
|
|
708
|
+
use_liger_loss = use_liger_loss,
|
|
709
|
+
base_model_attribute_name = base_model_attribute_name,
|
|
710
|
+
beta = beta,
|
|
711
|
+
f_alpha_divergence_coef = f_alpha_divergence_coef,
|
|
712
|
+
reference_free = reference_free,
|
|
713
|
+
label_smoothing = label_smoothing,
|
|
714
|
+
use_weighting = use_weighting,
|
|
715
|
+
rpo_alpha = rpo_alpha,
|
|
716
|
+
ld_alpha = ld_alpha,
|
|
717
|
+
discopop_tau = discopop_tau,
|
|
718
|
+
loss_weights = loss_weights,
|
|
719
|
+
sync_ref_model = sync_ref_model,
|
|
720
|
+
ref_model_mixup_alpha = ref_model_mixup_alpha,
|
|
721
|
+
ref_model_sync_steps = ref_model_sync_steps,
|
|
722
|
+
generate_during_eval = generate_during_eval,
|
|
723
|
+
padding_value = padding_value,**kwargs)
|
|
724
|
+
self.vllm_sampling_params = vllm_sampling_params
|
|
725
|
+
self.unsloth_num_chunks = unsloth_num_chunks
|
|
726
|
+
self.max_seq_length = max_seq_length
|
|
727
|
+
pass
|
|
728
|
+
|
|
729
|
+
class _UnslothDPOTrainer(BaseTrainer):
|
|
730
|
+
""""""
|
|
731
|
+
|
|
732
|
+
_tag_names = ["trl", "dpo"]
|
|
733
|
+
_name = "DPO"
|
|
734
|
+
_paper = {
|
|
735
|
+
"title": "Direct Preference Optimization: Your Language Model is Secretly a Reward Model",
|
|
736
|
+
"id": "2305.18290",
|
|
737
|
+
# docstyle-ignore
|
|
738
|
+
"citation": textwrap.dedent("""\
|
|
739
|
+
@inproceedings{rafailov2023direct,
|
|
740
|
+
title = {{Direct Preference Optimization: Your Language Model is Secretly a Reward Model}},
|
|
741
|
+
author = {Rafael Rafailov and Archit Sharma and Eric Mitchell and Christopher D. Manning and Stefano Ermon and Chelsea Finn},
|
|
742
|
+
year = 2023,
|
|
743
|
+
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},
|
|
744
|
+
url = {http://papers.nips.cc/paper_files/paper/2023/hash/a85b405ed65c6477a4fe8302b5e06ce7-Abstract-Conference.html},
|
|
745
|
+
editor = {Alice Oh and Tristan Naumann and Amir Globerson and Kate Saenko and Moritz Hardt and Sergey Levine},
|
|
746
|
+
}"""),
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
def __init__(
|
|
750
|
+
self,
|
|
751
|
+
model: Union[str, nn.Module, PreTrainedModel],
|
|
752
|
+
ref_model: Optional[Union[PreTrainedModel, nn.Module, str]] = None,
|
|
753
|
+
args: Optional[DPOConfig] = None,
|
|
754
|
+
data_collator: Optional[DataCollator] = None, # type: ignore
|
|
755
|
+
train_dataset: Optional[Union[Dataset, IterableDataset]] = None,
|
|
756
|
+
eval_dataset: Optional[Union[Dataset, IterableDataset, dict[str, Union[Dataset, IterableDataset]]]] = None,
|
|
757
|
+
processing_class: Optional[
|
|
758
|
+
Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin]
|
|
759
|
+
] = None,
|
|
760
|
+
compute_metrics: Optional[Callable[[EvalLoopOutput], dict]] = None,
|
|
761
|
+
callbacks: Optional[list[TrainerCallback]] = None,
|
|
762
|
+
optimizers: tuple[Optional[torch.optim.Optimizer], Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None),
|
|
763
|
+
optimizer_cls_and_kwargs: Optional[tuple[type[torch.optim.Optimizer], dict[str, Any]]] = None,
|
|
764
|
+
preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
|
|
765
|
+
peft_config: Optional["PeftConfig"] = None,
|
|
766
|
+
):
|
|
767
|
+
# Args
|
|
768
|
+
if args is None:
|
|
769
|
+
model_name = model if isinstance(model, str) else model.config._name_or_path
|
|
770
|
+
model_name = model_name.split("/")[-1]
|
|
771
|
+
args = DPOConfig(f"{model_name}-DPO")
|
|
772
|
+
|
|
773
|
+
# Model and reference model
|
|
774
|
+
if isinstance(model, str):
|
|
775
|
+
model = create_model_from_path(model, **args.model_init_kwargs or {})
|
|
776
|
+
else:
|
|
777
|
+
if args.model_init_kwargs is not None:
|
|
778
|
+
logger.warning(
|
|
779
|
+
"You passed `model_init_kwargs` to the `DPOConfig`, but your model is already instantiated. "
|
|
780
|
+
"The `model_init_kwargs` will be ignored."
|
|
781
|
+
)
|
|
782
|
+
model_id = model.config._name_or_path
|
|
783
|
+
if isinstance(ref_model, str):
|
|
784
|
+
ref_model = create_model_from_path(ref_model, **args.ref_model_init_kwargs or {})
|
|
785
|
+
else:
|
|
786
|
+
if args.ref_model_init_kwargs is not None:
|
|
787
|
+
logger.warning(
|
|
788
|
+
"You passed `ref_model_init_kwargs` to the `DPOConfig`, but your model is already instantiated. "
|
|
789
|
+
"The `ref_model_init_kwargs` will be ignored."
|
|
790
|
+
)
|
|
791
|
+
if ref_model is model:
|
|
792
|
+
raise ValueError(
|
|
793
|
+
"`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the "
|
|
794
|
+
"same as `model`, you can simply omit the `ref_model` argument and it will be created for you."
|
|
795
|
+
)
|
|
796
|
+
|
|
797
|
+
# Processing class
|
|
798
|
+
if processing_class is None:
|
|
799
|
+
processing_class = AutoProcessor.from_pretrained(model_id)
|
|
800
|
+
|
|
801
|
+
# Handle pad token for processors or tokenizers
|
|
802
|
+
if isinstance(processing_class, ProcessorMixin):
|
|
803
|
+
tokenizer = processing_class.tokenizer
|
|
804
|
+
self._is_vlm = True
|
|
805
|
+
elif isinstance(processing_class, PreTrainedTokenizerBase):
|
|
806
|
+
tokenizer = processing_class
|
|
807
|
+
self._is_vlm = False
|
|
808
|
+
else:
|
|
809
|
+
raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
|
|
810
|
+
|
|
811
|
+
# Get the pad token: if not provided, use the one from the processing class or the eos token
|
|
812
|
+
# if the processing class does not have a pad token.
|
|
813
|
+
if args.padding_value is not None: # deprecated, will be removed in 0.26.0.
|
|
814
|
+
warnings.warn(
|
|
815
|
+
"The `padding_value` argument is deprecated and will be removed in version 0.26.0. Please use "
|
|
816
|
+
"`pad_token` (str) instead."
|
|
817
|
+
)
|
|
818
|
+
self.pad_token_id = args.padding_value
|
|
819
|
+
else:
|
|
820
|
+
pad_token = args.pad_token or tokenizer.pad_token or tokenizer.eos_token
|
|
821
|
+
self.pad_token_id = tokenizer.convert_tokens_to_ids(pad_token)
|
|
822
|
+
if self.pad_token_id is None:
|
|
823
|
+
raise ValueError(
|
|
824
|
+
f"The specified `pad_token` ('{pad_token}') is not found in the vocabulary of the given "
|
|
825
|
+
f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `pad_token` exists "
|
|
826
|
+
"in the vocabulary before using it as a padding token."
|
|
827
|
+
)
|
|
828
|
+
|
|
829
|
+
# PEFT configuration and model wrapping
|
|
830
|
+
model = self._prepare_peft_model(model, ref_model, peft_config, args)
|
|
831
|
+
|
|
832
|
+
if args.generate_during_eval and not (is_wandb_available() or is_comet_available() or is_mlflow_available()):
|
|
833
|
+
raise ValueError(
|
|
834
|
+
"`generate_during_eval=True` requires Weights and Biases, MLFlow or Comet to be installed."
|
|
835
|
+
" Please install `wandb`, `mlflow` or `comet-ml` to resolve."
|
|
836
|
+
)
|
|
837
|
+
|
|
838
|
+
self.is_encoder_decoder = model.config.is_encoder_decoder
|
|
839
|
+
self.is_vision_model = model.config.model_type in MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES.keys()
|
|
840
|
+
self.is_peft_model = is_peft_available() and isinstance(model, PeftModel)
|
|
841
|
+
self.model_adapter_name = args.model_adapter_name
|
|
842
|
+
self.ref_adapter_name = args.ref_adapter_name
|
|
843
|
+
self.reference_free = args.reference_free
|
|
844
|
+
|
|
845
|
+
if ref_model:
|
|
846
|
+
self.ref_model = ref_model
|
|
847
|
+
elif self.is_peft_model or args.precompute_ref_log_probs:
|
|
848
|
+
# The `model` with adapters turned off will be used as the reference model
|
|
849
|
+
self.ref_model = None
|
|
850
|
+
else:
|
|
851
|
+
self.ref_model = create_reference_model(model)
|
|
852
|
+
|
|
853
|
+
# Disable dropout in the model and reference model
|
|
854
|
+
if args.disable_dropout:
|
|
855
|
+
disable_dropout_in_model(model)
|
|
856
|
+
if self.ref_model is not None:
|
|
857
|
+
disable_dropout_in_model(self.ref_model)
|
|
858
|
+
|
|
859
|
+
# Liger kernel
|
|
860
|
+
if args.use_liger_loss:
|
|
861
|
+
if not is_liger_kernel_available():
|
|
862
|
+
raise ImportError(
|
|
863
|
+
"You set `use_liger_loss=True` but the liger kernel is not available. "
|
|
864
|
+
"Please install liger-kernel first: `pip install liger-kernel`"
|
|
865
|
+
)
|
|
866
|
+
if args.loss_type not in ["sigmoid", "apo_zero", "apo_down", "sppo_hard", "nca_pair"]:
|
|
867
|
+
raise ValueError(
|
|
868
|
+
"You set `use_liger_loss=True` but the loss type is not from `[sigmoid, apo_zero, apo_down, sppo_hard, nca_pair`. "
|
|
869
|
+
"Please set `loss_type='[sigmoid | apo_zero | apo_down | sppo_hard | nca_pair]'` to use the liger kernel."
|
|
870
|
+
)
|
|
871
|
+
self.dpo_loss_fn = LigerFusedLinearDPOLoss(
|
|
872
|
+
ignore_index=args.label_pad_token_id,
|
|
873
|
+
beta=args.beta,
|
|
874
|
+
use_ref_model=not args.reference_free,
|
|
875
|
+
average_log_prob=False,
|
|
876
|
+
loss_type=args.loss_type,
|
|
877
|
+
)
|
|
878
|
+
# The trainer estimates the number of FLOPs [floating-point operations] using the number of elements in the
|
|
879
|
+
# input tensor associated with the key "input_ids". However, in DPO, the sampled data does not include the
|
|
880
|
+
# "input_ids" key. Instead, the available keys are "prompt_input_ids", "chosen_input_ids", and
|
|
881
|
+
# "rejected_input_ids". As a result, the trainer issues the warning: "Could not estimate the number of tokens
|
|
882
|
+
# of the input, floating-point operations will not be computed." To suppress this warning, we set the
|
|
883
|
+
# "estimate_tokens" key in the model's "warnings_issued" dictionary to True. This acts as a flag to indicate
|
|
884
|
+
# that the warning has already been issued.
|
|
885
|
+
model.warnings_issued["estimate_tokens"] = True
|
|
886
|
+
|
|
887
|
+
# Data collator
|
|
888
|
+
if data_collator is None:
|
|
889
|
+
data_collator = DataCollatorForPreference(pad_token_id=self.pad_token_id)
|
|
890
|
+
|
|
891
|
+
self.generate_during_eval = args.generate_during_eval
|
|
892
|
+
self.label_pad_token_id = args.label_pad_token_id
|
|
893
|
+
self.max_prompt_length = args.max_prompt_length
|
|
894
|
+
self.max_completion_length = args.max_completion_length
|
|
895
|
+
self.max_length = args.max_length
|
|
896
|
+
self.truncation_mode = args.truncation_mode
|
|
897
|
+
self.precompute_ref_log_probs = args.precompute_ref_log_probs
|
|
898
|
+
self.use_logits_to_keep = args.use_logits_to_keep
|
|
899
|
+
|
|
900
|
+
if args.padding_free:
|
|
901
|
+
if model.config._attn_implementation != "flash_attention_2":
|
|
902
|
+
logger.warning(
|
|
903
|
+
"Padding-free training is enabled, but the attention implementation is not set to "
|
|
904
|
+
"'flash_attention_2'. Padding-free training flattens batches into a single sequence, and "
|
|
905
|
+
"'flash_attention_2' is the only known attention mechanism that reliably supports this. Using "
|
|
906
|
+
"other implementations may lead to unexpected behavior. To ensure compatibility, set "
|
|
907
|
+
"`attn_implementation='flash_attention_2'` in the model configuration, or verify that your "
|
|
908
|
+
"attention mechanism can handle flattened sequences."
|
|
909
|
+
)
|
|
910
|
+
if args.per_device_train_batch_size == 1:
|
|
911
|
+
logger.warning(
|
|
912
|
+
"You are using a per_device_train_batch_size of 1 with padding-free training. Using a batch size "
|
|
913
|
+
"of 1 anihilate the benefits of padding-free training. Please consider increasing the batch size "
|
|
914
|
+
"to at least 2."
|
|
915
|
+
)
|
|
916
|
+
self.padding_free = args.padding_free
|
|
917
|
+
|
|
918
|
+
# Since ref_logs are precomputed on the first call to get_train/eval_dataloader
|
|
919
|
+
# keep track of first called to avoid computation of future calls
|
|
920
|
+
self._precomputed_train_ref_log_probs = False
|
|
921
|
+
self._precomputed_eval_ref_log_probs = False
|
|
922
|
+
|
|
923
|
+
self.beta = args.beta
|
|
924
|
+
self.label_smoothing = args.label_smoothing
|
|
925
|
+
self.loss_type = args.loss_type if isinstance(args.loss_type, list) else [args.loss_type]
|
|
926
|
+
self.loss_weights = args.loss_weights
|
|
927
|
+
self.aux_loss_enabled = getattr(model.config, "output_router_logits", False)
|
|
928
|
+
self.use_weighting = args.use_weighting
|
|
929
|
+
self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0)
|
|
930
|
+
if self.aux_loss_enabled and self.aux_loss_coef == 0.0:
|
|
931
|
+
logger.warning(
|
|
932
|
+
"You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to "
|
|
933
|
+
"`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value "
|
|
934
|
+
"greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary "
|
|
935
|
+
"loss.",
|
|
936
|
+
)
|
|
937
|
+
for loss_type in self.loss_type:
|
|
938
|
+
if (
|
|
939
|
+
loss_type in ["hinge", "ipo", "bco_pair", "sppo_hard", "nca_pair", "apo_zero", "apo_down"]
|
|
940
|
+
and args.label_smoothing > 0
|
|
941
|
+
):
|
|
942
|
+
logger.warning(
|
|
943
|
+
f"You are using the {loss_type} loss type that does not support label smoothing. The "
|
|
944
|
+
"`label_smoothing` parameter will be ignored. Set `label_smoothing` to `0.0` to remove this "
|
|
945
|
+
"warning.",
|
|
946
|
+
)
|
|
947
|
+
if loss_type == "kto_pair":
|
|
948
|
+
raise ValueError("Support for kto_pair has been removed in DPOTrainer. Please use KTOTrainer.")
|
|
949
|
+
|
|
950
|
+
self._stored_metrics = defaultdict(lambda: defaultdict(list))
|
|
951
|
+
self.f_divergence_type = args.f_divergence_type
|
|
952
|
+
self.f_divergence_params = {FDivergenceConstants.ALPHA_DIVERGENCE_COEF_KEY: args.f_alpha_divergence_coef}
|
|
953
|
+
self.dataset_num_proc = args.dataset_num_proc
|
|
954
|
+
|
|
955
|
+
# Dataset preparation
|
|
956
|
+
train_dataset = self._prepare_dataset(train_dataset, processing_class, args, "train")
|
|
957
|
+
if eval_dataset is not None:
|
|
958
|
+
if isinstance(eval_dataset, dict):
|
|
959
|
+
eval_dataset = {
|
|
960
|
+
key: self._prepare_dataset(dataset, processing_class, args, key)
|
|
961
|
+
for key, dataset in eval_dataset.items()
|
|
962
|
+
}
|
|
963
|
+
else:
|
|
964
|
+
eval_dataset = self._prepare_dataset(eval_dataset, processing_class, args, "eval")
|
|
965
|
+
|
|
966
|
+
super().__init__(
|
|
967
|
+
model=model,
|
|
968
|
+
args=args,
|
|
969
|
+
data_collator=data_collator,
|
|
970
|
+
train_dataset=train_dataset,
|
|
971
|
+
eval_dataset=eval_dataset,
|
|
972
|
+
processing_class=processing_class,
|
|
973
|
+
compute_metrics=compute_metrics,
|
|
974
|
+
callbacks=callbacks,
|
|
975
|
+
optimizers=optimizers,
|
|
976
|
+
optimizer_cls_and_kwargs=optimizer_cls_and_kwargs,
|
|
977
|
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
|
978
|
+
)
|
|
979
|
+
|
|
980
|
+
# Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
|
|
981
|
+
# model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
|
|
982
|
+
# self.model_accepts_loss_kwargs to False to enable scaling.
|
|
983
|
+
self.model_accepts_loss_kwargs = False
|
|
984
|
+
|
|
985
|
+
# Add tags for models that have been loaded with the correct transformers version
|
|
986
|
+
if hasattr(self.model, "add_model_tags"):
|
|
987
|
+
self.model.add_model_tags(self._tag_names)
|
|
988
|
+
|
|
989
|
+
if not hasattr(self, "accelerator"):
|
|
990
|
+
raise AttributeError(
|
|
991
|
+
"Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`."
|
|
992
|
+
)
|
|
993
|
+
|
|
994
|
+
# Deepspeed Zero-3 does not support precompute_ref_log_probs
|
|
995
|
+
if self.is_deepspeed_enabled:
|
|
996
|
+
if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs:
|
|
997
|
+
raise ValueError(
|
|
998
|
+
"You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`."
|
|
999
|
+
)
|
|
1000
|
+
|
|
1001
|
+
if self.ref_model is None:
|
|
1002
|
+
if not (self.is_peft_model or self.precompute_ref_log_probs):
|
|
1003
|
+
raise ValueError(
|
|
1004
|
+
"No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`"
|
|
1005
|
+
)
|
|
1006
|
+
if args.sync_ref_model:
|
|
1007
|
+
raise ValueError(
|
|
1008
|
+
"You currently cannot use `ref_model=None` with TR-DPO method. Please provide `ref_model`."
|
|
1009
|
+
)
|
|
1010
|
+
else:
|
|
1011
|
+
if self.is_deepspeed_enabled:
|
|
1012
|
+
self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator)
|
|
1013
|
+
elif self.is_fsdp_enabled:
|
|
1014
|
+
self.ref_model = prepare_fsdp(self.ref_model, self.accelerator)
|
|
1015
|
+
else:
|
|
1016
|
+
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
|
|
1017
|
+
|
|
1018
|
+
if args.sync_ref_model:
|
|
1019
|
+
if self.precompute_ref_log_probs:
|
|
1020
|
+
raise ValueError(
|
|
1021
|
+
"You cannot use `precompute_ref_log_probs=True` with TR-DPO method. Please set `precompute_ref_log_probs=False`."
|
|
1022
|
+
)
|
|
1023
|
+
|
|
1024
|
+
self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator))
|
|
1025
|
+
|
|
1026
|
+
if "bco_pair" in self.loss_type:
|
|
1027
|
+
self.running = RunningMoments(self.accelerator)
|
|
1028
|
+
|
|
1029
|
+
@property
|
|
1030
|
+
def padding_value(self):
|
|
1031
|
+
warnings.warn(
|
|
1032
|
+
"The `padding_value` property is deprecated and will be removed in version 0.26.0. Please use "
|
|
1033
|
+
"`pad_token_id` instead.",
|
|
1034
|
+
)
|
|
1035
|
+
return self.pad_token_id
|
|
1036
|
+
|
|
1037
|
+
@padding_value.setter
|
|
1038
|
+
def padding_value(self, value):
|
|
1039
|
+
warnings.warn(
|
|
1040
|
+
"The `padding_value` property is deprecated and will be removed in version 0.26.0. Please use "
|
|
1041
|
+
"`pad_token_id` instead.",
|
|
1042
|
+
)
|
|
1043
|
+
self.pad_token_id = value
|
|
1044
|
+
|
|
1045
|
+
def _prepare_peft_model(
|
|
1046
|
+
self, model: PreTrainedModel, ref_model: PreTrainedModel, peft_config: Any, args: DPOConfig
|
|
1047
|
+
) -> PreTrainedModel:
|
|
1048
|
+
"""Prepares a model for PEFT training."""
|
|
1049
|
+
# Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16`
|
|
1050
|
+
# has been called in order to properly call autocast if needed.
|
|
1051
|
+
self._peft_has_been_casted_to_bf16 = False
|
|
1052
|
+
|
|
1053
|
+
if not is_peft_available() and peft_config is not None:
|
|
1054
|
+
raise ValueError(
|
|
1055
|
+
"PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models"
|
|
1056
|
+
)
|
|
1057
|
+
elif is_peft_available() and peft_config is not None:
|
|
1058
|
+
# if model is a peft model and we have a peft_config, we merge and unload it first
|
|
1059
|
+
if isinstance(model, PeftModel):
|
|
1060
|
+
model = model.merge_and_unload()
|
|
1061
|
+
|
|
1062
|
+
if ref_model is not None and not args.force_use_ref_model:
|
|
1063
|
+
raise ValueError(
|
|
1064
|
+
"You passed both a ref_model and a peft_config. For training PEFT adapters with DPO there is no need to pass a reference"
|
|
1065
|
+
" model. Please pass `ref_model=None` in case you want to train PEFT adapters, or pass a ref_model with `force_use_ref_model=True` in DPOTrainer's init."
|
|
1066
|
+
" if you want to use a different ref_model."
|
|
1067
|
+
)
|
|
1068
|
+
|
|
1069
|
+
if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False):
|
|
1070
|
+
_support_gc_kwargs = hasattr(
|
|
1071
|
+
args, "gradient_checkpointing_kwargs"
|
|
1072
|
+
) and "gradient_checkpointing_kwargs" in list(
|
|
1073
|
+
inspect.signature(prepare_model_for_kbit_training).parameters
|
|
1074
|
+
)
|
|
1075
|
+
|
|
1076
|
+
prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing}
|
|
1077
|
+
|
|
1078
|
+
if _support_gc_kwargs:
|
|
1079
|
+
prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs
|
|
1080
|
+
|
|
1081
|
+
model = prepare_model_for_kbit_training(model, **prepare_model_kwargs)
|
|
1082
|
+
|
|
1083
|
+
else:
|
|
1084
|
+
model = self._prepare_gradient_checkpointing(model, args)
|
|
1085
|
+
|
|
1086
|
+
# get peft model with the given config
|
|
1087
|
+
model = get_peft_model(model, peft_config)
|
|
1088
|
+
if args.bf16 and getattr(model, "is_loaded_in_4bit", False):
|
|
1089
|
+
peft_module_casting_to_bf16(model)
|
|
1090
|
+
# If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager
|
|
1091
|
+
self._peft_has_been_casted_to_bf16 = True
|
|
1092
|
+
|
|
1093
|
+
else:
|
|
1094
|
+
model = self._prepare_gradient_checkpointing(model, args)
|
|
1095
|
+
|
|
1096
|
+
return model
|
|
1097
|
+
|
|
1098
|
+
def _prepare_gradient_checkpointing(self, model: PreTrainedModel, args: DPOConfig):
|
|
1099
|
+
"""Prepare the gradienting checkpointing for the model."""
|
|
1100
|
+
# For models that use gradient_checkpointing, we need to attach a hook that enables input
|
|
1101
|
+
# to explicitly have `requires_grad=True`, otherwise training will either silently
|
|
1102
|
+
# fail or completely fail.
|
|
1103
|
+
if args.gradient_checkpointing:
|
|
1104
|
+
# For backward compatibility with older versions of transformers
|
|
1105
|
+
if hasattr(model, "enable_input_require_grads"):
|
|
1106
|
+
model.enable_input_require_grads()
|
|
1107
|
+
else:
|
|
1108
|
+
|
|
1109
|
+
def make_inputs_require_grad(module, input, output):
|
|
1110
|
+
output.requires_grad_(True)
|
|
1111
|
+
|
|
1112
|
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
|
1113
|
+
|
|
1114
|
+
return model
|
|
1115
|
+
|
|
1116
|
+
def _prepare_dataset(
|
|
1117
|
+
self,
|
|
1118
|
+
dataset: Union[Dataset, IterableDataset],
|
|
1119
|
+
processing_class: Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin],
|
|
1120
|
+
args: DPOConfig,
|
|
1121
|
+
dataset_name: str,
|
|
1122
|
+
) -> Union[Dataset, IterableDataset]:
|
|
1123
|
+
# Build the kwargs for the `map` function
|
|
1124
|
+
map_kwargs = {}
|
|
1125
|
+
if isinstance(dataset, Dataset): # IterableDataset does not support num_proc nor writer_batch_size
|
|
1126
|
+
map_kwargs["num_proc"] = args.dataset_num_proc
|
|
1127
|
+
map_kwargs["writer_batch_size"] = 10
|
|
1128
|
+
|
|
1129
|
+
with PartialState().main_process_first():
|
|
1130
|
+
# Extract prompt if needed
|
|
1131
|
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
|
1132
|
+
map_kwargs["desc"] = f"Extracting prompt in {dataset_name} dataset"
|
|
1133
|
+
dataset = dataset.map(maybe_extract_prompt, **map_kwargs)
|
|
1134
|
+
|
|
1135
|
+
# Apply the chat template if needed
|
|
1136
|
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
|
1137
|
+
map_kwargs["desc"] = f"Applying chat template to {dataset_name} dataset"
|
|
1138
|
+
dataset = dataset.map(
|
|
1139
|
+
maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class, "tools": args.tools}, **map_kwargs
|
|
1140
|
+
)
|
|
1141
|
+
|
|
1142
|
+
# Tokenize the dataset
|
|
1143
|
+
if isinstance(dataset, Dataset): # `IterableDataset.map` does not support `desc`
|
|
1144
|
+
map_kwargs["desc"] = f"Tokenizing {dataset_name} dataset"
|
|
1145
|
+
|
|
1146
|
+
dataset = dataset.map(
|
|
1147
|
+
self.tokenize_row if not self.is_vision_model else self.process_row,
|
|
1148
|
+
remove_columns=["chosen", "rejected"],
|
|
1149
|
+
fn_kwargs={
|
|
1150
|
+
"processing_class": processing_class,
|
|
1151
|
+
"max_prompt_length": args.max_prompt_length,
|
|
1152
|
+
"max_completion_length": args.max_completion_length,
|
|
1153
|
+
# for enc-dec, we add the special tokens ([bos_token] + prompt + [eos_token]; completion + [eos_token])
|
|
1154
|
+
"add_special_tokens": False,
|
|
1155
|
+
},
|
|
1156
|
+
**map_kwargs,
|
|
1157
|
+
)
|
|
1158
|
+
|
|
1159
|
+
return dataset
|
|
1160
|
+
|
|
1161
|
+
@staticmethod
|
|
1162
|
+
def tokenize_row(
|
|
1163
|
+
features: dict[str, str],
|
|
1164
|
+
processing_class: PreTrainedTokenizerBase,
|
|
1165
|
+
max_prompt_length: Optional[int] = None,
|
|
1166
|
+
max_completion_length: Optional[int] = None,
|
|
1167
|
+
add_special_tokens: bool = True,
|
|
1168
|
+
) -> dict[str, list[int]]:
|
|
1169
|
+
"""
|
|
1170
|
+
Tokenize a row of the dataset.
|
|
1171
|
+
|
|
1172
|
+
Args:
|
|
1173
|
+
features (`dict[str, str]`):
|
|
1174
|
+
Row of the dataset, should contain the keys `"prompt"`, `"chosen"`, and `"rejected"`.
|
|
1175
|
+
processing_class ([`~transformers.PreTrainedTokenizerBase`]):
|
|
1176
|
+
Processing class used to process the data.
|
|
1177
|
+
max_prompt_length (`int` or `None`):
|
|
1178
|
+
Maximum length of the prompt sequence. If `None`, the prompt sequence is not truncated.
|
|
1179
|
+
max_completion_length (`int` or `None`):
|
|
1180
|
+
Maximum length of the completion sequences. If `None`, the completion sequences are not truncated.
|
|
1181
|
+
add_special_tokens (`bool`):
|
|
1182
|
+
Whether to add special tokens to the sequences. Typically used for encoder-decoder models. If `True`,
|
|
1183
|
+
the prompt sequence will have a bos token prepended and an eos token appended. In any case, the
|
|
1184
|
+
completion sequences will have an eos token appended.
|
|
1185
|
+
|
|
1186
|
+
Returns:
|
|
1187
|
+
`dict[str, list[int]]`:
|
|
1188
|
+
Tokenized sequences with the keys `"prompt_input_ids"`, `"chosen_input_ids"`, and
|
|
1189
|
+
`"rejected_input_ids".
|
|
1190
|
+
|
|
1191
|
+
Example:
|
|
1192
|
+
```python
|
|
1193
|
+
>>> from transformers import GPT2Tokenizer
|
|
1194
|
+
|
|
1195
|
+
>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
|
|
1196
|
+
>>> features = {"prompt": "The sky is", "chosen": " blue", "rejected": " green"}
|
|
1197
|
+
>>> DPOTrainer.tokenize_row(
|
|
1198
|
+
... features, tokenizer, max_prompt_length=3, max_completion_length=3, add_special_tokens=False
|
|
1199
|
+
... )
|
|
1200
|
+
{'prompt_input_ids': [464, 6766, 318], 'chosen_input_ids': [4171, 50256], 'rejected_input_ids': [4077, 50256]}
|
|
1201
|
+
```
|
|
1202
|
+
"""
|
|
1203
|
+
tokenizer = processing_class # the processing class is a tokenizer
|
|
1204
|
+
prompt_input_ids = tokenizer(features["prompt"], add_special_tokens=False)["input_ids"]
|
|
1205
|
+
chosen_input_ids = tokenizer(features["chosen"], add_special_tokens=False)["input_ids"]
|
|
1206
|
+
rejected_input_ids = tokenizer(features["rejected"], add_special_tokens=False)["input_ids"]
|
|
1207
|
+
|
|
1208
|
+
# Add special tokens (typically for encoder-decoder models)
|
|
1209
|
+
if add_special_tokens:
|
|
1210
|
+
if tokenizer.bos_token_id is not None:
|
|
1211
|
+
prompt_input_ids = [tokenizer.bos_token_id] + prompt_input_ids
|
|
1212
|
+
if tokenizer.eos_token_id is not None:
|
|
1213
|
+
prompt_input_ids = prompt_input_ids + [tokenizer.eos_token_id]
|
|
1214
|
+
chosen_input_ids = chosen_input_ids + [tokenizer.eos_token_id]
|
|
1215
|
+
rejected_input_ids = rejected_input_ids + [tokenizer.eos_token_id]
|
|
1216
|
+
|
|
1217
|
+
# Truncate prompt and completion sequences
|
|
1218
|
+
if max_prompt_length is not None:
|
|
1219
|
+
prompt_input_ids = prompt_input_ids[-max_prompt_length:]
|
|
1220
|
+
if max_completion_length is not None:
|
|
1221
|
+
chosen_input_ids = chosen_input_ids[:max_completion_length]
|
|
1222
|
+
rejected_input_ids = rejected_input_ids[:max_completion_length]
|
|
1223
|
+
|
|
1224
|
+
return {
|
|
1225
|
+
"prompt_input_ids": prompt_input_ids,
|
|
1226
|
+
"chosen_input_ids": chosen_input_ids,
|
|
1227
|
+
"rejected_input_ids": rejected_input_ids,
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
@staticmethod
|
|
1231
|
+
def process_row(
|
|
1232
|
+
features: dict[str, str],
|
|
1233
|
+
processing_class: PreTrainedTokenizerBase,
|
|
1234
|
+
max_prompt_length: Optional[int] = None,
|
|
1235
|
+
max_completion_length: Optional[int] = None,
|
|
1236
|
+
add_special_tokens: bool = True,
|
|
1237
|
+
) -> dict[str, list[int]]:
|
|
1238
|
+
"""
|
|
1239
|
+
Same as `tokenize_row` but for vision models. Please refer to `tokenize_row` for more information.
|
|
1240
|
+
"""
|
|
1241
|
+
processor, tokenizer = processing_class, processing_class.tokenizer # the processing class is a processor
|
|
1242
|
+
processed_features = processor(images=features["images"], text=features["prompt"], add_special_tokens=False)
|
|
1243
|
+
|
|
1244
|
+
prompt_input_ids = processed_features["input_ids"][0]
|
|
1245
|
+
pixel_values = processed_features["pixel_values"][0]
|
|
1246
|
+
chosen_input_ids = tokenizer(features["chosen"], add_special_tokens=False)["input_ids"]
|
|
1247
|
+
rejected_input_ids = tokenizer(features["rejected"], add_special_tokens=False)["input_ids"]
|
|
1248
|
+
|
|
1249
|
+
# Add special tokens (typically for encoder-decoder models)
|
|
1250
|
+
if add_special_tokens:
|
|
1251
|
+
if tokenizer.bos_token_id is not None:
|
|
1252
|
+
prompt_input_ids = [tokenizer.bos_token_id] + prompt_input_ids
|
|
1253
|
+
if tokenizer.eos_token_id is not None:
|
|
1254
|
+
prompt_input_ids = prompt_input_ids + [tokenizer.eos_token_id]
|
|
1255
|
+
chosen_input_ids = chosen_input_ids + [tokenizer.eos_token_id]
|
|
1256
|
+
rejected_input_ids = rejected_input_ids + [tokenizer.eos_token_id]
|
|
1257
|
+
|
|
1258
|
+
# Truncate prompt and completion sequences
|
|
1259
|
+
if max_prompt_length is not None:
|
|
1260
|
+
prompt_input_ids = prompt_input_ids[-max_prompt_length:]
|
|
1261
|
+
if max_completion_length is not None:
|
|
1262
|
+
chosen_input_ids = chosen_input_ids[:max_completion_length]
|
|
1263
|
+
rejected_input_ids = rejected_input_ids[:max_completion_length]
|
|
1264
|
+
|
|
1265
|
+
output = {
|
|
1266
|
+
"prompt_input_ids": prompt_input_ids,
|
|
1267
|
+
"pixel_values": pixel_values,
|
|
1268
|
+
"chosen_input_ids": chosen_input_ids,
|
|
1269
|
+
"rejected_input_ids": rejected_input_ids,
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
if "pixel_attention_mask" in processed_features:
|
|
1273
|
+
output["pixel_attention_mask"] = processed_features["pixel_attention_mask"][0]
|
|
1274
|
+
if "image_sizes" in processed_features:
|
|
1275
|
+
output["image_sizes"] = processed_features["image_sizes"][0]
|
|
1276
|
+
if "token_type_ids" in processed_features:
|
|
1277
|
+
output["token_type_ids"] = processed_features["token_type_ids"][0]
|
|
1278
|
+
|
|
1279
|
+
return output
|
|
1280
|
+
|
|
1281
|
+
def _set_signature_columns_if_needed(self):
|
|
1282
|
+
# If `self.args.remove_unused_columns` is True, non-signature columns are removed.
|
|
1283
|
+
# By default, this method sets `self._signature_columns` to the model's expected inputs.
|
|
1284
|
+
# In DPOTrainer, we preprocess data, so using the model's signature columns doesn't work.
|
|
1285
|
+
# Instead, we set them to the columns expected by `DataCollatorForPreference`, hence the override.
|
|
1286
|
+
if self._signature_columns is None:
|
|
1287
|
+
self._signature_columns = [
|
|
1288
|
+
"prompt_input_ids",
|
|
1289
|
+
"chosen_input_ids",
|
|
1290
|
+
"rejected_input_ids",
|
|
1291
|
+
"image_sizes",
|
|
1292
|
+
"token_type_ids",
|
|
1293
|
+
"ref_chosen_logps",
|
|
1294
|
+
"ref_rejected_logps",
|
|
1295
|
+
]
|
|
1296
|
+
|
|
1297
|
+
def get_train_dataloader(self) -> DataLoader:
|
|
1298
|
+
"""
|
|
1299
|
+
Returns the training [`~torch.utils.data.DataLoader`].
|
|
1300
|
+
|
|
1301
|
+
Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`.
|
|
1302
|
+
"""
|
|
1303
|
+
|
|
1304
|
+
if self.precompute_ref_log_probs and not self._precomputed_train_ref_log_probs:
|
|
1305
|
+
batch_size = self.args.precompute_ref_batch_size or self.args.per_device_train_batch_size
|
|
1306
|
+
dataloader_params = {
|
|
1307
|
+
"batch_size": batch_size,
|
|
1308
|
+
"collate_fn": self.data_collator,
|
|
1309
|
+
"num_workers": self.args.dataloader_num_workers,
|
|
1310
|
+
"pin_memory": self.args.dataloader_pin_memory,
|
|
1311
|
+
"shuffle": False,
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
# prepare dataloader
|
|
1315
|
+
data_loader = self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params))
|
|
1316
|
+
|
|
1317
|
+
ref_chosen_logps = []
|
|
1318
|
+
ref_rejected_logps = []
|
|
1319
|
+
for padded_batch in tqdm(iterable=data_loader, desc="Train dataset reference log probs"):
|
|
1320
|
+
ref_chosen_logp, ref_rejected_logp = self.compute_ref_log_probs(padded_batch)
|
|
1321
|
+
ref_chosen_logp, ref_rejected_logp = self.accelerator.gather_for_metrics(
|
|
1322
|
+
(ref_chosen_logp, ref_rejected_logp)
|
|
1323
|
+
)
|
|
1324
|
+
ref_chosen_logps.append(ref_chosen_logp.cpu())
|
|
1325
|
+
ref_rejected_logps.append(ref_rejected_logp.cpu())
|
|
1326
|
+
|
|
1327
|
+
# Unnecessary cache clearing to avoid OOM
|
|
1328
|
+
empty_cache()
|
|
1329
|
+
self.accelerator.free_memory()
|
|
1330
|
+
|
|
1331
|
+
all_ref_chosen_logps = torch.cat(ref_chosen_logps).float().numpy()
|
|
1332
|
+
all_ref_rejected_logps = torch.cat(ref_rejected_logps).float().numpy()
|
|
1333
|
+
|
|
1334
|
+
self.train_dataset = self.train_dataset.add_column(name="ref_chosen_logps", column=all_ref_chosen_logps)
|
|
1335
|
+
self.train_dataset = self.train_dataset.add_column(
|
|
1336
|
+
name="ref_rejected_logps", column=all_ref_rejected_logps
|
|
1337
|
+
)
|
|
1338
|
+
|
|
1339
|
+
self._precomputed_train_ref_log_probs = True
|
|
1340
|
+
|
|
1341
|
+
return super().get_train_dataloader()
|
|
1342
|
+
|
|
1343
|
+
def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader:
|
|
1344
|
+
"""
|
|
1345
|
+
Returns the evaluation [`~torch.utils.data.DataLoader`].
|
|
1346
|
+
|
|
1347
|
+
Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`.
|
|
1348
|
+
|
|
1349
|
+
Args:
|
|
1350
|
+
eval_dataset (`torch.utils.data.Dataset`, *optional*):
|
|
1351
|
+
If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted
|
|
1352
|
+
by the `model.forward()` method are automatically removed. It must implement `__len__`.
|
|
1353
|
+
"""
|
|
1354
|
+
if eval_dataset is None and self.eval_dataset is None:
|
|
1355
|
+
raise ValueError("Trainer: evaluation requires an eval_dataset.")
|
|
1356
|
+
eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset
|
|
1357
|
+
|
|
1358
|
+
if self.precompute_ref_log_probs and not self._precomputed_eval_ref_log_probs:
|
|
1359
|
+
batch_size = self.args.precompute_ref_batch_size or self.args.per_device_eval_batch_size
|
|
1360
|
+
dataloader_params = {
|
|
1361
|
+
"batch_size": batch_size,
|
|
1362
|
+
"collate_fn": self.data_collator,
|
|
1363
|
+
"num_workers": self.args.dataloader_num_workers,
|
|
1364
|
+
"pin_memory": self.args.dataloader_pin_memory,
|
|
1365
|
+
"shuffle": False,
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
# prepare dataloader
|
|
1369
|
+
data_loader = self.accelerator.prepare(DataLoader(eval_dataset, **dataloader_params))
|
|
1370
|
+
|
|
1371
|
+
ref_chosen_logps = []
|
|
1372
|
+
ref_rejected_logps = []
|
|
1373
|
+
for padded_batch in tqdm(iterable=data_loader, desc="Eval dataset reference log probs"):
|
|
1374
|
+
ref_chosen_logp, ref_rejected_logp = self.compute_ref_log_probs(padded_batch)
|
|
1375
|
+
ref_chosen_logp, ref_rejected_logp = self.accelerator.gather_for_metrics(
|
|
1376
|
+
(ref_chosen_logp, ref_rejected_logp)
|
|
1377
|
+
)
|
|
1378
|
+
ref_chosen_logps.append(ref_chosen_logp.cpu())
|
|
1379
|
+
ref_rejected_logps.append(ref_rejected_logp.cpu())
|
|
1380
|
+
|
|
1381
|
+
all_ref_chosen_logps = torch.cat(ref_chosen_logps).float().numpy()
|
|
1382
|
+
all_ref_rejected_logps = torch.cat(ref_rejected_logps).float().numpy()
|
|
1383
|
+
|
|
1384
|
+
eval_dataset = eval_dataset.add_column(name="ref_chosen_logps", column=all_ref_chosen_logps)
|
|
1385
|
+
eval_dataset = eval_dataset.add_column(name="ref_rejected_logps", column=all_ref_rejected_logps)
|
|
1386
|
+
|
|
1387
|
+
# Save calculated ref_chosen_logps and ref_rejected_logps to the eval_dataset for subsequent runs
|
|
1388
|
+
if self.eval_dataset is not None:
|
|
1389
|
+
self.eval_dataset = eval_dataset
|
|
1390
|
+
self._precomputed_eval_ref_log_probs = True
|
|
1391
|
+
|
|
1392
|
+
return super().get_eval_dataloader(eval_dataset=eval_dataset)
|
|
1393
|
+
|
|
1394
|
+
@contextmanager
|
|
1395
|
+
def null_ref_context(self):
|
|
1396
|
+
"""Context manager for handling null reference model (that is, peft adapter manipulation)."""
|
|
1397
|
+
with (
|
|
1398
|
+
self.accelerator.unwrap_model(self.model).disable_adapter()
|
|
1399
|
+
if self.is_peft_model and not self.ref_adapter_name
|
|
1400
|
+
else nullcontext()
|
|
1401
|
+
):
|
|
1402
|
+
if self.ref_adapter_name:
|
|
1403
|
+
self.model.set_adapter(self.ref_adapter_name)
|
|
1404
|
+
yield
|
|
1405
|
+
if self.ref_adapter_name:
|
|
1406
|
+
self.model.set_adapter(self.model_adapter_name or "default")
|
|
1407
|
+
|
|
1408
|
+
def compute_ref_log_probs(self, batch: dict[str, torch.LongTensor]) -> tuple[torch.Tensor, torch.Tensor]:
|
|
1409
|
+
"""Computes log probabilities of the reference model for a single padded batch of a DPO specific dataset."""
|
|
1410
|
+
compte_ref_context_manager = (
|
|
1411
|
+
autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
|
|
1412
|
+
)
|
|
1413
|
+
with torch.no_grad(), compte_ref_context_manager:
|
|
1414
|
+
if self.ref_model is None:
|
|
1415
|
+
with self.null_ref_context():
|
|
1416
|
+
ref_model_output = self.concatenated_forward(self.model, batch, is_ref_model=True)
|
|
1417
|
+
else:
|
|
1418
|
+
ref_model_output = self.concatenated_forward(self.ref_model, batch, is_ref_model=True)
|
|
1419
|
+
return ref_model_output["chosen_logps"], ref_model_output["rejected_logps"]
|
|
1420
|
+
|
|
1421
|
+
@staticmethod
|
|
1422
|
+
def concatenated_inputs(
|
|
1423
|
+
batch: dict[str, Union[list, torch.LongTensor]], padding_value: int
|
|
1424
|
+
) -> dict[str, torch.LongTensor]:
|
|
1425
|
+
"""
|
|
1426
|
+
Concatenate the `chosen` and `rejected` inputs from the batch into a single tensor for both the prompt and
|
|
1427
|
+
completion sequences.
|
|
1428
|
+
|
|
1429
|
+
Args:
|
|
1430
|
+
batch (`dict[str, Union[list, torch.LongTensor]]`):
|
|
1431
|
+
A batch of input data. The batch must contain the following keys:
|
|
1432
|
+
|
|
1433
|
+
- `"prompt_input_ids"`: Tensor of shape `(batch_size, prompt_length)` representing the prompt input
|
|
1434
|
+
IDs.
|
|
1435
|
+
- `"chosen_input_ids"`: Tensor of shape `(batch_size, chosen_length)` representing the chosen
|
|
1436
|
+
completion input IDs.
|
|
1437
|
+
- `"rejected_input_ids"`: Tensor of shape `(batch_size, rejected_length)` representing the rejected
|
|
1438
|
+
completion input IDs.
|
|
1439
|
+
- `"prompt_pixel_values"` (optional): Tensor for pixel values, if available.
|
|
1440
|
+
- `"prompt_pixel_attention_mask"` (optional): Tensor for pixel attention masks, if available.
|
|
1441
|
+
|
|
1442
|
+
padding_value (`int`):
|
|
1443
|
+
The padding value to use for the concatenated completion sequences (`chosen_input_ids` and
|
|
1444
|
+
`rejected_input_ids`).
|
|
1445
|
+
|
|
1446
|
+
Returns:
|
|
1447
|
+
`dict[str, torch.LongTensor]`: A dictionary containing:
|
|
1448
|
+
|
|
1449
|
+
- `"prompt_input_ids"`: Concatenated prompt input IDs of shape `(2 * batch_size, prompt_length)`.
|
|
1450
|
+
- `"completion_input_ids"`: Concatenated chosen and rejected completion input IDs of shape `(2 *
|
|
1451
|
+
batch_size, max_completion_length)`.
|
|
1452
|
+
- `"prompt_attention_mask"`: Concatenated prompt attention masks of shape `(2 * batch_size,
|
|
1453
|
+
prompt_length)`.
|
|
1454
|
+
- `"completion_attention_mask"`: Concatenated chosen and rejected attention masks of shape `(2 *
|
|
1455
|
+
batch_size, max_completion_length)`.
|
|
1456
|
+
- `"pixel_values"` (optional): Concatenated pixel values if `"prompt_pixel_values"` are present.
|
|
1457
|
+
- `"pixel_attention_mask"` (optional): Concatenated pixel attention masks if
|
|
1458
|
+
`"prompt_pixel_attention_mask"` are present.
|
|
1459
|
+
|
|
1460
|
+
Notes:
|
|
1461
|
+
The completion input IDs and attention masks are padded to the maximum completion length of the chosen or
|
|
1462
|
+
rejected sequences.
|
|
1463
|
+
"""
|
|
1464
|
+
output = {}
|
|
1465
|
+
|
|
1466
|
+
# For the prompt, the input_ids are the same for both the chosen and rejected responses
|
|
1467
|
+
output["prompt_input_ids"] = torch.cat([batch["prompt_input_ids"], batch["prompt_input_ids"]], dim=0)
|
|
1468
|
+
output["prompt_attention_mask"] = torch.cat(
|
|
1469
|
+
[batch["prompt_attention_mask"], batch["prompt_attention_mask"]], dim=0
|
|
1470
|
+
)
|
|
1471
|
+
if "pixel_values" in batch:
|
|
1472
|
+
output["pixel_values"] = torch.cat([batch["pixel_values"], batch["pixel_values"]], dim=0)
|
|
1473
|
+
|
|
1474
|
+
if "pixel_attention_mask" in batch:
|
|
1475
|
+
output["pixel_attention_mask"] = torch.cat(
|
|
1476
|
+
[batch["pixel_attention_mask"], batch["pixel_attention_mask"]], dim=0
|
|
1477
|
+
)
|
|
1478
|
+
if "image_sizes" in batch:
|
|
1479
|
+
output["image_sizes"] = torch.cat([batch["image_sizes"], batch["image_sizes"]], dim=0)
|
|
1480
|
+
if "token_type_ids" in batch:
|
|
1481
|
+
output["token_type_ids"] = torch.cat((batch["token_type_ids"], batch["token_type_ids"]))
|
|
1482
|
+
|
|
1483
|
+
# Concatenate the chosen and rejected completions
|
|
1484
|
+
max_completion_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1])
|
|
1485
|
+
output["completion_input_ids"] = torch.cat(
|
|
1486
|
+
(
|
|
1487
|
+
pad_to_length(batch["chosen_input_ids"], max_completion_length, pad_value=padding_value),
|
|
1488
|
+
pad_to_length(batch["rejected_input_ids"], max_completion_length, pad_value=padding_value),
|
|
1489
|
+
),
|
|
1490
|
+
)
|
|
1491
|
+
output["completion_attention_mask"] = torch.cat(
|
|
1492
|
+
(
|
|
1493
|
+
pad_to_length(batch["chosen_attention_mask"], max_completion_length, pad_value=0),
|
|
1494
|
+
pad_to_length(batch["rejected_attention_mask"], max_completion_length, pad_value=0),
|
|
1495
|
+
),
|
|
1496
|
+
)
|
|
1497
|
+
|
|
1498
|
+
return output
|
|
1499
|
+
|
|
1500
|
+
def dpo_loss(
|
|
1501
|
+
self,
|
|
1502
|
+
chosen_logps: torch.FloatTensor,
|
|
1503
|
+
rejected_logps: torch.FloatTensor,
|
|
1504
|
+
ref_chosen_logps: torch.FloatTensor,
|
|
1505
|
+
ref_rejected_logps: torch.FloatTensor,
|
|
1506
|
+
loss_type: str = "sigmoid",
|
|
1507
|
+
model_output: dict[str, torch.FloatTensor] = None,
|
|
1508
|
+
) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
|
|
1509
|
+
"""
|
|
1510
|
+
Compute the DPO loss for a batch of policy and reference model log probabilities.
|
|
1511
|
+
|
|
1512
|
+
Args:
|
|
1513
|
+
chosen_logps (`torch.FloatTensor`):
|
|
1514
|
+
Log probabilities of the model for the chosen responses. Shape: `(batch_size,)`.
|
|
1515
|
+
rejected_logps (`torch.FloatTensor`):
|
|
1516
|
+
Log probabilities of the model for the rejected responses. Shape: `(batch_size,)`.
|
|
1517
|
+
ref_chosen_logps (`torch.FloatTensor`):
|
|
1518
|
+
Log probabilities of the reference model for the chosen responses. Shape: `(batch_size,)`.
|
|
1519
|
+
ref_rejected_logps (`torch.FloatTensor`):
|
|
1520
|
+
Log probabilities of the reference model for the rejected responses. Shape: `(batch_size,)`.
|
|
1521
|
+
loss_type (`str`, defaults to `"sigmoid"`):
|
|
1522
|
+
The type of loss to compute. One of:
|
|
1523
|
+
- `"sigmoid"`: Sigmoid loss from the original [DPO](https://huggingface.co/papers/2305.18290) paper.
|
|
1524
|
+
- `"hinge"`: Hinge loss on the normalized likelihood from the
|
|
1525
|
+
[SLiC](https://huggingface.co/papers/2305.10425) paper.
|
|
1526
|
+
- `"ipo"`: IPO loss from the [IPO](https://huggingface.co/papers/2310.12036) paper.
|
|
1527
|
+
- `"exo_pair"`: Pairwise EXO loss from the [EXO](https://huggingface.co/papers/2402.00856) paper.
|
|
1528
|
+
- `"nca_pair"`: Pairwise NCA loss from the [NCA](https://huggingface.co/papers/2402.05369) paper.
|
|
1529
|
+
- `"robust"`: Unbiased estimate of the DPO loss that is robust to preference noise from the [Robust
|
|
1530
|
+
DPO](https://huggingface.co/papers/2403.00409) paper.
|
|
1531
|
+
- `"bco_pair"`: Pairwise BCO loss from the [BCO](https://huggingface.co/papers/2404.04656) paper.
|
|
1532
|
+
- `"sppo_hard"`: SPPO loss with hard label from the [SPPO](https://huggingface.co/papers/2405.00675)
|
|
1533
|
+
paper.
|
|
1534
|
+
- `"aot"`: AOT loss for paired datasets from the [AOT](https://huggingface.co/papers/2406.05882) paper.
|
|
1535
|
+
- `"aot_pair"`: AOT loss for unpaired datasets from the [AOT](https://huggingface.co/papers/2406.05882)
|
|
1536
|
+
paper.
|
|
1537
|
+
- `"discopop"`: DiscoPOP (a.k.a Log-Ratio Modulated Loss, LRML) loss from the
|
|
1538
|
+
[DiscoPOP](https://huggingface.co/papers/2406.08414) paper.
|
|
1539
|
+
- `"apo_zero"`: APO-zero loss from the [APO](https://huggingface.co/papers/2408.06266) paper.
|
|
1540
|
+
- `"apo_down"`: APO-down loss from the [APO](https://huggingface.co/papers/2408.06266) paper.
|
|
1541
|
+
- `"sft"`: Negative log-likelihood loss (standard supervised fine-tuning loss).
|
|
1542
|
+
model_output (`dict[str, torch.FloatTensor]`, *optional*):
|
|
1543
|
+
The output of the model's forward pass. This is used to compute auxiliary losses if enabled.
|
|
1544
|
+
|
|
1545
|
+
Returns:
|
|
1546
|
+
A tuple of three tensors: `(losses, chosen_rewards, rejected_rewards)`. The losses tensor contains the DPO
|
|
1547
|
+
loss for each example in the batch. The `chosen_rewards` and `rejected_rewards` tensors contain the rewards
|
|
1548
|
+
for the chosen and rejected responses, respectively.
|
|
1549
|
+
"""
|
|
1550
|
+
device = self.accelerator.device
|
|
1551
|
+
|
|
1552
|
+
# Get the log ratios for the chosen and rejected responses
|
|
1553
|
+
chosen_logratios = chosen_logps.to(device) - (not self.reference_free) * ref_chosen_logps.to(device)
|
|
1554
|
+
rejected_logratios = rejected_logps.to(device) - (not self.reference_free) * ref_rejected_logps.to(device)
|
|
1555
|
+
|
|
1556
|
+
if self.f_divergence_type == FDivergenceType.ALPHA_DIVERGENCE:
|
|
1557
|
+
# The alpha-divergence formula: (1 - u^-alpha) / alpha
|
|
1558
|
+
# The divergence difference between the chosen and rejected sample is:
|
|
1559
|
+
# (1 - u[w]^-alpha) / alpha - (1 - u[l]^-alpha) / alpha
|
|
1560
|
+
# = (u[l]^-alpha - u[w]^-alpha) / alpha
|
|
1561
|
+
# where u[w] and u[l] are the policy/reference probability ratios
|
|
1562
|
+
# for the chosen and rejected samples, respectively.
|
|
1563
|
+
alpha_coef = FDivergenceConstants.ALPHA_DIVERGENCE_COEF_DEFAULT
|
|
1564
|
+
if self.f_divergence_params and FDivergenceConstants.ALPHA_DIVERGENCE_COEF_KEY in self.f_divergence_params:
|
|
1565
|
+
alpha_coef = float(self.f_divergence_params[FDivergenceConstants.ALPHA_DIVERGENCE_COEF_KEY])
|
|
1566
|
+
logits = (cap_exp(rejected_logratios * -alpha_coef) - cap_exp(chosen_logratios * -alpha_coef)) / alpha_coef
|
|
1567
|
+
else:
|
|
1568
|
+
logratios = chosen_logps - rejected_logps
|
|
1569
|
+
if self.reference_free:
|
|
1570
|
+
ref_logratios = torch.tensor([0], dtype=logratios.dtype, device=logratios.device)
|
|
1571
|
+
else:
|
|
1572
|
+
ref_logratios = ref_chosen_logps - ref_rejected_logps
|
|
1573
|
+
|
|
1574
|
+
logratios = logratios.to(self.accelerator.device)
|
|
1575
|
+
ref_logratios = ref_logratios.to(self.accelerator.device)
|
|
1576
|
+
logits = logratios - ref_logratios
|
|
1577
|
+
|
|
1578
|
+
if self.f_divergence_type == FDivergenceType.JS_DIVERGENCE:
|
|
1579
|
+
# The js-divergence formula: log(2 * u / (1 + u))
|
|
1580
|
+
# The divergence difference between the chosen and rejected sample is:
|
|
1581
|
+
# log(2 * u[w] / (1 + u[w])) - log(2 * u[l] / (1 + u[l]))
|
|
1582
|
+
# = log(u[w]) - log(u[l]) - (log(1 + u[w]) - log(1 + u[l]))
|
|
1583
|
+
# where u[w] and u[l] are the policy/reference probability ratios
|
|
1584
|
+
# for the chosen and rejected samples, respectively.
|
|
1585
|
+
logits -= F.softplus(chosen_logratios) - F.softplus(rejected_logratios)
|
|
1586
|
+
|
|
1587
|
+
# The beta is a temperature parameter for the DPO loss, typically something in the range of 0.1 to 0.5.
|
|
1588
|
+
# We ignore the reference model as beta -> 0. The label_smoothing parameter encodes our uncertainty about the
|
|
1589
|
+
# labels and calculates a conservative DPO loss.
|
|
1590
|
+
if loss_type == "sigmoid":
|
|
1591
|
+
losses = (
|
|
1592
|
+
-F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing)
|
|
1593
|
+
- F.logsigmoid(-self.beta * logits) * self.label_smoothing
|
|
1594
|
+
)
|
|
1595
|
+
|
|
1596
|
+
elif loss_type == "robust":
|
|
1597
|
+
losses = (
|
|
1598
|
+
-F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing)
|
|
1599
|
+
+ F.logsigmoid(-self.beta * logits) * self.label_smoothing
|
|
1600
|
+
) / (1 - 2 * self.label_smoothing)
|
|
1601
|
+
|
|
1602
|
+
elif loss_type == "exo_pair":
|
|
1603
|
+
# eqn (16) of the EXO paper: https://huggingface.co/papers/2402.00856
|
|
1604
|
+
import math
|
|
1605
|
+
|
|
1606
|
+
if self.label_smoothing == 0:
|
|
1607
|
+
self.label_smoothing = 1e-3
|
|
1608
|
+
losses = (self.beta * logits).sigmoid() * (
|
|
1609
|
+
F.logsigmoid(self.beta * logits) - math.log(1 - self.label_smoothing)
|
|
1610
|
+
) + (-self.beta * logits).sigmoid() * (F.logsigmoid(-self.beta * logits) - math.log(self.label_smoothing))
|
|
1611
|
+
|
|
1612
|
+
elif loss_type == "hinge":
|
|
1613
|
+
losses = torch.relu(1 - self.beta * logits)
|
|
1614
|
+
|
|
1615
|
+
elif loss_type == "ipo":
|
|
1616
|
+
# eqn (17) of the paper where beta is the regularization parameter for the IPO loss, denoted by tau in the paper.
|
|
1617
|
+
losses = (logits - 1 / (2 * self.beta)) ** 2
|
|
1618
|
+
|
|
1619
|
+
elif loss_type == "bco_pair":
|
|
1620
|
+
chosen_logratios = chosen_logps - ref_chosen_logps
|
|
1621
|
+
rejected_logratios = rejected_logps - ref_rejected_logps
|
|
1622
|
+
chosen_rewards = self.beta * chosen_logratios
|
|
1623
|
+
rejected_rewards = self.beta * rejected_logratios
|
|
1624
|
+
rewards = torch.cat((chosen_rewards, rejected_rewards), 0).mean().detach()
|
|
1625
|
+
self.running.update(rewards)
|
|
1626
|
+
delta = self.running.mean
|
|
1627
|
+
losses = -F.logsigmoid((self.beta * chosen_logratios) - delta) - F.logsigmoid(
|
|
1628
|
+
-(self.beta * rejected_logratios - delta)
|
|
1629
|
+
)
|
|
1630
|
+
|
|
1631
|
+
elif loss_type == "sppo_hard":
|
|
1632
|
+
# In the paper (https://huggingface.co/papers/2405.00675), SPPO employs a soft probability approach,
|
|
1633
|
+
# estimated using the PairRM score. The probability calculation is conducted outside of the trainer class.
|
|
1634
|
+
# The version described here is the hard probability version, where P in Equation (4.7) of Algorithm 1 is
|
|
1635
|
+
# set to 1 for the winner and 0 for the loser.
|
|
1636
|
+
a = chosen_logps - ref_chosen_logps
|
|
1637
|
+
b = rejected_logps - ref_rejected_logps
|
|
1638
|
+
losses = (a - 0.5 / self.beta) ** 2 + (b + 0.5 / self.beta) ** 2
|
|
1639
|
+
|
|
1640
|
+
elif loss_type == "nca_pair":
|
|
1641
|
+
chosen_rewards = (chosen_logps - ref_chosen_logps) * self.beta
|
|
1642
|
+
rejected_rewards = (rejected_logps - ref_rejected_logps) * self.beta
|
|
1643
|
+
losses = (
|
|
1644
|
+
-F.logsigmoid(chosen_rewards)
|
|
1645
|
+
- 0.5 * F.logsigmoid(-chosen_rewards)
|
|
1646
|
+
- 0.5 * F.logsigmoid(-rejected_rewards)
|
|
1647
|
+
)
|
|
1648
|
+
|
|
1649
|
+
elif loss_type == "aot_pair":
|
|
1650
|
+
chosen_logratios = chosen_logps - ref_chosen_logps
|
|
1651
|
+
rejected_logratios = rejected_logps - ref_rejected_logps
|
|
1652
|
+
chosen_logratios_sorted, _ = torch.sort(chosen_logratios, dim=0)
|
|
1653
|
+
rejected_logratios_sorted, _ = torch.sort(rejected_logratios, dim=0)
|
|
1654
|
+
delta = chosen_logratios_sorted - rejected_logratios_sorted
|
|
1655
|
+
losses = (
|
|
1656
|
+
-F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing)
|
|
1657
|
+
- F.logsigmoid(-self.beta * delta) * self.label_smoothing
|
|
1658
|
+
)
|
|
1659
|
+
|
|
1660
|
+
elif loss_type == "aot":
|
|
1661
|
+
logratios = chosen_logps - rejected_logps
|
|
1662
|
+
ref_logratios = ref_chosen_logps - ref_rejected_logps
|
|
1663
|
+
logratios_sorted, _ = torch.sort(logratios, dim=0)
|
|
1664
|
+
ref_logratios_sorted, _ = torch.sort(ref_logratios, dim=0)
|
|
1665
|
+
delta = logratios_sorted - ref_logratios_sorted
|
|
1666
|
+
losses = (
|
|
1667
|
+
-F.logsigmoid(self.beta * delta) * (1 - self.label_smoothing)
|
|
1668
|
+
- F.logsigmoid(-self.beta * delta) * self.label_smoothing
|
|
1669
|
+
)
|
|
1670
|
+
|
|
1671
|
+
elif loss_type == "apo_zero":
|
|
1672
|
+
# Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266)
|
|
1673
|
+
# Use this loss when you believe the chosen outputs are better than your model's default output
|
|
1674
|
+
losses_chosen = 1 - F.sigmoid(self.beta * chosen_logratios) # Increase chosen likelihood
|
|
1675
|
+
losses_rejected = F.sigmoid(self.beta * rejected_logratios) # Decrease rejected likelihood
|
|
1676
|
+
losses = losses_chosen + losses_rejected
|
|
1677
|
+
|
|
1678
|
+
elif loss_type == "apo_down":
|
|
1679
|
+
# Eqn (8) of the APO paper (https://huggingface.co/papers/2408.06266)
|
|
1680
|
+
# Use this loss when you believe the chosen outputs are worse than your model's default output.
|
|
1681
|
+
# Decrease chosen likelihood and decrease rejected likelihood more
|
|
1682
|
+
losses_chosen = F.sigmoid(self.beta * chosen_logratios)
|
|
1683
|
+
losses_rejected = 1 - F.sigmoid(self.beta * (chosen_logratios - rejected_logratios))
|
|
1684
|
+
losses = losses_chosen + losses_rejected
|
|
1685
|
+
|
|
1686
|
+
elif loss_type == "discopop":
|
|
1687
|
+
# Eqn (5) of the DiscoPOP paper (https://huggingface.co/papers/2406.08414)
|
|
1688
|
+
# This loss was discovered with LLM discovery
|
|
1689
|
+
logratios = chosen_logps - rejected_logps
|
|
1690
|
+
ref_logratios = ref_chosen_logps - ref_rejected_logps
|
|
1691
|
+
logits = logratios - ref_logratios
|
|
1692
|
+
logits = logits * self.beta
|
|
1693
|
+
# Modulate the mixing coefficient based on the log ratio magnitudes
|
|
1694
|
+
log_ratio_modulation = torch.sigmoid(logits / self.args.discopop_tau)
|
|
1695
|
+
logistic_component = -F.logsigmoid(logits)
|
|
1696
|
+
exp_component = torch.exp(-logits)
|
|
1697
|
+
# Blend between logistic and exponential component based on log ratio modulation
|
|
1698
|
+
losses = logistic_component * (1 - log_ratio_modulation) + exp_component * log_ratio_modulation
|
|
1699
|
+
|
|
1700
|
+
elif loss_type == "sft":
|
|
1701
|
+
# SFT loss is the negative log likelihood loss on chosen responses
|
|
1702
|
+
# This acts as the generation loss component in MPO
|
|
1703
|
+
sft_loss = model_output["nll_loss"]
|
|
1704
|
+
# Create losses tensor with same shape as other losses (per-sample)
|
|
1705
|
+
batch_size = chosen_logps.shape[0]
|
|
1706
|
+
losses = sft_loss.expand(batch_size)
|
|
1707
|
+
# For SFT, we don't have preference rewards, so use zeros
|
|
1708
|
+
chosen_rewards = torch.zeros_like(chosen_logps)
|
|
1709
|
+
rejected_rewards = torch.zeros_like(rejected_logps)
|
|
1710
|
+
|
|
1711
|
+
else:
|
|
1712
|
+
raise ValueError(
|
|
1713
|
+
f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'exo_pair', "
|
|
1714
|
+
"'nca_pair', 'robust', 'bco_pair', 'sppo_hard', 'aot', 'aot_pair', 'discopop', 'apo_zero', "
|
|
1715
|
+
"'apo_down', 'sft']"
|
|
1716
|
+
)
|
|
1717
|
+
|
|
1718
|
+
chosen_rewards = self.beta * (chosen_logps.to(device) - ref_chosen_logps.to(device)).detach()
|
|
1719
|
+
rejected_rewards = self.beta * (rejected_logps.to(device) - ref_rejected_logps.to(device)).detach()
|
|
1720
|
+
|
|
1721
|
+
return losses, chosen_rewards, rejected_rewards
|
|
1722
|
+
|
|
1723
|
+
def _compute_loss_liger(
|
|
1724
|
+
self, model: nn.Module, batch: dict[str, Union[list, torch.LongTensor]]
|
|
1725
|
+
) -> dict[str, torch.Tensor]:
|
|
1726
|
+
unwrapped_model = self.accelerator.unwrap_model(model)
|
|
1727
|
+
concatenated_batch = self.concatenated_inputs(batch, padding_value=self.pad_token_id)
|
|
1728
|
+
|
|
1729
|
+
model_kwargs = {}
|
|
1730
|
+
if self.aux_loss_enabled:
|
|
1731
|
+
model_kwargs["output_router_logits"] = True
|
|
1732
|
+
|
|
1733
|
+
# Add the pixel values and attention masks for vision models
|
|
1734
|
+
if "pixel_values" in concatenated_batch:
|
|
1735
|
+
model_kwargs["pixel_values"] = concatenated_batch["pixel_values"]
|
|
1736
|
+
if "pixel_attention_mask" in concatenated_batch:
|
|
1737
|
+
model_kwargs["pixel_attention_mask"] = concatenated_batch["pixel_attention_mask"]
|
|
1738
|
+
if "image_sizes" in concatenated_batch:
|
|
1739
|
+
model_kwargs["image_sizes"] = concatenated_batch["image_sizes"]
|
|
1740
|
+
|
|
1741
|
+
prompt_attention_mask = concatenated_batch["prompt_attention_mask"]
|
|
1742
|
+
completion_attention_mask = concatenated_batch["completion_attention_mask"]
|
|
1743
|
+
|
|
1744
|
+
if self.is_encoder_decoder:
|
|
1745
|
+
# 1. Get encoder outputs
|
|
1746
|
+
encoder_outputs = unwrapped_model.get_encoder()(
|
|
1747
|
+
concatenated_batch["prompt_input_ids"],
|
|
1748
|
+
attention_mask=concatenated_batch["prompt_attention_mask"],
|
|
1749
|
+
return_dict=True,
|
|
1750
|
+
)
|
|
1751
|
+
# 2. Prepare decoder inputs
|
|
1752
|
+
decoder_input_ids = shift_tokens_right(
|
|
1753
|
+
concatenated_batch["completion_input_ids"],
|
|
1754
|
+
unwrapped_model.config.decoder_start_token_id,
|
|
1755
|
+
)
|
|
1756
|
+
# 3. Get decoder outputs
|
|
1757
|
+
decoder_outputs = unwrapped_model.get_decoder()(
|
|
1758
|
+
input_ids=decoder_input_ids,
|
|
1759
|
+
attention_mask=concatenated_batch["completion_attention_mask"],
|
|
1760
|
+
encoder_hidden_states=encoder_outputs.last_hidden_state,
|
|
1761
|
+
encoder_attention_mask=concatenated_batch["prompt_attention_mask"],
|
|
1762
|
+
use_cache=False,
|
|
1763
|
+
)
|
|
1764
|
+
hidden_states = decoder_outputs.last_hidden_state
|
|
1765
|
+
|
|
1766
|
+
ref_hidden_states = None
|
|
1767
|
+
if not self.reference_free and self.ref_model is not None:
|
|
1768
|
+
unwrapped_ref_model = self.accelerator.unwrap_model(self.ref_model)
|
|
1769
|
+
ref_encoder_outputs = unwrapped_ref_model.get_encoder()(
|
|
1770
|
+
concatenated_batch["prompt_input_ids"],
|
|
1771
|
+
attention_mask=concatenated_batch["prompt_attention_mask"],
|
|
1772
|
+
return_dict=True,
|
|
1773
|
+
)
|
|
1774
|
+
ref_decoder_outputs = unwrapped_ref_model.get_decoder()(
|
|
1775
|
+
input_ids=decoder_input_ids,
|
|
1776
|
+
attention_mask=concatenated_batch["completion_attention_mask"],
|
|
1777
|
+
encoder_hidden_states=ref_encoder_outputs.last_hidden_state,
|
|
1778
|
+
encoder_attention_mask=concatenated_batch["prompt_attention_mask"],
|
|
1779
|
+
use_cache=False,
|
|
1780
|
+
)
|
|
1781
|
+
ref_hidden_states = ref_decoder_outputs.last_hidden_state
|
|
1782
|
+
elif not self.reference_free:
|
|
1783
|
+
with self.null_ref_context():
|
|
1784
|
+
ref_encoder_outputs = unwrapped_model.get_encoder()(
|
|
1785
|
+
concatenated_batch["prompt_input_ids"],
|
|
1786
|
+
attention_mask=concatenated_batch["prompt_attention_mask"],
|
|
1787
|
+
return_dict=True,
|
|
1788
|
+
)
|
|
1789
|
+
ref_decoder_outputs = unwrapped_model.get_decoder()(
|
|
1790
|
+
input_ids=decoder_input_ids,
|
|
1791
|
+
attention_mask=concatenated_batch["completion_attention_mask"],
|
|
1792
|
+
encoder_hidden_states=ref_encoder_outputs.last_hidden_state,
|
|
1793
|
+
encoder_attention_mask=concatenated_batch["prompt_attention_mask"],
|
|
1794
|
+
use_cache=False,
|
|
1795
|
+
)
|
|
1796
|
+
ref_hidden_states = ref_decoder_outputs.last_hidden_state
|
|
1797
|
+
|
|
1798
|
+
labels = concatenated_batch["completion_input_ids"]
|
|
1799
|
+
loss_mask = completion_attention_mask.bool()
|
|
1800
|
+
else:
|
|
1801
|
+
# For decoder-only models
|
|
1802
|
+
input_ids = torch.cat(
|
|
1803
|
+
(concatenated_batch["prompt_input_ids"], concatenated_batch["completion_input_ids"]), dim=1
|
|
1804
|
+
)
|
|
1805
|
+
attention_mask = torch.cat(
|
|
1806
|
+
(concatenated_batch["prompt_attention_mask"], concatenated_batch["completion_attention_mask"]),
|
|
1807
|
+
dim=1,
|
|
1808
|
+
)
|
|
1809
|
+
# Mask the prompt but not the completion for the loss
|
|
1810
|
+
loss_mask = torch.cat(
|
|
1811
|
+
(torch.zeros_like(prompt_attention_mask), completion_attention_mask),
|
|
1812
|
+
dim=1,
|
|
1813
|
+
)
|
|
1814
|
+
|
|
1815
|
+
# Flush and truncate
|
|
1816
|
+
if self.max_length is not None and self.max_length < attention_mask.size(1):
|
|
1817
|
+
if self.truncation_mode == "keep_start":
|
|
1818
|
+
# Flush left to reduce the memory usage
|
|
1819
|
+
# [[0, 0, x, x, x, x], -> [[x, x, x, x],
|
|
1820
|
+
# [0, x, x, x, 0, 0]] [x, x, x, 0]]
|
|
1821
|
+
attention_mask, input_ids, loss_mask = flush_left(attention_mask, input_ids, loss_mask)
|
|
1822
|
+
attention_mask = attention_mask[:, : self.max_length]
|
|
1823
|
+
input_ids = input_ids[:, : self.max_length]
|
|
1824
|
+
loss_mask = loss_mask[:, : self.max_length]
|
|
1825
|
+
elif self.truncation_mode == "keep_end":
|
|
1826
|
+
# Flush right before truncating left, then flush left
|
|
1827
|
+
# [[0, 0, x, x, x, x], -> [[0, 0, x, x],
|
|
1828
|
+
# [0, x, x, x, 0, 0]] [0, x, x, x]]
|
|
1829
|
+
attention_mask, input_ids, loss_mask = flush_right(attention_mask, input_ids, loss_mask)
|
|
1830
|
+
input_ids = input_ids[:, -self.max_length :]
|
|
1831
|
+
attention_mask = attention_mask[:, -self.max_length :]
|
|
1832
|
+
loss_mask = loss_mask[:, -self.max_length :]
|
|
1833
|
+
attention_mask, input_ids, loss_mask = flush_left(attention_mask, input_ids, loss_mask)
|
|
1834
|
+
else:
|
|
1835
|
+
raise ValueError(
|
|
1836
|
+
f"Unknown truncation mode: '{self.truncation_mode}'. Should be one of ['keep_end', "
|
|
1837
|
+
"'keep_start']."
|
|
1838
|
+
)
|
|
1839
|
+
else:
|
|
1840
|
+
# Flush left to reduce the memory usage
|
|
1841
|
+
# [[0, 0, x, x, x, x], -> [[x, x, x, x],
|
|
1842
|
+
# [0, x, x, x, 0, 0]] [x, x, x, 0]]
|
|
1843
|
+
attention_mask, input_ids, loss_mask = flush_left(attention_mask, input_ids, loss_mask)
|
|
1844
|
+
|
|
1845
|
+
# Add logits_to_keep optimization
|
|
1846
|
+
if self.use_logits_to_keep:
|
|
1847
|
+
first_compute_index = loss_mask.nonzero(as_tuple=True)[1].min()
|
|
1848
|
+
logits_to_keep = (loss_mask.shape[1] - first_compute_index).item() + 1
|
|
1849
|
+
model_kwargs["logits_to_keep"] = logits_to_keep
|
|
1850
|
+
|
|
1851
|
+
model_kwargs["output_hidden_states"] = True
|
|
1852
|
+
|
|
1853
|
+
# Add padding-free training support
|
|
1854
|
+
if self.padding_free:
|
|
1855
|
+
input_ids = input_ids[attention_mask.bool()].unsqueeze(0)
|
|
1856
|
+
loss_mask = loss_mask[attention_mask.bool()].unsqueeze(0)
|
|
1857
|
+
position_ids = attention_mask.cumsum(1)[attention_mask.bool()].unsqueeze(0) - 1
|
|
1858
|
+
model_kwargs["position_ids"] = position_ids
|
|
1859
|
+
else:
|
|
1860
|
+
model_kwargs["attention_mask"] = attention_mask
|
|
1861
|
+
|
|
1862
|
+
# Get the base model outputs (before LM head)
|
|
1863
|
+
if hasattr(unwrapped_model, "get_decoder") and unwrapped_model.get_decoder() is not None:
|
|
1864
|
+
base_model = unwrapped_model.get_decoder()
|
|
1865
|
+
else:
|
|
1866
|
+
base_attr = getattr(unwrapped_model, "base_model_prefix", self.args.base_model_attribute_name)
|
|
1867
|
+
base_model = getattr(unwrapped_model, base_attr, unwrapped_model)
|
|
1868
|
+
|
|
1869
|
+
outputs = base_model(
|
|
1870
|
+
input_ids,
|
|
1871
|
+
use_cache=False,
|
|
1872
|
+
**model_kwargs,
|
|
1873
|
+
)
|
|
1874
|
+
hidden_states = outputs.last_hidden_state[:, :-1]
|
|
1875
|
+
|
|
1876
|
+
# Get reference hidden states if needed
|
|
1877
|
+
ref_hidden_states = None
|
|
1878
|
+
if not self.reference_free and self.ref_model is not None:
|
|
1879
|
+
unwrapped_ref_model = self.accelerator.unwrap_model(self.ref_model)
|
|
1880
|
+
if hasattr(unwrapped_ref_model, "get_decoder") and unwrapped_ref_model.get_decoder() is not None:
|
|
1881
|
+
ref_base_model = unwrapped_ref_model.get_decoder()
|
|
1882
|
+
else:
|
|
1883
|
+
ref_attr = getattr(unwrapped_ref_model, "base_model_prefix", self.args.base_model_attribute_name)
|
|
1884
|
+
ref_base_model = getattr(unwrapped_ref_model, ref_attr, unwrapped_ref_model)
|
|
1885
|
+
|
|
1886
|
+
ref_outputs = ref_base_model(
|
|
1887
|
+
input_ids,
|
|
1888
|
+
use_cache=False,
|
|
1889
|
+
**model_kwargs,
|
|
1890
|
+
)
|
|
1891
|
+
ref_hidden_states = ref_outputs.last_hidden_state[:, :-1]
|
|
1892
|
+
elif not self.reference_free:
|
|
1893
|
+
if hasattr(unwrapped_model, "get_decoder") and unwrapped_model.get_decoder() is not None:
|
|
1894
|
+
ref_base_model = unwrapped_model.get_decoder()
|
|
1895
|
+
else:
|
|
1896
|
+
ref_attr = getattr(unwrapped_model, "base_model_prefix", self.args.base_model_attribute_name)
|
|
1897
|
+
ref_base_model = getattr(unwrapped_model, ref_attr, unwrapped_model)
|
|
1898
|
+
with self.null_ref_context():
|
|
1899
|
+
ref_outputs = ref_base_model(
|
|
1900
|
+
input_ids,
|
|
1901
|
+
use_cache=False,
|
|
1902
|
+
**model_kwargs,
|
|
1903
|
+
)
|
|
1904
|
+
ref_hidden_states = ref_outputs.last_hidden_state[:, :-1]
|
|
1905
|
+
|
|
1906
|
+
masked_input_ids = torch.where(loss_mask != 0, input_ids, self.label_pad_token_id)
|
|
1907
|
+
labels = masked_input_ids[:, 1:] # Shift right for casual LM
|
|
1908
|
+
|
|
1909
|
+
# Get the LM head
|
|
1910
|
+
lm_head = unwrapped_model.get_output_embeddings()
|
|
1911
|
+
|
|
1912
|
+
# Get reference model weights if needed
|
|
1913
|
+
ref_weight = None
|
|
1914
|
+
ref_bias = None
|
|
1915
|
+
if not self.reference_free:
|
|
1916
|
+
if self.ref_model is not None:
|
|
1917
|
+
unwrapped_ref_model = self.accelerator.unwrap_model(self.ref_model)
|
|
1918
|
+
ref_lm_head = unwrapped_ref_model.get_output_embeddings()
|
|
1919
|
+
else:
|
|
1920
|
+
with self.null_ref_context():
|
|
1921
|
+
ref_lm_head = unwrapped_model.get_output_embeddings()
|
|
1922
|
+
ref_weight = ref_lm_head.weight
|
|
1923
|
+
ref_bias = ref_lm_head.bias if hasattr(ref_lm_head, "bias") else None
|
|
1924
|
+
|
|
1925
|
+
# Compute loss using Liger kernel
|
|
1926
|
+
loss_output = self.dpo_loss_fn(
|
|
1927
|
+
lm_head.weight,
|
|
1928
|
+
hidden_states,
|
|
1929
|
+
labels,
|
|
1930
|
+
bias=lm_head.bias if hasattr(lm_head, "bias") else None,
|
|
1931
|
+
ref_input=ref_hidden_states if not self.reference_free else None,
|
|
1932
|
+
ref_weight=ref_weight if not self.reference_free else None,
|
|
1933
|
+
ref_bias=ref_bias if not self.reference_free else None,
|
|
1934
|
+
)
|
|
1935
|
+
(
|
|
1936
|
+
loss,
|
|
1937
|
+
(chosen_logps, rejected_logps, chosen_logits_mean, rejected_logits_mean, nll_loss, *aux_outputs),
|
|
1938
|
+
) = loss_output
|
|
1939
|
+
|
|
1940
|
+
output = {
|
|
1941
|
+
"loss": loss,
|
|
1942
|
+
"chosen_logps": chosen_logps,
|
|
1943
|
+
"rejected_logps": rejected_logps,
|
|
1944
|
+
"mean_chosen_logits": chosen_logits_mean,
|
|
1945
|
+
"mean_rejected_logits": rejected_logits_mean,
|
|
1946
|
+
"nll_loss": nll_loss,
|
|
1947
|
+
"chosen_rewards": aux_outputs[0],
|
|
1948
|
+
"rejected_rewards": aux_outputs[1],
|
|
1949
|
+
}
|
|
1950
|
+
if self.aux_loss_enabled:
|
|
1951
|
+
output["aux_loss"] = outputs.aux_loss
|
|
1952
|
+
|
|
1953
|
+
return output
|
|
1954
|
+
|
|
1955
|
+
def concatenated_forward(
|
|
1956
|
+
self, model: nn.Module, batch: dict[str, Union[list, torch.LongTensor]], is_ref_model: bool = False
|
|
1957
|
+
) -> dict[str, torch.Tensor]:
|
|
1958
|
+
"""
|
|
1959
|
+
Runs the given model on the given batch of inputs, concatenating the chosen and rejected inputs together.
|
|
1960
|
+
|
|
1961
|
+
We do this to avoid doing two forward passes, because it's faster for FSDP.
|
|
1962
|
+
|
|
1963
|
+
Args:
|
|
1964
|
+
model:
|
|
1965
|
+
Model to run the forward pass on.
|
|
1966
|
+
batch:
|
|
1967
|
+
Batch of input data.
|
|
1968
|
+
is_ref_model:
|
|
1969
|
+
Whether this method is being called for the reference model. If `True`, length desensitization is not
|
|
1970
|
+
applied.
|
|
1971
|
+
"""
|
|
1972
|
+
num_examples = batch["prompt_input_ids"].shape[0]
|
|
1973
|
+
|
|
1974
|
+
concatenated_batch = self.concatenated_inputs(batch, padding_value=self.pad_token_id)
|
|
1975
|
+
|
|
1976
|
+
model_kwargs = {"use_cache": False}
|
|
1977
|
+
if self.aux_loss_enabled:
|
|
1978
|
+
model_kwargs["output_router_logits"] = True
|
|
1979
|
+
|
|
1980
|
+
# Add the pixel values and attention masks for vision models
|
|
1981
|
+
if "pixel_values" in concatenated_batch:
|
|
1982
|
+
model_kwargs["pixel_values"] = concatenated_batch["pixel_values"]
|
|
1983
|
+
if "pixel_attention_mask" in concatenated_batch:
|
|
1984
|
+
model_kwargs["pixel_attention_mask"] = concatenated_batch["pixel_attention_mask"]
|
|
1985
|
+
if "image_sizes" in concatenated_batch:
|
|
1986
|
+
model_kwargs["image_sizes"] = concatenated_batch["image_sizes"]
|
|
1987
|
+
|
|
1988
|
+
prompt_input_ids = concatenated_batch["prompt_input_ids"]
|
|
1989
|
+
prompt_attention_mask = concatenated_batch["prompt_attention_mask"]
|
|
1990
|
+
completion_input_ids = concatenated_batch["completion_input_ids"]
|
|
1991
|
+
completion_attention_mask = concatenated_batch["completion_attention_mask"]
|
|
1992
|
+
if self.is_encoder_decoder:
|
|
1993
|
+
labels = completion_input_ids
|
|
1994
|
+
labels[completion_attention_mask == 0] = self.label_pad_token_id
|
|
1995
|
+
outputs = model(
|
|
1996
|
+
input_ids=prompt_input_ids,
|
|
1997
|
+
attention_mask=prompt_attention_mask,
|
|
1998
|
+
labels=labels, # we need the labels for the logits to be returned
|
|
1999
|
+
**model_kwargs,
|
|
2000
|
+
)
|
|
2001
|
+
logits = outputs.logits
|
|
2002
|
+
loss_mask = completion_attention_mask.bool()
|
|
2003
|
+
else:
|
|
2004
|
+
# Concatenate the prompt and completion inputs
|
|
2005
|
+
input_ids = torch.cat((prompt_input_ids, completion_input_ids), dim=1)
|
|
2006
|
+
attention_mask = torch.cat((prompt_attention_mask, completion_attention_mask), dim=1)
|
|
2007
|
+
if "token_type_ids" in concatenated_batch:
|
|
2008
|
+
prompt_token_type_ids = concatenated_batch["token_type_ids"]
|
|
2009
|
+
token_type_ids = pad_to_length(prompt_token_type_ids, input_ids.shape[1], 0)
|
|
2010
|
+
# Mask the prompt but not the completion for the loss
|
|
2011
|
+
loss_mask = torch.cat(
|
|
2012
|
+
(torch.zeros_like(prompt_attention_mask), completion_attention_mask),
|
|
2013
|
+
dim=1,
|
|
2014
|
+
)
|
|
2015
|
+
|
|
2016
|
+
# Flush and truncate
|
|
2017
|
+
if self.max_length is not None and self.max_length < attention_mask.size(1):
|
|
2018
|
+
if self.truncation_mode == "keep_start":
|
|
2019
|
+
# Flush left to reduce the memory usage
|
|
2020
|
+
# [[0, 0, x, x, x, x], -> [[x, x, x, x],
|
|
2021
|
+
# [0, x, x, x, 0, 0]] [x, x, x, 0]]
|
|
2022
|
+
if "token_type_ids" in concatenated_batch:
|
|
2023
|
+
attention_mask, input_ids, loss_mask, token_type_ids = flush_left(
|
|
2024
|
+
attention_mask, input_ids, loss_mask, token_type_ids
|
|
2025
|
+
)
|
|
2026
|
+
else:
|
|
2027
|
+
attention_mask, input_ids, loss_mask = flush_left(attention_mask, input_ids, loss_mask)
|
|
2028
|
+
attention_mask = attention_mask[:, : self.max_length]
|
|
2029
|
+
input_ids = input_ids[:, : self.max_length]
|
|
2030
|
+
loss_mask = loss_mask[:, : self.max_length]
|
|
2031
|
+
elif self.truncation_mode == "keep_end":
|
|
2032
|
+
# Flush right before truncating left, then flush left
|
|
2033
|
+
# [[0, 0, x, x, x, x], -> [[0, 0, x, x],
|
|
2034
|
+
# [0, x, x, x, 0, 0]] [0, x, x, x]]
|
|
2035
|
+
if "token_type_ids" in concatenated_batch:
|
|
2036
|
+
attention_mask, input_ids, loss_mask, token_type_ids = flush_left(
|
|
2037
|
+
attention_mask, input_ids, loss_mask, token_type_ids
|
|
2038
|
+
)
|
|
2039
|
+
token_type_ids = token_type_ids[:, -self.max_length :]
|
|
2040
|
+
else:
|
|
2041
|
+
attention_mask, input_ids, loss_mask = flush_right(attention_mask, input_ids, loss_mask)
|
|
2042
|
+
input_ids = input_ids[:, -self.max_length :]
|
|
2043
|
+
attention_mask = attention_mask[:, -self.max_length :]
|
|
2044
|
+
loss_mask = loss_mask[:, -self.max_length :]
|
|
2045
|
+
if "token_type_ids" in concatenated_batch:
|
|
2046
|
+
attention_mask, input_ids, loss_mask, token_type_ids = flush_left(
|
|
2047
|
+
attention_mask, input_ids, loss_mask, token_type_ids
|
|
2048
|
+
)
|
|
2049
|
+
else:
|
|
2050
|
+
attention_mask, input_ids, loss_mask = flush_left(attention_mask, input_ids, loss_mask)
|
|
2051
|
+
else:
|
|
2052
|
+
raise ValueError(
|
|
2053
|
+
f"Unknown truncation mode: '{self.truncation_mode}'. Should be one of ['keep_end', "
|
|
2054
|
+
"'keep_start']."
|
|
2055
|
+
)
|
|
2056
|
+
else:
|
|
2057
|
+
# Flush left to reduce the memory usage
|
|
2058
|
+
# [[0, 0, x, x, x, x], -> [[x, x, x, x],
|
|
2059
|
+
# [0, x, x, x, 0, 0]] [x, x, x, 0]]
|
|
2060
|
+
if "token_type_ids" in concatenated_batch:
|
|
2061
|
+
attention_mask, input_ids, loss_mask, token_type_ids = flush_left(
|
|
2062
|
+
attention_mask, input_ids, loss_mask, token_type_ids
|
|
2063
|
+
)
|
|
2064
|
+
else:
|
|
2065
|
+
attention_mask, input_ids, loss_mask = flush_left(attention_mask, input_ids, loss_mask)
|
|
2066
|
+
|
|
2067
|
+
if "token_type_ids" in concatenated_batch:
|
|
2068
|
+
model_kwargs["token_type_ids"] = token_type_ids
|
|
2069
|
+
|
|
2070
|
+
if self.use_logits_to_keep:
|
|
2071
|
+
# Compute logits_to_keep based on loss_mask pattern:
|
|
2072
|
+
# [[0, 0, 0, x, x, x, x],
|
|
2073
|
+
# [0, 0, 0, x, x, x, 0]]
|
|
2074
|
+
# ^ start computing logits from here ([:, -(7-3+1):])
|
|
2075
|
+
first_compute_index = loss_mask.nonzero(as_tuple=True)[1].min()
|
|
2076
|
+
logits_to_keep = (loss_mask.shape[1] - first_compute_index).item() + 1 # +1 for the first label
|
|
2077
|
+
model_kwargs["logits_to_keep"] = logits_to_keep
|
|
2078
|
+
|
|
2079
|
+
model_kwargs["output_hidden_states"] = True
|
|
2080
|
+
|
|
2081
|
+
if self.padding_free:
|
|
2082
|
+
# Flatten the input_ids, position_ids, and loss_mask
|
|
2083
|
+
# input_ids = [[a, b, c, 0], -> input_ids = [[a, b, c, d, e, f, g]]
|
|
2084
|
+
# [d, e, f, g]] position_ids = [[0, 1, 2, 0, 1, 2, 3]]
|
|
2085
|
+
input_ids = input_ids[attention_mask.bool()].unsqueeze(0)
|
|
2086
|
+
loss_mask = loss_mask[attention_mask.bool()].unsqueeze(0)
|
|
2087
|
+
position_ids = attention_mask.cumsum(1)[attention_mask.bool()].unsqueeze(0) - 1
|
|
2088
|
+
model_kwargs["position_ids"] = position_ids
|
|
2089
|
+
else:
|
|
2090
|
+
model_kwargs["attention_mask"] = attention_mask
|
|
2091
|
+
|
|
2092
|
+
outputs = model(input_ids, **model_kwargs)
|
|
2093
|
+
logits = outputs.logits
|
|
2094
|
+
|
|
2095
|
+
# Offset the logits by one to align with the labels
|
|
2096
|
+
labels = torch.roll(input_ids, shifts=-1, dims=1)
|
|
2097
|
+
loss_mask = torch.roll(loss_mask, shifts=-1, dims=1).bool()
|
|
2098
|
+
|
|
2099
|
+
if self.use_logits_to_keep:
|
|
2100
|
+
# Align labels with logits
|
|
2101
|
+
# logits: -, -, [x2, x3, x4, x5, x6]
|
|
2102
|
+
# ^ --------- ^ after logits[:, :-1, :]
|
|
2103
|
+
# labels: [y0, y1, y2, y3, y4, y5, y6]
|
|
2104
|
+
# ^ --------- ^ with logits_to_keep=4, [:, -4:]
|
|
2105
|
+
# loss_mask: [0, 0, 0, 1, 1, 1, 1]
|
|
2106
|
+
labels = labels[:, -logits_to_keep:]
|
|
2107
|
+
loss_mask = loss_mask[:, -logits_to_keep:]
|
|
2108
|
+
|
|
2109
|
+
if logits.shape[:2] != labels.shape[:2]:
|
|
2110
|
+
# for LLaVA, the returned logits include the image tokens (placed before the text tokens)
|
|
2111
|
+
seq_len = labels.shape[1]
|
|
2112
|
+
logits = logits[:, -seq_len:]
|
|
2113
|
+
|
|
2114
|
+
# Compute the log probabilities of the labels
|
|
2115
|
+
labels[~loss_mask] = 0 # dummy token; we'll ignore the losses on these tokens later
|
|
2116
|
+
per_token_logps = selective_log_softmax(logits, labels)
|
|
2117
|
+
per_token_logps[~loss_mask] = 0
|
|
2118
|
+
per_token_logps = torch.roll(per_token_logps, shifts=1, dims=1)
|
|
2119
|
+
|
|
2120
|
+
if self.padding_free:
|
|
2121
|
+
# Unflatten the per_token_logps (shape: [1, sum_seq_len] -> [batch_size, seq_len])
|
|
2122
|
+
batch_size, seq_len = attention_mask.shape
|
|
2123
|
+
per_token_logps_ = torch.zeros(
|
|
2124
|
+
batch_size, seq_len, device=outputs.logits.device, dtype=outputs.logits.dtype
|
|
2125
|
+
)
|
|
2126
|
+
per_token_logps_[attention_mask.bool()] = per_token_logps
|
|
2127
|
+
per_token_logps = per_token_logps_
|
|
2128
|
+
|
|
2129
|
+
all_logps = per_token_logps[:, 1:].sum(-1)
|
|
2130
|
+
|
|
2131
|
+
output = {}
|
|
2132
|
+
|
|
2133
|
+
if self.use_weighting:
|
|
2134
|
+
with torch.no_grad():
|
|
2135
|
+
# Eq (2) of the WPO paper: https://huggingface.co/papers/2406.11827
|
|
2136
|
+
logprobs = F.log_softmax(logits, dim=-1)
|
|
2137
|
+
weights_adjustment_factor = torch.logsumexp(2 * logprobs, dim=-1) # same as sum(probs**2) in log space
|
|
2138
|
+
per_token_logps_adjusted = per_token_logps - weights_adjustment_factor
|
|
2139
|
+
all_weights = (per_token_logps_adjusted * loss_mask).sum(-1) / loss_mask.sum(-1)
|
|
2140
|
+
chosen_weights = all_weights[:num_examples]
|
|
2141
|
+
rejected_weights = all_weights[num_examples:]
|
|
2142
|
+
output["policy_weights"] = torch.clamp(torch.exp(chosen_weights + rejected_weights), max=1)
|
|
2143
|
+
|
|
2144
|
+
if self.args.rpo_alpha is not None or "sft" in self.loss_type:
|
|
2145
|
+
# Only use the chosen logits for the RPO loss or SFT loss
|
|
2146
|
+
chosen_logits = logits[:num_examples, :-1] if not self.is_encoder_decoder else logits[:num_examples]
|
|
2147
|
+
chosen_labels = labels[:num_examples, :-1] if not self.is_encoder_decoder else labels[:num_examples]
|
|
2148
|
+
|
|
2149
|
+
# Compute the log probabilities of the labels
|
|
2150
|
+
output["nll_loss"] = F.cross_entropy(
|
|
2151
|
+
torch.flatten(chosen_logits, end_dim=1), torch.flatten(chosen_labels, end_dim=1), ignore_index=0
|
|
2152
|
+
)
|
|
2153
|
+
|
|
2154
|
+
if "ipo" in self.loss_type:
|
|
2155
|
+
all_logps = all_logps / loss_mask.sum(-1)
|
|
2156
|
+
|
|
2157
|
+
if self.args.ld_alpha is not None and not is_ref_model:
|
|
2158
|
+
# Compute response lengths based on loss_mask
|
|
2159
|
+
completion_lengths = loss_mask.sum(dim=1)
|
|
2160
|
+
|
|
2161
|
+
chosen_lengths = completion_lengths[:num_examples]
|
|
2162
|
+
rejected_lengths = completion_lengths[num_examples:]
|
|
2163
|
+
public_lengths = torch.min(chosen_lengths, rejected_lengths) # l_p in the paper
|
|
2164
|
+
public_lengths = torch.cat([public_lengths, public_lengths], dim=0)
|
|
2165
|
+
|
|
2166
|
+
seq_len = per_token_logps.size(1)
|
|
2167
|
+
position_ids = torch.arange(seq_len, device=per_token_logps.device).expand_as(per_token_logps)
|
|
2168
|
+
|
|
2169
|
+
ld_mask = position_ids < public_lengths.unsqueeze(1)
|
|
2170
|
+
mask = position_ids < completion_lengths.unsqueeze(1)
|
|
2171
|
+
|
|
2172
|
+
front_mask = (ld_mask & mask).float()
|
|
2173
|
+
rear_mask = (~ld_mask & mask).float()
|
|
2174
|
+
front_logps = (per_token_logps * front_mask).sum(dim=1)
|
|
2175
|
+
rear_logps = (per_token_logps * rear_mask).sum(dim=1)
|
|
2176
|
+
|
|
2177
|
+
all_logps = front_logps + self.args.ld_alpha * rear_logps
|
|
2178
|
+
|
|
2179
|
+
output["chosen_logps"] = all_logps[:num_examples]
|
|
2180
|
+
output["rejected_logps"] = all_logps[num_examples:]
|
|
2181
|
+
|
|
2182
|
+
# Compute the mean logits
|
|
2183
|
+
if self.padding_free:
|
|
2184
|
+
# position_ids contains a sequence of range identifiers (e.g., [[0, 1, 2, 0, 1, 2, 3, ...]]).
|
|
2185
|
+
# There are 2*num_examples ranges in total: the first half corresponds to the chosen tokens,
|
|
2186
|
+
# and the second half to the rejected tokens.
|
|
2187
|
+
# To find the start of the rejected tokens, we look for the num_examples+1-th zero in pos_id.
|
|
2188
|
+
split_idx = (position_ids == 0).nonzero(as_tuple=True)[1][num_examples]
|
|
2189
|
+
mean_chosen_logits = logits[0, :split_idx][loss_mask[0, :split_idx]].mean()
|
|
2190
|
+
mean_rejected_logits = logits[0, split_idx:][loss_mask[0, split_idx:]].mean()
|
|
2191
|
+
else:
|
|
2192
|
+
mean_chosen_logits = logits[:num_examples][loss_mask[:num_examples]].mean()
|
|
2193
|
+
mean_rejected_logits = logits[num_examples:][loss_mask[num_examples:]].mean()
|
|
2194
|
+
|
|
2195
|
+
output["mean_chosen_logits"] = mean_chosen_logits
|
|
2196
|
+
output["mean_rejected_logits"] = mean_rejected_logits
|
|
2197
|
+
|
|
2198
|
+
if self.aux_loss_enabled:
|
|
2199
|
+
output["aux_loss"] = outputs.aux_loss
|
|
2200
|
+
|
|
2201
|
+
return output
|
|
2202
|
+
|
|
2203
|
+
def get_batch_loss_metrics(
|
|
2204
|
+
self,
|
|
2205
|
+
model: Union[PreTrainedModel, nn.Module],
|
|
2206
|
+
batch: dict[str, Union[list, torch.LongTensor]],
|
|
2207
|
+
train_eval: Literal["train", "eval"] = "train",
|
|
2208
|
+
) -> tuple[torch.Tensor, dict[str, float]]:
|
|
2209
|
+
"""Compute the DPO loss and other metrics for the given batch of inputs for train or test."""
|
|
2210
|
+
metrics = {}
|
|
2211
|
+
|
|
2212
|
+
if self.args.use_liger_loss:
|
|
2213
|
+
model_output = self._compute_loss_liger(model, batch)
|
|
2214
|
+
losses = model_output["loss"]
|
|
2215
|
+
chosen_rewards = model_output["chosen_rewards"]
|
|
2216
|
+
rejected_rewards = model_output["rejected_rewards"]
|
|
2217
|
+
else:
|
|
2218
|
+
model_output = self.concatenated_forward(model, batch)
|
|
2219
|
+
|
|
2220
|
+
# if ref_chosen_logps and ref_rejected_logps in batch use them, otherwise use the reference model
|
|
2221
|
+
if "ref_chosen_logps" in batch and "ref_rejected_logps" in batch:
|
|
2222
|
+
ref_chosen_logps = batch["ref_chosen_logps"]
|
|
2223
|
+
ref_rejected_logps = batch["ref_rejected_logps"]
|
|
2224
|
+
else:
|
|
2225
|
+
ref_chosen_logps, ref_rejected_logps = self.compute_ref_log_probs(batch)
|
|
2226
|
+
|
|
2227
|
+
# Initialize combined losses
|
|
2228
|
+
losses = 0
|
|
2229
|
+
chosen_rewards = 0
|
|
2230
|
+
rejected_rewards = 0
|
|
2231
|
+
|
|
2232
|
+
# Compute losses for each loss type
|
|
2233
|
+
for idx, loss_type in enumerate(self.loss_type):
|
|
2234
|
+
# Compute individual loss using standard DPO loss function
|
|
2235
|
+
_losses, _chosen_rewards, _rejected_rewards = self.dpo_loss(
|
|
2236
|
+
model_output["chosen_logps"],
|
|
2237
|
+
model_output["rejected_logps"],
|
|
2238
|
+
ref_chosen_logps,
|
|
2239
|
+
ref_rejected_logps,
|
|
2240
|
+
loss_type,
|
|
2241
|
+
model_output,
|
|
2242
|
+
)
|
|
2243
|
+
|
|
2244
|
+
# Add weighted contributions
|
|
2245
|
+
weight = self.loss_weights[idx] if self.loss_weights else 1.0
|
|
2246
|
+
losses = losses + _losses * weight
|
|
2247
|
+
chosen_rewards = chosen_rewards + _chosen_rewards * weight
|
|
2248
|
+
rejected_rewards = rejected_rewards + _rejected_rewards * weight
|
|
2249
|
+
|
|
2250
|
+
reward_accuracies = (chosen_rewards > rejected_rewards).float()
|
|
2251
|
+
|
|
2252
|
+
if self.args.rpo_alpha is not None:
|
|
2253
|
+
losses = losses + self.args.rpo_alpha * model_output["nll_loss"] # RPO loss from V3 of the paper
|
|
2254
|
+
|
|
2255
|
+
if self.use_weighting:
|
|
2256
|
+
losses = losses * model_output["policy_weights"]
|
|
2257
|
+
|
|
2258
|
+
if self.aux_loss_enabled:
|
|
2259
|
+
losses = losses + self.aux_loss_coef * model_output["aux_loss"]
|
|
2260
|
+
|
|
2261
|
+
prefix = "eval_" if train_eval == "eval" else ""
|
|
2262
|
+
metrics[f"{prefix}rewards/chosen"] = self.accelerator.gather_for_metrics(chosen_rewards).mean().item()
|
|
2263
|
+
metrics[f"{prefix}rewards/rejected"] = self.accelerator.gather_for_metrics(rejected_rewards).mean().item()
|
|
2264
|
+
metrics[f"{prefix}rewards/accuracies"] = self.accelerator.gather_for_metrics(reward_accuracies).mean().item()
|
|
2265
|
+
metrics[f"{prefix}rewards/margins"] = (
|
|
2266
|
+
self.accelerator.gather_for_metrics(chosen_rewards - rejected_rewards).mean().item()
|
|
2267
|
+
)
|
|
2268
|
+
metrics[f"{prefix}logps/chosen"] = (
|
|
2269
|
+
self.accelerator.gather_for_metrics(model_output["chosen_logps"]).detach().mean().item()
|
|
2270
|
+
)
|
|
2271
|
+
metrics[f"{prefix}logps/rejected"] = (
|
|
2272
|
+
self.accelerator.gather_for_metrics(model_output["rejected_logps"]).detach().mean().item()
|
|
2273
|
+
)
|
|
2274
|
+
metrics[f"{prefix}logits/chosen"] = (
|
|
2275
|
+
self.accelerator.gather_for_metrics(model_output["mean_chosen_logits"]).detach().mean().item()
|
|
2276
|
+
)
|
|
2277
|
+
metrics[f"{prefix}logits/rejected"] = (
|
|
2278
|
+
self.accelerator.gather_for_metrics(model_output["mean_rejected_logits"]).detach().mean().item()
|
|
2279
|
+
)
|
|
2280
|
+
if self.args.rpo_alpha is not None or "sft" in self.loss_type:
|
|
2281
|
+
metrics[f"{prefix}nll_loss"] = (
|
|
2282
|
+
self.accelerator.gather_for_metrics(model_output["nll_loss"]).detach().mean().item()
|
|
2283
|
+
)
|
|
2284
|
+
if self.aux_loss_enabled:
|
|
2285
|
+
metrics[f"{prefix}aux_loss"] = (
|
|
2286
|
+
self.accelerator.gather_for_metrics(model_output["aux_loss"]).detach().mean().item()
|
|
2287
|
+
)
|
|
2288
|
+
|
|
2289
|
+
return losses.mean(), metrics
|
|
2290
|
+
|
|
2291
|
+
def compute_loss(
|
|
2292
|
+
self,
|
|
2293
|
+
model: Union[PreTrainedModel, nn.Module],
|
|
2294
|
+
inputs: dict[str, Union[torch.Tensor, Any]],
|
|
2295
|
+
return_outputs=False,
|
|
2296
|
+
num_items_in_batch=None,
|
|
2297
|
+
) -> Union[torch.Tensor, tuple[torch.Tensor, dict[str, float]]]:
|
|
2298
|
+
compute_loss_context_manager = (
|
|
2299
|
+
autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
|
|
2300
|
+
)
|
|
2301
|
+
with compute_loss_context_manager:
|
|
2302
|
+
loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train")
|
|
2303
|
+
|
|
2304
|
+
# Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class:
|
|
2305
|
+
loss = loss.to(self.args.device)
|
|
2306
|
+
# force log the metrics
|
|
2307
|
+
self.store_metrics(metrics, train_eval="train")
|
|
2308
|
+
|
|
2309
|
+
if return_outputs:
|
|
2310
|
+
return loss, metrics
|
|
2311
|
+
|
|
2312
|
+
return loss
|
|
2313
|
+
|
|
2314
|
+
def generate_from_model_and_ref(self, model, batch: dict[str, torch.LongTensor]) -> tuple[str, str]:
|
|
2315
|
+
"""Generate samples from the model and reference model for the given batch of inputs."""
|
|
2316
|
+
|
|
2317
|
+
# If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with
|
|
2318
|
+
# the torch amp context manager as some hidden states are silently casted to full precision.
|
|
2319
|
+
generate_context_manager = (
|
|
2320
|
+
autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
|
|
2321
|
+
)
|
|
2322
|
+
|
|
2323
|
+
with generate_context_manager:
|
|
2324
|
+
policy_output = model.generate(
|
|
2325
|
+
input_ids=batch["prompt_input_ids"],
|
|
2326
|
+
attention_mask=batch["prompt_attention_mask"],
|
|
2327
|
+
max_length=self.max_length,
|
|
2328
|
+
do_sample=True,
|
|
2329
|
+
pad_token_id=self.pad_token_id,
|
|
2330
|
+
)
|
|
2331
|
+
|
|
2332
|
+
# if ref_output in batch use that otherwise use the reference model
|
|
2333
|
+
if "ref_output" in batch:
|
|
2334
|
+
ref_output = batch["ref_output"]
|
|
2335
|
+
else:
|
|
2336
|
+
if self.ref_model is None:
|
|
2337
|
+
with self.null_ref_context():
|
|
2338
|
+
ref_output = self.model.generate(
|
|
2339
|
+
input_ids=batch["prompt_input_ids"],
|
|
2340
|
+
attention_mask=batch["prompt_attention_mask"],
|
|
2341
|
+
max_length=self.max_length,
|
|
2342
|
+
do_sample=True,
|
|
2343
|
+
pad_token_id=self.pad_token_id,
|
|
2344
|
+
)
|
|
2345
|
+
else:
|
|
2346
|
+
ref_output = self.ref_model.generate(
|
|
2347
|
+
input_ids=batch["prompt_input_ids"],
|
|
2348
|
+
attention_mask=batch["prompt_attention_mask"],
|
|
2349
|
+
max_length=self.max_length,
|
|
2350
|
+
do_sample=True,
|
|
2351
|
+
pad_token_id=self.pad_token_id,
|
|
2352
|
+
)
|
|
2353
|
+
|
|
2354
|
+
policy_output = pad_to_length(policy_output, self.max_length, self.pad_token_id)
|
|
2355
|
+
policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True)
|
|
2356
|
+
|
|
2357
|
+
ref_output = pad_to_length(ref_output, self.max_length, self.pad_token_id)
|
|
2358
|
+
ref_output_decoded = self.processing_class.batch_decode(ref_output, skip_special_tokens=True)
|
|
2359
|
+
|
|
2360
|
+
return policy_output_decoded, ref_output_decoded
|
|
2361
|
+
|
|
2362
|
+
def prediction_step(
|
|
2363
|
+
self,
|
|
2364
|
+
model: Union[PreTrainedModel, nn.Module],
|
|
2365
|
+
inputs: dict[str, Union[torch.Tensor, Any]],
|
|
2366
|
+
prediction_loss_only: bool,
|
|
2367
|
+
ignore_keys: Optional[list[str]] = None,
|
|
2368
|
+
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]:
|
|
2369
|
+
if ignore_keys is None:
|
|
2370
|
+
if hasattr(model, "config"):
|
|
2371
|
+
ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", [])
|
|
2372
|
+
else:
|
|
2373
|
+
ignore_keys = []
|
|
2374
|
+
|
|
2375
|
+
prediction_context_manager = (
|
|
2376
|
+
autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
|
|
2377
|
+
)
|
|
2378
|
+
|
|
2379
|
+
with torch.no_grad(), prediction_context_manager:
|
|
2380
|
+
loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval")
|
|
2381
|
+
|
|
2382
|
+
# force log the metrics
|
|
2383
|
+
self.store_metrics(metrics, train_eval="eval")
|
|
2384
|
+
|
|
2385
|
+
if prediction_loss_only:
|
|
2386
|
+
return loss.detach(), None, None
|
|
2387
|
+
|
|
2388
|
+
# logits for the chosen and rejected samples from model
|
|
2389
|
+
logits_dict = {
|
|
2390
|
+
"eval_logits/chosen": metrics["eval_logits/chosen"],
|
|
2391
|
+
"eval_logits/rejected": metrics["eval_logits/rejected"],
|
|
2392
|
+
}
|
|
2393
|
+
logits = [v for k, v in logits_dict.items() if k not in ignore_keys]
|
|
2394
|
+
logits = torch.tensor(logits, device=self.accelerator.device)
|
|
2395
|
+
labels = torch.zeros(logits.shape[0], device=self.accelerator.device)
|
|
2396
|
+
|
|
2397
|
+
return (loss.detach(), logits, labels)
|
|
2398
|
+
|
|
2399
|
+
def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None:
|
|
2400
|
+
for key, value in metrics.items():
|
|
2401
|
+
self._stored_metrics[train_eval][key].append(value)
|
|
2402
|
+
|
|
2403
|
+
def evaluation_loop(
|
|
2404
|
+
self,
|
|
2405
|
+
dataloader: DataLoader,
|
|
2406
|
+
description: str,
|
|
2407
|
+
prediction_loss_only: Optional[bool] = None,
|
|
2408
|
+
ignore_keys: Optional[list[str]] = None,
|
|
2409
|
+
metric_key_prefix: str = "eval",
|
|
2410
|
+
) -> EvalLoopOutput:
|
|
2411
|
+
"""
|
|
2412
|
+
Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by
|
|
2413
|
+
`Trainer.evaluate()` and `Trainer.predict()`.
|
|
2414
|
+
|
|
2415
|
+
Works both with or without labels.
|
|
2416
|
+
"""
|
|
2417
|
+
|
|
2418
|
+
# Sample and save to game log if requested (for one batch to save time)
|
|
2419
|
+
if self.generate_during_eval:
|
|
2420
|
+
# Generate random indices within the range of the total number of samples
|
|
2421
|
+
num_samples = len(dataloader.dataset)
|
|
2422
|
+
random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size)
|
|
2423
|
+
|
|
2424
|
+
# Use dataloader.dataset.select to get the random batch without iterating over the DataLoader
|
|
2425
|
+
random_batch_dataset = dataloader.dataset.select(random_indices)
|
|
2426
|
+
random_batch = self.data_collator(random_batch_dataset)
|
|
2427
|
+
random_batch = self._prepare_inputs(random_batch)
|
|
2428
|
+
|
|
2429
|
+
policy_output_decoded, ref_output_decoded = self.generate_from_model_and_ref(self.model, random_batch)
|
|
2430
|
+
|
|
2431
|
+
table = pd.DataFrame(
|
|
2432
|
+
columns=["Prompt", "Policy", "Ref Model"],
|
|
2433
|
+
data=[
|
|
2434
|
+
[prompt, pol[len(prompt) :], ref[len(prompt) :]]
|
|
2435
|
+
for prompt, pol, ref in zip(
|
|
2436
|
+
random_batch_dataset["prompt"], policy_output_decoded, ref_output_decoded
|
|
2437
|
+
)
|
|
2438
|
+
],
|
|
2439
|
+
)
|
|
2440
|
+
if "wandb" in self.args.report_to and self.accelerator.is_main_process:
|
|
2441
|
+
wandb.log({"game_log": wandb.Table(data=table)})
|
|
2442
|
+
|
|
2443
|
+
if "comet_ml" in self.args.report_to:
|
|
2444
|
+
log_table_to_comet_experiment(
|
|
2445
|
+
name="game_log.csv",
|
|
2446
|
+
table=table,
|
|
2447
|
+
)
|
|
2448
|
+
|
|
2449
|
+
if "mlflow" in self.args.report_to and self.accelerator.is_main_process:
|
|
2450
|
+
mlflow.log_table(data=table, artifact_file="game_log.json")
|
|
2451
|
+
|
|
2452
|
+
# Base evaluation
|
|
2453
|
+
initial_output = super().evaluation_loop(
|
|
2454
|
+
dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix
|
|
2455
|
+
)
|
|
2456
|
+
|
|
2457
|
+
return initial_output
|
|
2458
|
+
|
|
2459
|
+
def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None:
|
|
2460
|
+
"""
|
|
2461
|
+
Log `logs` on the various objects watching training, including stored metrics.
|
|
2462
|
+
|
|
2463
|
+
Args:
|
|
2464
|
+
logs (`dict[str, float]`):
|
|
2465
|
+
The values to log.
|
|
2466
|
+
start_time (`float`, *optional*):
|
|
2467
|
+
Start time of the training.
|
|
2468
|
+
"""
|
|
2469
|
+
# logs either has 'loss' or 'eval_loss'
|
|
2470
|
+
train_eval = "train" if "loss" in logs else "eval"
|
|
2471
|
+
# Add averaged stored metrics to logs
|
|
2472
|
+
for key, metrics in self._stored_metrics[train_eval].items():
|
|
2473
|
+
logs[key] = torch.tensor(metrics).mean().item()
|
|
2474
|
+
del self._stored_metrics[train_eval]
|
|
2475
|
+
return super().log(logs, start_time)
|
|
2476
|
+
|
|
2477
|
+
# Ensure the model card is saved along with the checkpoint
|
|
2478
|
+
def _save_checkpoint(self, model, trial):
|
|
2479
|
+
if self.args.hub_model_id is None:
|
|
2480
|
+
model_name = Path(self.args.output_dir).name
|
|
2481
|
+
else:
|
|
2482
|
+
model_name = self.args.hub_model_id.split("/")[-1]
|
|
2483
|
+
self.create_model_card(model_name=model_name)
|
|
2484
|
+
super()._save_checkpoint(model, trial)
|
|
2485
|
+
class UnslothDPOTrainer(_UnslothDPOTrainer):
|
|
2486
|
+
"""
|
|
2487
|
+
|
|
2488
|
+
Trainer for Direct Preference Optimization (DPO) method.
|
|
2489
|
+
|
|
2490
|
+
This class is a wrapper around the [`transformers.Trainer`] class and inherits all of its attributes and methods.
|
|
2491
|
+
|
|
2492
|
+
Args:
|
|
2493
|
+
model (`Union[str, PreTrainedModel]`):
|
|
2494
|
+
Model to be trained. Can be either:
|
|
2495
|
+
|
|
2496
|
+
- A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
|
|
2497
|
+
path to a *directory* containing model weights saved using
|
|
2498
|
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
|
|
2499
|
+
using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in
|
|
2500
|
+
`args.model_init_kwargs`.
|
|
2501
|
+
- A [`~transformers.PreTrainedModel`] object. Only causal language models are supported.
|
|
2502
|
+
ref_model ([`PreTrainedModelWrapper`]):
|
|
2503
|
+
Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation
|
|
2504
|
+
and loss. If no reference model is provided, the trainer will create a reference model with the same
|
|
2505
|
+
architecture as the model to be optimized.
|
|
2506
|
+
args ([`DPOConfig`], *optional*):
|
|
2507
|
+
Configuration for this trainer. If `None`, a default configuration is used.
|
|
2508
|
+
data_collator ([`~transformers.DataCollator`], *optional*):
|
|
2509
|
+
Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`.
|
|
2510
|
+
Will default to [`DataCollatorForPreference`].
|
|
2511
|
+
train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
|
|
2512
|
+
Dataset to use for training. DPO supports [preference](#preference) type and. The format of the samples can
|
|
2513
|
+
be either:
|
|
2514
|
+
|
|
2515
|
+
- [Standard](dataset_formats#standard): Each sample contains plain text.
|
|
2516
|
+
- [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
|
|
2517
|
+
and content).
|
|
2518
|
+
eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Union[Dataset, IterableDataset]]`):
|
|
2519
|
+
Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
|
|
2520
|
+
processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
|
|
2521
|
+
Processing class used to process the data. If `None`, the processing class is loaded from the model's name
|
|
2522
|
+
with [`~transformers.AutoTokenizer.from_pretrained`].
|
|
2523
|
+
compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
|
|
2524
|
+
The function that will be used to compute metrics at evaluation. Must take a [`EvalPrediction`] and return
|
|
2525
|
+
a dictionary string to metric values. *Note* When passing TrainingArgs with `batch_eval_metrics` set to
|
|
2526
|
+
`True`, your compute_metrics function must take a boolean `compute_result` argument. This will be triggered
|
|
2527
|
+
after the last eval batch to signal that the function needs to calculate and return the global summary
|
|
2528
|
+
statistics rather than accumulating the batch-level statistics.
|
|
2529
|
+
callbacks (list of [`~transformers.TrainerCallback`], *optional*):
|
|
2530
|
+
List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
|
|
2531
|
+
in [here](https://huggingface.co/docs/transformers/main_classes/callback).
|
|
2532
|
+
|
|
2533
|
+
If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
|
|
2534
|
+
method.
|
|
2535
|
+
optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`, *optional*, defaults to `(None, None)`):
|
|
2536
|
+
A tuple containing the optimizer and the scheduler to use. Will default to an instance of [`AdamW`] on your
|
|
2537
|
+
model and a scheduler given by [`get_linear_schedule_with_warmup`] controlled by `args`.
|
|
2538
|
+
optimizer_cls_and_kwargs (`Tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *optional*):
|
|
2539
|
+
A tuple containing the optimizer class and keyword arguments to use. Overrides `optim` and `optim_args` in
|
|
2540
|
+
`args`. Incompatible with the `optimizers` argument.
|
|
2541
|
+
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*):
|
|
2542
|
+
A function that preprocess the logits right before caching them at each evaluation step. Must take two
|
|
2543
|
+
tensors, the logits and the labels, and return the logits once processed as desired. The modifications made
|
|
2544
|
+
by this function will be reflected in the predictions received by `compute_metrics`.
|
|
2545
|
+
|
|
2546
|
+
Note that the labels (second parameter) will be `None` if the dataset does not have them.
|
|
2547
|
+
peft_config ([`~peft.PeftConfig`], *optional*):
|
|
2548
|
+
PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
|
|
2549
|
+
|
|
2550
|
+
"""
|
|
2551
|
+
def __init__(
|
|
2552
|
+
self,
|
|
2553
|
+
model,
|
|
2554
|
+
ref_model = None,
|
|
2555
|
+
args = None,
|
|
2556
|
+
data_collator = None,
|
|
2557
|
+
train_dataset = None,
|
|
2558
|
+
eval_dataset = None,
|
|
2559
|
+
processing_class = None,
|
|
2560
|
+
compute_metrics = None,
|
|
2561
|
+
callbacks = None,
|
|
2562
|
+
optimizer_cls_and_kwargs = None,
|
|
2563
|
+
preprocess_logits_for_metrics = None,
|
|
2564
|
+
peft_config = None,
|
|
2565
|
+
**kwargs
|
|
2566
|
+
):
|
|
2567
|
+
if args is None: args = UnslothDPOConfig()
|
|
2568
|
+
use_bf16 = getattr(args, 'bf16', False)
|
|
2569
|
+
if type(use_bf16) is not bool: use_bf16 = False
|
|
2570
|
+
use_fp16 = getattr(args, 'fp16', False)
|
|
2571
|
+
if type(use_fp16) is not bool: use_fp16 = False
|
|
2572
|
+
force_float32 = False
|
|
2573
|
+
full_finetuning = os.environ.get('UNSLOTH_ENABLE_FULL_FINETUNING', '0') == '1'
|
|
2574
|
+
if not full_finetuning and (os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '1'):
|
|
2575
|
+
print('Unsloth: Switching to float32 training since model cannot work with float16')
|
|
2576
|
+
force_float32 = True
|
|
2577
|
+
mixed_precision_dtype = os.environ.get('UNSLOTH_MIXED_PRECISION', 'float32')
|
|
2578
|
+
dtype = getattr(model.config, 'dtype', None) or getattr(model.config, 'torch_dtype', None)
|
|
2579
|
+
if dtype is None: dtype = model.get_input_embeddings().weight.dtype
|
|
2580
|
+
from unsloth_zoo.utils import _get_dtype
|
|
2581
|
+
dtype = _get_dtype(dtype)
|
|
2582
|
+
float16 = dtype == torch.float16
|
|
2583
|
+
if not force_float32 and (float16 and use_bf16): raise TypeError('Unsloth: Model is in float16 precision but you want to use bfloat16 precision. Set fp16 to `True` and bf16 to `False`')
|
|
2584
|
+
if not force_float32 and (not float16 and use_fp16): raise TypeError('Unsloth: Model is in bfloat16 precision but you want to use float16 precision. Set fp16 to `False` and bf16 to `True`')
|
|
2585
|
+
if force_float32:
|
|
2586
|
+
# Forced float32 training
|
|
2587
|
+
args.fp16 = False
|
|
2588
|
+
args.bf16 = False
|
|
2589
|
+
os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'
|
|
2590
|
+
if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'
|
|
2591
|
+
# args.mixed_precision is a new argument which needs to be set now
|
|
2592
|
+
elif (not use_bf16 and not use_fp16) and mixed_precision_dtype == 'float32':
|
|
2593
|
+
# Mixed precision training
|
|
2594
|
+
args.fp16 = float16
|
|
2595
|
+
args.bf16 = not float16
|
|
2596
|
+
os.environ['ACCELERATE_MIXED_PRECISION'] = 'fp16' if float16 else 'bf16'
|
|
2597
|
+
if hasattr(args, 'mixed_precision'): args.mixed_precision = 'fp16' if float16 else 'bf16'
|
|
2598
|
+
# args.mixed_precision is a new argument which needs to be set now
|
|
2599
|
+
elif mixed_precision_dtype == 'bfloat16':
|
|
2600
|
+
# Both False since bfloat16 full finetuning doesn't do any autocasting.
|
|
2601
|
+
args.fp16 = False
|
|
2602
|
+
args.bf16 = False
|
|
2603
|
+
os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'
|
|
2604
|
+
if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'
|
|
2605
|
+
# args.mixed_precision is a new argument which needs to be set now
|
|
2606
|
+
|
|
2607
|
+
if getattr(args, 'eval_dataset', None) is not None and getattr(args, 'eval_strategy', 'no') == 'no':
|
|
2608
|
+
args.eval_strategy = 'steps'
|
|
2609
|
+
if getattr(args, 'eval_steps', None) is None: args.eval_steps = 0.1
|
|
2610
|
+
ga_steps = getattr(args, 'gradient_accumulation_steps', None)
|
|
2611
|
+
if ga_steps is not None and ga_steps > 1:
|
|
2612
|
+
from transformers import __version__ as transformers_version
|
|
2613
|
+
if Version(transformers_version) <= Version('4.45.2'):
|
|
2614
|
+
print('**** Unsloth: Please use our fixed gradient_accumulation_steps by updating transformers, TRL and Unsloth!\n'
|
|
2615
|
+
'`pip install --upgrade --no-cache-dir --force-reinstall --no-deps unsloth transformers trl unsloth_zoo`')
|
|
2616
|
+
if getattr(args, 'eval_strategy', 'no') != 'no':
|
|
2617
|
+
eval_bsz = getattr(args, 'per_device_eval_batch_size', 8)
|
|
2618
|
+
if eval_bsz == 8 and args.per_device_train_batch_size < eval_bsz: args.per_device_eval_batch_size = args.per_device_train_batch_size
|
|
2619
|
+
if getattr(args, 'eval_accumulation_steps', None) is None and ga_steps is not None: args.eval_accumulation_steps = ga_steps
|
|
2620
|
+
fp16_full_eval = getattr(args, 'fp16_full_eval', False)
|
|
2621
|
+
if type(fp16_full_eval) is not bool: fp16_full_eval = False
|
|
2622
|
+
bf16_full_eval = getattr(args, 'bf16_full_eval', False)
|
|
2623
|
+
if type(bf16_full_eval) is not bool: bf16_full_eval = False
|
|
2624
|
+
if args.fp16 and bf16_full_eval: args.bf16_full_eval = False; args.fp16_full_eval = True
|
|
2625
|
+
if args.bf16 and fp16_full_eval: args.bf16_full_eval = True; args.fp16_full_eval = False
|
|
2626
|
+
if force_float32:
|
|
2627
|
+
args.bf16_full_eval = False
|
|
2628
|
+
args.fp16_full_eval = False
|
|
2629
|
+
elif os.environ.get('UNSLOTH_MIXED_PRECISION', 'float32') == 'bfloat16':
|
|
2630
|
+
args.bf16_full_eval = True
|
|
2631
|
+
args.fp16_full_eval = False
|
|
2632
|
+
elif not bf16_full_eval and not fp16_full_eval:
|
|
2633
|
+
args.bf16_full_eval = args.bf16
|
|
2634
|
+
args.fp16_full_eval = args.fp16
|
|
2635
|
+
_output_logits = False
|
|
2636
|
+
if locals().get('compute_metrics', None) is not None: _output_logits = True
|
|
2637
|
+
if locals().get('preprocess_logits_for_metrics', None) is not None: _output_logits = True
|
|
2638
|
+
if _output_logits:
|
|
2639
|
+
os.environ['UNSLOTH_RETURN_LOGITS'] = '1'
|
|
2640
|
+
if 'max_seq_length' not in locals() and not hasattr(args, 'max_seq_length'):
|
|
2641
|
+
pass
|
|
2642
|
+
else:
|
|
2643
|
+
model_max_seq_length = getattr(model, 'max_seq_length', None)
|
|
2644
|
+
args_max_seq_length = getattr(args, 'max_seq_length', None)
|
|
2645
|
+
if args_max_seq_length is None and model_max_seq_length is not None:
|
|
2646
|
+
max_seq_length = model.max_seq_length
|
|
2647
|
+
if hasattr(args, 'max_seq_length'): args.max_seq_length = max_seq_length
|
|
2648
|
+
if model is not None and hasattr(model, 'for_training'):
|
|
2649
|
+
model.for_training(use_gradient_checkpointing=getattr(args, 'gradient_checkpointing', True))
|
|
2650
|
+
if 'tokenizer' in locals() and hasattr(tokenizer, 'padding_side'): tokenizer.padding_side = 'right'
|
|
2651
|
+
if 'processing_class' in locals():
|
|
2652
|
+
if hasattr(processing_class, 'padding_side'): processing_class.padding_side = 'right'
|
|
2653
|
+
if hasattr(processing_class, 'tokenizer') and hasattr(processing_class.tokenizer, 'padding_side'): processing_class.tokenizer.padding_side = 'right'
|
|
2654
|
+
__tokenizer = processing_class if 'processing_class' in locals() else tokenizer
|
|
2655
|
+
from unsloth_zoo.vision_utils import UnslothVisionDataCollator
|
|
2656
|
+
if not isinstance(data_collator, UnslothVisionDataCollator):
|
|
2657
|
+
if isinstance(data_collator, DataCollatorForSeq2Seq) and 'labels' not in train_dataset.column_names:
|
|
2658
|
+
data_collator = TransformersDataCollatorForLanguageModeling(
|
|
2659
|
+
__tokenizer,
|
|
2660
|
+
mlm = False,
|
|
2661
|
+
mlm_probability = 0.0,
|
|
2662
|
+
pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
|
|
2663
|
+
)
|
|
2664
|
+
elif isinstance(data_collator, TransformersDataCollatorForLanguageModeling) and 'labels' in train_dataset.column_names:
|
|
2665
|
+
data_collator = DataCollatorForSeq2Seq(
|
|
2666
|
+
__tokenizer,
|
|
2667
|
+
pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
|
|
2668
|
+
)
|
|
2669
|
+
else:
|
|
2670
|
+
if hasattr(args, 'remove_unused_columns'): args.remove_unused_columns = False
|
|
2671
|
+
if hasattr(args, 'dataset_text_field'): args.dataset_text_field = ''
|
|
2672
|
+
if hasattr(args, 'dataset_kwargs'): args.dataset_kwargs = {'skip_prepare_dataset': True}
|
|
2673
|
+
if not isinstance(data_collator, UnslothVisionDataCollator):
|
|
2674
|
+
if not hasattr(__tokenizer, 'pad') and hasattr(__tokenizer, 'tokenizer'):
|
|
2675
|
+
if isinstance(data_collator, DataCollatorForSeq2Seq):
|
|
2676
|
+
data_collator = DataCollatorForSeq2Seq(
|
|
2677
|
+
__tokenizer.tokenizer,
|
|
2678
|
+
pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
|
|
2679
|
+
)
|
|
2680
|
+
else:
|
|
2681
|
+
data_collator = TransformersDataCollatorForLanguageModeling(
|
|
2682
|
+
__tokenizer.tokenizer,
|
|
2683
|
+
mlm = False,
|
|
2684
|
+
mlm_probability = 0.0,
|
|
2685
|
+
pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
|
|
2686
|
+
)
|
|
2687
|
+
other_metrics = []
|
|
2688
|
+
|
|
2689
|
+
from unsloth_zoo.logging_utils import PatchRLStatistics
|
|
2690
|
+
PatchRLStatistics('dpo_trainer', other_metrics)
|
|
2691
|
+
if hasattr(train_dataset, 'column_names'):
|
|
2692
|
+
column_names = set(train_dataset.column_names)
|
|
2693
|
+
check = ['chosen', 'rejected', 'prompt', 'chosen_input_ids', 'chosen_attention_mask',
|
|
2694
|
+
'chosen_labels', 'rejected_input_ids', 'rejected_attention_mask', 'rejected_labels',
|
|
2695
|
+
'prompt_input_ids', 'prompt_attention_mask']
|
|
2696
|
+
if all(x in column_names for x in check):
|
|
2697
|
+
train_dataset = train_dataset.remove_columns(['chosen', 'rejected', 'prompt'])
|
|
2698
|
+
del check, column_names
|
|
2699
|
+
|
|
2700
|
+
# [TODO] Fix up DataParallel multiplying batch sizes
|
|
2701
|
+
# [TODO] DDP works, but DP seems to not work? [TODO]
|
|
2702
|
+
if getattr(args, "parallel_mode", None) == ParallelMode.NOT_DISTRIBUTED and args.n_gpu > 1:
|
|
2703
|
+
if getattr(args, "_n_gpu", 1) != 1:
|
|
2704
|
+
args._n_gpu = 1
|
|
2705
|
+
if "model" in locals() and hasattr(model, "for_training"):
|
|
2706
|
+
model.for_training(use_gradient_checkpointing=getattr(args, 'gradient_checkpointing', True))
|
|
2707
|
+
super().__init__(
|
|
2708
|
+
model = model,
|
|
2709
|
+
ref_model = ref_model,
|
|
2710
|
+
args = args,
|
|
2711
|
+
data_collator = data_collator,
|
|
2712
|
+
train_dataset = train_dataset,
|
|
2713
|
+
eval_dataset = eval_dataset,
|
|
2714
|
+
processing_class = processing_class,
|
|
2715
|
+
compute_metrics = compute_metrics,
|
|
2716
|
+
callbacks = callbacks,
|
|
2717
|
+
optimizer_cls_and_kwargs = optimizer_cls_and_kwargs,
|
|
2718
|
+
preprocess_logits_for_metrics = preprocess_logits_for_metrics,
|
|
2719
|
+
peft_config = peft_config,**kwargs)
|
|
2720
|
+
if "model" in locals() and hasattr(model, "for_inference"):
|
|
2721
|
+
model.for_inference()
|
|
2722
|
+
if hasattr(self, 'neftune_hook_handle'):
|
|
2723
|
+
self.neftune_hook_handle.remove()
|
|
2724
|
+
if hasattr(self, 'neftune_hook_handle'): del self.neftune_hook_handle
|
|
2725
|
+
if getattr(args, 'neftune_noise_alpha', None) is not None:
|
|
2726
|
+
model.get_input_embeddings().neftune_noise_alpha = self.neftune_noise_alpha
|
|
2727
|
+
pass
|
|
2728
|
+
if hasattr(self, 'accelerator'):
|
|
2729
|
+
scaler = self.accelerator.scaler
|
|
2730
|
+
current_model = model
|
|
2731
|
+
while hasattr(current_model, 'model'):
|
|
2732
|
+
current_model.accelerator_scaler = scaler
|
|
2733
|
+
current_model = current_model.model
|
|
2734
|
+
current_model.accelerator_scaler = scaler
|
|
2735
|
+
pass
|
|
2736
|
+
if hasattr(self, 'train'):
|
|
2737
|
+
self.train = MethodType(prepare_for_training_mode(self.__class__.train), self)
|
|
2738
|
+
pass
|
|
2739
|
+
|
|
2740
|
+
pass
|
|
2741
|
+
|
|
2742
|
+
|
|
2743
|
+
if hasattr(logger, "addFilter"):
|
|
2744
|
+
import logging
|
|
2745
|
+
class HideLoggingMessage(logging.Filter):
|
|
2746
|
+
def __init__(self, text): self.text = text
|
|
2747
|
+
def filter(self, x): return not (self.text in x.getMessage())
|
|
2748
|
+
pass
|
|
2749
|
+
logger.addFilter(HideLoggingMessage("`use_cache=True`"))
|
|
2750
|
+
|