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.
Files changed (111) hide show
  1. package/lib/api-client.js +1 -1
  2. package/lib/chat-mode.js +7 -2
  3. package/package.json +1 -1
  4. package/unsloth_compiled_cache/.locks/.lock.AqlmLoraLinear_peft_forward.py +0 -0
  5. package/unsloth_compiled_cache/.locks/.lock.AwqLoraLinear_peft_forward.py +0 -0
  6. package/unsloth_compiled_cache/.locks/.lock.BatchNorm1d.py +0 -0
  7. package/unsloth_compiled_cache/.locks/.lock.BatchNorm2d.py +0 -0
  8. package/unsloth_compiled_cache/.locks/.lock.BatchNorm3d.py +0 -0
  9. package/unsloth_compiled_cache/.locks/.lock.Conv1d.py +0 -0
  10. package/unsloth_compiled_cache/.locks/.lock.Conv2d.py +0 -0
  11. package/unsloth_compiled_cache/.locks/.lock.Conv3d.py +0 -0
  12. package/unsloth_compiled_cache/.locks/.lock.ConvTranspose1d.py +0 -0
  13. package/unsloth_compiled_cache/.locks/.lock.ConvTranspose2d.py +0 -0
  14. package/unsloth_compiled_cache/.locks/.lock.ConvTranspose3d.py +0 -0
  15. package/unsloth_compiled_cache/.locks/.lock.GPTQLoraLinear_peft_forward.py +0 -0
  16. package/unsloth_compiled_cache/.locks/.lock.GroupNorm.py +0 -0
  17. package/unsloth_compiled_cache/.locks/.lock.LayerNorm.py +0 -0
  18. package/unsloth_compiled_cache/.locks/.lock.Linear4bit_peft_forward.py +0 -0
  19. package/unsloth_compiled_cache/.locks/.lock.Linear8bitLt_peft_forward.py +0 -0
  20. package/unsloth_compiled_cache/.locks/.lock.Linear_peft_forward.py +0 -0
  21. package/unsloth_compiled_cache/.locks/.lock.LoraParallelLinear_peft_forward.py +0 -0
  22. package/unsloth_compiled_cache/.locks/.lock.RMSNorm.py +0 -0
  23. package/unsloth_compiled_cache/.locks/.lock.UnslothBCOTrainer.py +0 -0
  24. package/unsloth_compiled_cache/.locks/.lock.UnslothCPOTrainer.py +0 -0
  25. package/unsloth_compiled_cache/.locks/.lock.UnslothDPOTrainer.py +0 -0
  26. package/unsloth_compiled_cache/.locks/.lock.UnslothGKDTrainer.py +0 -0
  27. package/unsloth_compiled_cache/.locks/.lock.UnslothGRPOTrainer.py +0 -0
  28. package/unsloth_compiled_cache/.locks/.lock.UnslothKTOTrainer.py +0 -0
  29. package/unsloth_compiled_cache/.locks/.lock.UnslothNashMDTrainer.py +0 -0
  30. package/unsloth_compiled_cache/.locks/.lock.UnslothORPOTrainer.py +0 -0
  31. package/unsloth_compiled_cache/.locks/.lock.UnslothOnlineDPOTrainer.py +0 -0
  32. package/unsloth_compiled_cache/.locks/.lock.UnslothPPOTrainer.py +0 -0
  33. package/unsloth_compiled_cache/.locks/.lock.UnslothPRMTrainer.py +0 -0
  34. package/unsloth_compiled_cache/.locks/.lock.UnslothRLOOTrainer.py +0 -0
  35. package/unsloth_compiled_cache/.locks/.lock.UnslothRewardTrainer.py +0 -0
  36. package/unsloth_compiled_cache/.locks/.lock.UnslothSFTTrainer.py +0 -0
  37. package/unsloth_compiled_cache/.locks/.lock.UnslothXPOTrainer.py +0 -0
  38. package/unsloth_compiled_cache/.locks/.lock.unsloth_compiled_module_qwen3_moe.py +0 -0
  39. package/unsloth_compiled_cache/.locks/.lock.unsloth_compiled_module_siglip.py +0 -0
  40. package/unsloth_compiled_cache/AqlmLoraLinear_peft_forward.py +88 -0
  41. package/unsloth_compiled_cache/AwqLoraLinear_peft_forward.py +87 -0
  42. package/unsloth_compiled_cache/BatchNorm1d.py +117 -0
  43. package/unsloth_compiled_cache/BatchNorm2d.py +117 -0
  44. package/unsloth_compiled_cache/BatchNorm3d.py +117 -0
  45. package/unsloth_compiled_cache/Conv1d.py +70 -0
  46. package/unsloth_compiled_cache/Conv2d.py +70 -0
  47. package/unsloth_compiled_cache/Conv3d.py +70 -0
  48. package/unsloth_compiled_cache/ConvTranspose1d.py +97 -0
  49. package/unsloth_compiled_cache/ConvTranspose2d.py +106 -0
  50. package/unsloth_compiled_cache/ConvTranspose3d.py +98 -0
  51. package/unsloth_compiled_cache/GPTQLoraLinear_peft_forward.py +95 -0
  52. package/unsloth_compiled_cache/GroupNorm.py +70 -0
  53. package/unsloth_compiled_cache/LayerNorm.py +72 -0
  54. package/unsloth_compiled_cache/Linear4bit_peft_forward.py +115 -0
  55. package/unsloth_compiled_cache/Linear8bitLt_peft_forward.py +113 -0
  56. package/unsloth_compiled_cache/Linear_peft_forward.py +104 -0
  57. package/unsloth_compiled_cache/LoraParallelLinear_peft_forward.py +91 -0
  58. package/unsloth_compiled_cache/RMSNorm.py +73 -0
  59. package/unsloth_compiled_cache/UnslothBCOTrainer.py +2026 -0
  60. package/unsloth_compiled_cache/UnslothCPOTrainer.py +1806 -0
  61. package/unsloth_compiled_cache/UnslothDPOTrainer.py +2750 -0
  62. package/unsloth_compiled_cache/UnslothGKDTrainer.py +1157 -0
  63. package/unsloth_compiled_cache/UnslothGRPOTrainer.py +3607 -0
  64. package/unsloth_compiled_cache/UnslothKTOTrainer.py +2220 -0
  65. package/unsloth_compiled_cache/UnslothNashMDTrainer.py +1210 -0
  66. package/unsloth_compiled_cache/UnslothORPOTrainer.py +1730 -0
  67. package/unsloth_compiled_cache/UnslothOnlineDPOTrainer.py +2313 -0
  68. package/unsloth_compiled_cache/UnslothPPOTrainer.py +1504 -0
  69. package/unsloth_compiled_cache/UnslothPRMTrainer.py +979 -0
  70. package/unsloth_compiled_cache/UnslothRLOOTrainer.py +2674 -0
  71. package/unsloth_compiled_cache/UnslothRewardTrainer.py +1197 -0
  72. package/unsloth_compiled_cache/UnslothSFTTrainer.py +1416 -0
  73. package/unsloth_compiled_cache/UnslothXPOTrainer.py +1255 -0
  74. package/unsloth_compiled_cache/__pycache__/AqlmLoraLinear_peft_forward.cpython-312.pyc +0 -0
  75. package/unsloth_compiled_cache/__pycache__/AwqLoraLinear_peft_forward.cpython-312.pyc +0 -0
  76. package/unsloth_compiled_cache/__pycache__/BatchNorm1d.cpython-312.pyc +0 -0
  77. package/unsloth_compiled_cache/__pycache__/BatchNorm2d.cpython-312.pyc +0 -0
  78. package/unsloth_compiled_cache/__pycache__/BatchNorm3d.cpython-312.pyc +0 -0
  79. package/unsloth_compiled_cache/__pycache__/Conv1d.cpython-312.pyc +0 -0
  80. package/unsloth_compiled_cache/__pycache__/Conv2d.cpython-312.pyc +0 -0
  81. package/unsloth_compiled_cache/__pycache__/Conv3d.cpython-312.pyc +0 -0
  82. package/unsloth_compiled_cache/__pycache__/ConvTranspose1d.cpython-312.pyc +0 -0
  83. package/unsloth_compiled_cache/__pycache__/ConvTranspose2d.cpython-312.pyc +0 -0
  84. package/unsloth_compiled_cache/__pycache__/ConvTranspose3d.cpython-312.pyc +0 -0
  85. package/unsloth_compiled_cache/__pycache__/GPTQLoraLinear_peft_forward.cpython-312.pyc +0 -0
  86. package/unsloth_compiled_cache/__pycache__/GroupNorm.cpython-312.pyc +0 -0
  87. package/unsloth_compiled_cache/__pycache__/LayerNorm.cpython-312.pyc +0 -0
  88. package/unsloth_compiled_cache/__pycache__/Linear4bit_peft_forward.cpython-312.pyc +0 -0
  89. package/unsloth_compiled_cache/__pycache__/Linear8bitLt_peft_forward.cpython-312.pyc +0 -0
  90. package/unsloth_compiled_cache/__pycache__/Linear_peft_forward.cpython-312.pyc +0 -0
  91. package/unsloth_compiled_cache/__pycache__/LoraParallelLinear_peft_forward.cpython-312.pyc +0 -0
  92. package/unsloth_compiled_cache/__pycache__/RMSNorm.cpython-312.pyc +0 -0
  93. package/unsloth_compiled_cache/__pycache__/UnslothBCOTrainer.cpython-312.pyc +0 -0
  94. package/unsloth_compiled_cache/__pycache__/UnslothCPOTrainer.cpython-312.pyc +0 -0
  95. package/unsloth_compiled_cache/__pycache__/UnslothDPOTrainer.cpython-312.pyc +0 -0
  96. package/unsloth_compiled_cache/__pycache__/UnslothGKDTrainer.cpython-312.pyc +0 -0
  97. package/unsloth_compiled_cache/__pycache__/UnslothGRPOTrainer.cpython-312.pyc +0 -0
  98. package/unsloth_compiled_cache/__pycache__/UnslothKTOTrainer.cpython-312.pyc +0 -0
  99. package/unsloth_compiled_cache/__pycache__/UnslothNashMDTrainer.cpython-312.pyc +0 -0
  100. package/unsloth_compiled_cache/__pycache__/UnslothORPOTrainer.cpython-312.pyc +0 -0
  101. package/unsloth_compiled_cache/__pycache__/UnslothOnlineDPOTrainer.cpython-312.pyc +0 -0
  102. package/unsloth_compiled_cache/__pycache__/UnslothPPOTrainer.cpython-312.pyc +0 -0
  103. package/unsloth_compiled_cache/__pycache__/UnslothPRMTrainer.cpython-312.pyc +0 -0
  104. package/unsloth_compiled_cache/__pycache__/UnslothRLOOTrainer.cpython-312.pyc +0 -0
  105. package/unsloth_compiled_cache/__pycache__/UnslothRewardTrainer.cpython-312.pyc +0 -0
  106. package/unsloth_compiled_cache/__pycache__/UnslothSFTTrainer.cpython-312.pyc +0 -0
  107. package/unsloth_compiled_cache/__pycache__/UnslothXPOTrainer.cpython-312.pyc +0 -0
  108. package/unsloth_compiled_cache/__pycache__/unsloth_compiled_module_qwen3_moe.cpython-312.pyc +0 -0
  109. package/unsloth_compiled_cache/__pycache__/unsloth_compiled_module_siglip.cpython-312.pyc +0 -0
  110. package/unsloth_compiled_cache/unsloth_compiled_module_qwen3_moe.py +726 -0
  111. package/unsloth_compiled_cache/unsloth_compiled_module_siglip.py +534 -0
