cciwon-code-review-cli 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/bin/code-review.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,1416 @@
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.sft_trainer import (Any, AutoProcessor, BaseTrainer, Callable, DataCollator, DataCollatorForLanguageModeling, DataCollatorForVisionLanguageModeling, Dataset, EvalPrediction, FLASH_ATTENTION_VARIANTS, IterableDataset, Optional, Path, PeftConfig, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, SFTConfig, SFTTrainer, TrainerCallback, TrainingArguments, Union, clone_chat_template, contextlib, create_model_from_path, dataclass, defaultdict, dft_loss, get_act_offloading_ctx_manager, is_conversational, logger, logging, nn, os, pack_dataset, pad, prepare_peft_model, selective_log_softmax, torch, Callable, DataCollator, DataCollatorForLanguageModeling, Dataset, IterableDataset, Optional, Union, os, pack_dataset, pad, Optional, PreTrainedModel, logger, os, torch, os)
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 UnslothSFTConfig(SFTConfig):
199
+ """
200
+
201
+ Configuration class for the [`SFTTrainer`].
202
+
203
+ This class includes only the parameters that are specific to SFT training. For a full list of training arguments,
204
+ please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may
205
+ differ from those in [`~transformers.TrainingArguments`].
206
+
207
+ Using [`~transformers.HfArgumentParser`] we can turn this class into
208
+ [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the
209
+ command line.
210
+
211
+ Parameters:
212
+ > Parameters that control the model
213
+
214
+ model_init_kwargs (`dict[str, Any]`, *optional*):
215
+ Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model`
216
+ argument of the [`SFTTrainer`] is provided as a string. If you're training a MoE architecture and want to
217
+ include the load balancing/auxilliary loss as a part of the final loss, remember to set
218
+ `output_router_logits=True` in this dictionary.
219
+ chat_template_path (`str`, *optional*):
220
+ If specified, sets the model's chat template. This can either be the path to a tokenizer (local directory
221
+ or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, you must
222
+ ensure that any special tokens referenced in the template are added to the tokenizer and that the model's
223
+ embedding layer is resized accordingly.
224
+
225
+ > Parameters that control the data preprocessing
226
+
227
+ dataset_text_field (`str`, *optional*, defaults to `"text"`):
228
+ Name of the column that contains text data in the dataset.
229
+ dataset_kwargs (`dict[str, Any]`, *optional*):
230
+ Dictionary of optional keyword arguments for the dataset preparation. The only supported key is
231
+ `skip_prepare_dataset`. When the model is a VLM, `skip_prepare_dataset` is automatically treated as `True`
232
+ regardless of the provided value, since preprocessing is done on the fly.
233
+ dataset_num_proc (`int`, *optional*):
234
+ Number of processes to use for processing the dataset.
235
+ eos_token (`str`, *optional*):
236
+ Token used to indicate the end of a turn or sequence. If `None`, it defaults to
237
+ `processing_class.eos_token`.
238
+ pad_token (`str`, *optional*):
239
+ Token used for padding. If `None`, it defaults to `processing_class.pad_token`, or if that is also `None`,
240
+ it falls back to `processing_class.eos_token`.
241
+ max_length (`int` or `None`, *optional*, defaults to `1024`):
242
+ Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the right.
243
+ If `None`, no truncation is applied. When packing is enabled, this value sets the sequence length.
244
+ packing (`bool`, *optional*, defaults to `False`):
245
+ Whether to group multiple sequences into fixed-length blocks to improve computational efficiency and reduce
246
+ padding. Uses `max_length` to define sequence length.
247
+ packing_strategy (`str`, *optional*, defaults to `"bfd"`):
248
+ Strategy for packing sequences. Can be either `"bfd"` (best-fit decreasing, default), or `"wrapped"`.
249
+ padding_free (`bool`, *optional*, defaults to `False`):
250
+ Whether to perform forward passes without padding by flattening all sequences in the batch into a single
251
+ continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this is only
252
+ supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch structure. When
253
+ packing is enabled with strategy `"bfd"`, padding-free is enabled, regardless of the value of this
254
+ parameter.
255
+ pad_to_multiple_of (`int`, *optional*):
256
+ If set, the sequences will be padded to a multiple of this value.
257
+ eval_packing (`bool`, *optional*):
258
+ Whether to pack the eval dataset. If `None`, uses the same value as `packing`.
259
+
260
+ > Parameters that control the training
261
+
262
+ completion_only_loss (`bool`, *optional*):
263
+ Whether to compute loss only on the completion part of the sequence. If set to `True`, loss is computed
264
+ only on the completion, which is supported only for [prompt-completion](#prompt-completion) datasets. If
265
+ `False`, loss is computed on the entire sequence. If `None` (default), the behavior depends on the dataset:
266
+ loss is computed on the completion for [prompt-completion](#prompt-completion) datasets, and on the full
267
+ sequence for [language modeling](#language-modeling) datasets.
268
+ assistant_only_loss (`bool`, *optional*, defaults to `False`):
269
+ Whether to compute loss only on the assistant part of the sequence. If set to `True`, loss is computed only
270
+ on the assistant responses, which is supported only for [conversational](#conversational) datasets. If
271
+ `False`, loss is computed on the entire sequence.
272
+ loss_type (`str`, *optional*, defaults to `"nll"`):
273
+ Type of loss to use. Possible values are `"nll"` (negative log-likelihood, default) and `"dft"` (Dynamic
274
+ Fine-Tuning, as described in [this paper](https://huggingface.co/papers/2508.05629)).
275
+ activation_offloading (`bool`, *optional*, defaults to `False`):
276
+ Whether to offload the activations to the CPU.
277
+
278
+ """
279
+ vllm_sampling_params: Optional[Any] = field(
280
+ default = None,
281
+ metadata = {'help': 'vLLM SamplingParams'},
282
+ )
283
+ unsloth_num_chunks : Optional[int] = field(
284
+ default = -1,
285
+ metadata = {'help': 'Chunk size to reduce memory usage. -1 is most efficient.'},
286
+ )
287
+ max_seq_length : Optional[int] = field(
288
+ default = None,
289
+ metadata = {'help': 'Maximum sequence length to truncate to.'},
290
+ )
291
+ def __init__(
292
+ self,
293
+ output_dir = None,
294
+ overwrite_output_dir = None,
295
+ do_train = False,
296
+ do_eval = False,
297
+ do_predict = False,
298
+ eval_strategy = 'no',
299
+ prediction_loss_only = False,
300
+ per_device_train_batch_size = 4,
301
+ per_device_eval_batch_size = 4,
302
+ per_gpu_train_batch_size = None,
303
+ per_gpu_eval_batch_size = None,
304
+ gradient_accumulation_steps = 2,
305
+ eval_accumulation_steps = 2,
306
+ eval_delay = 0,
307
+ torch_empty_cache_steps = 250,
308
+ learning_rate = 5e-05,
309
+ weight_decay = 0.01,
310
+ adam_beta1 = 0.9,
311
+ adam_beta2 = 0.999,
312
+ adam_epsilon = 1e-08,
313
+ max_grad_norm = 1.0,
314
+ num_train_epochs = 3.0,
315
+ max_steps = -1,
316
+ lr_scheduler_type = 'linear',
317
+ warmup_ratio = 0.1,
318
+ warmup_steps = 0,
319
+ log_level = 'passive',
320
+ log_level_replica = 'warning',
321
+ log_on_each_node = True,
322
+ logging_dir = None,
323
+ logging_strategy = 'steps',
324
+ logging_first_step = False,
325
+ logging_steps = 1,
326
+ logging_nan_inf_filter = False,
327
+ save_strategy = 'steps',
328
+ save_steps = 500,
329
+ save_total_limit = None,
330
+ save_safetensors = True,
331
+ save_on_each_node = False,
332
+ save_only_model = False,
333
+ restore_callback_states_from_checkpoint = False,
334
+ no_cuda = False,
335
+ use_cpu = False,
336
+ use_mps_device = False,
337
+ seed = 3407,
338
+ data_seed = 3407,
339
+ jit_mode_eval = False,
340
+ bf16 = False,
341
+ fp16 = False,
342
+ fp16_opt_level = 'O1',
343
+ half_precision_backend = 'auto',
344
+ bf16_full_eval = False,
345
+ fp16_full_eval = False,
346
+ tf32 = None,
347
+ local_rank = -1,
348
+ ddp_backend = None,
349
+ tpu_num_cores = None,
350
+ tpu_metrics_debug = False,
351
+ debug = '',
352
+ dataloader_drop_last = False,
353
+ eval_steps = None,
354
+ dataloader_num_workers = 0,
355
+ dataloader_prefetch_factor = None,
356
+ past_index = -1,
357
+ run_name = None,
358
+ disable_tqdm = None,
359
+ remove_unused_columns = True,
360
+ label_names = None,
361
+ load_best_model_at_end = False,
362
+ metric_for_best_model = None,
363
+ greater_is_better = None,
364
+ ignore_data_skip = False,
365
+ fsdp = None,
366
+ fsdp_min_num_params = 0,
367
+ fsdp_config = None,
368
+ fsdp_transformer_layer_cls_to_wrap = None,
369
+ accelerator_config = None,
370
+ parallelism_config = None,
371
+ deepspeed = None,
372
+ label_smoothing_factor = 0.0,
373
+ optim = 'adamw_8bit',
374
+ optim_args = None,
375
+ adafactor = False,
376
+ group_by_length = False,
377
+ length_column_name = 'length',
378
+ report_to = 'none',
379
+ project = 'huggingface',
380
+ trackio_space_id = 'trackio',
381
+ ddp_find_unused_parameters = None,
382
+ ddp_bucket_cap_mb = None,
383
+ ddp_broadcast_buffers = None,
384
+ dataloader_pin_memory = True,
385
+ dataloader_persistent_workers = False,
386
+ skip_memory_metrics = True,
387
+ use_legacy_prediction_loop = False,
388
+ push_to_hub = False,
389
+ resume_from_checkpoint = None,
390
+ hub_model_id = None,
391
+ hub_strategy = 'every_save',
392
+ hub_token = None,
393
+ hub_private_repo = None,
394
+ hub_always_push = False,
395
+ hub_revision = None,
396
+ gradient_checkpointing = True,
397
+ gradient_checkpointing_kwargs = None,
398
+ include_inputs_for_metrics = False,
399
+ eval_do_concat_batches = True,
400
+ fp16_backend = 'auto',
401
+ push_to_hub_model_id = None,
402
+ push_to_hub_organization = None,
403
+ push_to_hub_token = None,
404
+ mp_parameters = '',
405
+ auto_find_batch_size = False,
406
+ full_determinism = False,
407
+ torchdynamo = None,
408
+ ray_scope = 'last',
409
+ ddp_timeout = 1800,
410
+ torch_compile = False,
411
+ torch_compile_backend = None,
412
+ torch_compile_mode = None,
413
+ include_tokens_per_second = False,
414
+ include_num_input_tokens_seen = False,
415
+ neftune_noise_alpha = None,
416
+ optim_target_modules = None,
417
+ batch_eval_metrics = False,
418
+ eval_on_start = False,
419
+ use_liger_kernel = False,
420
+ liger_kernel_config = None,
421
+ eval_use_gather_object = False,
422
+ average_tokens_across_devices = True,
423
+ model_init_kwargs = None,
424
+ chat_template_path = None,
425
+ dataset_text_field = 'text',
426
+ dataset_kwargs = None,
427
+ dataset_num_proc = None,
428
+ eos_token = None,
429
+ pad_token = None,
430
+ max_length = 1024,
431
+ packing = False,
432
+ packing_strategy = 'bfd',
433
+ padding_free = False,
434
+ pad_to_multiple_of = None,
435
+ eval_packing = None,
436
+ completion_only_loss = None,
437
+ assistant_only_loss = False,
438
+ loss_type = 'nll',
439
+ activation_offloading = False,
440
+ vllm_sampling_params = None,
441
+ unsloth_num_chunks = -1,
442
+ max_seq_length = None,
443
+ **kwargs,
444
+ ):
445
+ 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!')
446
+ 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!')
447
+ if output_dir is None and save_strategy == 'steps' and save_steps == 500:
448
+ output_dir = 'unsloth_training_checkpoints'
449
+ save_strategy = 'no'
450
+ if dataset_num_proc is None:
451
+ from multiprocessing import cpu_count
452
+ dataset_num_proc = min(max(cpu_count()+4, 2), 64)
453
+ if os.environ.get('UNSLOTH_ENABLE_FLEX_ATTENTION', '0') == '1':
454
+ from unsloth_zoo.flex_attention import HAS_FLEX_ATTENTION
455
+ if HAS_FLEX_ATTENTION and pad_to_multiple_of is None:
456
+ from unsloth_zoo.flex_attention import FLEX_ATTENTION_BLOCK_SIZE
457
+ pad_to_multiple_of = FLEX_ATTENTION_BLOCK_SIZE
458
+
459
+
460
+ super().__init__(
461
+ output_dir = output_dir,
462
+ overwrite_output_dir = overwrite_output_dir,
463
+ do_train = do_train,
464
+ do_eval = do_eval,
465
+ do_predict = do_predict,
466
+ eval_strategy = eval_strategy,
467
+ prediction_loss_only = prediction_loss_only,
468
+ per_device_train_batch_size = per_device_train_batch_size,
469
+ per_device_eval_batch_size = per_device_eval_batch_size,
470
+ per_gpu_train_batch_size = per_gpu_train_batch_size,
471
+ per_gpu_eval_batch_size = per_gpu_eval_batch_size,
472
+ gradient_accumulation_steps = gradient_accumulation_steps,
473
+ eval_accumulation_steps = eval_accumulation_steps,
474
+ eval_delay = eval_delay,
475
+ torch_empty_cache_steps = torch_empty_cache_steps,
476
+ learning_rate = learning_rate,
477
+ weight_decay = weight_decay,
478
+ adam_beta1 = adam_beta1,
479
+ adam_beta2 = adam_beta2,
480
+ adam_epsilon = adam_epsilon,
481
+ max_grad_norm = max_grad_norm,
482
+ num_train_epochs = num_train_epochs,
483
+ max_steps = max_steps,
484
+ lr_scheduler_type = lr_scheduler_type,
485
+ warmup_ratio = warmup_ratio,
486
+ warmup_steps = warmup_steps,
487
+ log_level = log_level,
488
+ log_level_replica = log_level_replica,
489
+ log_on_each_node = log_on_each_node,
490
+ logging_dir = logging_dir,
491
+ logging_strategy = logging_strategy,
492
+ logging_first_step = logging_first_step,
493
+ logging_steps = logging_steps,
494
+ logging_nan_inf_filter = logging_nan_inf_filter,
495
+ save_strategy = save_strategy,
496
+ save_steps = save_steps,
497
+ save_total_limit = save_total_limit,
498
+ save_safetensors = save_safetensors,
499
+ save_on_each_node = save_on_each_node,
500
+ save_only_model = save_only_model,
501
+ restore_callback_states_from_checkpoint = restore_callback_states_from_checkpoint,
502
+ no_cuda = no_cuda,
503
+ use_cpu = use_cpu,
504
+ use_mps_device = use_mps_device,
505
+ seed = seed,
506
+ data_seed = data_seed,
507
+ jit_mode_eval = jit_mode_eval,
508
+ bf16 = bf16,
509
+ fp16 = fp16,
510
+ fp16_opt_level = fp16_opt_level,
511
+ half_precision_backend = half_precision_backend,
512
+ bf16_full_eval = bf16_full_eval,
513
+ fp16_full_eval = fp16_full_eval,
514
+ tf32 = tf32,
515
+ local_rank = local_rank,
516
+ ddp_backend = ddp_backend,
517
+ tpu_num_cores = tpu_num_cores,
518
+ tpu_metrics_debug = tpu_metrics_debug,
519
+ debug = debug,
520
+ dataloader_drop_last = dataloader_drop_last,
521
+ eval_steps = eval_steps,
522
+ dataloader_num_workers = dataloader_num_workers,
523
+ dataloader_prefetch_factor = dataloader_prefetch_factor,
524
+ past_index = past_index,
525
+ run_name = run_name,
526
+ disable_tqdm = disable_tqdm,
527
+ remove_unused_columns = remove_unused_columns,
528
+ label_names = label_names,
529
+ load_best_model_at_end = load_best_model_at_end,
530
+ metric_for_best_model = metric_for_best_model,
531
+ greater_is_better = greater_is_better,
532
+ ignore_data_skip = ignore_data_skip,
533
+ fsdp = fsdp,
534
+ fsdp_min_num_params = fsdp_min_num_params,
535
+ fsdp_config = fsdp_config,
536
+ fsdp_transformer_layer_cls_to_wrap = fsdp_transformer_layer_cls_to_wrap,
537
+ accelerator_config = accelerator_config,
538
+ parallelism_config = parallelism_config,
539
+ deepspeed = deepspeed,
540
+ label_smoothing_factor = label_smoothing_factor,
541
+ optim = optim,
542
+ optim_args = optim_args,
543
+ adafactor = adafactor,
544
+ group_by_length = group_by_length,
545
+ length_column_name = length_column_name,
546
+ report_to = report_to,
547
+ project = project,
548
+ trackio_space_id = trackio_space_id,
549
+ ddp_find_unused_parameters = ddp_find_unused_parameters,
550
+ ddp_bucket_cap_mb = ddp_bucket_cap_mb,
551
+ ddp_broadcast_buffers = ddp_broadcast_buffers,
552
+ dataloader_pin_memory = dataloader_pin_memory,
553
+ dataloader_persistent_workers = dataloader_persistent_workers,
554
+ skip_memory_metrics = skip_memory_metrics,
555
+ use_legacy_prediction_loop = use_legacy_prediction_loop,
556
+ push_to_hub = push_to_hub,
557
+ resume_from_checkpoint = resume_from_checkpoint,
558
+ hub_model_id = hub_model_id,
559
+ hub_strategy = hub_strategy,
560
+ hub_token = hub_token,
561
+ hub_private_repo = hub_private_repo,
562
+ hub_always_push = hub_always_push,
563
+ hub_revision = hub_revision,
564
+ gradient_checkpointing = gradient_checkpointing,
565
+ gradient_checkpointing_kwargs = gradient_checkpointing_kwargs,
566
+ include_inputs_for_metrics = include_inputs_for_metrics,
567
+ eval_do_concat_batches = eval_do_concat_batches,
568
+ fp16_backend = fp16_backend,
569
+ push_to_hub_model_id = push_to_hub_model_id,
570
+ push_to_hub_organization = push_to_hub_organization,
571
+ push_to_hub_token = push_to_hub_token,
572
+ mp_parameters = mp_parameters,
573
+ auto_find_batch_size = auto_find_batch_size,
574
+ full_determinism = full_determinism,
575
+ torchdynamo = torchdynamo,
576
+ ray_scope = ray_scope,
577
+ ddp_timeout = ddp_timeout,
578
+ torch_compile = torch_compile,
579
+ torch_compile_backend = torch_compile_backend,
580
+ torch_compile_mode = torch_compile_mode,
581
+ include_tokens_per_second = include_tokens_per_second,
582
+ include_num_input_tokens_seen = include_num_input_tokens_seen,
583
+ neftune_noise_alpha = neftune_noise_alpha,
584
+ optim_target_modules = optim_target_modules,
585
+ batch_eval_metrics = batch_eval_metrics,
586
+ eval_on_start = eval_on_start,
587
+ use_liger_kernel = use_liger_kernel,
588
+ liger_kernel_config = liger_kernel_config,
589
+ eval_use_gather_object = eval_use_gather_object,
590
+ average_tokens_across_devices = average_tokens_across_devices,
591
+ model_init_kwargs = model_init_kwargs,
592
+ chat_template_path = chat_template_path,
593
+ dataset_text_field = dataset_text_field,
594
+ dataset_kwargs = dataset_kwargs,
595
+ dataset_num_proc = dataset_num_proc,
596
+ eos_token = eos_token,
597
+ pad_token = pad_token,
598
+ max_length = max_length,
599
+ packing = packing,
600
+ packing_strategy = packing_strategy,
601
+ padding_free = padding_free,
602
+ pad_to_multiple_of = pad_to_multiple_of,
603
+ eval_packing = eval_packing,
604
+ completion_only_loss = completion_only_loss,
605
+ assistant_only_loss = assistant_only_loss,
606
+ loss_type = loss_type,
607
+ activation_offloading = activation_offloading,**kwargs)
608
+ self.vllm_sampling_params = vllm_sampling_params
609
+ self.unsloth_num_chunks = unsloth_num_chunks
610
+ self.max_seq_length = max_seq_length
611
+ pass
612
+
613
+ class _UnslothSFTTrainer(BaseTrainer):
614
+ """"""
615
+
616
+ _tag_names = ["trl", "sft"]
617
+ _name = "SFT"
618
+
619
+ def __init__(
620
+ self,
621
+ model: Union[str, PreTrainedModel],
622
+ args: Optional[Union[SFTConfig, TrainingArguments]] = None,
623
+ data_collator: Optional[DataCollator] = None,
624
+ train_dataset: Optional[Union[Dataset, IterableDataset]] = None,
625
+ eval_dataset: Optional[Union[Dataset, dict[str, Dataset]]] = None,
626
+ processing_class: Optional[Union[PreTrainedTokenizerBase, ProcessorMixin]] = None,
627
+ compute_loss_func: Optional[Callable] = None,
628
+ compute_metrics: Optional[Callable[[EvalPrediction], dict]] = None,
629
+ callbacks: Optional[list[TrainerCallback]] = None,
630
+ optimizers: tuple[Optional[torch.optim.Optimizer], Optional[torch.optim.lr_scheduler.LambdaLR]] = (None, None),
631
+ optimizer_cls_and_kwargs: Optional[tuple[type[torch.optim.Optimizer], dict[str, Any]]] = None,
632
+ preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
633
+ peft_config: Optional["PeftConfig"] = None,
634
+ formatting_func: Optional[Callable[[dict], str]] = None,
635
+ ):
636
+ # Args
637
+ if args is None:
638
+ model_name = model if isinstance(model, str) else model.config._name_or_path
639
+ model_name = model_name.split("/")[-1]
640
+ args = SFTConfig(f"{model_name}-SFT")
641
+ elif isinstance(args, TrainingArguments) and not isinstance(args, SFTConfig):
642
+ dict_args = args.to_dict()
643
+ dict_args["hub_token"] = args.hub_token # to_dict hides the hub_token
644
+ dict_args.pop("push_to_hub_token")
645
+ args = SFTConfig(**dict_args)
646
+
647
+ # Model
648
+ if isinstance(model, str):
649
+ model = create_model_from_path(model, **args.model_init_kwargs or {})
650
+ else:
651
+ if args.model_init_kwargs is not None:
652
+ logger.warning(
653
+ "You passed `model_init_kwargs` to the `SFTConfig`, but your model is already instantiated. "
654
+ "The `model_init_kwargs` will be ignored."
655
+ )
656
+ model_id = model.config._name_or_path
657
+
658
+ # Processing class
659
+ if processing_class is None:
660
+ processing_class = AutoProcessor.from_pretrained(model_id)
661
+
662
+ # Handle pad token for processors or tokenizers
663
+ if isinstance(processing_class, ProcessorMixin):
664
+ tokenizer = processing_class.tokenizer
665
+ self._is_vlm = False
666
+ elif isinstance(processing_class, PreTrainedTokenizerBase):
667
+ tokenizer = processing_class
668
+ self._is_vlm = False
669
+ else:
670
+ raise TypeError("The `processing_class` must be either a `PreTrainedTokenizerBase` or a `ProcessorMixin`")
671
+
672
+ if args.eos_token is not None:
673
+ eos_token = args.eos_token
674
+ eos_token_id = tokenizer.convert_tokens_to_ids(eos_token)
675
+ if eos_token_id is None:
676
+ raise ValueError(
677
+ f"The specified `eos_token` ('{eos_token}') is not found in the vocabulary of the given "
678
+ f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `eos_token` exists "
679
+ "in the vocabulary before using it as an EOS token."
680
+ )
681
+ tokenizer.eos_token_id = eos_token_id
682
+
683
+ if args.chat_template_path is not None:
684
+ if os.path.isfile(args.chat_template_path) and args.chat_template_path.endswith((".jinja", ".j2")):
685
+ with open(args.chat_template_path, encoding="utf-8") as chat_template_file:
686
+ processing_class.chat_template = chat_template_file.read()
687
+ added_tokens = []
688
+ else:
689
+ model, processing_class, added_tokens = clone_chat_template(
690
+ model, processing_class, args.chat_template_path
691
+ )
692
+ else:
693
+ added_tokens = []
694
+
695
+ # Catch some wrong configurations related to VLMs
696
+ if self._is_vlm and args.packing:
697
+ raise ValueError(
698
+ "Packing is not supported for vision-language models. Please set `packing=False` in the SFTConfig."
699
+ )
700
+ if self._is_vlm and args.padding_free:
701
+ raise ValueError(
702
+ "Padding-free training is yet not supported for vision-language models. Please set "
703
+ "`padding_free=False` in the `SFTConfig`."
704
+ )
705
+ if self._is_vlm and args.assistant_only_loss:
706
+ raise ValueError(
707
+ "Assistant-only loss is not yet supported for vision-language models. Please set "
708
+ "`assistant_only_loss=False` in the `SFTConfig`."
709
+ )
710
+
711
+ # PEFT configuration and model wrapping
712
+ if False:
713
+ if added_tokens:
714
+ # Ensure that the added tokens are trainable
715
+ if peft_config.trainable_token_indices is None:
716
+ peft_config.trainable_token_indices = {"embed_tokens": added_tokens}
717
+ elif "embed_tokens" not in peft_config.trainable_token_indices:
718
+ peft_config.trainable_token_indices["embed_tokens"] = added_tokens
719
+ else:
720
+ peft_config.trainable_token_indices["embed_tokens"].extend(added_tokens)
721
+
722
+ # Ensure that the lm_head is trainable
723
+ if peft_config.modules_to_save is None or "lm_head" not in peft_config.modules_to_save:
724
+ logger.warning(
725
+ "Cloning chat template added new tokens to the tokenizer, but 'lm_head' is not in PEFT's "
726
+ "`modules_to_save`. As a result, the model may not learn to generate outputs with these new "
727
+ "tokens, leading to degraded generation quality. To fix this, add "
728
+ "`modules_to_save=['lm_head']` to your PEFT configuration."
729
+ )
730
+
731
+ if peft_config.modules_to_save is None:
732
+ peft_config.modules_to_save = ["lm_head"]
733
+ else:
734
+ peft_config.modules_to_save.append("lm_head")
735
+
736
+ # In Prompt Tuning a small set of trainable virtual tokens [continuous prompt embeddings] is prepended to the
737
+ # input. We store the number of these tokens so we can account for them correctly when calculating accuracy.
738
+ self.num_virtual_tokens = 0
739
+
740
+ if False:
741
+ model = prepare_peft_model(model, peft_config, args)
742
+ if model.active_adapter in model.peft_config:
743
+ peft_model_config = model.peft_config[model.active_adapter]
744
+ self.num_virtual_tokens = getattr(peft_model_config, "num_virtual_tokens", 0)
745
+
746
+ # Data collator
747
+ # BFD packing requires padding-free mode; otherwise, the collator outputs padded attention masks, causing
748
+ # FlashAttention to ignore position_ids and recompute them incorrectly from the padded attention mask.
749
+ self.padding_free = args.padding_free or (args.packing and args.packing_strategy == "bfd")
750
+ use_flash_attention = model.config._attn_implementation in FLASH_ATTENTION_VARIANTS
751
+ if self.padding_free:
752
+ if data_collator is not None:
753
+ raise ValueError("Passing a custom data collator is not supported when using padding-free.")
754
+ if args.packing and args.packing_strategy == "wrapped":
755
+ logger.warning(
756
+ "You are passing `padding_free=True` with the 'wrapped' packing strategy, which is not "
757
+ "recommended. Please refer to the documentation to understand why this is not recommended."
758
+ )
759
+ if not use_flash_attention:
760
+ logger.warning(
761
+ "Padding-free training is enabled, but the attention implementation is not set to a supported "
762
+ "flash attention variant. Padding-free training flattens batches into a single sequence, and only "
763
+ "the following implementations are known to reliably support this: "
764
+ f"{', '.join(sorted(FLASH_ATTENTION_VARIANTS))}. Using other implementations may lead to "
765
+ "unexpected behavior. To ensure compatibility, set `attn_implementation` in the model "
766
+ "configuration to one of these supported options or verify that your attention mechanism can "
767
+ "handle flattened sequences."
768
+ )
769
+
770
+ if args.per_device_train_batch_size == 1 and not args.packing:
771
+ logger.warning(
772
+ "You are using a per_device_train_batch_size of 1 with padding-free training. Using a batch size "
773
+ "of 1 anihilate the benefits of padding-free training. Please consider increasing the batch size "
774
+ "to at least 2."
775
+ )
776
+
777
+ # Decide whether to use completion-only loss: if not specified, then it is set to True if the dataset format
778
+ # is prompt-completion, and False if the dataset format is language modeling.
779
+ dataset_sample = next(iter(train_dataset))
780
+ if args.completion_only_loss is None:
781
+ self.completion_only_loss = "prompt" in dataset_sample and "completion" in dataset_sample
782
+ else:
783
+ self.completion_only_loss = args.completion_only_loss
784
+
785
+ self._is_vision_dataset = "image" in dataset_sample or "images" in dataset_sample
786
+ if self._is_vision_dataset and not self._is_vlm:
787
+ raise ValueError(
788
+ "The dataset appears to be vision-related (contains 'image' or 'images' keys), but the provided "
789
+ "model does not seem to be a vision-language model. Please check your model and dataset."
790
+ )
791
+
792
+ if data_collator is None and not self._is_vision_dataset:
793
+ # Get the pad token: if not provided, use the one from the processing class or the eos token
794
+ # if the processing class does not have a pad token.
795
+ pad_token = args.pad_token or tokenizer.pad_token or tokenizer.eos_token
796
+ pad_token_id = tokenizer.convert_tokens_to_ids(pad_token)
797
+ if pad_token_id is None:
798
+ raise ValueError(
799
+ f"The specified `pad_token` ('{pad_token}') is not found in the vocabulary of the given "
800
+ f"`processing_class` ({processing_class.__class__.__name__}). Ensure that the `pad_token` exists "
801
+ "in the vocabulary before using it as a padding token."
802
+ )
803
+ data_collator = DataCollatorForLanguageModeling(
804
+ pad_token_id=pad_token_id,
805
+ completion_only_loss=self.completion_only_loss,
806
+ padding_free=self.padding_free,
807
+ pad_to_multiple_of=args.pad_to_multiple_of,
808
+ )
809
+ elif data_collator is None and self._is_vision_dataset:
810
+ data_collator = DataCollatorForVisionLanguageModeling(
811
+ processor=processing_class,
812
+ max_length=args.max_length,
813
+ completion_only_loss=self.completion_only_loss,
814
+ pad_to_multiple_of=args.pad_to_multiple_of,
815
+ dataset_text_field=args.dataset_text_field,
816
+ )
817
+
818
+ if args.packing and args.packing_strategy == "bfd" and not use_flash_attention:
819
+ logger.warning(
820
+ "You are using packing, but the attention implementation is not set to a supported flash attention "
821
+ "variant. Packing gathers multiple samples into a single sequence, and only the following "
822
+ f"implementations are known to reliably support this: {', '.join(sorted(FLASH_ATTENTION_VARIANTS))}. "
823
+ "Using other implementations may lead to cross-contamination between samples. To avoid this, either "
824
+ "disable packing by setting `packing=False`, or set `attn_implementation` in the model configuration "
825
+ "to one of these supported options."
826
+ )
827
+ if args.assistant_only_loss and not is_conversational(dataset_sample):
828
+ raise ValueError(
829
+ "You set `assistant_only_loss=True`, but the dataset is not conversational. This option is only "
830
+ "supported for conversational datasets."
831
+ )
832
+
833
+ # Dataset
834
+ # Skip dataset preparation if `skip_prepare_dataset=True` in `dataset_kwargs`, or if it's a VLM, where
835
+ # preprocessing [e.g., image-to-pixel conversion] is too costly and done on the fly instead.
836
+ skip_prepare_dataset = (
837
+ args.dataset_kwargs is not None
838
+ and args.dataset_kwargs.get("skip_prepare_dataset", False)
839
+ or self._is_vision_dataset
840
+ )
841
+ if not skip_prepare_dataset:
842
+ if self.completion_only_loss and formatting_func:
843
+ raise ValueError(
844
+ "A formatting function was provided while `completion_only_loss=True`, which is incompatible. "
845
+ "Using a formatter converts the dataset to a language modeling type, conflicting with "
846
+ "completion-only loss. To resolve this, apply your formatting function before passing the "
847
+ "dataset, or disable `completion_only_loss` in `SFTConfig`."
848
+ )
849
+ train_dataset = self._prepare_dataset(
850
+ train_dataset, processing_class, args, args.packing, formatting_func, "train"
851
+ )
852
+ if eval_dataset is not None:
853
+ packing = args.packing if args.eval_packing is None else args.eval_packing
854
+ if isinstance(eval_dataset, dict):
855
+ eval_dataset = {
856
+ key: self._prepare_dataset(dataset, processing_class, args, packing, formatting_func, key)
857
+ for key, dataset in eval_dataset.items()
858
+ }
859
+ else:
860
+ eval_dataset = self._prepare_dataset(
861
+ eval_dataset, processing_class, args, packing, formatting_func, "eval"
862
+ )
863
+
864
+ # Loss function
865
+ if args.loss_type == "nll":
866
+ pass # use the default loss
867
+ elif args.loss_type == "dft":
868
+ if compute_loss_func is not None:
869
+ raise ValueError(
870
+ "You passed a `compute_loss_func` together with `loss_type='dft'` to the `SFTTrainer`. "
871
+ "When using `loss_type='dft'`, the loss function is internally set to the DFT loss, so passing a "
872
+ "`compute_loss_func` is not allowed."
873
+ )
874
+ compute_loss_func = dft_loss
875
+ else:
876
+ raise ValueError(f"Invalid `loss_type` {args.loss_type} passed. Supported values are 'nll' and 'dft'.")
877
+
878
+ # Initialize the metrics
879
+ self._metrics = {"train": defaultdict(list), "eval": defaultdict(list)}
880
+ self._total_train_tokens = 0
881
+
882
+ # Initialize the Trainer. Parent class will handle:
883
+ # - DeepSpeed configuration [through create_accelerator_and_postprocess]
884
+ # - FSDP setup
885
+ # - Distributed training setup
886
+ # - Optimizer and scheduler creation
887
+
888
+ super().__init__(
889
+ model=model,
890
+ args=args,
891
+ data_collator=data_collator,
892
+ train_dataset=train_dataset,
893
+ eval_dataset=eval_dataset,
894
+ processing_class=processing_class,
895
+ compute_loss_func=compute_loss_func,
896
+ compute_metrics=compute_metrics,
897
+ callbacks=callbacks,
898
+ optimizers=optimizers,
899
+ optimizer_cls_and_kwargs=optimizer_cls_and_kwargs,
900
+ preprocess_logits_for_metrics=preprocess_logits_for_metrics,
901
+ )
902
+
903
+ # Initialize activation offloading context
904
+ if self.args.activation_offloading:
905
+ self.maybe_activation_offload_context = get_act_offloading_ctx_manager(model=self.model)
906
+ else:
907
+ self.maybe_activation_offload_context = contextlib.nullcontext()
908
+
909
+ # Add tags for models that have been loaded with the correct transformers version
910
+ if hasattr(self.model, "add_model_tags"):
911
+ self.model.add_model_tags(self._tag_names)
912
+
913
+ self.aux_loss_enabled = getattr(model.config, "output_router_logits", False)
914
+
915
+ def _prepare_dataset(
916
+ self,
917
+ dataset: Union[Dataset, IterableDataset],
918
+ processing_class,
919
+ args,
920
+ packing: bool,
921
+ formatting_func: Optional[Callable[[dict], str]],
922
+ dataset_name: str,
923
+ ) -> Union[Dataset, IterableDataset]:
924
+ # All Unsloth Zoo code licensed under LGPLv3
925
+ try:
926
+ if isinstance(dataset, ConstantLengthDataset): return dataset
927
+ except:
928
+ pass
929
+
930
+ map_kwargs = {}
931
+ use_desc = isinstance(dataset, Dataset)
932
+ is_vlm = hasattr(processing_class, "tokenizer")
933
+ tokenizer = processing_class
934
+ if is_vlm: tokenizer = processing_class.tokenizer
935
+
936
+ # Get max length
937
+ max_seq_length = getattr(args, "max_length", 0)
938
+ if max_seq_length == 0: max_seq_length = getattr(args, "max_seq_length", 0)
939
+ if max_seq_length == 0: max_seq_length = getattr(self, "max_seq_length", 0)
940
+ if max_seq_length == 0: max_seq_length = getattr(self, "max_seq", 0)
941
+ if max_seq_length == 0: raise RuntimeError("Unsloth: max_seq_length is 0! Please specify one!")
942
+ dataset_text_field = getattr(args, "dataset_text_field", "text")
943
+ do_truncation = max_seq_length != 0
944
+ do_formatting_func = False
945
+ do_tokenize = True
946
+
947
+ # Get correct column names
948
+ column_names = set(next(iter(dataset)).keys())
949
+ used_column_names = ["input_ids"]
950
+ if "attention_mask" in column_names:
951
+ used_column_names.append("attention_mask")
952
+
953
+ # Check if already tokenized so skip
954
+ from transformers import DataCollatorForSeq2Seq, DataCollatorForLanguageModeling
955
+ if "labels" in column_names:
956
+ # Most likely forgot data collator!
957
+ if is_vlm and not hasattr(tokenizer, "pad"):
958
+ # Check if processing_class has a .pad, if not, use tokenizer.tokenizer
959
+ raise RuntimeError(f"Unsloth: {processing_class.__class__} does not have .pad!")
960
+ self.data_collator = DataCollatorForSeq2Seq(tokenizer)
961
+ used_column_names.append("labels")
962
+ do_tokenize = False
963
+ elif "input_ids" in column_names:
964
+ # Skip dataset prep, and set data collator
965
+ if is_vlm and not hasattr(tokenizer, "pad"):
966
+ # Check if processing_class has a .pad, if not, use tokenizer.tokenizer
967
+ raise RuntimeError(f"Unsloth: {processing_class.__class__} does not have .pad!")
968
+ self.data_collator = DataCollatorForLanguageModeling(tokenizer, mlm = False)
969
+ do_tokenize = False
970
+ elif dataset_text_field not in column_names:
971
+ do_formatting_func = True
972
+ if formatting_func is None:
973
+ raise RuntimeError("Unsloth: You must specify a `formatting_func`")
974
+ pass
975
+
976
+ if do_tokenize:
977
+ # Check double BOS tokens
978
+ if do_formatting_func:
979
+ test_text = formatting_func(next(iter(dataset)))
980
+ if not isinstance(test_text, list):
981
+ raise ValueError(
982
+ "Unsloth: The `formatting_func` should return a list of processed strings."
983
+ )
984
+ test_text = test_text[0]
985
+ else:
986
+ test_text = next(iter(dataset))[dataset_text_field][0]
987
+
988
+ # Get chat template
989
+ chat_template = getattr(processing_class, 'chat_template', '')
990
+ if chat_template == '' and is_vlm:
991
+ chat_template = getattr(tokenizer, 'chat_template', '')
992
+ if chat_template is None:
993
+ chat_template = ''
994
+
995
+ # Get bos_token
996
+ add_special_tokens = True
997
+ bos_token_1 = getattr(processing_class, 'bos_token', None)
998
+ bos_token_2 = getattr(tokenizer, 'bos_token', None)
999
+ bos_token = bos_token_1 or bos_token_2
1000
+
1001
+ if bos_token is not None:
1002
+ if test_text.startswith(bos_token) or bos_token in chat_template:
1003
+ add_special_tokens = False
1004
+ print("Unsloth: We found double BOS tokens - we shall remove one automatically.")
1005
+ pass
1006
+
1007
+ # Create tokenize function
1008
+ def _tokenize(example):
1009
+ return tokenizer(
1010
+ example[dataset_text_field] if not do_formatting_func else formatting_func(example),
1011
+ truncation = do_truncation,
1012
+ max_length = max_seq_length,
1013
+ return_token_type_ids = False,
1014
+ add_special_tokens = add_special_tokens,
1015
+ )
1016
+ pass
1017
+
1018
+ if not isinstance(dataset, IterableDataset):
1019
+ dataset_num_proc = getattr(args, "dataset_num_proc", None)
1020
+ if dataset_num_proc is None:
1021
+ from multiprocessing import cpu_count
1022
+ dataset_num_proc = max(cpu_count()+4, 2)
1023
+ map_kwargs["num_proc"] = dataset_num_proc
1024
+ else:
1025
+ map_kwargs["batch_size"] = dataset._ex_iterable.batch_size
1026
+
1027
+ if use_desc: map_kwargs["desc"] = f'Unsloth: Tokenizing ["{dataset_text_field}"]'
1028
+ dataset = dataset.map(_tokenize, batched = True, **map_kwargs)
1029
+
1030
+ # If VLM, switch data collator since .pad is needed!
1031
+ if is_vlm and not hasattr(processing_class, "pad"):
1032
+ data_collator = DataCollatorForLanguageModeling(tokenizer, mlm = False)
1033
+ self.data_collator = data_collator
1034
+ pass
1035
+ pass
1036
+ if packing:
1037
+ # Try using new packing which works in TRL
1038
+ try:
1039
+ pack_dataset
1040
+ except:
1041
+ print("Unsloth: Hugging Face's packing is currently buggy - we're disabling it for now!")
1042
+ return dataset
1043
+
1044
+ if max_seq_length == 0:
1045
+ raise ValueError("When packing is enabled, `max_seq_length` can't be `None`.")
1046
+
1047
+ if use_desc: map_kwargs["desc"] = f"Unsloth: Packing {dataset_name} dataset"
1048
+ dataset = pack_dataset(
1049
+ dataset.select_columns(used_column_names),
1050
+ max_seq_length,
1051
+ getattr(args, "packing_strategy", "bfd"),
1052
+ map_kwargs,
1053
+ )
1054
+ pass
1055
+ return dataset
1056
+
1057
+ def _set_signature_columns_if_needed(self):
1058
+ # If `self.args.remove_unused_columns` is True, non-signature columns are removed.
1059
+ # By default, this method sets `self._signature_columns` to the model's expected inputs (usually, "input_ids"
1060
+ # and "attention_mask"). When using `train_on_completion_only` we add a "completion_mask" column to the
1061
+ # dataset. So we need to override the default signature columns to include "completion_mask" as well.
1062
+ if self._signature_columns is None:
1063
+ if self._is_vision_dataset:
1064
+ self._signature_columns = ["messages", "prompt", "completion", "images"]
1065
+ else:
1066
+ self._signature_columns = ["input_ids", "labels", "seq_lengths", "completion_mask", "assistant_masks"]
1067
+
1068
+ def compute_loss(
1069
+ self, model, inputs, return_outputs = False, num_items_in_batch = None
1070
+ ):
1071
+ outputs = super().compute_loss(
1072
+ model,
1073
+ inputs,
1074
+ return_outputs = return_outputs,
1075
+ num_items_in_batch = num_items_in_batch,
1076
+ )
1077
+ return outputs
1078
+
1079
+ # Override training step to add activation offloading context.
1080
+ def training_step(self, *args, **kwargs):
1081
+ with self.maybe_activation_offload_context:
1082
+ return super().training_step(*args, **kwargs)
1083
+
1084
+ def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None:
1085
+ mode = "train" if self.model.training else "eval"
1086
+ metrics = {key: sum(val) / len(val) for key, val in self._metrics[mode].items()} # average the metrics
1087
+
1088
+ # This method can be called both in training and evaluation. When called in evaluation, the keys in `logs`
1089
+ # start with "eval_". We need to add the prefix "eval_" to the keys in `metrics` to match the format.
1090
+ if mode == "eval":
1091
+ metrics = {f"eval_{key}": val for key, val in metrics.items()}
1092
+
1093
+ logs.update(metrics)
1094
+ super().log(logs, start_time)
1095
+ self._metrics[mode].clear()
1096
+
1097
+ # Ensure the model card is saved along with the checkpoint
1098
+ def _save_checkpoint(self, model, trial):
1099
+ if self.args.hub_model_id is None:
1100
+ model_name = Path(self.args.output_dir).name
1101
+ else:
1102
+ model_name = self.args.hub_model_id.split("/")[-1]
1103
+ self.create_model_card(model_name=model_name)
1104
+ super()._save_checkpoint(model, trial)
1105
+ class UnslothSFTTrainer(_UnslothSFTTrainer):
1106
+ """
1107
+
1108
+ Trainer for Supervised Fine-Tuning (SFT) method.
1109
+
1110
+ This class is a wrapper around the [`~transformers.Trainer`] class and inherits all of its attributes and methods.
1111
+
1112
+ Example:
1113
+
1114
+ ```python
1115
+ from datasets import load_dataset
1116
+ from trl import SFTTrainer
1117
+
1118
+ dataset = load_dataset("roneneldan/TinyStories", split="train[:1%]")
1119
+
1120
+ trainer = SFTTrainer(model="Qwen/Qwen2-0.5B-Instruct", train_dataset=dataset)
1121
+ trainer.train()
1122
+ ```
1123
+
1124
+ Args:
1125
+ model (`Union[str, PreTrainedModel]`):
1126
+ Model to be trained. Can be either:
1127
+
1128
+ - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a
1129
+ path to a *directory* containing model weights saved using
1130
+ [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded
1131
+ using `<ModelArchitecture>.from_pretrained` (where `<ModelArchitecture>` is derived from the model
1132
+ config) with the keyword arguments in `args.model_init_kwargs`.
1133
+ - A [`~transformers.PreTrainedModel`] object.
1134
+ If you're training a model with an MoE architecture and want to include the load balancing/auxilliary loss
1135
+ as a part of the final loss, remember to set the `output_router_logits` config of the model to `True`.
1136
+ args ([`SFTConfig`], *optional*):
1137
+ Configuration for this trainer. If `None`, a default configuration is used.
1138
+ data_collator ([`~transformers.DataCollator`], *optional*):
1139
+ Function to use to form a batch from a list of elements of the processed `train_dataset` or `eval_dataset`.
1140
+ Will default to [`~trainer.sft_trainer.DataCollatorForLanguageModeling`] if the model is a language model
1141
+ and [`~trainer.sft_trainer.DataCollatorForVisionLanguageModeling`] if the model is a vision-language model.
1142
+ train_dataset ([`~datasets.Dataset`] or [`~datasets.IterableDataset`]):
1143
+ Dataset to use for training. SFT supports both [language modeling](#language-modeling) type and
1144
+ [prompt-completion](#prompt-completion) type. The format of the samples can be either:
1145
+
1146
+ - [Standard](dataset_formats#standard): Each sample contains plain text.
1147
+ - [Conversational](dataset_formats#conversational): Each sample contains structured messages (e.g., role
1148
+ and content).
1149
+
1150
+ The trainer also supports processed datasets (tokenized) as long as they contain an `input_ids` field.
1151
+ eval_dataset ([`~datasets.Dataset`], [`~datasets.IterableDataset`] or `dict[str, Union[Dataset, IterableDataset]]`):
1152
+ Dataset to use for evaluation. It must meet the same requirements as `train_dataset`.
1153
+ processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.ProcessorMixin`], *optional*):
1154
+ Processing class used to process the data. If `None`, the processing class is loaded from the model's name
1155
+ with [`~transformers.AutoProcessor.from_pretrained`]. A padding token, `tokenizer.pad_token`, must be set.
1156
+ If the processing class has not set a padding token, `tokenizer.eos_token` will be used as the default.
1157
+ compute_loss_func (`Callable`, *optional*):
1158
+ A function that accepts the raw model outputs, labels, and the number of items in the entire accumulated
1159
+ batch (batch_size * gradient_accumulation_steps) and returns the loss. For example, see the default [loss
1160
+ function](https://github.com/huggingface/transformers/blob/052e652d6d53c2b26ffde87e039b723949a53493/src/transformers/trainer.py#L3618)
1161
+ used by [`Trainer`].
1162
+ compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*):
1163
+ The function that will be used to compute metrics at evaluation. Must take a
1164
+ [`~transformers.EvalPrediction`] and return a dictionary string to metric values. When passing
1165
+ [`SFTConfig`] with `batch_eval_metrics` set to `True`, your `compute_metrics` function must take a boolean
1166
+ `compute_result` argument. This will be triggered after the last eval batch to signal that the function
1167
+ needs to calculate and return the global summary statistics rather than accumulating the batch-level
1168
+ statistics.
1169
+ callbacks (list of [`~transformers.TrainerCallback`], *optional*):
1170
+ List of callbacks to customize the training loop. Will add those to the list of default callbacks detailed
1171
+ in [here](https://huggingface.co/docs/transformers/main_classes/callback).
1172
+
1173
+ If you want to remove one of the default callbacks used, use the [`~transformers.Trainer.remove_callback`]
1174
+ method.
1175
+ optimizers (`tuple[Optional[torch.optim.Optimizer], Optional[torch.optim.lr_scheduler.LambdaLR]]`, *optional*, defaults to `(None, None)`):
1176
+ A tuple containing the optimizer and the scheduler to use. Will default to an instance of `AdamW` on your
1177
+ model and a scheduler given by [`~transformers.get_linear_schedule_with_warmup`] controlled by `args`.
1178
+ optimizer_cls_and_kwargs (`tuple[Type[torch.optim.Optimizer], Dict[str, Any]]`, *optional*):
1179
+ A tuple containing the optimizer class and keyword arguments to use. Overrides `optim` and `optim_args` in
1180
+ `args`. Incompatible with the `optimizers` argument.
1181
+
1182
+ Unlike `optimizers`, this argument avoids the need to place model parameters on the correct devices before
1183
+ initializing the Trainer.
1184
+ preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *optional*):
1185
+ A function that preprocess the logits right before caching them at each evaluation step. Must take two
1186
+ tensors, the logits and the labels, and return the logits once processed as desired. The modifications made
1187
+ by this function will be reflected in the predictions received by `compute_metrics`.
1188
+
1189
+ Note that the labels (second parameter) will be `None` if the dataset does not have them.
1190
+ peft_config ([`~peft.PeftConfig`], *optional*):
1191
+ PEFT configuration used to wrap the model. If `None`, the model is not wrapped.
1192
+ formatting_func (`Callable`, *optional*):
1193
+ Formatting function applied to the dataset before tokenization. Applying the formatting function explicitly
1194
+ converts the dataset into a [language modeling](#language-modeling) type.
1195
+
1196
+ """
1197
+ def __init__(
1198
+ self,
1199
+ model,
1200
+ args = None,
1201
+ data_collator = None,
1202
+ train_dataset = None,
1203
+ eval_dataset = None,
1204
+ processing_class = None,
1205
+ compute_loss_func = None,
1206
+ compute_metrics = None,
1207
+ callbacks = None,
1208
+ optimizer_cls_and_kwargs = None,
1209
+ preprocess_logits_for_metrics = None,
1210
+ peft_config = None,
1211
+ formatting_func = None,
1212
+ **kwargs
1213
+ ):
1214
+ if args is None: args = UnslothSFTConfig()
1215
+ use_bf16 = getattr(args, 'bf16', False)
1216
+ if type(use_bf16) is not bool: use_bf16 = False
1217
+ use_fp16 = getattr(args, 'fp16', False)
1218
+ if type(use_fp16) is not bool: use_fp16 = False
1219
+ force_float32 = False
1220
+ full_finetuning = os.environ.get('UNSLOTH_ENABLE_FULL_FINETUNING', '0') == '1'
1221
+ if not full_finetuning and (os.environ.get('UNSLOTH_FORCE_FLOAT32', '0') == '1'):
1222
+ print('Unsloth: Switching to float32 training since model cannot work with float16')
1223
+ force_float32 = True
1224
+ mixed_precision_dtype = os.environ.get('UNSLOTH_MIXED_PRECISION', 'float32')
1225
+ dtype = getattr(model.config, 'dtype', None) or getattr(model.config, 'torch_dtype', None)
1226
+ if dtype is None: dtype = model.get_input_embeddings().weight.dtype
1227
+ from unsloth_zoo.utils import _get_dtype
1228
+ dtype = _get_dtype(dtype)
1229
+ float16 = dtype == torch.float16
1230
+ 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`')
1231
+ 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`')
1232
+ if force_float32:
1233
+ # Forced float32 training
1234
+ args.fp16 = False
1235
+ args.bf16 = False
1236
+ os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'
1237
+ if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'
1238
+ # args.mixed_precision is a new argument which needs to be set now
1239
+ elif (not use_bf16 and not use_fp16) and mixed_precision_dtype == 'float32':
1240
+ # Mixed precision training
1241
+ args.fp16 = float16
1242
+ args.bf16 = not float16
1243
+ os.environ['ACCELERATE_MIXED_PRECISION'] = 'fp16' if float16 else 'bf16'
1244
+ if hasattr(args, 'mixed_precision'): args.mixed_precision = 'fp16' if float16 else 'bf16'
1245
+ # args.mixed_precision is a new argument which needs to be set now
1246
+ elif mixed_precision_dtype == 'bfloat16':
1247
+ # Both False since bfloat16 full finetuning doesn't do any autocasting.
1248
+ args.fp16 = False
1249
+ args.bf16 = False
1250
+ os.environ['ACCELERATE_MIXED_PRECISION'] = 'no'
1251
+ if hasattr(args, 'mixed_precision'): args.mixed_precision = 'no'
1252
+ # args.mixed_precision is a new argument which needs to be set now
1253
+
1254
+ if getattr(args, 'eval_dataset', None) is not None and getattr(args, 'eval_strategy', 'no') == 'no':
1255
+ args.eval_strategy = 'steps'
1256
+ if getattr(args, 'eval_steps', None) is None: args.eval_steps = 0.1
1257
+ ga_steps = getattr(args, 'gradient_accumulation_steps', None)
1258
+ if ga_steps is not None and ga_steps > 1:
1259
+ from transformers import __version__ as transformers_version
1260
+ if Version(transformers_version) <= Version('4.45.2'):
1261
+ print('**** Unsloth: Please use our fixed gradient_accumulation_steps by updating transformers, TRL and Unsloth!\n'
1262
+ '`pip install --upgrade --no-cache-dir --force-reinstall --no-deps unsloth transformers trl unsloth_zoo`')
1263
+ if getattr(args, 'eval_strategy', 'no') != 'no':
1264
+ eval_bsz = getattr(args, 'per_device_eval_batch_size', 8)
1265
+ 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
1266
+ if getattr(args, 'eval_accumulation_steps', None) is None and ga_steps is not None: args.eval_accumulation_steps = ga_steps
1267
+ fp16_full_eval = getattr(args, 'fp16_full_eval', False)
1268
+ if type(fp16_full_eval) is not bool: fp16_full_eval = False
1269
+ bf16_full_eval = getattr(args, 'bf16_full_eval', False)
1270
+ if type(bf16_full_eval) is not bool: bf16_full_eval = False
1271
+ if args.fp16 and bf16_full_eval: args.bf16_full_eval = False; args.fp16_full_eval = True
1272
+ if args.bf16 and fp16_full_eval: args.bf16_full_eval = True; args.fp16_full_eval = False
1273
+ if force_float32:
1274
+ args.bf16_full_eval = False
1275
+ args.fp16_full_eval = False
1276
+ elif os.environ.get('UNSLOTH_MIXED_PRECISION', 'float32') == 'bfloat16':
1277
+ args.bf16_full_eval = True
1278
+ args.fp16_full_eval = False
1279
+ elif not bf16_full_eval and not fp16_full_eval:
1280
+ args.bf16_full_eval = args.bf16
1281
+ args.fp16_full_eval = args.fp16
1282
+ _output_logits = False
1283
+ if locals().get('compute_metrics', None) is not None: _output_logits = True
1284
+ if locals().get('preprocess_logits_for_metrics', None) is not None: _output_logits = True
1285
+ if _output_logits:
1286
+ os.environ['UNSLOTH_RETURN_LOGITS'] = '1'
1287
+ if 'max_seq_length' not in locals() and not hasattr(args, 'max_seq_length'):
1288
+ pass
1289
+ else:
1290
+ model_max_seq_length = getattr(model, 'max_seq_length', None)
1291
+ args_max_seq_length = getattr(args, 'max_seq_length', None)
1292
+ if args_max_seq_length is None and model_max_seq_length is not None:
1293
+ max_seq_length = model.max_seq_length
1294
+ if hasattr(args, 'max_seq_length'): args.max_seq_length = max_seq_length
1295
+ if 'max_length' not in locals() and not hasattr(args, 'max_length'):
1296
+ pass
1297
+ else:
1298
+ if hasattr(args, 'max_seq_length') and args.max_seq_length is not None and args.max_seq_length > 0:
1299
+ if hasattr(args, 'max_length'):
1300
+ args.max_length = args.max_seq_length
1301
+ max_length = args.max_length
1302
+ else:
1303
+ model_max_length = getattr(model, 'max_seq_length', None)
1304
+ if model_max_length is None: model_max_length = getattr(model, 'max_length', None)
1305
+ if model_max_length is not None:
1306
+ args.max_length = model_max_length
1307
+ max_length = args.max_length
1308
+ elif hasattr(args, 'max_length') and args.max_length is not None:
1309
+ max_length = args.max_length
1310
+ # if we are here, then we are in a weird case where max_length is set but max_seq_length is not set
1311
+ setattr(model, 'max_seq_length', max_length)
1312
+ else:
1313
+ print('Unsloth: We did not find `max_seq_length` or `max_length` in the model or args. We will set it to 1024.')
1314
+ args.max_length = 1024
1315
+ if model is not None and hasattr(model, 'for_training'):
1316
+ model.for_training(use_gradient_checkpointing=getattr(args, 'gradient_checkpointing', True))
1317
+ if 'tokenizer' in locals() and hasattr(tokenizer, 'padding_side'): tokenizer.padding_side = 'right'
1318
+ if 'processing_class' in locals():
1319
+ if hasattr(processing_class, 'padding_side'): processing_class.padding_side = 'right'
1320
+ if hasattr(processing_class, 'tokenizer') and hasattr(processing_class.tokenizer, 'padding_side'): processing_class.tokenizer.padding_side = 'right'
1321
+ __tokenizer = processing_class if 'processing_class' in locals() else tokenizer
1322
+ from unsloth_zoo.vision_utils import UnslothVisionDataCollator
1323
+ if not isinstance(data_collator, UnslothVisionDataCollator):
1324
+ if isinstance(data_collator, DataCollatorForSeq2Seq) and 'labels' not in train_dataset.column_names:
1325
+ data_collator = TransformersDataCollatorForLanguageModeling(
1326
+ __tokenizer,
1327
+ mlm = False,
1328
+ mlm_probability = 0.0,
1329
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
1330
+ )
1331
+ elif isinstance(data_collator, TransformersDataCollatorForLanguageModeling) and 'labels' in train_dataset.column_names:
1332
+ data_collator = DataCollatorForSeq2Seq(
1333
+ __tokenizer,
1334
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
1335
+ )
1336
+ else:
1337
+ if hasattr(args, 'remove_unused_columns'): args.remove_unused_columns = False
1338
+ if hasattr(args, 'dataset_text_field'): args.dataset_text_field = ''
1339
+ if hasattr(args, 'dataset_kwargs'): args.dataset_kwargs = {'skip_prepare_dataset': True}
1340
+ if not isinstance(data_collator, UnslothVisionDataCollator):
1341
+ if not hasattr(__tokenizer, 'pad') and hasattr(__tokenizer, 'tokenizer'):
1342
+ if isinstance(data_collator, DataCollatorForSeq2Seq):
1343
+ data_collator = DataCollatorForSeq2Seq(
1344
+ __tokenizer.tokenizer,
1345
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
1346
+ )
1347
+ else:
1348
+ data_collator = TransformersDataCollatorForLanguageModeling(
1349
+ __tokenizer.tokenizer,
1350
+ mlm = False,
1351
+ mlm_probability = 0.0,
1352
+ pad_to_multiple_of = getattr(args, 'pad_to_multiple_of', None),
1353
+ )
1354
+ other_metrics = []
1355
+
1356
+ from unsloth_zoo.logging_utils import PatchRLStatistics
1357
+ PatchRLStatistics('sft_trainer', other_metrics)
1358
+ IGNORED_TOKENIZER_NAMES = os.environ.get('UNSLOTH_IGNORED_TOKENIZER_NAMES', '').split('\n')
1359
+ from unsloth_zoo.tokenizer_utils import fix_untrained_tokens
1360
+ from unsloth_zoo.training_utils import fix_zero_training_loss
1361
+ if 'tokenizer' not in locals(): tokenizer = processing_class
1362
+ fix_untrained_tokens(model, tokenizer, train_dataset, IGNORED_TOKENIZER_NAMES, eps = 1e-16)
1363
+ fix_zero_training_loss(model, tokenizer, train_dataset)
1364
+
1365
+ # [TODO] Fix up DataParallel multiplying batch sizes
1366
+ # [TODO] DDP works, but DP seems to not work? [TODO]
1367
+ if getattr(args, "parallel_mode", None) == ParallelMode.NOT_DISTRIBUTED and args.n_gpu > 1:
1368
+ if getattr(args, "_n_gpu", 1) != 1:
1369
+ args._n_gpu = 1
1370
+ if "model" in locals() and hasattr(model, "for_training"):
1371
+ model.for_training(use_gradient_checkpointing=getattr(args, 'gradient_checkpointing', True))
1372
+ super().__init__(
1373
+ model = model,
1374
+ args = args,
1375
+ data_collator = data_collator,
1376
+ train_dataset = train_dataset,
1377
+ eval_dataset = eval_dataset,
1378
+ processing_class = processing_class,
1379
+ compute_loss_func = compute_loss_func,
1380
+ compute_metrics = compute_metrics,
1381
+ callbacks = callbacks,
1382
+ optimizer_cls_and_kwargs = optimizer_cls_and_kwargs,
1383
+ preprocess_logits_for_metrics = preprocess_logits_for_metrics,
1384
+ peft_config = peft_config,
1385
+ formatting_func = formatting_func,**kwargs)
1386
+ if "model" in locals() and hasattr(model, "for_inference"):
1387
+ model.for_inference()
1388
+ if hasattr(self, 'neftune_hook_handle'):
1389
+ self.neftune_hook_handle.remove()
1390
+ if hasattr(self, 'neftune_hook_handle'): del self.neftune_hook_handle
1391
+ if getattr(args, 'neftune_noise_alpha', None) is not None:
1392
+ model.get_input_embeddings().neftune_noise_alpha = self.neftune_noise_alpha
1393
+ pass
1394
+ if hasattr(self, 'accelerator'):
1395
+ scaler = self.accelerator.scaler
1396
+ current_model = model
1397
+ while hasattr(current_model, 'model'):
1398
+ current_model.accelerator_scaler = scaler
1399
+ current_model = current_model.model
1400
+ current_model.accelerator_scaler = scaler
1401
+ pass
1402
+ if hasattr(self, 'train'):
1403
+ self.train = MethodType(prepare_for_training_mode(self.__class__.train), self)
1404
+ pass
1405
+
1406
+ pass
1407
+
1408
+
1409
+ if hasattr(logger, "addFilter"):
1410
+ import logging
1411
+ class HideLoggingMessage(logging.Filter):
1412
+ def __init__(self, text): self.text = text
1413
+ def filter(self, x): return not (self.text in x.getMessage())
1414
+ pass
1415
+ logger.addFilter(HideLoggingMessage("`use_cache=True`"))
1416
+