cciwon-code-review-cli 2.0.2 → 2.0.4
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/lib/api-client.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,1210 @@
|
|
|
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.nash_md_trainer import (Any, BaseImageProcessor, BasePairwiseJudge, Callable, Dataset, EvalPrediction, F, FeatureExtractionMixin, GeometricMixtureWrapper, IterableDataset, NashMDConfig, NashMDTrainer, OnlineDPOTrainer, OptimizerNames, Optional, PeftModel, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, SIMPLE_CHAT_TEMPLATE, TrainerCallback, Union, empty_cache, get_reward, is_conversational, is_peft_available, jinja2, maybe_apply_chat_template, nn, selective_log_softmax, textwrap, torch, truncate_right, unwrap_model_for_generation)
|
|
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 UnslothNashMDConfig(NashMDConfig):
|
|
199
|
+
"""
|
|
200
|
+
|
|
201
|
+
Configuration class for the [`NashMDTrainer`].
|
|
202
|
+
|
|
203
|
+
Subclass of [`OnlineDPOConfig`] we can use all its arguments and add the following:
|
|
204
|
+
|
|
205
|
+
Parameters:
|
|
206
|
+
mixture_coef (`float` or `list[float]`, *optional*, defaults to `0.5`):
|
|
207
|
+
Logit mixture coefficient for the model and reference model. If a list of floats is provided then the
|
|
208
|
+
mixture coefficient is selected for each new epoch and the last coefficient is used for the rest of the
|
|
209
|
+
epochs.
|
|
210
|
+
|
|
211
|
+
"""
|
|
212
|
+
vllm_sampling_params: Optional[Any] = field(
|
|
213
|
+
default = None,
|
|
214
|
+
metadata = {'help': 'vLLM SamplingParams'},
|
|
215
|
+
)
|
|
216
|
+
unsloth_num_chunks : Optional[int] = field(
|
|
217
|
+
default = -1,
|
|
218
|
+
metadata = {'help': 'Chunk size to reduce memory usage. -1 is most efficient.'},
|
|
219
|
+
)
|
|
220
|
+
max_seq_length : Optional[int] = field(
|
|
221
|
+
default = None,
|
|
222
|
+
metadata = {'help': 'Maximum sequence length to truncate to.'},
|
|
223
|
+
)
|
|
224
|
+
def __init__(
|
|
225
|
+
self,
|
|
226
|
+
output_dir = None,
|
|
227
|
+
overwrite_output_dir = None,
|
|
228
|
+
do_train = False,
|
|
229
|
+
do_eval = False,
|
|
230
|
+
do_predict = False,
|
|
231
|
+
eval_strategy = 'no',
|
|
232
|
+
prediction_loss_only = False,
|
|
233
|
+
per_device_train_batch_size = 4,
|
|
234
|
+
per_device_eval_batch_size = 4,
|
|
235
|
+
per_gpu_train_batch_size = None,
|
|
236
|
+
per_gpu_eval_batch_size = None,
|
|
237
|
+
gradient_accumulation_steps = 2,
|
|
238
|
+
eval_accumulation_steps = 2,
|
|
239
|
+
eval_delay = 0,
|
|
240
|
+
torch_empty_cache_steps = 250,
|
|
241
|
+
learning_rate = 5e-05,
|
|
242
|
+
weight_decay = 0.01,
|
|
243
|
+
adam_beta1 = 0.9,
|
|
244
|
+
adam_beta2 = 0.999,
|
|
245
|
+
adam_epsilon = 1e-08,
|
|
246
|
+
max_grad_norm = 1.0,
|
|
247
|
+
num_train_epochs = 3.0,
|
|
248
|
+
max_steps = -1,
|
|
249
|
+
lr_scheduler_type = 'linear',
|
|
250
|
+
warmup_ratio = 0.1,
|
|
251
|
+
warmup_steps = 0,
|
|
252
|
+
log_level = 'passive',
|
|
253
|
+
log_level_replica = 'warning',
|
|
254
|
+
log_on_each_node = True,
|
|
255
|
+
logging_dir = None,
|
|
256
|
+
logging_strategy = 'steps',
|
|
257
|
+
logging_first_step = False,
|
|
258
|
+
logging_steps = 1,
|
|
259
|
+
logging_nan_inf_filter = False,
|
|
260
|
+
save_strategy = 'steps',
|
|
261
|
+
save_steps = 500,
|
|
262
|
+
save_total_limit = None,
|
|
263
|
+
save_safetensors = True,
|
|
264
|
+
save_on_each_node = False,
|
|
265
|
+
save_only_model = False,
|
|
266
|
+
restore_callback_states_from_checkpoint = False,
|
|
267
|
+
no_cuda = False,
|
|
268
|
+
use_cpu = False,
|
|
269
|
+
use_mps_device = False,
|
|
270
|
+
seed = 3407,
|
|
271
|
+
data_seed = 3407,
|
|
272
|
+
jit_mode_eval = False,
|
|
273
|
+
bf16 = False,
|
|
274
|
+
fp16 = False,
|
|
275
|
+
fp16_opt_level = 'O1',
|
|
276
|
+
half_precision_backend = 'auto',
|
|
277
|
+
bf16_full_eval = False,
|
|
278
|
+
fp16_full_eval = False,
|
|
279
|
+
tf32 = None,
|
|
280
|
+
local_rank = -1,
|
|
281
|
+
ddp_backend = None,
|
|
282
|
+
tpu_num_cores = None,
|
|
283
|
+
tpu_metrics_debug = False,
|
|
284
|
+
debug = '',
|
|
285
|
+
dataloader_drop_last = False,
|
|
286
|
+
eval_steps = None,
|
|
287
|
+
dataloader_num_workers = 0,
|
|
288
|
+
dataloader_prefetch_factor = None,
|
|
289
|
+
past_index = -1,
|
|
290
|
+
run_name = None,
|
|
291
|
+
disable_tqdm = None,
|
|
292
|
+
remove_unused_columns = True,
|
|
293
|
+
label_names = None,
|
|
294
|
+
load_best_model_at_end = False,
|
|
295
|
+
metric_for_best_model = None,
|
|
296
|
+
greater_is_better = None,
|
|
297
|
+
ignore_data_skip = False,
|
|
298
|
+
fsdp = None,
|
|
299
|
+
fsdp_min_num_params = 0,
|
|
300
|
+
fsdp_config = None,
|
|
301
|
+
fsdp_transformer_layer_cls_to_wrap = None,
|
|
302
|
+
accelerator_config = None,
|
|
303
|
+
parallelism_config = None,
|
|
304
|
+
deepspeed = None,
|
|
305
|
+
label_smoothing_factor = 0.0,
|
|
306
|
+
optim = 'adamw_8bit',
|
|
307
|
+
optim_args = None,
|
|
308
|
+
adafactor = False,
|
|
309
|
+
group_by_length = False,
|
|
310
|
+
length_column_name = 'length',
|
|
311
|
+
report_to = 'none',
|
|
312
|
+
project = 'huggingface',
|
|
313
|
+
trackio_space_id = 'trackio',
|
|
314
|
+
ddp_find_unused_parameters = None,
|
|
315
|
+
ddp_bucket_cap_mb = None,
|
|
316
|
+
ddp_broadcast_buffers = None,
|
|
317
|
+
dataloader_pin_memory = True,
|
|
318
|
+
dataloader_persistent_workers = False,
|
|
319
|
+
skip_memory_metrics = True,
|
|
320
|
+
use_legacy_prediction_loop = False,
|
|
321
|
+
push_to_hub = False,
|
|
322
|
+
resume_from_checkpoint = None,
|
|
323
|
+
hub_model_id = None,
|
|
324
|
+
hub_strategy = 'every_save',
|
|
325
|
+
hub_token = None,
|
|
326
|
+
hub_private_repo = None,
|
|
327
|
+
hub_always_push = False,
|
|
328
|
+
hub_revision = None,
|
|
329
|
+
gradient_checkpointing = True,
|
|
330
|
+
gradient_checkpointing_kwargs = None,
|
|
331
|
+
include_inputs_for_metrics = False,
|
|
332
|
+
eval_do_concat_batches = True,
|
|
333
|
+
fp16_backend = 'auto',
|
|
334
|
+
push_to_hub_model_id = None,
|
|
335
|
+
push_to_hub_organization = None,
|
|
336
|
+
push_to_hub_token = None,
|
|
337
|
+
mp_parameters = '',
|
|
338
|
+
auto_find_batch_size = False,
|
|
339
|
+
full_determinism = False,
|
|
340
|
+
torchdynamo = None,
|
|
341
|
+
ray_scope = 'last',
|
|
342
|
+
ddp_timeout = 1800,
|
|
343
|
+
torch_compile = False,
|
|
344
|
+
torch_compile_backend = None,
|
|
345
|
+
torch_compile_mode = None,
|
|
346
|
+
include_tokens_per_second = False,
|
|
347
|
+
include_num_input_tokens_seen = False,
|
|
348
|
+
neftune_noise_alpha = None,
|
|
349
|
+
optim_target_modules = None,
|
|
350
|
+
batch_eval_metrics = False,
|
|
351
|
+
eval_on_start = False,
|
|
352
|
+
use_liger_kernel = False,
|
|
353
|
+
liger_kernel_config = None,
|
|
354
|
+
eval_use_gather_object = False,
|
|
355
|
+
average_tokens_across_devices = True,
|
|
356
|
+
reward_model_path = None,
|
|
357
|
+
judge = None,
|
|
358
|
+
max_new_tokens = 64,
|
|
359
|
+
max_length = 512,
|
|
360
|
+
temperature = 0.9,
|
|
361
|
+
top_p = 1.0,
|
|
362
|
+
top_k = None,
|
|
363
|
+
min_p = None,
|
|
364
|
+
repetition_penalty = 1.0,
|
|
365
|
+
generation_kwargs = {},
|
|
366
|
+
use_transformers_paged = False,
|
|
367
|
+
cache_implementation = None,
|
|
368
|
+
missing_eos_penalty = None,
|
|
369
|
+
loss_type = 'sigmoid',
|
|
370
|
+
disable_dropout = True,
|
|
371
|
+
use_vllm = False,
|
|
372
|
+
vllm_model_impl = 'vllm',
|
|
373
|
+
vllm_guided_decoding_regex = None,
|
|
374
|
+
vllm_gpu_memory_utilization = 0.55,
|
|
375
|
+
vllm_mode = 'colocate',
|
|
376
|
+
vllm_server_base_url = None,
|
|
377
|
+
vllm_server_host = '0.0.0.0',
|
|
378
|
+
vllm_server_port = 8000,
|
|
379
|
+
vllm_server_timeout = 240.0,
|
|
380
|
+
vllm_tensor_parallel_size = 1,
|
|
381
|
+
ds3_gather_for_generation = True,
|
|
382
|
+
model_init_kwargs = None,
|
|
383
|
+
reward_weights = None,
|
|
384
|
+
dataset_num_proc = None,
|
|
385
|
+
gpu_memory_utilization = None,
|
|
386
|
+
vllm_sampling_params = None,
|
|
387
|
+
unsloth_num_chunks = -1,
|
|
388
|
+
max_seq_length = None,
|
|
389
|
+
**kwargs,
|
|
390
|
+
):
|
|
391
|
+
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!')
|
|
392
|
+
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!')
|
|
393
|
+
if output_dir is None and save_strategy == 'steps' and save_steps == 500:
|
|
394
|
+
output_dir = 'unsloth_training_checkpoints'
|
|
395
|
+
save_strategy = 'no'
|
|
396
|
+
if dataset_num_proc is None:
|
|
397
|
+
from multiprocessing import cpu_count
|
|
398
|
+
dataset_num_proc = min(max(cpu_count()+4, 2), 64)
|
|
399
|
+
if temperature <= 0:
|
|
400
|
+
raise MathError('Unsloth: Please set a positive non-zero temperature since your results will be wrong.')
|
|
401
|
+
elif temperature >= 10:
|
|
402
|
+
raise MathError('Unsloth: Please set a positive non-zero temperature less than 10, since sampling will be quite erratic.')
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
super().__init__(
|
|
406
|
+
output_dir = output_dir,
|
|
407
|
+
overwrite_output_dir = overwrite_output_dir,
|
|
408
|
+
do_train = do_train,
|
|
409
|
+
do_eval = do_eval,
|
|
410
|
+
do_predict = do_predict,
|
|
411
|
+
eval_strategy = eval_strategy,
|
|
412
|
+
prediction_loss_only = prediction_loss_only,
|
|
413
|
+
per_device_train_batch_size = per_device_train_batch_size,
|
|
414
|
+
per_device_eval_batch_size = per_device_eval_batch_size,
|
|
415
|
+
per_gpu_train_batch_size = per_gpu_train_batch_size,
|
|
416
|
+
per_gpu_eval_batch_size = per_gpu_eval_batch_size,
|
|
417
|
+
gradient_accumulation_steps = gradient_accumulation_steps,
|
|
418
|
+
eval_accumulation_steps = eval_accumulation_steps,
|
|
419
|
+
eval_delay = eval_delay,
|
|
420
|
+
torch_empty_cache_steps = torch_empty_cache_steps,
|
|
421
|
+
learning_rate = learning_rate,
|
|
422
|
+
weight_decay = weight_decay,
|
|
423
|
+
adam_beta1 = adam_beta1,
|
|
424
|
+
adam_beta2 = adam_beta2,
|
|
425
|
+
adam_epsilon = adam_epsilon,
|
|
426
|
+
max_grad_norm = max_grad_norm,
|
|
427
|
+
num_train_epochs = num_train_epochs,
|
|
428
|
+
max_steps = max_steps,
|
|
429
|
+
lr_scheduler_type = lr_scheduler_type,
|
|
430
|
+
warmup_ratio = warmup_ratio,
|
|
431
|
+
warmup_steps = warmup_steps,
|
|
432
|
+
log_level = log_level,
|
|
433
|
+
log_level_replica = log_level_replica,
|
|
434
|
+
log_on_each_node = log_on_each_node,
|
|
435
|
+
logging_dir = logging_dir,
|
|
436
|
+
logging_strategy = logging_strategy,
|
|
437
|
+
logging_first_step = logging_first_step,
|
|
438
|
+
logging_steps = logging_steps,
|
|
439
|
+
logging_nan_inf_filter = logging_nan_inf_filter,
|
|
440
|
+
save_strategy = save_strategy,
|
|
441
|
+
save_steps = save_steps,
|
|
442
|
+
save_total_limit = save_total_limit,
|
|
443
|
+
save_safetensors = save_safetensors,
|
|
444
|
+
save_on_each_node = save_on_each_node,
|
|
445
|
+
save_only_model = save_only_model,
|
|
446
|
+
restore_callback_states_from_checkpoint = restore_callback_states_from_checkpoint,
|
|
447
|
+
no_cuda = no_cuda,
|
|
448
|
+
use_cpu = use_cpu,
|
|
449
|
+
use_mps_device = use_mps_device,
|
|
450
|
+
seed = seed,
|
|
451
|
+
data_seed = data_seed,
|
|
452
|
+
jit_mode_eval = jit_mode_eval,
|
|
453
|
+
bf16 = bf16,
|
|
454
|
+
fp16 = fp16,
|
|
455
|
+
fp16_opt_level = fp16_opt_level,
|
|
456
|
+
half_precision_backend = half_precision_backend,
|
|
457
|
+
bf16_full_eval = bf16_full_eval,
|
|
458
|
+
fp16_full_eval = fp16_full_eval,
|
|
459
|
+
tf32 = tf32,
|
|
460
|
+
local_rank = local_rank,
|
|
461
|
+
ddp_backend = ddp_backend,
|
|
462
|
+
tpu_num_cores = tpu_num_cores,
|
|
463
|
+
tpu_metrics_debug = tpu_metrics_debug,
|
|
464
|
+
debug = debug,
|
|
465
|
+
dataloader_drop_last = dataloader_drop_last,
|
|
466
|
+
eval_steps = eval_steps,
|
|
467
|
+
dataloader_num_workers = dataloader_num_workers,
|
|
468
|
+
dataloader_prefetch_factor = dataloader_prefetch_factor,
|
|
469
|
+
past_index = past_index,
|
|
470
|
+
run_name = run_name,
|
|
471
|
+
disable_tqdm = disable_tqdm,
|
|
472
|
+
remove_unused_columns = remove_unused_columns,
|
|
473
|
+
label_names = label_names,
|
|
474
|
+
load_best_model_at_end = load_best_model_at_end,
|
|
475
|
+
metric_for_best_model = metric_for_best_model,
|
|
476
|
+
greater_is_better = greater_is_better,
|
|
477
|
+
ignore_data_skip = ignore_data_skip,
|
|
478
|
+
fsdp = fsdp,
|
|
479
|
+
fsdp_min_num_params = fsdp_min_num_params,
|
|
480
|
+
fsdp_config = fsdp_config,
|
|
481
|
+
fsdp_transformer_layer_cls_to_wrap = fsdp_transformer_layer_cls_to_wrap,
|
|
482
|
+
accelerator_config = accelerator_config,
|
|
483
|
+
parallelism_config = parallelism_config,
|
|
484
|
+
deepspeed = deepspeed,
|
|
485
|
+
label_smoothing_factor = label_smoothing_factor,
|
|
486
|
+
optim = optim,
|
|
487
|
+
optim_args = optim_args,
|
|
488
|
+
adafactor = adafactor,
|
|
489
|
+
group_by_length = group_by_length,
|
|
490
|
+
length_column_name = length_column_name,
|
|
491
|
+
report_to = report_to,
|
|
492
|
+
project = project,
|
|
493
|
+
trackio_space_id = trackio_space_id,
|
|
494
|
+
ddp_find_unused_parameters = ddp_find_unused_parameters,
|
|
495
|
+
ddp_bucket_cap_mb = ddp_bucket_cap_mb,
|
|
496
|
+
ddp_broadcast_buffers = ddp_broadcast_buffers,
|
|
497
|
+
dataloader_pin_memory = dataloader_pin_memory,
|
|
498
|
+
dataloader_persistent_workers = dataloader_persistent_workers,
|
|
499
|
+
skip_memory_metrics = skip_memory_metrics,
|
|
500
|
+
use_legacy_prediction_loop = use_legacy_prediction_loop,
|
|
501
|
+
push_to_hub = push_to_hub,
|
|
502
|
+
resume_from_checkpoint = resume_from_checkpoint,
|
|
503
|
+
hub_model_id = hub_model_id,
|
|
504
|
+
hub_strategy = hub_strategy,
|
|
505
|
+
hub_token = hub_token,
|
|
506
|
+
hub_private_repo = hub_private_repo,
|
|
507
|
+
hub_always_push = hub_always_push,
|
|
508
|
+
hub_revision = hub_revision,
|
|
509
|
+
gradient_checkpointing = gradient_checkpointing,
|
|
510
|
+
gradient_checkpointing_kwargs = gradient_checkpointing_kwargs,
|
|
511
|
+
include_inputs_for_metrics = include_inputs_for_metrics,
|
|
512
|
+
eval_do_concat_batches = eval_do_concat_batches,
|
|
513
|
+
fp16_backend = fp16_backend,
|
|
514
|
+
push_to_hub_model_id = push_to_hub_model_id,
|
|
515
|
+
push_to_hub_organization = push_to_hub_organization,
|
|
516
|
+
push_to_hub_token = push_to_hub_token,
|
|
517
|
+
mp_parameters = mp_parameters,
|
|
518
|
+
auto_find_batch_size = auto_find_batch_size,
|
|
519
|
+
full_determinism = full_determinism,
|
|
520
|
+
torchdynamo = torchdynamo,
|
|
521
|
+
ray_scope = ray_scope,
|
|
522
|
+
ddp_timeout = ddp_timeout,
|
|
523
|
+
torch_compile = torch_compile,
|
|
524
|
+
torch_compile_backend = torch_compile_backend,
|
|
525
|
+
torch_compile_mode = torch_compile_mode,
|
|
526
|
+
include_tokens_per_second = include_tokens_per_second,
|
|
527
|
+
include_num_input_tokens_seen = include_num_input_tokens_seen,
|
|
528
|
+
neftune_noise_alpha = neftune_noise_alpha,
|
|
529
|
+
optim_target_modules = optim_target_modules,
|
|
530
|
+
batch_eval_metrics = batch_eval_metrics,
|
|
531
|
+
eval_on_start = eval_on_start,
|
|
532
|
+
use_liger_kernel = use_liger_kernel,
|
|
533
|
+
liger_kernel_config = liger_kernel_config,
|
|
534
|
+
eval_use_gather_object = eval_use_gather_object,
|
|
535
|
+
average_tokens_across_devices = average_tokens_across_devices,
|
|
536
|
+
reward_model_path = reward_model_path,
|
|
537
|
+
judge = judge,
|
|
538
|
+
max_new_tokens = max_new_tokens,
|
|
539
|
+
max_length = max_length,
|
|
540
|
+
temperature = temperature,
|
|
541
|
+
top_p = top_p,
|
|
542
|
+
top_k = top_k,
|
|
543
|
+
min_p = min_p,
|
|
544
|
+
repetition_penalty = repetition_penalty,
|
|
545
|
+
generation_kwargs = generation_kwargs,
|
|
546
|
+
use_transformers_paged = use_transformers_paged,
|
|
547
|
+
cache_implementation = cache_implementation,
|
|
548
|
+
missing_eos_penalty = missing_eos_penalty,
|
|
549
|
+
loss_type = loss_type,
|
|
550
|
+
disable_dropout = disable_dropout,
|
|
551
|
+
use_vllm = use_vllm,
|
|
552
|
+
vllm_model_impl = vllm_model_impl,
|
|
553
|
+
vllm_guided_decoding_regex = vllm_guided_decoding_regex,
|
|
554
|
+
vllm_gpu_memory_utilization = vllm_gpu_memory_utilization,
|
|
555
|
+
vllm_mode = vllm_mode,
|
|
556
|
+
vllm_server_base_url = vllm_server_base_url,
|
|
557
|
+
vllm_server_host = vllm_server_host,
|
|
558
|
+
vllm_server_port = vllm_server_port,
|
|
559
|
+
vllm_server_timeout = vllm_server_timeout,
|
|
560
|
+
vllm_tensor_parallel_size = vllm_tensor_parallel_size,
|
|
561
|
+
ds3_gather_for_generation = ds3_gather_for_generation,
|
|
562
|
+
model_init_kwargs = model_init_kwargs,
|
|
563
|
+
reward_weights = reward_weights,
|
|
564
|
+
dataset_num_proc = dataset_num_proc,
|
|
565
|
+
gpu_memory_utilization = gpu_memory_utilization,**kwargs)
|
|
566
|
+
self.vllm_sampling_params = vllm_sampling_params
|
|
567
|
+
self.unsloth_num_chunks = unsloth_num_chunks
|
|
568
|
+
self.max_seq_length = max_seq_length
|
|
569
|
+
pass
|
|
570
|
+
|
|
571
|
+
class _UnslothNashMDTrainer(OnlineDPOTrainer):
|
|
572
|
+
""""""
|
|
573
|
+
|
|
574
|
+
_tag_names = ["trl", "nash-md"]
|
|
575
|
+
_name = "Nash-MD"
|
|
576
|
+
_paper = {
|
|
577
|
+
"title": "Nash Learning from Human Feedback",
|
|
578
|
+
"id": "2312.00886",
|
|
579
|
+
# docstyle-ignore
|
|
580
|
+
"citation": textwrap.dedent("""\
|
|
581
|
+
@inproceedings{munos2024nash,
|
|
582
|
+
title = {{Nash Learning from Human Feedback}},
|
|
583
|
+
author = {R{\'{e}}mi Munos and Michal Valko and Daniele Calandriello and Mohammad Gheshlaghi Azar and Mark Rowland and Zhaohan Daniel Guo and Yunhao Tang and Matthieu Geist and Thomas Mesnard and C{\\^{o}}me Fiegel and Andrea Michi and Marco Selvi and Sertan Girgin and Nikola Momchev and Olivier Bachem and Daniel J. Mankowitz and Doina Precup and Bilal Piot},
|
|
584
|
+
year = 2024,
|
|
585
|
+
booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024},
|
|
586
|
+
publisher = {OpenReview.net},
|
|
587
|
+
url = {https://openreview.net/forum?id=Y5AmNYiyCQ}
|
|
588
|
+
}"""),
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
def __init__(
|
|
592
|
+
self,
|
|
593
|
+
model: Union[PreTrainedModel, nn.Module] = None,
|
|
594
|
+
ref_model: Union[PreTrainedModel, nn.Module] = None,
|
|
595
|
+
reward_funcs: Union[PreTrainedModel, nn.Module, None] = None,
|
|
596
|
+
judge: Optional[BasePairwiseJudge] = None,
|
|
597
|
+
args: Optional[NashMDConfig] = None,
|
|
598
|
+
data_collator: Optional[Callable] = None,
|
|
599
|
+
train_dataset: Optional[Union[Dataset, IterableDataset]] = None,
|
|
600
|
+
eval_dataset: Optional[Union[Dataset, dict[str, Dataset]]] = None,
|
|
601
|
+
processing_class: Optional[
|
|
602
|
+
Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin]
|
|
603
|
+
] = None,
|
|
604
|
+
peft_config: Optional[dict] = None,
|
|
605
|
+
compute_metrics: Optional[Callable[[EvalPrediction], dict]] = None,
|
|
606
|
+
callbacks: Optional[list[TrainerCallback]] = None,
|
|
607
|
+
optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
|
|
608
|
+
preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
|
|
609
|
+
# Deprecated parameters
|
|
610
|
+
reward_model: Optional[Union[PreTrainedModel, nn.Module]] = None,
|
|
611
|
+
) -> None:
|
|
612
|
+
super().__init__(
|
|
613
|
+
model=model,
|
|
614
|
+
ref_model=ref_model,
|
|
615
|
+
reward_funcs=reward_funcs,
|
|
616
|
+
judge=judge,
|
|
617
|
+
args=args,
|
|
618
|
+
data_collator=data_collator,
|
|
619
|
+
train_dataset=train_dataset,
|
|
620
|
+
eval_dataset=eval_dataset,
|
|
621
|
+
processing_class=processing_class,
|
|
622
|
+
reward_processing_classes=processing_class,
|
|
623
|
+
peft_config=peft_config,
|
|
624
|
+
compute_metrics=compute_metrics,
|
|
625
|
+
callbacks=callbacks,
|
|
626
|
+
optimizers=optimizers,
|
|
627
|
+
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
|
|
628
|
+
reward_model=reward_model,
|
|
629
|
+
)
|
|
630
|
+
|
|
631
|
+
self._mixture_coef = self.args.mixture_coef
|
|
632
|
+
|
|
633
|
+
# Overwrite the stats dictionary to include NashMD specific statistics
|
|
634
|
+
self.stats = {
|
|
635
|
+
# Remove "non_score_reward", "rlhf_reward", "scores_margin"
|
|
636
|
+
# Add "mixture_coef"
|
|
637
|
+
"loss/kl": [],
|
|
638
|
+
"objective/entropy": [],
|
|
639
|
+
"loss/score": [],
|
|
640
|
+
"rewards/probabilities": [],
|
|
641
|
+
"rewards/accuracies": [],
|
|
642
|
+
"rewards/margins": [],
|
|
643
|
+
"logps/chosen": [],
|
|
644
|
+
"logps/rejected": [],
|
|
645
|
+
"val/model_contain_eos_token": [],
|
|
646
|
+
"val/ref_contain_eos_token": [],
|
|
647
|
+
"beta": [],
|
|
648
|
+
"mixture_coef": [],
|
|
649
|
+
}
|
|
650
|
+
if self.reward_funcs is not None:
|
|
651
|
+
if len(self.reward_funcs) != 1:
|
|
652
|
+
raise ValueError("NashMDTrainer only supports one reward function/model.")
|
|
653
|
+
self.reward_funcs = self.reward_funcs[0]
|
|
654
|
+
self.stats["rewards/chosen"] = []
|
|
655
|
+
self.stats["rewards/rejected"] = []
|
|
656
|
+
|
|
657
|
+
@property
|
|
658
|
+
def mixture_coef(self):
|
|
659
|
+
if isinstance(self._mixture_coef, list):
|
|
660
|
+
epoch = self.state.epoch
|
|
661
|
+
return self._mixture_coef[epoch] if epoch < len(self._mixture_coef) else self._mixture_coef[-1]
|
|
662
|
+
else:
|
|
663
|
+
return self._mixture_coef
|
|
664
|
+
|
|
665
|
+
def _generate_completions(self, model, prompts):
|
|
666
|
+
# Generate completions from the policy model.
|
|
667
|
+
with unwrap_model_for_generation(model, self.accelerator) as unwrapped_policy_for_gen_ctx:
|
|
668
|
+
model_output = unwrapped_policy_for_gen_ctx.generate(
|
|
669
|
+
input_ids=prompts["input_ids"],
|
|
670
|
+
attention_mask=prompts["attention_mask"],
|
|
671
|
+
generation_config=self.generation_config,
|
|
672
|
+
)
|
|
673
|
+
|
|
674
|
+
# Get the DDP/FSDP unwrapped version of the main model.
|
|
675
|
+
# This will be the policy model for GeometricMixtureWrapper (PEFT adapters active if PEFT is used).
|
|
676
|
+
policy_model_for_gmw = self.accelerator.unwrap_model(model)
|
|
677
|
+
|
|
678
|
+
# Determine the correct reference model for GeometricMixtureWrapper.
|
|
679
|
+
# This also needs to be DDP/FSDP unwrapped.
|
|
680
|
+
ref_model_for_gmw: torch.nn.Module
|
|
681
|
+
if self.ref_model is None:
|
|
682
|
+
# No explicit ref_model is provided.
|
|
683
|
+
# Use the base of the main `model` if it's a PEFT model.
|
|
684
|
+
# policy_model_for_gmw is already DDP-unwrapped.
|
|
685
|
+
if is_peft_available() and isinstance(policy_model_for_gmw, PeftModel):
|
|
686
|
+
ref_model_for_gmw = policy_model_for_gmw.get_base_model()
|
|
687
|
+
else:
|
|
688
|
+
# Not a PEFT model (or PEFT not available), or already a base model.
|
|
689
|
+
# Use the DDP-unwrapped policy model itself as the reference.
|
|
690
|
+
ref_model_for_gmw = policy_model_for_gmw
|
|
691
|
+
else:
|
|
692
|
+
# An explicit ref_model is provided. Unwrap it for DDP/FSDP.
|
|
693
|
+
ref_model_for_gmw = self.accelerator.unwrap_model(self.ref_model)
|
|
694
|
+
|
|
695
|
+
# Both models given to GeometricMixtureWrapper (policy_model_for_gmw and ref_model_for_gmw) are DDP-unwrapped.
|
|
696
|
+
with torch.no_grad(): # Ensure no_grad context for mixture model generation
|
|
697
|
+
mixture_model = GeometricMixtureWrapper(
|
|
698
|
+
model=policy_model_for_gmw,
|
|
699
|
+
ref_model=ref_model_for_gmw,
|
|
700
|
+
generation_config=self.generation_config,
|
|
701
|
+
mixture_coef=self.mixture_coef,
|
|
702
|
+
device=self.accelerator.device,
|
|
703
|
+
)
|
|
704
|
+
|
|
705
|
+
mixture_output = mixture_model.generate(
|
|
706
|
+
input_ids=prompts["input_ids"],
|
|
707
|
+
attention_mask=prompts["attention_mask"],
|
|
708
|
+
generation_config=self.generation_config,
|
|
709
|
+
)
|
|
710
|
+
|
|
711
|
+
return model_output, mixture_output
|
|
712
|
+
|
|
713
|
+
def _process_completions(self, model_output, mixture_output, prompts):
|
|
714
|
+
context_length = prompts["input_ids"].shape[1]
|
|
715
|
+
|
|
716
|
+
# Process model completions
|
|
717
|
+
model_completion_ids = model_output[:, context_length:]
|
|
718
|
+
model_completion_ids, model_completion_mask = truncate_right(
|
|
719
|
+
model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id
|
|
720
|
+
)
|
|
721
|
+
model_data = {
|
|
722
|
+
"input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1),
|
|
723
|
+
"attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1),
|
|
724
|
+
"raw": prompts["raw"],
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
# Process reference model completions
|
|
728
|
+
mixture_completion_ids = mixture_output[:, context_length:]
|
|
729
|
+
mixture_completion_ids, mixture_completion_mask = truncate_right(
|
|
730
|
+
mixture_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id
|
|
731
|
+
)
|
|
732
|
+
mixture_data = {
|
|
733
|
+
"input_ids": torch.cat((prompts["input_ids"], mixture_completion_ids), dim=1),
|
|
734
|
+
"attention_mask": torch.cat((prompts["attention_mask"], mixture_completion_mask), dim=1),
|
|
735
|
+
"raw": prompts["raw"],
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
return model_data, mixture_data
|
|
739
|
+
|
|
740
|
+
def _compute_rewards(self, model_data, mixture_data, context_length):
|
|
741
|
+
with torch.no_grad():
|
|
742
|
+
_, model_scores, _ = get_reward(
|
|
743
|
+
self.reward_funcs, model_data["input_ids"], self.processing_class.pad_token_id, context_length
|
|
744
|
+
)
|
|
745
|
+
_, mixture_scores, _ = get_reward(
|
|
746
|
+
self.reward_funcs, mixture_data["input_ids"], self.processing_class.pad_token_id, context_length
|
|
747
|
+
)
|
|
748
|
+
|
|
749
|
+
# Apply EOS penalty if needed
|
|
750
|
+
if self.args.missing_eos_penalty is not None:
|
|
751
|
+
model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1)
|
|
752
|
+
mixture_contain_eos = torch.any(mixture_data["input_ids"] == self.processing_class.eos_token_id, dim=-1)
|
|
753
|
+
model_scores[~model_contain_eos] -= self.args.missing_eos_penalty
|
|
754
|
+
mixture_scores[~mixture_contain_eos] -= self.args.missing_eos_penalty
|
|
755
|
+
|
|
756
|
+
return model_scores, mixture_scores
|
|
757
|
+
|
|
758
|
+
def _compute_judge(self, model_data, mixture_data, context_length):
|
|
759
|
+
prompts = model_data["raw"]
|
|
760
|
+
model_data_completions = self.processing_class.batch_decode(
|
|
761
|
+
model_data["input_ids"][:, context_length:], skip_special_tokens=True
|
|
762
|
+
)
|
|
763
|
+
model_data_completions = [completion.strip() for completion in model_data_completions]
|
|
764
|
+
|
|
765
|
+
mixture_data_completions = self.processing_class.batch_decode(
|
|
766
|
+
mixture_data["input_ids"][:, context_length:], skip_special_tokens=True
|
|
767
|
+
)
|
|
768
|
+
mixture_data_completions = [completion.strip() for completion in mixture_data_completions]
|
|
769
|
+
if is_conversational({"prompt": prompts[0]}):
|
|
770
|
+
model_data_completions = [
|
|
771
|
+
[{"role": "assistant", "content": completion}] for completion in model_data_completions
|
|
772
|
+
]
|
|
773
|
+
environment = jinja2.Environment()
|
|
774
|
+
template = environment.from_string(SIMPLE_CHAT_TEMPLATE)
|
|
775
|
+
prompts = [template.render(messages=message) for message in prompts]
|
|
776
|
+
model_data_completions = [template.render(messages=completion) for completion in model_data_completions]
|
|
777
|
+
|
|
778
|
+
mixture_data_completions = [
|
|
779
|
+
[{"role": "assistant", "content": completion}] for completion in mixture_data_completions
|
|
780
|
+
]
|
|
781
|
+
mixture_data_completions = [
|
|
782
|
+
template.render(messages=completion) for completion in mixture_data_completions
|
|
783
|
+
]
|
|
784
|
+
|
|
785
|
+
probability = self.judge.judge(
|
|
786
|
+
prompts,
|
|
787
|
+
list(zip(model_data_completions, mixture_data_completions)),
|
|
788
|
+
return_scores=True,
|
|
789
|
+
)
|
|
790
|
+
return torch.tensor(probability, device=model_data["input_ids"].device)
|
|
791
|
+
|
|
792
|
+
def _compute_logprobs(self, model, model_data, context_length):
|
|
793
|
+
def compute_logprobs_for_data(m, data):
|
|
794
|
+
output = m(data["input_ids"], attention_mask=data["attention_mask"])
|
|
795
|
+
logits = output.logits[:, context_length - 1 : -1]
|
|
796
|
+
token_logprobs = selective_log_softmax(logits, data["input_ids"][:, context_length:])
|
|
797
|
+
return token_logprobs
|
|
798
|
+
|
|
799
|
+
# Compute logprobs for model completions under the model
|
|
800
|
+
model_logprobs_model_data = compute_logprobs_for_data(model, model_data)
|
|
801
|
+
|
|
802
|
+
# Compute logprobs of model completions under the reference model
|
|
803
|
+
with torch.no_grad():
|
|
804
|
+
if self.ref_model is None:
|
|
805
|
+
with model.disable_adapter():
|
|
806
|
+
ref_logprobs_model_data = compute_logprobs_for_data(model, model_data)
|
|
807
|
+
else:
|
|
808
|
+
ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data)
|
|
809
|
+
|
|
810
|
+
# Mask padding tokens
|
|
811
|
+
model_padding_mask = model_data["attention_mask"][:, context_length:] == 0
|
|
812
|
+
model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0)
|
|
813
|
+
ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0)
|
|
814
|
+
|
|
815
|
+
return (model_logprobs_model_data, ref_logprobs_model_data)
|
|
816
|
+
|
|
817
|
+
def _compute_losses(
|
|
818
|
+
self,
|
|
819
|
+
model_logprobs_model_data,
|
|
820
|
+
ref_logprobs_model_data,
|
|
821
|
+
probability,
|
|
822
|
+
):
|
|
823
|
+
# reinforce score where 0.5 is a control variate
|
|
824
|
+
score = (probability - 0.5) * model_logprobs_model_data.sum(1)
|
|
825
|
+
|
|
826
|
+
# kl divergence via reinforce
|
|
827
|
+
with torch.no_grad():
|
|
828
|
+
log_ratio = model_logprobs_model_data - ref_logprobs_model_data
|
|
829
|
+
kl_div_log = log_ratio.sum(1)
|
|
830
|
+
kl_div_loss = (log_ratio * model_logprobs_model_data).sum(1)
|
|
831
|
+
|
|
832
|
+
# final loss
|
|
833
|
+
loss = self.beta * kl_div_loss - score
|
|
834
|
+
|
|
835
|
+
return loss.mean(), score, kl_div_log
|
|
836
|
+
|
|
837
|
+
def _log_statistics(
|
|
838
|
+
self,
|
|
839
|
+
model_data,
|
|
840
|
+
mixture_data,
|
|
841
|
+
model_logprobs_model_data,
|
|
842
|
+
ref_logprobs_model_data,
|
|
843
|
+
probability,
|
|
844
|
+
score,
|
|
845
|
+
kl_div,
|
|
846
|
+
context_length,
|
|
847
|
+
model_scores=None,
|
|
848
|
+
mixture_scores=None,
|
|
849
|
+
):
|
|
850
|
+
# Helper function to gather and compute mean
|
|
851
|
+
def gather_mean(tensor):
|
|
852
|
+
return self.accelerator.gather_for_metrics(tensor).mean().item()
|
|
853
|
+
|
|
854
|
+
# Log score
|
|
855
|
+
self.stats["loss/score"].append(gather_mean(score))
|
|
856
|
+
# Log KL divergence
|
|
857
|
+
self.stats["loss/kl"].append(gather_mean(kl_div))
|
|
858
|
+
|
|
859
|
+
# Log logprobs
|
|
860
|
+
model_logprobs_model_data_sum = model_logprobs_model_data.sum(1)
|
|
861
|
+
ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1)
|
|
862
|
+
|
|
863
|
+
self.stats["logps/chosen"].append(gather_mean(model_logprobs_model_data_sum))
|
|
864
|
+
self.stats["logps/rejected"].append(gather_mean(ref_logprobs_model_data_sum))
|
|
865
|
+
|
|
866
|
+
# Log rewards
|
|
867
|
+
if self.reward_funcs is not None:
|
|
868
|
+
self.stats["rewards/chosen"].append(gather_mean(model_scores))
|
|
869
|
+
self.stats["rewards/rejected"].append(gather_mean(mixture_scores))
|
|
870
|
+
|
|
871
|
+
# Log probabilities
|
|
872
|
+
self.stats["rewards/probabilities"].append(gather_mean(probability))
|
|
873
|
+
|
|
874
|
+
# Calculate entropy for model data
|
|
875
|
+
entropy_model_data = -model_logprobs_model_data.sum(1)
|
|
876
|
+
self.stats["objective/entropy"].append(gather_mean(entropy_model_data))
|
|
877
|
+
|
|
878
|
+
# Calculate margins
|
|
879
|
+
margin = model_logprobs_model_data_sum - ref_logprobs_model_data_sum
|
|
880
|
+
self.stats["rewards/margins"].append(gather_mean(margin))
|
|
881
|
+
|
|
882
|
+
# Calculate accuracy
|
|
883
|
+
accuracy = (margin > 0).float()
|
|
884
|
+
self.stats["rewards/accuracies"].append(gather_mean(accuracy))
|
|
885
|
+
|
|
886
|
+
# Log EOS token statistics
|
|
887
|
+
model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1)
|
|
888
|
+
mixture_eos = (mixture_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1)
|
|
889
|
+
self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float()))
|
|
890
|
+
self.stats["val/ref_contain_eos_token"].append(gather_mean(mixture_eos.float()))
|
|
891
|
+
|
|
892
|
+
# Log beta and mixture coef
|
|
893
|
+
self.stats["beta"].append(self.beta)
|
|
894
|
+
self.stats["mixture_coef"].append(self.mixture_coef)
|
|
895
|
+
|
|
896
|
+
def training_step(
|
|
897
|
+
self, model: nn.Module, inputs: dict[str, Union[torch.Tensor, Any]], num_items_in_batch: Optional[int] = None
|
|
898
|
+
) -> torch.Tensor:
|
|
899
|
+
model.train()
|
|
900
|
+
|
|
901
|
+
# Apply chat template and tokenize the input
|
|
902
|
+
batch_size = len(next(iter(inputs.values())))
|
|
903
|
+
prompts = inputs["prompt"]
|
|
904
|
+
inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)]
|
|
905
|
+
inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs]
|
|
906
|
+
inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs]
|
|
907
|
+
inputs = self.data_collator(inputs)
|
|
908
|
+
|
|
909
|
+
# need the prompt_ only
|
|
910
|
+
inputs = self._prepare_inputs(inputs)
|
|
911
|
+
context_length = inputs["prompt_input_ids"].shape[1]
|
|
912
|
+
prompts = {
|
|
913
|
+
"input_ids": inputs["prompt_input_ids"],
|
|
914
|
+
"attention_mask": inputs["prompt_attention_mask"],
|
|
915
|
+
"raw": prompts,
|
|
916
|
+
}
|
|
917
|
+
del inputs
|
|
918
|
+
|
|
919
|
+
# Sample completions from both the model and the reference model
|
|
920
|
+
model_output, mixture_output = self._generate_completions(model, prompts)
|
|
921
|
+
|
|
922
|
+
# Process model completions
|
|
923
|
+
model_data, mixture_data = self._process_completions(model_output, mixture_output, prompts)
|
|
924
|
+
|
|
925
|
+
# Compute rewards
|
|
926
|
+
if self.reward_funcs is not None:
|
|
927
|
+
model_scores, mixture_scores = self._compute_rewards(model_data, mixture_data, context_length)
|
|
928
|
+
# probability of the model data vs the mixture data
|
|
929
|
+
probability = F.sigmoid(model_scores - mixture_scores)
|
|
930
|
+
else:
|
|
931
|
+
model_scores, mixture_scores = None, None
|
|
932
|
+
probability = self._compute_judge(model_data, mixture_data, context_length)
|
|
933
|
+
|
|
934
|
+
# Compute logprobs
|
|
935
|
+
model_logprobs_model_data, ref_logprobs_model_data = self._compute_logprobs(model, model_data, context_length)
|
|
936
|
+
|
|
937
|
+
# Compute loss
|
|
938
|
+
loss, score, kl_div = self._compute_losses(model_logprobs_model_data, ref_logprobs_model_data, probability)
|
|
939
|
+
|
|
940
|
+
# Log everything
|
|
941
|
+
self._log_statistics(
|
|
942
|
+
model_data,
|
|
943
|
+
mixture_data,
|
|
944
|
+
model_logprobs_model_data.detach(),
|
|
945
|
+
ref_logprobs_model_data,
|
|
946
|
+
probability,
|
|
947
|
+
score.detach(),
|
|
948
|
+
kl_div.detach(),
|
|
949
|
+
context_length,
|
|
950
|
+
model_scores,
|
|
951
|
+
mixture_scores,
|
|
952
|
+
)
|
|
953
|
+
|
|
954
|
+
if (
|
|
955
|
+
self.args.torch_empty_cache_steps is not None
|
|
956
|
+
and self.state.global_step % self.args.torch_empty_cache_steps == 0
|
|
957
|
+
):
|
|
958
|
+
empty_cache()
|
|
959
|
+
|
|
960
|
+
kwargs = {}
|
|
961
|
+
# For LOMO optimizers you need to explicitly use the learning rate
|
|
962
|
+
if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]:
|
|
963
|
+
kwargs["learning_rate"] = self._get_learning_rate()
|
|
964
|
+
|
|
965
|
+
if self.args.n_gpu > 1:
|
|
966
|
+
loss = loss.mean() # mean() to average on multi-gpu parallel training
|
|
967
|
+
|
|
968
|
+
self.accelerator.backward(loss, **kwargs)
|
|
969
|
+
|
|
970
|
+
return loss.detach() / self.args.gradient_accumulation_steps
|
|
971
|
+
class UnslothNashMDTrainer(_UnslothNashMDTrainer):
|
|
972
|
+
"""
|
|
973
|
+
|
|
974
|
+
Trainer for the Nash-MD method.
|
|
975
|
+
|
|
976
|
+
It is implemented as a subclass of [`OnlineDPOTrainer`].
|
|
977
|
+
|
|
978
|
+
Args:
|
|
979
|
+
model ([`~transformers.PreTrainedModel`]):
|
|
980
|
+
The model to train, preferably an `AutoModelForCausalLM`.
|
|
981
|
+
ref_model ([`PreTrainedModelWrapper`]):
|
|
982
|
+
Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation
|
|
983
|
+
and loss. If no reference model is provided, the trainer will create a reference model with the same
|
|
984
|
+
architecture as the model to be optimized.
|
|
985
|
+
reward_funcs ([`~transformers.PreTrainedModel`]):
|
|
986
|
+
The reward model to score completions with, preferably an
|
|
987
|
+
[`~transformers.AutoModelForSequenceClassification`].
|
|
988
|
+
judge ([`BasePairwiseJudge`]):
|
|
989
|
+
The judge to use for pairwise comparison of model completions.
|
|
990
|
+
args ([`NashMDConfig`]):
|
|
991
|
+
The NashMD config arguments to use for training.
|
|
992
|
+
data_collator ([`~transformers.DataCollator`]):
|
|
993
|
+
The data collator to use for training. If None is specified, the default data collator
|
|
994
|
+
([`DPODataCollatorWithPadding`]) will be used which will pad the sequences to the maximum length of the
|
|
995
|
+
sequences in the batch, given a dataset of paired sequences.
|
|
996
|
+
train_dataset ([`~datasets.Dataset`]):
|
|
997
|
+
The dataset to use for training.
|
|
998
|
+
eval_dataset ([`~datasets.Dataset`]):
|
|
999
|
+
The dataset to use for evaluation.
|
|
1000
|
+
processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
|
|
1001
|
+
Processing class used to process the data. If provided, will be used to automatically process the inputs
|
|
1002
|
+
for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
|
|
1003
|
+
reuse the fine-tuned model.
|
|
1004
|
+
peft_config (`dict`):
|
|
1005
|
+
The peft config to use for training.
|
|
1006
|
+
compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
|
|
1007
|
+
The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
|
|
1008
|
+
metric values.
|
|
1009
|
+
callbacks (`list[transformers.TrainerCallback]`):
|
|
1010
|
+
The callbacks to use for training.
|
|
1011
|
+
optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
|
|
1012
|
+
The optimizer and scheduler to use for training.
|
|
1013
|
+
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
|
|
1014
|
+
The function to use to preprocess the logits before computing the metrics.
|
|
1015
|
+
|
|
1016
|
+
reward_model:
|
|
1017
|
+
|
|
1018
|
+
<Deprecated version="0.22.0">
|
|
1019
|
+
|
|
1020
|
+
This parameter is deprecated and will be removed in version 0.25.0. Use `reward_funcs` instead.
|
|
1021
|
+
|
|
1022
|
+
</Deprecated>
|
|
1023
|
+
|
|
1024
|
+
"""
|
|
1025
|
+
def __init__(
|
|
1026
|
+
self,
|
|
1027
|
+
model = None,
|
|
1028
|
+
ref_model = None,
|
|
1029
|
+
reward_funcs = None,
|
|
1030
|
+
judge = None,
|
|
1031
|
+
args = None,
|
|
1032
|
+
data_collator = None,
|
|
1033
|
+
train_dataset = None,
|
|
1034
|
+
eval_dataset = None,
|
|
1035
|
+
processing_class = None,
|
|
1036
|
+
peft_config = None,
|
|
1037
|
+
compute_metrics = None,
|
|
1038
|
+
callbacks = None,
|
|
1039
|
+
preprocess_logits_for_metrics = None,
|
|
1040
|
+
reward_model = None,
|
|
1041
|
+
**kwargs
|
|
1042
|
+
):
|
|
1043
|
+
if args is None: args = UnslothNashMDConfig()
|
|
1044
|
+
use_bf16 = getattr(args, 'bf16', False)
|
|
1045
|
+
if type(use_bf16) is not bool: use_bf16 = False
|
|
1046
|
+
use_fp16 = getattr(args, 'fp16', False)
|
|
1047
|
+
if type(use_fp16) is not bool: use_fp16 = False
|
|
1048
|
+
force_float32 = False
|
|
1049
|
+
full_finetuning = os.environ.get('UNSLOTH_ENABLE_FULL_FINETUNING', '0') == '1'
|
|
1050
|
+
if not full_finetuning and (os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '1'):
|
|
1051
|
+
print('Unsloth: Switching to float32 training since model cannot work with float16')
|
|
1052
|
+
force_float32 = True
|
|
1053
|
+
mixed_precision_dtype = os.environ.get('UNSLOTH_MIXED_PRECISION', 'float32')
|
|
1054
|
+
dtype = getattr(model.config, 'dtype', None) or getattr(model.config, 'torch_dtype', None)
|
|
1055
|
+
if dtype is None: dtype = model.get_input_embeddings().weight.dtype
|
|
1056
|
+
from unsloth_zoo.utils import _get_dtype
|
|
1057
|
+
dtype = _get_dtype(dtype)
|
|
1058
|
+
float16 = dtype == torch.float16
|
|
1059
|
+
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`')
|
|
1060
|
+
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`')
|
|
1061
|
+
if force_float32:
|
|
1062
|
+
# Forced float32 training
|
|
1063
|
+
args.fp16 = False
|
|
1064
|
+
args.bf16 = False
|
|
1065
|
+
os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'
|
|
1066
|
+
if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'
|
|
1067
|
+
# args.mixed_precision is a new argument which needs to be set now
|
|
1068
|
+
elif (not use_bf16 and not use_fp16) and mixed_precision_dtype == 'float32':
|
|
1069
|
+
# Mixed precision training
|
|
1070
|
+
args.fp16 = float16
|
|
1071
|
+
args.bf16 = not float16
|
|
1072
|
+
os.environ['ACCELERATE_MIXED_PRECISION'] = 'fp16' if float16 else 'bf16'
|
|
1073
|
+
if hasattr(args, 'mixed_precision'): args.mixed_precision = 'fp16' if float16 else 'bf16'
|
|
1074
|
+
# args.mixed_precision is a new argument which needs to be set now
|
|
1075
|
+
elif mixed_precision_dtype == 'bfloat16':
|
|
1076
|
+
# Both False since bfloat16 full finetuning doesn't do any autocasting.
|
|
1077
|
+
args.fp16 = False
|
|
1078
|
+
args.bf16 = False
|
|
1079
|
+
os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'
|
|
1080
|
+
if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'
|
|
1081
|
+
# args.mixed_precision is a new argument which needs to be set now
|
|
1082
|
+
|
|
1083
|
+
if getattr(args, 'eval_dataset', None) is not None and getattr(args, 'eval_strategy', 'no') == 'no':
|
|
1084
|
+
args.eval_strategy = 'steps'
|
|
1085
|
+
if getattr(args, 'eval_steps', None) is None: args.eval_steps = 0.1
|
|
1086
|
+
ga_steps = getattr(args, 'gradient_accumulation_steps', None)
|
|
1087
|
+
if ga_steps is not None and ga_steps > 1:
|
|
1088
|
+
from transformers import __version__ as transformers_version
|
|
1089
|
+
if Version(transformers_version) <= Version('4.45.2'):
|
|
1090
|
+
print('**** Unsloth: Please use our fixed gradient_accumulation_steps by updating transformers, TRL and Unsloth!\n'
|
|
1091
|
+
'`pip install --upgrade --no-cache-dir --force-reinstall --no-deps unsloth transformers trl unsloth_zoo`')
|
|
1092
|
+
if getattr(args, 'eval_strategy', 'no') != 'no':
|
|
1093
|
+
eval_bsz = getattr(args, 'per_device_eval_batch_size', 8)
|
|
1094
|
+
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
|
|
1095
|
+
if getattr(args, 'eval_accumulation_steps', None) is None and ga_steps is not None: args.eval_accumulation_steps = ga_steps
|
|
1096
|
+
fp16_full_eval = getattr(args, 'fp16_full_eval', False)
|
|
1097
|
+
if type(fp16_full_eval) is not bool: fp16_full_eval = False
|
|
1098
|
+
bf16_full_eval = getattr(args, 'bf16_full_eval', False)
|
|
1099
|
+
if type(bf16_full_eval) is not bool: bf16_full_eval = False
|
|
1100
|
+
if args.fp16 and bf16_full_eval: args.bf16_full_eval = False; args.fp16_full_eval = True
|
|
1101
|
+
if args.bf16 and fp16_full_eval: args.bf16_full_eval = True; args.fp16_full_eval = False
|
|
1102
|
+
if force_float32:
|
|
1103
|
+
args.bf16_full_eval = False
|
|
1104
|
+
args.fp16_full_eval = False
|
|
1105
|
+
elif os.environ.get('UNSLOTH_MIXED_PRECISION', 'float32') == 'bfloat16':
|
|
1106
|
+
args.bf16_full_eval = True
|
|
1107
|
+
args.fp16_full_eval = False
|
|
1108
|
+
elif not bf16_full_eval and not fp16_full_eval:
|
|
1109
|
+
args.bf16_full_eval = args.bf16
|
|
1110
|
+
args.fp16_full_eval = args.fp16
|
|
1111
|
+
_output_logits = False
|
|
1112
|
+
if locals().get('compute_metrics', None) is not None: _output_logits = True
|
|
1113
|
+
if locals().get('preprocess_logits_for_metrics', None) is not None: _output_logits = True
|
|
1114
|
+
if _output_logits:
|
|
1115
|
+
os.environ['UNSLOTH_RETURN_LOGITS'] = '1'
|
|
1116
|
+
if 'max_seq_length' not in locals() and not hasattr(args, 'max_seq_length'):
|
|
1117
|
+
pass
|
|
1118
|
+
else:
|
|
1119
|
+
model_max_seq_length = getattr(model, 'max_seq_length', None)
|
|
1120
|
+
args_max_seq_length = getattr(args, 'max_seq_length', None)
|
|
1121
|
+
if args_max_seq_length is None and model_max_seq_length is not None:
|
|
1122
|
+
max_seq_length = model.max_seq_length
|
|
1123
|
+
if hasattr(args, 'max_seq_length'): args.max_seq_length = max_seq_length
|
|
1124
|
+
if model is not None and hasattr(model, 'for_training'):
|
|
1125
|
+
model.for_training(use_gradient_checkpointing=getattr(args, 'gradient_checkpointing', True))
|
|
1126
|
+
if 'tokenizer' in locals() and hasattr(tokenizer, 'padding_side'): tokenizer.padding_side = 'right'
|
|
1127
|
+
if 'processing_class' in locals():
|
|
1128
|
+
if hasattr(processing_class, 'padding_side'): processing_class.padding_side = 'right'
|
|
1129
|
+
if hasattr(processing_class, 'tokenizer') and hasattr(processing_class.tokenizer, 'padding_side'): processing_class.tokenizer.padding_side = 'right'
|
|
1130
|
+
__tokenizer = processing_class if 'processing_class' in locals() else tokenizer
|
|
1131
|
+
from unsloth_zoo.vision_utils import UnslothVisionDataCollator
|
|
1132
|
+
if not isinstance(data_collator, UnslothVisionDataCollator):
|
|
1133
|
+
if isinstance(data_collator, DataCollatorForSeq2Seq) and 'labels' not in train_dataset.column_names:
|
|
1134
|
+
data_collator = TransformersDataCollatorForLanguageModeling(
|
|
1135
|
+
__tokenizer,
|
|
1136
|
+
mlm = False,
|
|
1137
|
+
mlm_probability = 0.0,
|
|
1138
|
+
pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
|
|
1139
|
+
)
|
|
1140
|
+
elif isinstance(data_collator, TransformersDataCollatorForLanguageModeling) and 'labels' in train_dataset.column_names:
|
|
1141
|
+
data_collator = DataCollatorForSeq2Seq(
|
|
1142
|
+
__tokenizer,
|
|
1143
|
+
pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
|
|
1144
|
+
)
|
|
1145
|
+
else:
|
|
1146
|
+
if hasattr(args, 'remove_unused_columns'): args.remove_unused_columns = False
|
|
1147
|
+
if hasattr(args, 'dataset_text_field'): args.dataset_text_field = ''
|
|
1148
|
+
if hasattr(args, 'dataset_kwargs'): args.dataset_kwargs = {'skip_prepare_dataset': True}
|
|
1149
|
+
if not isinstance(data_collator, UnslothVisionDataCollator):
|
|
1150
|
+
if not hasattr(__tokenizer, 'pad') and hasattr(__tokenizer, 'tokenizer'):
|
|
1151
|
+
if isinstance(data_collator, DataCollatorForSeq2Seq):
|
|
1152
|
+
data_collator = DataCollatorForSeq2Seq(
|
|
1153
|
+
__tokenizer.tokenizer,
|
|
1154
|
+
pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
|
|
1155
|
+
)
|
|
1156
|
+
else:
|
|
1157
|
+
data_collator = TransformersDataCollatorForLanguageModeling(
|
|
1158
|
+
__tokenizer.tokenizer,
|
|
1159
|
+
mlm = False,
|
|
1160
|
+
mlm_probability = 0.0,
|
|
1161
|
+
pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
|
|
1162
|
+
)
|
|
1163
|
+
other_metrics = []
|
|
1164
|
+
|
|
1165
|
+
from unsloth_zoo.logging_utils import PatchRLStatistics
|
|
1166
|
+
PatchRLStatistics('nash_md_trainer', other_metrics)
|
|
1167
|
+
|
|
1168
|
+
# [TODO] Fix up DataParallel multiplying batch sizes
|
|
1169
|
+
# [TODO] DDP works, but DP seems to not work? [TODO]
|
|
1170
|
+
if getattr(args, "parallel_mode", None) == ParallelMode.NOT_DISTRIBUTED and args.n_gpu > 1:
|
|
1171
|
+
if getattr(args, "_n_gpu", 1) != 1:
|
|
1172
|
+
args._n_gpu = 1
|
|
1173
|
+
if "model" in locals() and hasattr(model, "for_training"):
|
|
1174
|
+
model.for_training(use_gradient_checkpointing=getattr(args, 'gradient_checkpointing', True))
|
|
1175
|
+
super().__init__(
|
|
1176
|
+
model = model,
|
|
1177
|
+
ref_model = ref_model,
|
|
1178
|
+
reward_funcs = reward_funcs,
|
|
1179
|
+
judge = judge,
|
|
1180
|
+
args = args,
|
|
1181
|
+
data_collator = data_collator,
|
|
1182
|
+
train_dataset = train_dataset,
|
|
1183
|
+
eval_dataset = eval_dataset,
|
|
1184
|
+
processing_class = processing_class,
|
|
1185
|
+
peft_config = peft_config,
|
|
1186
|
+
compute_metrics = compute_metrics,
|
|
1187
|
+
callbacks = callbacks,
|
|
1188
|
+
preprocess_logits_for_metrics = preprocess_logits_for_metrics,
|
|
1189
|
+
reward_model = reward_model,**kwargs)
|
|
1190
|
+
if "model" in locals() and hasattr(model, "for_inference"):
|
|
1191
|
+
model.for_inference()
|
|
1192
|
+
if hasattr(self, 'neftune_hook_handle'):
|
|
1193
|
+
self.neftune_hook_handle.remove()
|
|
1194
|
+
if hasattr(self, 'neftune_hook_handle'): del self.neftune_hook_handle
|
|
1195
|
+
if getattr(args, 'neftune_noise_alpha', None) is not None:
|
|
1196
|
+
model.get_input_embeddings().neftune_noise_alpha = self.neftune_noise_alpha
|
|
1197
|
+
pass
|
|
1198
|
+
if hasattr(self, 'accelerator'):
|
|
1199
|
+
scaler = self.accelerator.scaler
|
|
1200
|
+
current_model = model
|
|
1201
|
+
while hasattr(current_model, 'model'):
|
|
1202
|
+
current_model.accelerator_scaler = scaler
|
|
1203
|
+
current_model = current_model.model
|
|
1204
|
+
current_model.accelerator_scaler = scaler
|
|
1205
|
+
pass
|
|
1206
|
+
if hasattr(self, 'train'):
|
|
1207
|
+
self.train = MethodType(prepare_for_training_mode(self.__class__.train), self)
|
|
1208
|
+
pass
|
|
1209
|
+
|
|
1210
|
+
pass
|