@@ -0,0 +1,1730 @@
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.orpo_trainer import (Any, AutoModelForCausalLM, BaseImageProcessor, BaseTrainer, Callable, DPODataCollatorWithPadding, DataCollator, DataLoader, Dataset, EvalLoopOutput, F, FeatureExtractionMixin, Literal, ORPOConfig, ORPOTrainer, Optional, PartialState, Path, PeftModel, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, TrainerCallback, Union, add_bos_token_if_needed, add_eos_token_if_needed, autocast, defaultdict, disable_dropout_in_model, inspect, is_comet_available, is_peft_available, is_torch_fx_proxy, is_torch_xla_available, is_wandb_available, log_table_to_comet_experiment, logger, logging, maybe_apply_chat_template, maybe_extract_prompt, nn, np, nullcontext, os, pad_to_length, pd, peft_module_casting_to_bf16, prepare_model_for_kbit_training, random, selective_log_softmax, textwrap, torch, warnings, F, Optional, PeftModel, PreTrainedModel, is_peft_available, logger, os, 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 UnslothORPOConfig(ORPOConfig):
199
+ """
200
+
201
+ Configuration class for the [`ORPOTrainer`].
202
+
203
+ This class includes only the parameters that are specific to ORPO 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
+ max_length (`int` or `None`, *optional*, defaults to `1024`):
213
+ Maximum length of the sequences (prompt + completion) in the batch. This argument is required if you want
214
+ to use the default data collator.
215
+ max_prompt_length (`int` or `None`, *optional*, defaults to `512`):
216
+ Maximum length of the prompt. This argument is required if you want to use the default data collator.
217
+ max_completion_length (`int`, *optional*):
218
+ Maximum length of the completion. This argument is required if you want to use the default data collator
219
+ and your model is an encoder-decoder.
220
+ beta (`float`, *optional*, defaults to `0.1`):
221
+ Parameter controlling the relative ratio loss weight in the ORPO loss. In the
222
+ [paper](https://huggingface.co/papers/2403.07691), it is denoted by λ. In the
223
+ [code](https://github.com/xfactlab/orpo), it is denoted by `alpha`.
224
+ disable_dropout (`bool`, *optional*, defaults to `True`):
225
+ Whether to disable dropout in the model.
226
+ label_pad_token_id (`int`, *optional*, defaults to `-100`):
227
+ Label pad token id. This argument is required if you want to use the default data collator.
228
+ padding_value (`int`, *optional*):
229
+ Padding value to use. If `None`, the padding value of the tokenizer is used.
230
+ truncation_mode (`str`, *optional*, defaults to `"keep_end"`):
231
+ Truncation mode to use when the prompt is too long. Possible values are `"keep_end"` or `"keep_start"`.
232
+ This argument is required if you want to use the default data collator.
233
+ generate_during_eval (`bool`, *optional*, defaults to `False`):
234
+ If `True`, generates and logs completions from the model to W&B or Comet during evaluation.
235
+ is_encoder_decoder (`bool`, *optional*):
236
+ When using the `model_init` argument (callable) to instantiate the model instead of the `model` argument,
237
+ you need to specify if the model returned by the callable is an encoder-decoder model.
238
+ model_init_kwargs (`dict[str, Any]`, *optional*):
239
+ Keyword arguments to pass to `AutoModelForCausalLM.from_pretrained` when instantiating the model from a
240
+ string.
241
+ dataset_num_proc (`int`, *optional*):
242
+ Number of processes to use for processing the dataset.
243
+
244
+ """
245
+ vllm_sampling_params: Optional[Any] = field(
246
+ default = None,
247
+ metadata = {'help': 'vLLM SamplingParams'},
248
+ )
249
+ unsloth_num_chunks : Optional[int] = field(
250
+ default = -1,
251
+ metadata = {'help': 'Chunk size to reduce memory usage. -1 is most efficient.'},
252
+ )
253
+ max_seq_length : Optional[int] = field(
254
+ default = None,
255
+ metadata = {'help': 'Maximum sequence length to truncate to.'},
256
+ )
257
+ def __init__(
258
+ self,
259
+ output_dir = None,
260
+ overwrite_output_dir = None,
261
+ do_train = False,
262
+ do_eval = False,
263
+ do_predict = False,
264
+ eval_strategy = 'no',
265
+ prediction_loss_only = False,
266
+ per_device_train_batch_size = 4,
267
+ per_device_eval_batch_size = 4,
268
+ per_gpu_train_batch_size = None,
269
+ per_gpu_eval_batch_size = None,
270
+ gradient_accumulation_steps = 2,
271
+ eval_accumulation_steps = 2,
272
+ eval_delay = 0,
273
+ torch_empty_cache_steps = 250,
274
+ learning_rate = 5e-05,
275
+ weight_decay = 0.01,
276
+ adam_beta1 = 0.9,
277
+ adam_beta2 = 0.999,
278
+ adam_epsilon = 1e-08,
279
+ max_grad_norm = 1.0,
280
+ num_train_epochs = 3.0,
281
+ max_steps = -1,
282
+ lr_scheduler_type = 'linear',
283
+ warmup_ratio = 0.1,
284
+ warmup_steps = 0,
285
+ log_level = 'passive',
286
+ log_level_replica = 'warning',
287
+ log_on_each_node = True,
288
+ logging_dir = None,
289
+ logging_strategy = 'steps',
290
+ logging_first_step = False,
291
+ logging_steps = 1,
292
+ logging_nan_inf_filter = False,
293
+ save_strategy = 'steps',
294
+ save_steps = 500,
295
+ save_total_limit = None,
296
+ save_safetensors = True,
297
+ save_on_each_node = False,
298
+ save_only_model = False,
299
+ restore_callback_states_from_checkpoint = False,
300
+ no_cuda = False,
301
+ use_cpu = False,
302
+ use_mps_device = False,
303
+ seed = 3407,
304
+ data_seed = 3407,
305
+ jit_mode_eval = False,
306
+ bf16 = False,
307
+ fp16 = False,
308
+ fp16_opt_level = 'O1',
309
+ half_precision_backend = 'auto',
310
+ bf16_full_eval = False,
311
+ fp16_full_eval = False,
312
+ tf32 = None,
313
+ local_rank = -1,
314
+ ddp_backend = None,
315
+ tpu_num_cores = None,
316
+ tpu_metrics_debug = False,
317
+ debug = '',
318
+ dataloader_drop_last = False,
319
+ eval_steps = None,
320
+ dataloader_num_workers = 0,
321
+ dataloader_prefetch_factor = None,
322
+ past_index = -1,
323
+ run_name = None,
324
+ disable_tqdm = None,
325
+ remove_unused_columns = True,
326
+ label_names = None,
327
+ load_best_model_at_end = False,
328
+ metric_for_best_model = None,
329
+ greater_is_better = None,
330
+ ignore_data_skip = False,
331
+ fsdp = None,
332
+ fsdp_min_num_params = 0,
333
+ fsdp_config = None,
334
+ fsdp_transformer_layer_cls_to_wrap = None,
335
+ accelerator_config = None,
336
+ parallelism_config = None,
337
+ deepspeed = None,
338
+ label_smoothing_factor = 0.0,
339
+ optim = 'adamw_8bit',
340
+ optim_args = None,
341
+ adafactor = False,
342
+ group_by_length = False,
343
+ length_column_name = 'length',
344
+ report_to = 'none',
345
+ project = 'huggingface',
346
+ trackio_space_id = 'trackio',
347
+ ddp_find_unused_parameters = None,
348
+ ddp_bucket_cap_mb = None,
349
+ ddp_broadcast_buffers = None,
350
+ dataloader_pin_memory = True,
351
+ dataloader_persistent_workers = False,
352
+ skip_memory_metrics = True,
353
+ use_legacy_prediction_loop = False,
354
+ push_to_hub = False,
355
+ resume_from_checkpoint = None,
356
+ hub_model_id = None,
357
+ hub_strategy = 'every_save',
358
+ hub_token = None,
359
+ hub_private_repo = None,
360
+ hub_always_push = False,
361
+ hub_revision = None,
362
+ gradient_checkpointing = True,
363
+ gradient_checkpointing_kwargs = None,
364
+ include_inputs_for_metrics = False,
365
+ eval_do_concat_batches = True,
366
+ fp16_backend = 'auto',
367
+ push_to_hub_model_id = None,
368
+ push_to_hub_organization = None,
369
+ push_to_hub_token = None,
370
+ mp_parameters = '',
371
+ auto_find_batch_size = False,
372
+ full_determinism = False,
373
+ torchdynamo = None,
374
+ ray_scope = 'last',
375
+ ddp_timeout = 1800,
376
+ torch_compile = False,
377
+ torch_compile_backend = None,
378
+ torch_compile_mode = None,
379
+ include_tokens_per_second = False,
380
+ include_num_input_tokens_seen = False,
381
+ neftune_noise_alpha = None,
382
+ optim_target_modules = None,
383
+ batch_eval_metrics = False,
384
+ eval_on_start = False,
385
+ use_liger_kernel = False,
386
+ liger_kernel_config = None,
387
+ eval_use_gather_object = False,
388
+ average_tokens_across_devices = True,
389
+ max_length = 1024,
390
+ max_prompt_length = 512,
391
+ max_completion_length = None,
392
+ beta = 0.1,
393
+ disable_dropout = True,
394
+ label_pad_token_id = -100,
395
+ padding_value = None,
396
+ truncation_mode = 'keep_end',
397
+ generate_during_eval = False,
398
+ is_encoder_decoder = None,
399
+ model_init_kwargs = None,
400
+ dataset_num_proc = None,
401
+ vllm_sampling_params = None,
402
+ unsloth_num_chunks = -1,
403
+ max_seq_length = None,
404
+ **kwargs,
405
+ ):
406
+ 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!')
407
+ 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!')
408
+ if output_dir is None and save_strategy == 'steps' and save_steps == 500:
409
+ output_dir = 'unsloth_training_checkpoints'
410
+ save_strategy = 'no'
411
+ if dataset_num_proc is None:
412
+ from multiprocessing import cpu_count
413
+ dataset_num_proc = min(max(cpu_count()+4, 2), 64)
414
+
415
+ super().__init__(
416
+ output_dir = output_dir,
417
+ overwrite_output_dir = overwrite_output_dir,
418
+ do_train = do_train,
419
+ do_eval = do_eval,
420
+ do_predict = do_predict,
421
+ eval_strategy = eval_strategy,
422
+ prediction_loss_only = prediction_loss_only,
423
+ per_device_train_batch_size = per_device_train_batch_size,
424
+ per_device_eval_batch_size = per_device_eval_batch_size,
425
+ per_gpu_train_batch_size = per_gpu_train_batch_size,
426
+ per_gpu_eval_batch_size = per_gpu_eval_batch_size,
427
+ gradient_accumulation_steps = gradient_accumulation_steps,
428
+ eval_accumulation_steps = eval_accumulation_steps,
429
+ eval_delay = eval_delay,
430
+ torch_empty_cache_steps = torch_empty_cache_steps,
431
+ learning_rate = learning_rate,
432
+ weight_decay = weight_decay,
433
+ adam_beta1 = adam_beta1,
434
+ adam_beta2 = adam_beta2,
435
+ adam_epsilon = adam_epsilon,
436
+ max_grad_norm = max_grad_norm,
437
+ num_train_epochs = num_train_epochs,
438
+ max_steps = max_steps,
439
+ lr_scheduler_type = lr_scheduler_type,
440
+ warmup_ratio = warmup_ratio,
441
+ warmup_steps = warmup_steps,
442
+ log_level = log_level,
443
+ log_level_replica = log_level_replica,
444
+ log_on_each_node = log_on_each_node,
445
+ logging_dir = logging_dir,
446
+ logging_strategy = logging_strategy,
447
+ logging_first_step = logging_first_step,
448
+ logging_steps = logging_steps,
449
+ logging_nan_inf_filter = logging_nan_inf_filter,
450
+ save_strategy = save_strategy,
451
+ save_steps = save_steps,
452
+ save_total_limit = save_total_limit,
453
+ save_safetensors = save_safetensors,
454
+ save_on_each_node = save_on_each_node,
455
+ save_only_model = save_only_model,
456
+ restore_callback_states_from_checkpoint = restore_callback_states_from_checkpoint,
457
+ no_cuda = no_cuda,
458
+ use_cpu = use_cpu,
459
+ use_mps_device = use_mps_device,
460
+ seed = seed,
461
+ data_seed = data_seed,
462
+ jit_mode_eval = jit_mode_eval,
463
+ bf16 = bf16,
464
+ fp16 = fp16,
465
+ fp16_opt_level = fp16_opt_level,
466
+ half_precision_backend = half_precision_backend,
467
+ bf16_full_eval = bf16_full_eval,
468
+ fp16_full_eval = fp16_full_eval,
469
+ tf32 = tf32,
470
+ local_rank = local_rank,
471
+ ddp_backend = ddp_backend,
472
+ tpu_num_cores = tpu_num_cores,
473
+ tpu_metrics_debug = tpu_metrics_debug,
474
+ debug = debug,
475
+ dataloader_drop_last = dataloader_drop_last,
476
+ eval_steps = eval_steps,
477
+ dataloader_num_workers = dataloader_num_workers,
478
+ dataloader_prefetch_factor = dataloader_prefetch_factor,
479
+ past_index = past_index,
480
+ run_name = run_name,
481
+ disable_tqdm = disable_tqdm,
482
+ remove_unused_columns = remove_unused_columns,
483
+ label_names = label_names,
484
+ load_best_model_at_end = load_best_model_at_end,
485
+ metric_for_best_model = metric_for_best_model,
486
+ greater_is_better = greater_is_better,
487
+ ignore_data_skip = ignore_data_skip,
488
+ fsdp = fsdp,
489
+ fsdp_min_num_params = fsdp_min_num_params,
490
+ fsdp_config = fsdp_config,
491
+ fsdp_transformer_layer_cls_to_wrap = fsdp_transformer_layer_cls_to_wrap,
492
+ accelerator_config = accelerator_config,
493
+ parallelism_config = parallelism_config,
494
+ deepspeed = deepspeed,
495
+ label_smoothing_factor = label_smoothing_factor,
496
+ optim = optim,
497
+ optim_args = optim_args,
498
+ adafactor = adafactor,
499
+ group_by_length = group_by_length,
500
+ length_column_name = length_column_name,
501
+ report_to = report_to,
502
+ project = project,
503
+ trackio_space_id = trackio_space_id,
504
+ ddp_find_unused_parameters = ddp_find_unused_parameters,
505
+ ddp_bucket_cap_mb = ddp_bucket_cap_mb,
506
+ ddp_broadcast_buffers = ddp_broadcast_buffers,
507
+ dataloader_pin_memory = dataloader_pin_memory,
508
+ dataloader_persistent_workers = dataloader_persistent_workers,
509
+ skip_memory_metrics = skip_memory_metrics,
510
+ use_legacy_prediction_loop = use_legacy_prediction_loop,
511
+ push_to_hub = push_to_hub,
512
+ resume_from_checkpoint = resume_from_checkpoint,
513
+ hub_model_id = hub_model_id,
514
+ hub_strategy = hub_strategy,
515
+ hub_token = hub_token,
516
+ hub_private_repo = hub_private_repo,
517
+ hub_always_push = hub_always_push,
518
+ hub_revision = hub_revision,
519
+ gradient_checkpointing = gradient_checkpointing,
520
+ gradient_checkpointing_kwargs = gradient_checkpointing_kwargs,
521
+ include_inputs_for_metrics = include_inputs_for_metrics,
522
+ eval_do_concat_batches = eval_do_concat_batches,
523
+ fp16_backend = fp16_backend,
524
+ push_to_hub_model_id = push_to_hub_model_id,
525
+ push_to_hub_organization = push_to_hub_organization,
526
+ push_to_hub_token = push_to_hub_token,
527
+ mp_parameters = mp_parameters,
528
+ auto_find_batch_size = auto_find_batch_size,
529
+ full_determinism = full_determinism,
530
+ torchdynamo = torchdynamo,
531
+ ray_scope = ray_scope,
532
+ ddp_timeout = ddp_timeout,
533
+ torch_compile = torch_compile,
534
+ torch_compile_backend = torch_compile_backend,
535
+ torch_compile_mode = torch_compile_mode,
536
+ include_tokens_per_second = include_tokens_per_second,
537
+ include_num_input_tokens_seen = include_num_input_tokens_seen,
538
+ neftune_noise_alpha = neftune_noise_alpha,
539
+ optim_target_modules = optim_target_modules,
540
+ batch_eval_metrics = batch_eval_metrics,
541
+ eval_on_start = eval_on_start,
542
+ use_liger_kernel = use_liger_kernel,
543
+ liger_kernel_config = liger_kernel_config,
544
+ eval_use_gather_object = eval_use_gather_object,
545
+ average_tokens_across_devices = average_tokens_across_devices,
546
+ max_length = max_length,
547
+ max_prompt_length = max_prompt_length,
548
+ max_completion_length = max_completion_length,
549
+ beta = beta,
550
+ disable_dropout = disable_dropout,
551
+ label_pad_token_id = label_pad_token_id,
552
+ padding_value = padding_value,
553
+ truncation_mode = truncation_mode,
554
+ generate_during_eval = generate_during_eval,
555
+ is_encoder_decoder = is_encoder_decoder,
556
+ model_init_kwargs = model_init_kwargs,
557
+ dataset_num_proc = dataset_num_proc,**kwargs)
558
+ self.vllm_sampling_params = vllm_sampling_params
559
+ self.unsloth_num_chunks = unsloth_num_chunks
560
+ self.max_seq_length = max_seq_length
561
+ pass
562
+
563
+ class _UnslothORPOTrainer(BaseTrainer):
564
+ r""""""
565
+
566
+ _tag_names = ["trl", "orpo"]
567
+ _name = "ORPO"
568
+ _paper = {
569
+ "title": "ORPO: Monolithic Preference Optimization without Reference Model",
570
+ "id": "2403.07691",
571
+ # docstyle-ignore
572
+ "citation": textwrap.dedent("""\
573
+ @article{hong2024orpo,
574
+ title = {{ORPO: Monolithic Preference Optimization without Reference Model}},
575
+ author = {Jiwoo Hong and Noah Lee and James Thorne},
576
+ year = 2024,
577
+ eprint = {arXiv:2403.07691}
578
+ }"""),
579
+ }
580
+
581
+ def __init__(
582
+ self,
583
+ model: Optional[Union[PreTrainedModel, nn.Module, str]] = None,
584
+ args: Optional[ORPOConfig] = None,
585
+ data_collator: Optional[DataCollator] = None,
586
+ train_dataset: Optional[Dataset] = None,
587
+ eval_dataset: Optional[Union[Dataset, dict[str, Dataset]]] = None,
588
+ processing_class: Optional[
589
+ Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin]
590
+ ] = None,
591
+ model_init: Optional[Callable[[], PreTrainedModel]] = None,
592
+ callbacks: Optional[list[TrainerCallback]] = None,
593
+ optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
594
+ preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
595
+ peft_config: Optional[dict] = None,
596
+ compute_metrics: Optional[Callable[[EvalLoopOutput], dict]] = None,
597
+ ):
598
+ if not os.environ.get("TRL_EXPERIMENTAL_SILENCE"):
599
+ warnings.warn(
600
+ "This trainer will soon be moved to trl.experimental and is a candidate for removal. If you rely on "
601
+ "it and want it to remain, please share your comments here: "
602
+ "https://github.com/huggingface/trl/issues/4223. Silence this warning by setting environment variable "
603
+ "TRL_EXPERIMENTAL_SILENCE=1."
604
+ )
605
+ if args.model_init_kwargs is None:
606
+ model_init_kwargs = {}
607
+ elif not isinstance(model, str):
608
+ raise ValueError("You passed model_kwargs to the ORPOTrainer. But your model is already instantiated.")
609
+ else:
610
+ model_init_kwargs = args.model_init_kwargs
611
+ dtype = model_init_kwargs.get("dtype")
612
+ if dtype is not None:
613
+ # Convert to `torch.dtype` if an str is passed
614
+ if isinstance(dtype, str) and dtype != "auto":
615
+ dtype = getattr(torch, dtype)
616
+ if dtype != "auto" and not isinstance(dtype, torch.dtype):
617
+ raise ValueError(
618
+ f"Invalid `dtype` passed to the ORPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {dtype}."
619
+ )
620
+ model_init_kwargs["dtype"] = dtype
621
+
622
+ if isinstance(model, str):
623
+ model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
624
+
625
+ # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16`
626
+ # has been called in order to properly call autocast if needed.
627
+ self._peft_has_been_casted_to_bf16 = False
628
+
629
+ if not is_peft_available() and peft_config is not None:
630
+ raise ValueError(
631
+ "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models"
632
+ )
633
+ elif is_peft_available() and peft_config is not None:
634
+ # if model is a peft model and we have a peft_config, we merge and unload it first
635
+ if isinstance(model, PeftModel):
636
+ model = model.merge_and_unload()
637
+
638
+ if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False):
639
+ _support_gc_kwargs = hasattr(
640
+ args, "gradient_checkpointing_kwargs"
641
+ ) and "gradient_checkpointing_kwargs" in list(
642
+ inspect.signature(prepare_model_for_kbit_training).parameters
643
+ )
644
+
645
+ prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing}
646
+
647
+ if _support_gc_kwargs:
648
+ prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs
649
+
650
+ model = prepare_model_for_kbit_training(model, **prepare_model_kwargs)
651
+ elif args.gradient_checkpointing:
652
+ # For backward compatibility with older versions of transformers
653
+ if hasattr(model, "enable_input_require_grads"):
654
+ model.enable_input_require_grads()
655
+ else:
656
+
657
+ def make_inputs_require_grad(module, input, output):
658
+ output.requires_grad_(True)
659
+
660
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
661
+
662
+ # get peft model with the given config
663
+ model = model
664
+ if args.bf16 and getattr(model, "is_loaded_in_4bit", False):
665
+ peft_module_casting_to_bf16(model)
666
+ # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager
667
+ self._peft_has_been_casted_to_bf16 = True
668
+
669
+ # For models that use gradient_checkpointing, we need to attach a hook that enables input
670
+ # to explicitly have `requires_grad=True`, otherwise training will either silently
671
+ # fail or completely fail.
672
+ elif args.gradient_checkpointing:
673
+ # For backward compatibility with older versions of transformers
674
+ if hasattr(model, "enable_input_require_grads"):
675
+ model.enable_input_require_grads()
676
+ else:
677
+
678
+ def make_inputs_require_grad(module, input, output):
679
+ output.requires_grad_(True)
680
+
681
+ model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
682
+
683
+ if args.generate_during_eval and not (is_wandb_available() or is_comet_available()):
684
+ raise ValueError(
685
+ "`generate_during_eval=True` requires Weights and Biases or Comet to be installed."
686
+ " Please install `wandb` or `comet-ml` to resolve."
687
+ )
688
+
689
+ if model is not None:
690
+ self.is_encoder_decoder = model.config.is_encoder_decoder
691
+ elif args.is_encoder_decoder is None:
692
+ raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.")
693
+ else:
694
+ self.is_encoder_decoder = args.is_encoder_decoder
695
+
696
+ if self.is_encoder_decoder:
697
+ self.decoder_start_token_id = model.config.decoder_start_token_id
698
+ self.pad_token_id = model.config.pad_token_id
699
+
700
+ if processing_class is None:
701
+ raise ValueError("processing_class must be specified to tokenize a ORPO dataset.")
702
+ if args.max_length is None:
703
+ logger.warning(
704
+ "`max_length` is not set in the ORPOConfig's init"
705
+ " it will default to `512` by default, but you should do it yourself in the future.",
706
+ )
707
+ max_length = 512
708
+ else:
709
+ max_length = args.max_length
710
+ if args.max_prompt_length is None:
711
+ logger.warning(
712
+ "`max_prompt_length` is not set in the ORPOConfig's init"
713
+ " it will default to `128` by default, but you should do it yourself in the future.",
714
+ )
715
+ max_prompt_length = 128
716
+ else:
717
+ max_prompt_length = args.max_prompt_length
718
+
719
+ if args.max_completion_length is None and self.is_encoder_decoder:
720
+ logger.warning(
721
+ "When using an encoder decoder architecture, you should set `max_completion_length` in the ORPOConfig's init"
722
+ " it will default to `128` by default, but you should do it yourself in the future.",
723
+ )
724
+ self.max_completion_length = 128
725
+ else:
726
+ self.max_completion_length = args.max_completion_length
727
+
728
+ if data_collator is None:
729
+ data_collator = DPODataCollatorWithPadding(
730
+ pad_token_id=processing_class.pad_token_id,
731
+ label_pad_token_id=args.label_pad_token_id,
732
+ is_encoder_decoder=self.is_encoder_decoder,
733
+ )
734
+
735
+ if args.remove_unused_columns:
736
+ args.remove_unused_columns = False
737
+ # warn users
738
+ logger.warning(
739
+ "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments"
740
+ " we have set it for you, but you should do it yourself in the future.",
741
+ )
742
+
743
+ self.use_dpo_data_collator = True
744
+ else:
745
+ self.use_dpo_data_collator = False
746
+
747
+ # Disable dropout in the model and reference model
748
+ if args.disable_dropout:
749
+ disable_dropout_in_model(model)
750
+
751
+ self.max_length = max_length
752
+ self.generate_during_eval = args.generate_during_eval
753
+ self.label_pad_token_id = args.label_pad_token_id
754
+ self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id
755
+ self.max_prompt_length = max_prompt_length
756
+ self.truncation_mode = args.truncation_mode
757
+ self.processing_class = processing_class
758
+
759
+ self.beta = args.beta
760
+ self.aux_loss_enabled = getattr(model.config, "output_router_logits", False)
761
+ self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0)
762
+ if self.aux_loss_enabled and self.aux_loss_coef == 0.0:
763
+ logger.warning(
764
+ "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to "
765
+ "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value "
766
+ "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary "
767
+ "loss.",
768
+ )
769
+
770
+ self._stored_metrics = defaultdict(lambda: defaultdict(list))
771
+
772
+ # The trainer estimates the number of FLOPs [floating-point operations] using the number of elements in the
773
+ # input tensor associated with the key "input_ids". However, in ORPO, the sampled data does not include the
774
+ # "input_ids" key. Instead, the available keys are "prompt_input_ids", "chosen_input_ids", and
775
+ # "rejected_input_ids". As a result, the trainer issues the warning: "Could not estimate the number of tokens
776
+ # of the input, floating-point operations will not be computed." To suppress this warning, we set the
777
+ # "estimate_tokens" key in the model's "warnings_issued" dictionary to True. This acts as a flag to indicate
778
+ # that the warning has already been issued.
779
+ model.warnings_issued["estimate_tokens"] = True
780
+
781
+ # Compute that only on the main process for faster data processing.
782
+ # see: https://github.com/huggingface/trl/pull/1255
783
+ with PartialState().main_process_first():
784
+ # Extract the prompt if needed, and apply the chat template if needed
785
+ train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc)
786
+ train_dataset = train_dataset.map(
787
+ maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc
788
+ )
789
+ train_dataset = train_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc)
790
+ if eval_dataset is not None:
791
+ eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc)
792
+ eval_dataset = eval_dataset.map(
793
+ maybe_apply_chat_template,
794
+ fn_kwargs={"tokenizer": processing_class},
795
+ num_proc=args.dataset_num_proc,
796
+ )
797
+ eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc)
798
+
799
+ super().__init__(
800
+ model=model,
801
+ args=args,
802
+ data_collator=data_collator,
803
+ train_dataset=train_dataset,
804
+ eval_dataset=eval_dataset,
805
+ processing_class=processing_class,
806
+ model_init=model_init,
807
+ compute_metrics=compute_metrics,
808
+ callbacks=callbacks,
809
+ optimizers=optimizers,
810
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
811
+ )
812
+
813
+ # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the
814
+ # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set
815
+ # self.model_accepts_loss_kwargs to False to enable scaling.
816
+ self.model_accepts_loss_kwargs = False
817
+
818
+ # Add tags for models that have been loaded with the correct transformers version
819
+ if hasattr(self.model, "add_model_tags"):
820
+ self.model.add_model_tags(self._tag_names)
821
+
822
+ if not hasattr(self, "accelerator"):
823
+ raise AttributeError(
824
+ "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`."
825
+ )
826
+
827
+ def build_tokenized_answer(self, prompt, answer):
828
+ """
829
+ Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. It does ensure `enc(a + b) = enc(a) + enc(a +
830
+ b)[len(enc(a)):]`. Reference:
831
+ https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
832
+ """
833
+
834
+ full_tokenized = self.processing_class(prompt + answer, add_special_tokens=False)
835
+ prompt_input_ids = self.processing_class(prompt, add_special_tokens=False)["input_ids"]
836
+
837
+ answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :]
838
+ answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :]
839
+
840
+ # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]`
841
+ full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids])
842
+
843
+ # Prepare input tokens for token by token comparison
844
+ full_input_ids = np.array(full_tokenized["input_ids"])
845
+
846
+ if len(full_input_ids) != len(full_concat_input_ids):
847
+ raise ValueError("Prompt input ids and answer input ids should have the same length.")
848
+
849
+ # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens
850
+ # can be merged together when tokenizing prompt+answer. This could result
851
+ # on the last token from the prompt being different when tokenized on its own
852
+ # vs when done as prompt+answer.
853
+ response_token_ids_start_idx = len(prompt_input_ids)
854
+
855
+ # If tokenized prompt is different than both prompt+answer, then it means the
856
+ # last token has changed due to merging.
857
+ if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]:
858
+ response_token_ids_start_idx -= 1
859
+
860
+ prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx]
861
+ prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx]
862
+
863
+ if len(prompt_input_ids) != len(prompt_attention_mask):
864
+ raise ValueError("Prompt input ids and attention mask should have the same length.")
865
+
866
+ answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:]
867
+ answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:]
868
+
869
+ return dict(
870
+ prompt_input_ids=prompt_input_ids,
871
+ prompt_attention_mask=prompt_attention_mask,
872
+ input_ids=answer_input_ids,
873
+ attention_mask=answer_attention_mask,
874
+ )
875
+
876
+ def tokenize_row(self, feature, model: Optional[Union[PreTrainedModel, nn.Module]] = None) -> dict:
877
+ """Tokenize a single row from a ORPO specific dataset.
878
+
879
+ At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt +
880
+ chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long,
881
+ we truncate the chosen/rejected.
882
+
883
+ We also create the labels for the chosen/rejected responses, which are of length equal to the sum of the length
884
+ of the prompt and the chosen/rejected response, with label_pad_token_id for the prompt tokens.
885
+ """
886
+ batch = {}
887
+ prompt = feature["prompt"]
888
+ chosen = feature["chosen"]
889
+ rejected = feature["rejected"]
890
+
891
+ if not self.is_encoder_decoder:
892
+ # Check issues below for more details
893
+ # 1. https://github.com/huggingface/trl/issues/907
894
+ # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257
895
+ # 3. https://github.com/LianjiaTech/BELLE/issues/337
896
+
897
+ if not isinstance(prompt, str):
898
+ raise ValueError(f"prompt should be an str but got {type(prompt)}")
899
+ prompt_tokens = self.processing_class(prompt, add_special_tokens=False)
900
+ prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()}
901
+
902
+ if not isinstance(chosen, str):
903
+ raise ValueError(f"chosen should be an str but got {type(chosen)}")
904
+ chosen_tokens = self.build_tokenized_answer(prompt, chosen)
905
+
906
+ if not isinstance(rejected, str):
907
+ raise ValueError(f"rejected should be an str but got {type(rejected)}")
908
+ rejected_tokens = self.build_tokenized_answer(prompt, rejected)
909
+
910
+ # Last prompt token might get merged by tokenizer and
911
+ # it should not be included for generation if that happens
912
+ prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"])
913
+
914
+ chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"])
915
+ rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"])
916
+ prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids)
917
+
918
+ for k, v in prompt_tokens.items():
919
+ prompt_tokens[k] = v[:prompt_len_input_ids]
920
+
921
+ # Make sure prompts only have one different token at most an
922
+ # and length only differs by 1 at most
923
+ num_diff_tokens = sum(
924
+ a != b for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"])
925
+ )
926
+ num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids)
927
+ if num_diff_tokens > 1 or num_diff_len > 1:
928
+ raise ValueError(
929
+ "Chosen and rejected prompt_input_ids might only differ on the "
930
+ "last token due to tokenizer merge ops."
931
+ )
932
+
933
+ # add BOS token to head of prompt. Avoid adding if it's already there
934
+ prompt_tokens, chosen_tokens, rejected_tokens = add_bos_token_if_needed(
935
+ self.processing_class.bos_token_id,
936
+ prompt_len_input_ids,
937
+ prompt_tokens,
938
+ chosen_prompt_len_input_ids,
939
+ chosen_tokens,
940
+ rejected_prompt_len_input_ids,
941
+ rejected_tokens,
942
+ )
943
+
944
+ # add EOS token to end of answer. Avoid adding if it's already there
945
+ chosen_tokens, rejected_tokens = add_eos_token_if_needed(
946
+ self.processing_class.eos_token_id, chosen_tokens, rejected_tokens
947
+ )
948
+
949
+ longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"]))
950
+
951
+ # if combined sequence is too long, truncate the prompt
952
+ for answer_tokens in [chosen_tokens, rejected_tokens, prompt_tokens]:
953
+ if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
954
+ if self.truncation_mode == "keep_start":
955
+ for k in ["prompt_input_ids", "prompt_attention_mask"]:
956
+ answer_tokens[k] = answer_tokens[k][: self.max_prompt_length]
957
+ elif self.truncation_mode == "keep_end":
958
+ for k in ["prompt_input_ids", "prompt_attention_mask"]:
959
+ answer_tokens[k] = answer_tokens[k][-self.max_prompt_length :]
960
+ else:
961
+ raise ValueError(f"Unknown truncation mode: {self.truncation_mode}")
962
+
963
+ # if that's still too long, truncate the response
964
+ for answer_tokens in [chosen_tokens, rejected_tokens]:
965
+ if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length:
966
+ for k in ["input_ids", "attention_mask"]:
967
+ answer_tokens[k] = answer_tokens[k][: self.max_length - self.max_prompt_length]
968
+
969
+ # Create labels
970
+ chosen_sequence_tokens = {
971
+ k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"]
972
+ }
973
+ rejected_sequence_tokens = {
974
+ k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"]
975
+ }
976
+ chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:]
977
+ chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [
978
+ self.label_pad_token_id
979
+ ] * len(chosen_tokens["prompt_input_ids"])
980
+ rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:]
981
+ rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [
982
+ self.label_pad_token_id
983
+ ] * len(rejected_tokens["prompt_input_ids"])
984
+
985
+ for k, toks in {
986
+ "chosen_": chosen_sequence_tokens,
987
+ "rejected_": rejected_sequence_tokens,
988
+ "": prompt_tokens,
989
+ }.items():
990
+ for type_key, tokens in toks.items():
991
+ if type_key == "token_type_ids":
992
+ continue
993
+ batch[f"{k}{type_key}"] = tokens
994
+
995
+ else:
996
+ chosen_tokens = self.processing_class(
997
+ chosen, truncation=True, max_length=self.max_completion_length, add_special_tokens=True
998
+ )
999
+ rejected_tokens = self.processing_class(
1000
+ rejected, truncation=True, max_length=self.max_completion_length, add_special_tokens=True
1001
+ )
1002
+ prompt_tokens = self.processing_class(
1003
+ prompt, truncation=True, max_length=self.max_prompt_length, add_special_tokens=True
1004
+ )
1005
+
1006
+ batch["chosen_labels"] = chosen_tokens["input_ids"]
1007
+ batch["rejected_labels"] = rejected_tokens["input_ids"]
1008
+ batch["prompt_input_ids"] = prompt_tokens["input_ids"]
1009
+ batch["prompt_attention_mask"] = prompt_tokens["attention_mask"]
1010
+
1011
+ if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"):
1012
+ batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(
1013
+ labels=torch.tensor(batch["rejected_labels"])
1014
+ )
1015
+ batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels(
1016
+ labels=torch.tensor(batch["chosen_labels"])
1017
+ )
1018
+
1019
+ if is_torch_xla_available():
1020
+ # Pad the sequences to global max_length to avoid TorchXLA recompilation
1021
+ for k in batch:
1022
+ if "labels" in k or self.is_encoder_decoder:
1023
+ pad_value = self.label_pad_token_id
1024
+ elif k.endswith("_input_ids"):
1025
+ pad_value = self.padding_value
1026
+ elif k.endswith("_attention_mask"):
1027
+ pad_value = 0
1028
+ batch[k] = batch[k] + [pad_value] * (self.max_length - len(batch[k]))
1029
+ return batch
1030
+
1031
+ @staticmethod
1032
+ def concatenated_inputs(
1033
+ batch: dict[str, Union[list, torch.LongTensor]],
1034
+ is_encoder_decoder: bool = False,
1035
+ label_pad_token_id: int = -100,
1036
+ padding_value: int = 0,
1037
+ device: Optional[torch.device] = None,
1038
+ ) -> dict[str, torch.LongTensor]:
1039
+ """Concatenate the chosen and rejected inputs into a single tensor.
1040
+
1041
+ Args:
1042
+ batch:
1043
+ A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors
1044
+ of shape (batch_size, sequence_length).
1045
+ is_encoder_decoder:
1046
+ Whether the model is an encoder-decoder model.
1047
+ label_pad_token_id:
1048
+ The label pad token id.
1049
+ padding_value:
1050
+ The padding value to use for the concatenated inputs_ids.
1051
+ device:
1052
+ The device for the concatenated inputs.
1053
+
1054
+ Returns:
1055
+ A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'.
1056
+ """
1057
+ concatenated_batch = {}
1058
+
1059
+ if is_encoder_decoder:
1060
+ max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1])
1061
+ else:
1062
+ max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1])
1063
+
1064
+ for k in batch:
1065
+ if k.startswith("chosen") and isinstance(batch[k], torch.Tensor):
1066
+ if "labels" in k or is_encoder_decoder:
1067
+ pad_value = label_pad_token_id
1068
+ elif k.endswith("_input_ids"):
1069
+ pad_value = padding_value
1070
+ elif k.endswith("_attention_mask"):
1071
+ pad_value = 0
1072
+ concatenated_key = k.replace("chosen", "concatenated")
1073
+ concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value)
1074
+ for k in batch:
1075
+ if k.startswith("rejected") and isinstance(batch[k], torch.Tensor):
1076
+ if "labels" in k or is_encoder_decoder:
1077
+ pad_value = label_pad_token_id
1078
+ elif k.endswith("_input_ids"):
1079
+ pad_value = padding_value
1080
+ elif k.endswith("_attention_mask"):
1081
+ pad_value = 0
1082
+ concatenated_key = k.replace("rejected", "concatenated")
1083
+ concatenated_batch[concatenated_key] = torch.cat(
1084
+ (
1085
+ concatenated_batch[concatenated_key],
1086
+ pad_to_length(batch[k], max_length, pad_value=pad_value),
1087
+ ),
1088
+ dim=0,
1089
+ ).to(device=device)
1090
+
1091
+ if is_encoder_decoder:
1092
+ concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device)
1093
+ concatenated_batch["concatenated_attention_mask"] = (
1094
+ batch["prompt_attention_mask"].repeat(2, 1).to(device=device)
1095
+ )
1096
+
1097
+ return concatenated_batch
1098
+
1099
+ def odds_ratio_loss(
1100
+ self,
1101
+ policy_chosen_logps: torch.FloatTensor,
1102
+ policy_rejected_logps: torch.FloatTensor,
1103
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
1104
+ """Compute ORPO's odds ratio (OR) loss for a batch of policy and reference model log probabilities.
1105
+
1106
+ Args:
1107
+ policy_chosen_logps:
1108
+ Log probabilities of the policy model for the chosen responses. Shape: (batch_size,)
1109
+ policy_rejected_logps:
1110
+ Log probabilities of the policy model for the rejected responses. Shape: (batch_size,)
1111
+
1112
+ Returns:
1113
+ A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). The losses tensor contains the ORPO
1114
+ loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for
1115
+ the chosen and rejected responses, respectively. The log odds ratio of the chosen responses over the
1116
+ rejected responses ratio for logging purposes. The `log(sigmoid(log_odds_chosen))` for logging purposes.
1117
+ """
1118
+
1119
+ # Derived from Eqs. (4) and (7) from https://huggingface.co/papers/2403.07691 by using log identities and exp(log(P(y|x)) = P(y|x)
1120
+ log_odds = (policy_chosen_logps - policy_rejected_logps) - (
1121
+ torch.log1p(-torch.exp(policy_chosen_logps)) - torch.log1p(-torch.exp(policy_rejected_logps))
1122
+ )
1123
+ ratio = F.logsigmoid(log_odds)
1124
+ losses = self.beta * ratio
1125
+
1126
+ chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach()
1127
+ rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach()
1128
+
1129
+ return losses, chosen_rewards, rejected_rewards, torch.mean(ratio), torch.mean(log_odds)
1130
+
1131
+ @staticmethod
1132
+ def get_batch_logps(
1133
+ logits: torch.FloatTensor,
1134
+ labels: torch.LongTensor,
1135
+ average_log_prob: bool = False,
1136
+ label_pad_token_id: int = -100,
1137
+ is_encoder_decoder: bool = False,
1138
+ ) -> torch.FloatTensor:
1139
+ """Compute the log probabilities of the given labels under the given logits.
1140
+
1141
+ Args:
1142
+ logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size)
1143
+ labels:
1144
+ Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are
1145
+ ignored. Shape: (batch_size, sequence_length)
1146
+ average_log_prob:
1147
+ If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the
1148
+ log probabilities of the (non-masked) tokens.
1149
+ label_pad_token_id: The label pad token id.
1150
+ is_encoder_decoder: Whether the model is an encoder-decoder model.
1151
+
1152
+ Returns:
1153
+ A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the
1154
+ given logits.
1155
+ """
1156
+ if logits.shape[:-1] != labels.shape:
1157
+ raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.")
1158
+
1159
+ if not is_encoder_decoder:
1160
+ labels = labels[:, 1:].clone()
1161
+ logits = logits[:, :-1, :]
1162
+ loss_mask = labels != label_pad_token_id
1163
+
1164
+ # dummy token; we'll ignore the losses on these tokens later
1165
+ labels = torch.where(labels == label_pad_token_id, 0, labels)
1166
+
1167
+ per_token_logps = selective_log_softmax(logits, labels)
1168
+
1169
+ if average_log_prob:
1170
+ return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1)
1171
+ else:
1172
+ return (per_token_logps * loss_mask).sum(-1)
1173
+
1174
+ def concatenated_forward(
1175
+ self, model: nn.Module, batch: dict[str, Union[list, torch.LongTensor]]
1176
+ ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]:
1177
+ """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together.
1178
+
1179
+ We do this to avoid doing two forward passes, because it's faster for FSDP.
1180
+ """
1181
+ concatenated_batch = self.concatenated_inputs(
1182
+ batch,
1183
+ is_encoder_decoder=self.is_encoder_decoder,
1184
+ label_pad_token_id=self.label_pad_token_id,
1185
+ padding_value=self.padding_value,
1186
+ device=self.accelerator.device,
1187
+ )
1188
+ len_chosen = batch["chosen_labels"].shape[0]
1189
+
1190
+ model_kwargs = (
1191
+ {
1192
+ "decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]),
1193
+ }
1194
+ if self.is_encoder_decoder
1195
+ else {}
1196
+ )
1197
+
1198
+ if self.aux_loss_enabled:
1199
+ model_kwargs["output_router_logits"] = True
1200
+
1201
+ outputs = model(
1202
+ concatenated_batch["concatenated_input_ids"],
1203
+ attention_mask=concatenated_batch["concatenated_attention_mask"],
1204
+ use_cache=False,
1205
+ **model_kwargs,
1206
+ )
1207
+ all_logits = outputs.logits
1208
+
1209
+ def cross_entropy_loss(logits, labels):
1210
+ if not self.is_encoder_decoder:
1211
+ # Shift so that tokens < n predict n
1212
+ logits = logits[..., :-1, :].contiguous()
1213
+ labels = labels[..., 1:].contiguous()
1214
+ # Flatten the tokens
1215
+ loss_fct = nn.CrossEntropyLoss()
1216
+ logits = logits.view(-1, logits.shape[-1])
1217
+ labels = labels.view(-1)
1218
+ # Enable model parallelism
1219
+ labels = labels.to(logits.device)
1220
+ loss = loss_fct(logits, labels)
1221
+ return loss
1222
+
1223
+ if self.is_encoder_decoder:
1224
+ labels = concatenated_batch["concatenated_labels"].clone()
1225
+ else:
1226
+ labels = concatenated_batch["concatenated_input_ids"].clone()
1227
+ attention_mask = concatenated_batch["concatenated_attention_mask"]
1228
+ labels = torch.where(attention_mask == 1, labels, self.label_pad_token_id)
1229
+ # orpo chosen nll loss is computed over the full prompt and response
1230
+ chosen_nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen])
1231
+
1232
+ all_logps = self.get_batch_logps(
1233
+ all_logits,
1234
+ concatenated_batch["concatenated_labels"],
1235
+ average_log_prob=True,
1236
+ is_encoder_decoder=self.is_encoder_decoder,
1237
+ label_pad_token_id=self.label_pad_token_id,
1238
+ )
1239
+
1240
+ chosen_logps = all_logps[:len_chosen]
1241
+ rejected_logps = all_logps[len_chosen:]
1242
+
1243
+ if not self.is_encoder_decoder:
1244
+ chosen_logits = all_logits[:len_chosen, :-1, :]
1245
+ rejected_logits = all_logits[len_chosen:, :-1, :]
1246
+ else:
1247
+ chosen_logits = all_logits[:len_chosen]
1248
+ rejected_logits = all_logits[len_chosen:]
1249
+
1250
+ if self.aux_loss_enabled:
1251
+ return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss, outputs.aux_loss)
1252
+
1253
+ return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss)
1254
+
1255
+ def get_batch_loss_metrics(
1256
+ self,
1257
+ model,
1258
+ batch: dict[str, Union[list, torch.LongTensor]],
1259
+ train_eval: Literal["train", "eval"] = "train",
1260
+ ):
1261
+ """Compute the ORPO loss and other metrics for the given batch of inputs for train or test."""
1262
+ metrics = {}
1263
+
1264
+ forward_output = self.concatenated_forward(model, batch)
1265
+ (
1266
+ policy_chosen_logps,
1267
+ policy_rejected_logps,
1268
+ policy_chosen_logits,
1269
+ policy_rejected_logits,
1270
+ policy_nll_loss,
1271
+ ) = forward_output[:5]
1272
+ if self.aux_loss_enabled:
1273
+ aux_loss = forward_output[5]
1274
+
1275
+ losses, chosen_rewards, rejected_rewards, log_odds_ratio, log_odds_chosen = self.odds_ratio_loss(
1276
+ policy_chosen_logps, policy_rejected_logps
1277
+ )
1278
+ # full ORPO loss
1279
+ loss = policy_nll_loss - losses.mean()
1280
+
1281
+ reward_accuracies = (chosen_rewards > rejected_rewards).float()
1282
+
1283
+ prefix = "eval_" if train_eval == "eval" else ""
1284
+ metrics[f"{prefix}rewards/chosen"] = self.accelerator.gather_for_metrics(chosen_rewards).mean()
1285
+ metrics[f"{prefix}rewards/rejected"] = self.accelerator.gather_for_metrics(rejected_rewards).mean()
1286
+ metrics[f"{prefix}rewards/accuracies"] = self.accelerator.gather_for_metrics(reward_accuracies).mean()
1287
+ metrics[f"{prefix}rewards/margins"] = self.accelerator.gather_for_metrics(
1288
+ chosen_rewards - rejected_rewards
1289
+ ).mean()
1290
+ metrics[f"{prefix}logps/rejected"] = self.accelerator.gather_for_metrics(policy_rejected_logps).detach().mean()
1291
+ metrics[f"{prefix}logps/chosen"] = self.accelerator.gather_for_metrics(policy_chosen_logps).detach().mean()
1292
+ metrics[f"{prefix}logits/rejected"] = self.accelerator.gather_for_metrics(
1293
+ policy_rejected_logits.detach().mean()
1294
+ ).mean()
1295
+ metrics[f"{prefix}logits/chosen"] = self.accelerator.gather_for_metrics(
1296
+ policy_chosen_logits.detach().mean()
1297
+ ).mean()
1298
+ metrics[f"{prefix}nll_loss"] = self.accelerator.gather_for_metrics(policy_nll_loss).detach().mean()
1299
+ metrics[f"{prefix}log_odds_ratio"] = self.accelerator.gather_for_metrics(log_odds_ratio).detach().mean()
1300
+ metrics[f"{prefix}log_odds_chosen"] = self.accelerator.gather_for_metrics(log_odds_chosen).detach().mean()
1301
+ if is_torch_xla_available():
1302
+ xm.mark_step() # needed because .item() calls
1303
+ for k, v in metrics.items():
1304
+ metrics[k] = v.item()
1305
+ if self.aux_loss_enabled:
1306
+ loss += self.aux_loss_coef * aux_loss
1307
+
1308
+ return loss, metrics
1309
+
1310
+ def compute_loss(
1311
+ self,
1312
+ model: Union[PreTrainedModel, nn.Module],
1313
+ inputs: dict[str, Union[torch.Tensor, Any]],
1314
+ return_outputs=False,
1315
+ num_items_in_batch=None,
1316
+ ) -> Union[torch.Tensor, tuple[torch.Tensor, dict[str, torch.Tensor]]]:
1317
+ compute_loss_context_manager = (
1318
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
1319
+ )
1320
+
1321
+ with compute_loss_context_manager:
1322
+ loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train")
1323
+
1324
+ # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class:
1325
+ loss = loss.to(self.args.device)
1326
+
1327
+ # force log the metrics
1328
+ self.store_metrics(metrics, train_eval="train")
1329
+
1330
+ if return_outputs:
1331
+ return (loss, metrics)
1332
+ return loss
1333
+
1334
+ def generate_from_model(self, model, batch: dict[str, torch.LongTensor]) -> str:
1335
+ """Generate samples from the model and reference model for the given batch of inputs."""
1336
+
1337
+ # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with
1338
+ # the torch amp context manager as some hidden states are silently casted to full precision.
1339
+ generate_context_manager = (
1340
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
1341
+ )
1342
+
1343
+ with generate_context_manager:
1344
+ policy_output = model.generate(
1345
+ input_ids=batch["prompt_input_ids"],
1346
+ attention_mask=batch["prompt_attention_mask"],
1347
+ max_length=self.max_length,
1348
+ do_sample=True,
1349
+ pad_token_id=self.processing_class.pad_token_id,
1350
+ )
1351
+
1352
+ policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id)
1353
+ policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True)
1354
+
1355
+ return policy_output_decoded
1356
+
1357
+ def prediction_step(
1358
+ self,
1359
+ model: Union[PreTrainedModel, nn.Module],
1360
+ inputs: dict[str, Union[torch.Tensor, Any]],
1361
+ prediction_loss_only: bool,
1362
+ ignore_keys: Optional[list[str]] = None,
1363
+ ):
1364
+ if not self.use_dpo_data_collator:
1365
+ logger.warning(
1366
+ "prediction_step is only implemented for DPODataCollatorWithPadding, and you passed a datacollator that is different than "
1367
+ "DPODataCollatorWithPadding - you might see unexpected behavior. Alternatively, you can implement your own prediction_step method if you are using a custom data collator"
1368
+ )
1369
+ if ignore_keys is None:
1370
+ if hasattr(model, "config"):
1371
+ ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", [])
1372
+ else:
1373
+ ignore_keys = []
1374
+
1375
+ prediction_context_manager = (
1376
+ autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext()
1377
+ )
1378
+
1379
+ with torch.no_grad(), prediction_context_manager:
1380
+ loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval")
1381
+
1382
+ # force log the metrics
1383
+ self.store_metrics(metrics, train_eval="eval")
1384
+
1385
+ if prediction_loss_only:
1386
+ return (loss.detach(), None, None)
1387
+
1388
+ # logits for the chosen and rejected samples from model
1389
+ logits_dict = {
1390
+ "eval_logits/chosen": metrics["eval_logits/chosen"],
1391
+ "eval_logits/rejected": metrics["eval_logits/rejected"],
1392
+ }
1393
+ logits = [v for k, v in logits_dict.items() if k not in ignore_keys]
1394
+ logits = torch.tensor(logits, device=self.accelerator.device)
1395
+ labels = torch.zeros(logits.shape[0], device=self.accelerator.device)
1396
+
1397
+ return (loss.detach(), logits, labels)
1398
+
1399
+ def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None:
1400
+ for key, value in metrics.items():
1401
+ self._stored_metrics[train_eval][key].append(value)
1402
+
1403
+ def evaluation_loop(
1404
+ self,
1405
+ dataloader: DataLoader,
1406
+ description: str,
1407
+ prediction_loss_only: Optional[bool] = None,
1408
+ ignore_keys: Optional[list[str]] = None,
1409
+ metric_key_prefix: str = "eval",
1410
+ ) -> EvalLoopOutput:
1411
+ """
1412
+ Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by
1413
+ `Trainer.evaluate()` and `Trainer.predict()`.
1414
+
1415
+ Works both with or without labels.
1416
+ """
1417
+
1418
+ # Sample and save to game log if requested (for one batch to save time)
1419
+ if self.generate_during_eval:
1420
+ # Generate random indices within the range of the total number of samples
1421
+ num_samples = len(dataloader.dataset)
1422
+ random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size)
1423
+
1424
+ # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader
1425
+ random_batch_dataset = dataloader.dataset.select(random_indices)
1426
+ random_batch = self.data_collator(random_batch_dataset)
1427
+ random_batch = self._prepare_inputs(random_batch)
1428
+
1429
+ policy_output_decoded = self.generate_from_model(self.model, random_batch)
1430
+
1431
+ table = pd.DataFrame(
1432
+ columns=["Prompt", "Policy"],
1433
+ data=[
1434
+ [prompt, pol[len(prompt) :]] for prompt, pol in zip(random_batch["prompt"], policy_output_decoded)
1435
+ ],
1436
+ )
1437
+ if "wandb" in self.args.report_to:
1438
+ wandb.log({"game_log": wandb.Table(data=table)})
1439
+
1440
+ if "comet_ml" in self.args.report_to:
1441
+ log_table_to_comet_experiment(
1442
+ name="game_log.csv",
1443
+ table=table,
1444
+ )
1445
+
1446
+ # Base evaluation
1447
+ initial_output = super().evaluation_loop(
1448
+ dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix
1449
+ )
1450
+
1451
+ return initial_output
1452
+
1453
+ def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None:
1454
+ """
1455
+ Log `logs` on the various objects watching training, including stored metrics.
1456
+
1457
+ Args:
1458
+ logs (`dict[str, float]`):
1459
+ The values to log.
1460
+ start_time (`float`, *optional*):
1461
+ Start time of the training.
1462
+ """
1463
+ # logs either has 'loss' or 'eval_loss'
1464
+ train_eval = "train" if "loss" in logs else "eval"
1465
+ # Add averaged stored metrics to logs
1466
+ for key, metrics in self._stored_metrics[train_eval].items():
1467
+ logs[key] = torch.tensor(metrics).mean().item()
1468
+ del self._stored_metrics[train_eval]
1469
+ return super().log(logs, start_time)
1470
+
1471
+ def _shift_right(self, input_ids):
1472
+ if self.decoder_start_token_id is None:
1473
+ raise ValueError(
1474
+ "model.config.decoder_start_token_id has to be defined. It is usually set to the pad_token_id."
1475
+ )
1476
+
1477
+ # shift inputs to the right
1478
+ if is_torch_fx_proxy(input_ids):
1479
+ # Item assignment is not supported natively for proxies.
1480
+ shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), self.decoder_start_token_id)
1481
+ shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1)
1482
+ else:
1483
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
1484
+ shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
1485
+ shifted_input_ids[..., 0] = self.decoder_start_token_id
1486
+
1487
+ if self.pad_token_id is None:
1488
+ raise ValueError("model.config.pad_token_id has to be defined.")
1489
+ # replace possible -100 values in labels by `pad_token_id`
1490
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, self.pad_token_id)
1491
+
1492
+ return shifted_input_ids
1493
+
1494
+ # Ensure the model card is saved along with the checkpoint
1495
+ def _save_checkpoint(self, model, trial):
1496
+ if self.args.hub_model_id is None:
1497
+ model_name = Path(self.args.output_dir).name
1498
+ else:
1499
+ model_name = self.args.hub_model_id.split("/")[-1]
1500
+ self.create_model_card(model_name=model_name)
1501
+ super()._save_checkpoint(model, trial)
1502
+ class UnslothORPOTrainer(_UnslothORPOTrainer):
1503
+ """
1504
+
1505
+ Initialize ORPOTrainer.
1506
+
1507
+ Args:
1508
+ model ([`~transformers.PreTrainedModel`]):
1509
+ The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`].
1510
+ args ([`ORPOConfig`]):
1511
+ The ORPO config arguments to use for training.
1512
+ data_collator ([`~transformers.DataCollator`]):
1513
+ The data collator to use for training. If None is specified, the default data collator
1514
+ ([`DPODataCollatorWithPadding`]) will be used which will pad the sequences to the maximum length of the
1515
+ sequences in the batch, given a dataset of paired sequences.
1516
+ train_dataset ([`~datasets.Dataset`]):
1517
+ The dataset to use for training.
1518
+ eval_dataset ([`~datasets.Dataset`]):
1519
+ The dataset to use for evaluation.
1520
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*):
1521
+ Processing class used to process the data. If provided, will be used to automatically process the inputs
1522
+ for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
1523
+ reuse the fine-tuned model.
1524
+ model_init (`Callable[[], transformers.PreTrainedModel]`):
1525
+ The model initializer to use for training. If None is specified, the default model initializer will be
1526
+ used.
1527
+ callbacks (`list[transformers.TrainerCallback]`):
1528
+ The callbacks to use for training.
1529
+ optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
1530
+ The optimizer and scheduler to use for training.
1531
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
1532
+ The function to use to preprocess the logits before computing the metrics.
1533
+ peft_config (`dict`, defaults to `None`):
1534
+ The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in
1535
+ a PEFT model.
1536
+ compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
1537
+ The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to
1538
+ metric values.
1539
+
1540
+ """
1541
+ def __init__(
1542
+ self,
1543
+ model = None,
1544
+ args = None,
1545
+ data_collator = None,
1546
+ train_dataset = None,
1547
+ eval_dataset = None,
1548
+ processing_class = None,
1549
+ model_init = None,
1550
+ callbacks = None,
1551
+ preprocess_logits_for_metrics = None,
1552
+ peft_config = None,
1553
+ compute_metrics = None,
1554
+ **kwargs
1555
+ ):
1556
+ if args is None: args = UnslothORPOConfig()
1557
+ use_bf16 = getattr(args, 'bf16', False)
1558
+ if type(use_bf16) is not bool: use_bf16 = False
1559
+ use_fp16 = getattr(args, 'fp16', False)
1560
+ if type(use_fp16) is not bool: use_fp16 = False
1561
+ force_float32 = False
1562
+ full_finetuning = os.environ.get('UNSLOTH_ENABLE_FULL_FINETUNING', '0') == '1'
1563
+ if not full_finetuning and (os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '1'):
1564
+ print('Unsloth: Switching to float32 training since model cannot work with float16')
1565
+ force_float32 = True
1566
+ mixed_precision_dtype = os.environ.get('UNSLOTH_MIXED_PRECISION', 'float32')
1567
+ dtype = getattr(model.config, 'dtype', None) or getattr(model.config, 'torch_dtype', None)
1568
+ if dtype is None: dtype = model.get_input_embeddings().weight.dtype
1569
+ from unsloth_zoo.utils import _get_dtype
1570
+ dtype = _get_dtype(dtype)
1571
+ float16 = dtype == torch.float16
1572
+ 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`')
1573
+ 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`')
1574
+ if force_float32:
1575
+ # Forced float32 training
1576
+ args.fp16 = False
1577
+ args.bf16 = False
1578
+ os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'
1579
+ if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'
1580
+ # args.mixed_precision is a new argument which needs to be set now
1581
+ elif (not use_bf16 and not use_fp16) and mixed_precision_dtype == 'float32':
1582
+ # Mixed precision training
1583
+ args.fp16 = float16
1584
+ args.bf16 = not float16
1585
+ os.environ['ACCELERATE_MIXED_PRECISION'] = 'fp16' if float16 else 'bf16'
1586
+ if hasattr(args, 'mixed_precision'): args.mixed_precision = 'fp16' if float16 else 'bf16'
1587
+ # args.mixed_precision is a new argument which needs to be set now
1588
+ elif mixed_precision_dtype == 'bfloat16':
1589
+ # Both False since bfloat16 full finetuning doesn't do any autocasting.
1590
+ args.fp16 = False
1591
+ args.bf16 = False
1592
+ os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'
1593
+ if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'
1594
+ # args.mixed_precision is a new argument which needs to be set now
1595
+
1596
+ if getattr(args, 'eval_dataset', None) is not None and getattr(args, 'eval_strategy', 'no') == 'no':
1597
+ args.eval_strategy = 'steps'
1598
+ if getattr(args, 'eval_steps', None) is None: args.eval_steps = 0.1
1599
+ ga_steps = getattr(args, 'gradient_accumulation_steps', None)
1600
+ if ga_steps is not None and ga_steps > 1:
1601
+ from transformers import __version__ as transformers_version
1602
+ if Version(transformers_version) <= Version('4.45.2'):
1603
+ print('**** Unsloth: Please use our fixed gradient_accumulation_steps by updating transformers, TRL and Unsloth!\n'
1604
+ '`pip install --upgrade --no-cache-dir --force-reinstall --no-deps unsloth transformers trl unsloth_zoo`')
1605
+ if getattr(args, 'eval_strategy', 'no') != 'no':
1606
+ eval_bsz = getattr(args, 'per_device_eval_batch_size', 8)
1607
+ 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
1608
+ if getattr(args, 'eval_accumulation_steps', None) is None and ga_steps is not None: args.eval_accumulation_steps = ga_steps
1609
+ fp16_full_eval = getattr(args, 'fp16_full_eval', False)
1610
+ if type(fp16_full_eval) is not bool: fp16_full_eval = False
1611
+ bf16_full_eval = getattr(args, 'bf16_full_eval', False)
1612
+ if type(bf16_full_eval) is not bool: bf16_full_eval = False
1613
+ if args.fp16 and bf16_full_eval: args.bf16_full_eval = False; args.fp16_full_eval = True
1614
+ if args.bf16 and fp16_full_eval: args.bf16_full_eval = True; args.fp16_full_eval = False
1615
+ if force_float32:
1616
+ args.bf16_full_eval = False
1617
+ args.fp16_full_eval = False
1618
+ elif os.environ.get('UNSLOTH_MIXED_PRECISION', 'float32') == 'bfloat16':
1619
+ args.bf16_full_eval = True
1620
+ args.fp16_full_eval = False
1621
+ elif not bf16_full_eval and not fp16_full_eval:
1622
+ args.bf16_full_eval = args.bf16
1623
+ args.fp16_full_eval = args.fp16
1624
+ _output_logits = False
1625
+ if locals().get('compute_metrics', None) is not None: _output_logits = True
1626
+ if locals().get('preprocess_logits_for_metrics', None) is not None: _output_logits = True
1627
+ if _output_logits:
1628
+ os.environ['UNSLOTH_RETURN_LOGITS'] = '1'
1629
+ if 'max_seq_length' not in locals() and not hasattr(args, 'max_seq_length'):
1630
+ pass
1631
+ else:
1632
+ model_max_seq_length = getattr(model, 'max_seq_length', None)
1633
+ args_max_seq_length = getattr(args, 'max_seq_length', None)
1634
+ if args_max_seq_length is None and model_max_seq_length is not None:
1635
+ max_seq_length = model.max_seq_length
1636
+ if hasattr(args, 'max_seq_length'): args.max_seq_length = max_seq_length
1637
+ if model is not None and hasattr(model, 'for_training'):
1638
+ model.for_training(use_gradient_checkpointing=getattr(args, 'gradient_checkpointing', True))
1639
+ if 'tokenizer' in locals() and hasattr(tokenizer, 'padding_side'): tokenizer.padding_side = 'right'
1640
+ if 'processing_class' in locals():
1641
+ if hasattr(processing_class, 'padding_side'): processing_class.padding_side = 'right'
1642
+ if hasattr(processing_class, 'tokenizer') and hasattr(processing_class.tokenizer, 'padding_side'): processing_class.tokenizer.padding_side = 'right'
1643
+ __tokenizer = processing_class if 'processing_class' in locals() else tokenizer
1644
+ from unsloth_zoo.vision_utils import UnslothVisionDataCollator
1645
+ if not isinstance(data_collator, UnslothVisionDataCollator):
1646
+ if isinstance(data_collator, DataCollatorForSeq2Seq) and 'labels' not in train_dataset.column_names:
1647
+ data_collator = TransformersDataCollatorForLanguageModeling(
1648
+ __tokenizer,
1649
+ mlm = False,
1650
+ mlm_probability = 0.0,
1651
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
1652
+ )
1653
+ elif isinstance(data_collator, TransformersDataCollatorForLanguageModeling) and 'labels' in train_dataset.column_names:
1654
+ data_collator = DataCollatorForSeq2Seq(
1655
+ __tokenizer,
1656
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
1657
+ )
1658
+ else:
1659
+ if hasattr(args, 'remove_unused_columns'): args.remove_unused_columns = False
1660
+ if hasattr(args, 'dataset_text_field'): args.dataset_text_field = ''
1661
+ if hasattr(args, 'dataset_kwargs'): args.dataset_kwargs = {'skip_prepare_dataset': True}
1662
+ if not isinstance(data_collator, UnslothVisionDataCollator):
1663
+ if not hasattr(__tokenizer, 'pad') and hasattr(__tokenizer, 'tokenizer'):
1664
+ if isinstance(data_collator, DataCollatorForSeq2Seq):
1665
+ data_collator = DataCollatorForSeq2Seq(
1666
+ __tokenizer.tokenizer,
1667
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
1668
+ )
1669
+ else:
1670
+ data_collator = TransformersDataCollatorForLanguageModeling(
1671
+ __tokenizer.tokenizer,
1672
+ mlm = False,
1673
+ mlm_probability = 0.0,
1674
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
1675
+ )
1676
+ other_metrics = []
1677
+
1678
+ from unsloth_zoo.logging_utils import PatchRLStatistics
1679
+ PatchRLStatistics('orpo_trainer', other_metrics)
1680
+
1681
+ # [TODO] Fix up DataParallel multiplying batch sizes
1682
+ # [TODO] DDP works, but DP seems to not work? [TODO]
1683
+ if getattr(args, "parallel_mode", None) == ParallelMode.NOT_DISTRIBUTED and args.n_gpu > 1:
1684
+ if getattr(args, "_n_gpu", 1) != 1:
1685
+ args._n_gpu = 1
1686
+ if "model" in locals() and hasattr(model, "for_training"):
1687
+ model.for_training(use_gradient_checkpointing=getattr(args, 'gradient_checkpointing', True))
1688
+ super().__init__(
1689
+ model = model,
1690
+ args = args,
1691
+ data_collator = data_collator,
1692
+ train_dataset = train_dataset,
1693
+ eval_dataset = eval_dataset,
1694
+ processing_class = processing_class,
1695
+ model_init = model_init,
1696
+ callbacks = callbacks,
1697
+ preprocess_logits_for_metrics = preprocess_logits_for_metrics,
1698
+ peft_config = peft_config,
1699
+ compute_metrics = compute_metrics,**kwargs)
1700
+ if "model" in locals() and hasattr(model, "for_inference"):
1701
+ model.for_inference()
1702
+ if hasattr(self, 'neftune_hook_handle'):
1703
+ self.neftune_hook_handle.remove()
1704
+ if hasattr(self, 'neftune_hook_handle'): del self.neftune_hook_handle
1705
+ if getattr(args, 'neftune_noise_alpha', None) is not None:
1706
+ model.get_input_embeddings().neftune_noise_alpha = self.neftune_noise_alpha
1707
+ pass
1708
+ if hasattr(self, 'accelerator'):
1709
+ scaler = self.accelerator.scaler
1710
+ current_model = model
1711
+ while hasattr(current_model, 'model'):
1712
+ current_model.accelerator_scaler = scaler
1713
+ current_model = current_model.model
1714
+ current_model.accelerator_scaler = scaler
1715
+ pass
1716
+ if hasattr(self, 'train'):
1717
+ self.train = MethodType(prepare_for_training_mode(self.__class__.train), self)
1718
+ pass
1719
+
1720
+ pass
1721
+
1722
+
1723
+ if hasattr(logger, "addFilter"):
1724
+ import logging
1725
+ class HideLoggingMessage(logging.Filter):
1726
+ def __init__(self, text): self.text = text
1727
+ def filter(self, x): return not (self.text in x.getMessage())
1728
+ pass
1729
+ logger.addFilter(HideLoggingMessage("`use_cache=True`"))
1730
+