-
Notifications
You must be signed in to change notification settings - Fork 3
/
trainer.py
2062 lines (1791 loc) Β· 97.2 KB
/
trainer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# DPO Authors: Rafael Rafailov, Archit Sharma, Eric Mitchell, Stefano Ermon, Christopher D. Manning, and Chelsea Finn 2023
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import inspect
import os
import random
import textwrap
import warnings
from collections import defaultdict
from contextlib import contextmanager, nullcontext
from copy import deepcopy
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union
import numpy as np
np.random.seed(0)
import torch
torch.manual_seed(41)
import torch.amp as amp
import torch.nn as nn
import torch.nn.functional as F
from accelerate import PartialState
from accelerate.utils import is_deepspeed_available, tqdm
from datasets import Dataset
from huggingface_hub.utils._deprecation import _deprecate_arguments
from torch.utils.data import DataLoader
from transformers import (
AutoModelForCausalLM,
LlamaConfig,
MistralConfig,
AutoConfig,
BaseImageProcessor,
DataCollator,
FeatureExtractionMixin,
PreTrainedModel,
PreTrainedTokenizerBase,
ProcessorMixin,
Trainer,
is_wandb_available,
)
from transformers.models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES
from transformers.trainer_callback import TrainerCallback
from transformers.trainer_utils import EvalLoopOutput
from transformers.utils import is_peft_available
from transformers.utils.deprecation import deprecate_kwarg
from trl.models.modeling_base import PreTrainedModelWrapper, create_reference_model
from trl.trainer.callbacks import SyncRefModelCallback
from trl.trainer.utils import (
DPODataCollatorWithPadding,
RunningMoments,
add_bos_token_if_needed,
add_eos_token_if_needed,
cap_exp,
disable_dropout_in_model,
generate_model_card,
pad_to_length,
peft_module_casting_to_bf16,
)
from trl.data_utils import maybe_extract_prompt
from data.utils import maybe_apply_chat_template
from data.collators import DPOPrefixSharingPackedDataCollatorWithPadding, DPOPrefixSharingDataCollatorWithPadding
from modeling.dpo_flex_attn_masks import construct_dpo_mask, construct_dpo_mask_with_packing
from benchmark.utils import CudaTimer
from config import DPOConfig, FDivergenceConstants, FDivergenceType
from modeling.llama_patches import LlamaForCausalLMFlexAttn
from modeling.mistral_patches import MistralForCausalLMFlexAttn
from data.packing import MultipackBatchSampler
from data.patch_datasets import patch_torch_to_work_with_hf
from torch.utils.data import RandomSampler
if is_peft_available():
from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training
if is_wandb_available():
import wandb
if is_deepspeed_available():
import deepspeed
def _maybe_process_batch_for_prefix_sharing(batch, indexes: List[int], chosen_tokens, rejected_tokens, args):
if args.prefix_sharing:
for k in ['input_ids', 'attention_mask']:
batch[k] = [chosen_tokens[i][f"prompt_{k}"] + chosen_tokens[i][k] + chosen_tokens[i][f"prompt_{k}"][-1:] + rejected_tokens[i][k] for i in range(len(chosen_tokens))]
prompt_lens = [len(chosen_row["prompt_input_ids"]) for chosen_row in chosen_tokens]
chosen_lens = [len(chosen_row["input_ids"]) for chosen_row in chosen_tokens]
rejected_lens = [len(rejected_row["input_ids"]) for rejected_row in rejected_tokens]
batch["labels"] = [ [] for _ in chosen_tokens]
for i, chosen_row in enumerate(chosen_tokens):
batch["labels"][i] = [args.label_pad_token_id] * prompt_lens[i] + chosen_row["input_ids"] + [args.label_pad_token_id] + rejected_tokens[i]["input_ids"]
batch["length"] = [len(tokens) for tokens in batch["input_ids"]]
batch["position_ids"] = [list(range(prompt_len + chosen_len)) + list(range(prompt_len - 1, prompt_len + rejected_len)) for prompt_len, chosen_len, rejected_len in zip(prompt_lens, chosen_lens, rejected_lens)]
if args.enable_packing:
batch["sequence_id"] = [[idx for _ in range(length)] for idx, length in zip(indexes, batch["length"]) ]
batch["chosen_index"] = [[prompt_len - 1 for _ in range(length)] for prompt_len, length in zip(prompt_lens, batch["length"])]
batch["rejected_index"] = [[prompt_len + chosen_len for _ in range(length)] for prompt_len, chosen_len, length in zip(prompt_lens, chosen_lens, batch["length"])]
batch["end_index"] =[[prompt_len + chosen_len + rejected_len + 1 for _ in range(length)] for prompt_len, chosen_len, rejected_len, length in zip(prompt_lens, chosen_lens, rejected_lens, batch["length"])]
else:
batch["chosen_index"] = [prompt_len - 1 for prompt_len in prompt_lens]
batch["rejected_index"] = [prompt_len + chosen_len for prompt_len, chosen_len in zip(prompt_lens, chosen_lens)]
batch["end_index"] = [prompt_len + chosen_len + rejected_len + 1 for prompt_len, chosen_len, rejected_len in zip(prompt_lens, chosen_lens, rejected_lens)]
return batch
def _tokenize(
features: Dict[str, List],
indexes: List[int],
tokenizer: PreTrainedTokenizerBase,
args: DPOConfig,
processor: Optional[Callable] = None,
model: Optional[PreTrainedModel] = None,
) -> Dict[str, List]:
"""
Tokenizes and processes a batch of input features using the provided tokenizer and processor.
"""
batch = defaultdict(list)
if model is None:
prompt = features["prompt"]
images = features.get("images", [None] * len(features["prompt"]))
prompt_tokens = _process_prompt(prompt, processor, tokenizer, images)
chosen_tokens = _process_answer(prompt, features["chosen"], processor, tokenizer, images)
rejected_tokens = _process_answer(prompt, features["rejected"], processor, tokenizer, images)
prompt_len_input_ids = _adjust_prompt_length(prompt_tokens, chosen_tokens, rejected_tokens)
prompt_tokens, chosen_tokens, rejected_tokens = _add_special_tokens(
tokenizer, prompt_len_input_ids, prompt_tokens, chosen_tokens, rejected_tokens
)
_truncate_tokens(chosen_tokens, rejected_tokens, prompt_tokens, args)
_build_sequence_tokens(batch, chosen_tokens, args, "chosen")
_build_sequence_tokens(batch, rejected_tokens, args, "rejected")
_append_prompt_tokens_to_batch(batch, prompt_tokens)
_maybe_process_batch_for_prefix_sharing(batch, indexes, chosen_tokens, rejected_tokens, args)
else:
_tokenize_encoder_decoder(batch, tokenizer, features["prompt"], features["chosen"], features["rejected"], args)
return dict(batch)
def _process_prompt(
prompts: List[str], processor: Optional[Callable], tokenizer: PreTrainedTokenizerBase, images: List[Optional[Any]]
) -> List[Dict[str, List[int]]]:
"""
Processes a list of prompts by tokenizing them, optionally using a processor for additional processing.
"""
if processor:
processor_kwargs = (
{"add_special_tokens": False} if "add_special_tokens" in inspect.signature(processor).parameters else {}
)
prompt_tokens = []
for prompt, image in zip(prompts, images):
tokens = processor(images=image, text=prompt, **processor_kwargs)
tokens = {k: v[0] for k, v in tokens.items()}
if not isinstance(tokens["input_ids"], list):
tokens["input_ids"] = tokens["input_ids"].tolist()
tokens["attention_mask"] = tokens["attention_mask"].tolist()
prompt_tokens.append(tokens)
else:
prompt_tokens = [tokenizer(prompt, add_special_tokens=False) for prompt in prompts]
return [{f"prompt_{k}": v for k, v in tokens.items()} for tokens in prompt_tokens]
def _process_answer(
prompts: List[str],
answers: List[str],
processor: Optional[Callable],
tokenizer: PreTrainedTokenizerBase,
images: List[Optional[Any]],
) -> List[Dict[str, Any]]:
return [
_build_tokenized_answer(prompt, answer, image, processor=processor, tokenizer=tokenizer)
for prompt, answer, image in zip(prompts, answers, images)
]
def _adjust_prompt_length(
prompt_tokens: List[Dict[str, List[int]]],
chosen_tokens: List[Dict[str, List[int]]],
rejected_tokens: List[Dict[str, List[int]]],
) -> List[int]:
prompt_len_input_ids = []
for p_tokens, c_tokens, r_tokens in zip(prompt_tokens, chosen_tokens, rejected_tokens):
c_len = len(c_tokens["prompt_input_ids"])
r_len = len(r_tokens["prompt_input_ids"])
min_len = min(c_len, r_len)
for k, v in p_tokens.items():
p_tokens[k] = v[:min_len]
num_diff_tokens = sum([a != b for a, b in zip(c_tokens["prompt_input_ids"], r_tokens["prompt_input_ids"])])
num_diff_len = abs(c_len - r_len)
if num_diff_tokens > 1 or num_diff_len > 1:
raise ValueError(
"Chosen and rejected prompt_input_ids might only differ on the last token due to tokenizer merge ops."
)
prompt_len_input_ids.append(min_len)
return prompt_len_input_ids
def _add_special_tokens(
tokenizer: PreTrainedTokenizerBase,
prompt_len_input_ids: List[int],
prompt_tokens: List[Dict[str, List[int]]],
chosen_tokens: List[Dict[str, List[int]]],
rejected_tokens: List[Dict[str, List[int]]],
) -> Tuple[List[Dict[str, List[int]]], List[Dict[str, List[int]]], List[Dict[str, List[int]]]]:
for i in range(len(prompt_tokens)):
prompt_tokens[i], chosen_tokens[i], rejected_tokens[i] = add_bos_token_if_needed(
tokenizer.bos_token_id,
prompt_len_input_ids[i],
prompt_tokens[i],
len(chosen_tokens[i]["prompt_input_ids"]),
chosen_tokens[i],
len(rejected_tokens[i]["prompt_input_ids"]),
rejected_tokens[i],
)
chosen_tokens[i], rejected_tokens[i] = add_eos_token_if_needed(
tokenizer.eos_token_id, chosen_tokens[i], rejected_tokens[i]
)
return prompt_tokens, chosen_tokens, rejected_tokens
def _truncate_tokens(
chosen_tokens: List[Dict[str, List[int]]],
rejected_tokens: List[Dict[str, List[int]]],
prompt_tokens: List[Dict[str, List[int]]],
args: DPOConfig,
) -> None:
"""
Truncates the tokens in chosen, rejected, and prompt sequences to ensure they fit within the maximum length constraints.
"""
if args.truncation_mode not in ["keep_start", "keep_end"]:
raise ValueError(f"Invalid truncation mode: {args.truncation_mode}")
for c_tokens, r_tokens, p_tokens in zip(chosen_tokens, rejected_tokens, prompt_tokens):
longer_response_length = max(len(c_tokens["input_ids"]), len(r_tokens["input_ids"]))
# if combined sequence is too long, truncate the prompt
for answer_tokens in [c_tokens, r_tokens, p_tokens]:
if len(answer_tokens["prompt_input_ids"]) + longer_response_length > args.max_length:
if args.truncation_mode == "keep_start":
for k in ["prompt_input_ids", "prompt_attention_mask"]:
answer_tokens[k] = answer_tokens[k][: args.max_prompt_length]
elif args.truncation_mode == "keep_end":
for k in ["prompt_input_ids", "prompt_attention_mask"]:
answer_tokens[k] = answer_tokens[k][-args.max_prompt_length :]
# if that's still too long, truncate the response from the end
for answer_tokens in [c_tokens, r_tokens]:
if len(answer_tokens["prompt_input_ids"]) + longer_response_length > args.max_length:
for k in ["input_ids", "attention_mask"]:
answer_tokens[k] = answer_tokens[k][: args.max_length - args.max_prompt_length]
def _build_sequence_tokens(
batch: Dict[str, List[int]], tokens: List[Dict[str, List[int]]], args: DPOConfig, prefix: str
) -> None:
for token in tokens:
sequence_tokens = {f"{prefix}_{k}": token[f"prompt_{k}"] + token[k] for k in ["input_ids", "attention_mask"]}
sequence_tokens[f"{prefix}_labels"] = sequence_tokens[f"{prefix}_input_ids"][:]
sequence_tokens[f"{prefix}_labels"][: len(token["prompt_input_ids"])] = [args.label_pad_token_id] * len(
token["prompt_input_ids"]
)
for k, v in sequence_tokens.items():
batch[k].append(v)
def _append_prompt_tokens_to_batch(batch: Dict[str, List[int]], prompt_tokens: List[Dict[str, List[int]]]) -> None:
for p_tokens in prompt_tokens:
for k, v in p_tokens.items():
batch[k].append(v)
def _tokenize_encoder_decoder(
batch: Dict[str, List[int]],
tokenizer: PreTrainedTokenizerBase,
prompt: List[str],
chosen: List[str],
rejected: List[str],
args: DPOConfig,
) -> None:
chosen_tokens = tokenizer(chosen, truncation=True, max_length=args.max_completion_length, add_special_tokens=True)
rejected_tokens = tokenizer(
rejected, truncation=True, max_length=args.max_completion_length, add_special_tokens=True
)
prompt_tokens = tokenizer(prompt, truncation=True, max_length=args.max_prompt_length, add_special_tokens=True)
batch["chosen_labels"] = chosen_tokens["input_ids"]
batch["rejected_labels"] = rejected_tokens["input_ids"]
batch["prompt_input_ids"] = prompt_tokens["input_ids"]
batch["prompt_attention_mask"] = prompt_tokens["attention_mask"]
def _build_tokenized_answer(
prompt: str,
answer: str,
images: Optional[List[Any]] = None,
processor: Optional[Callable] = None,
tokenizer: Optional[PreTrainedTokenizerBase] = None,
) -> Dict[str, Any]:
"""
Build tokenized response, handling vision models and different tokenizers.
"""
def tokenize(text, images=None):
if processor:
processor_kwargs = (
{"add_special_tokens": False}
if "add_special_tokens" in inspect.signature(processor).parameters
else {}
)
tokenized = processor(images=images, text=text, **processor_kwargs)
tokenized = {k: v[0] for k, v in tokenized.items()}
if not isinstance(tokenized["input_ids"], list):
tokenized["input_ids"] = tokenized["input_ids"].tolist()
tokenized["attention_mask"] = tokenized["attention_mask"].tolist()
else:
tokenized = tokenizer(text, add_special_tokens=False)
return tokenized
full_tokenized = tokenize(prompt + answer, images)
prompt_tokenized = tokenize(prompt, images)
prompt_input_ids = prompt_tokenized["input_ids"]
answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :]
answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :]
if len(full_tokenized["input_ids"]) != len(prompt_input_ids + answer_input_ids):
raise ValueError("Prompt input ids and answer input ids should have the same length.")
# On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens
# can be merged together when tokenizing prompt+answer. This could result
# on the last token from the prompt being different when tokenized on its own
# vs when done as prompt+answer.
response_token_ids_start_idx = len(prompt_input_ids)
# If tokenized prompt is different than both prompt+answer, then it means the
# last token has changed due to merging.
if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]:
response_token_ids_start_idx -= 1
prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx]
prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx]
if len(prompt_input_ids) != len(prompt_attention_mask):
raise ValueError("Prompt input ids and attention mask should have the same length.")
return_dict = {
"prompt_input_ids": prompt_input_ids,
"prompt_attention_mask": prompt_attention_mask,
"input_ids": answer_input_ids,
"attention_mask": answer_attention_mask,
}
if "pixel_values" in full_tokenized:
return_dict["prompt_pixel_values"] = full_tokenized["pixel_values"]
if "pixel_attention_mask" in full_tokenized:
return_dict["prompt_pixel_attention_mask"] = full_tokenized["pixel_attention_mask"]
return return_dict
class DPOTrainer(Trainer):
r"""
Initialize DPOTrainer.
Args:
model (`transformers.PreTrainedModel`):
The model to train, preferably an `AutoModelForSequenceClassification`.
ref_model (`PreTrainedModelWrapper`):
Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no
reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized.
args (`DPOConfig`):
The DPO config arguments to use for training.
data_collator (`transformers.DataCollator`):
The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used
which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences.
train_dataset (`datasets.Dataset`):
The dataset to use for training.
eval_dataset (`datasets.Dataset`):
The dataset to use for evaluation.
processing_class (`PreTrainedTokenizerBase` or `BaseImageProcessor` or `FeatureExtractionMixin` or `ProcessorMixin`, *optional*):
Processing class used to process the data. If provided, will be used to automatically process the inputs
for the model, and it will be saved along the model to make it easier to rerun an interrupted training or
reuse the fine-tuned model.
This supercedes the `tokenizer` argument, which is now deprecated.
model_init (`Callable[[], transformers.PreTrainedModel]`):
The model initializer to use for training. If None is specified, the default model initializer will be used.
callbacks (`List[transformers.TrainerCallback]`):
The callbacks to use for training.
optimizers (`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`):
The optimizer and scheduler to use for training.
preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`):
The function to use to preprocess the logits before computing the metrics.
peft_config (`Dict`, defaults to `None`):
The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model.
compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*):
The function to use to compute the metrics. Must take a `EvalPrediction` and return
a dictionary string to metric values.
"""
_tag_names = ["trl", "dpo"]
@_deprecate_arguments(
version="0.13.0",
deprecated_args=[
"beta",
"label_smoothing",
"loss_type",
"label_pad_token_id",
"padding_value",
"truncation_mode",
"max_length",
"max_prompt_length",
"max_target_length",
"is_encoder_decoder",
"disable_dropout",
"generate_during_eval",
"precompute_ref_log_probs",
"dataset_num_proc",
"model_init_kwargs",
"ref_model_init_kwargs",
"model_adapter_name",
"ref_adapter_name",
"reference_free",
"force_use_ref_model",
],
custom_message="Deprecated positional argument(s) used in DPOTrainer, please use the DPOConfig to set these arguments instead.",
)
@deprecate_kwarg("tokenizer", new_name="processing_class", version="0.14.0", raise_if_both_names=True)
def __init__(
self,
model: Optional[Union[PreTrainedModel, nn.Module, str]] = None,
ref_model: Optional[Union[PreTrainedModel, nn.Module, str]] = None,
beta: float = 0.1,
label_smoothing: float = 0,
loss_type: Optional[str] = None,
args: Optional[DPOConfig] = None,
data_collator: Optional[DataCollator] = None,
label_pad_token_id: int = -100,
padding_value: Optional[int] = None,
truncation_mode: str = "keep_end",
train_dataset: Optional[Dataset] = None,
eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None,
processing_class: Optional[
Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin]
] = None,
model_init: Optional[Callable[[], PreTrainedModel]] = None,
callbacks: Optional[List[TrainerCallback]] = None,
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
max_length: Optional[int] = None,
max_prompt_length: Optional[int] = None,
max_target_length: Optional[int] = None,
peft_config: Optional[Dict] = None,
is_encoder_decoder: Optional[bool] = None,
disable_dropout: bool = True,
generate_during_eval: bool = False,
compute_metrics: Optional[Callable[[EvalLoopOutput], Dict]] = None,
precompute_ref_log_probs: bool = False,
dataset_num_proc: Optional[int] = None,
model_init_kwargs: Optional[Dict] = None,
ref_model_init_kwargs: Optional[Dict] = None,
model_adapter_name: Optional[str] = None,
ref_adapter_name: Optional[str] = None,
reference_free: bool = False,
force_use_ref_model: bool = False,
):
if not isinstance(model, str) and ref_model is model:
raise ValueError(
"`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the "
"same as `model`, you must mass a copy of it, or `None` if you use peft."
)
if args.prefix_sharing and (data_collator or not isinstance(model, str)):
raise ValueError("`model` or `data_collator` cannot be passed to the DPOTrainer as arguments with prefix sharing")
if args.enable_packing:
patch_torch_to_work_with_hf()
if not args.packing_length:
warnings.warn(
"`packing_length` not provided, setting to 2*`max_length`"
)
args.packing_length = 2 * args.max_length
if model_init_kwargs is not None:
warnings.warn(
"You passed `model_init_kwargs` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.model_init_kwargs = model_init_kwargs
if args.model_init_kwargs is None:
model_init_kwargs = {}
elif not isinstance(model, str):
raise ValueError(
"You passed model_init_kwargs to the DPOTrainer/DPOConfig, but your model is already instantiated."
)
else:
model_init_kwargs = args.model_init_kwargs
torch_dtype = model_init_kwargs.get("torch_dtype")
if torch_dtype is not None:
# Convert to `torch.dtype` if an str is passed
if isinstance(torch_dtype, str) and torch_dtype != "auto":
torch_dtype = getattr(torch, torch_dtype)
if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype):
raise ValueError(
f"Invalid `torch_dtype` passed to the DPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}."
)
model_init_kwargs["torch_dtype"] = torch_dtype
if ref_model_init_kwargs is not None:
warnings.warn(
"You passed `ref_model_init_kwargs` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.ref_model_init_kwargs = ref_model_init_kwargs
if args.ref_model_init_kwargs is None:
ref_model_init_kwargs = {}
elif not isinstance(ref_model, str):
raise ValueError(
"You passed ref_model_init_kwargs to the DPOTrainer/DPOConfig, but your ref_model is already instantiated."
)
else:
ref_model_init_kwargs = args.ref_model_init_kwargs
torch_dtype = ref_model_init_kwargs.get("torch_dtype")
if torch_dtype is not None:
# Convert to `torch.dtype` if an str is passed
if isinstance(torch_dtype, str) and torch_dtype != "auto":
torch_dtype = getattr(torch, torch_dtype)
if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype):
raise ValueError(
f"Invalid `torch_dtype` passed to the DPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}."
)
ref_model_init_kwargs["torch_dtype"] = torch_dtype
if isinstance(model, str):
warnings.warn(
"You passed a model_id to the DPOTrainer. This will automatically create an "
"`AutoModelForCausalLM` or a `PeftModel` (if you passed a `peft_config`) for you."
)
if args.prefix_sharing:
config = AutoConfig.from_pretrained(model)
if isinstance(config, LlamaConfig):
model = LlamaForCausalLMFlexAttn.from_pretrained(model, **model_init_kwargs)
elif isinstance(config, MistralConfig):
model = MistralForCausalLMFlexAttn.from_pretrained(model, **model_init_kwargs)
else:
raise NotImplementedError(f"flex attention not implemented for model {model}")
else:
model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs)
if isinstance(ref_model, str):
warnings.warn(
"You passed a ref model_id to the DPOTrainer. This will automatically create an "
"`AutoModelForCausalLM`"
)
if args.prefix_sharing:
config = AutoConfig.from_pretrained(ref_model)
if isinstance(config, LlamaConfig):
ref_model = LlamaForCausalLMFlexAttn.from_pretrained(ref_model, **ref_model_init_kwargs)
elif isinstance(config, MistralConfig):
ref_model = MistralForCausalLMFlexAttn.from_pretrained(ref_model, **ref_model_init_kwargs)
else:
raise NotImplementedError(f"flex attention not implemented for model {ref_model}")
else:
ref_model = AutoModelForCausalLM.from_pretrained(ref_model, **ref_model_init_kwargs)
# Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16`
# has been called in order to properly call autocast if needed.
self._peft_has_been_casted_to_bf16 = False
if force_use_ref_model:
warnings.warn(
"You passed `force_use_ref_model` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.force_use_ref_model = force_use_ref_model
if not is_peft_available() and peft_config is not None:
raise ValueError(
"PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models"
)
elif is_peft_available() and peft_config is not None:
# if model is a peft model and we have a peft_config, we merge and unload it first
if isinstance(model, PeftModel):
model = model.merge_and_unload()
if ref_model is not None and not args.force_use_ref_model:
raise ValueError(
"You passed both a ref_model and a peft_config. For training PEFT adapters with DPO there is no need to pass a reference"
" model. Please pass `ref_model=None` in case you want to train PEFT adapters, or pass a ref_model with `force_use_ref_model=True` in DPOTrainer's init."
" if you want to use a different ref_model."
)
if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False):
_support_gc_kwargs = hasattr(
args, "gradient_checkpointing_kwargs"
) and "gradient_checkpointing_kwargs" in list(
inspect.signature(prepare_model_for_kbit_training).parameters
)
prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing}
if _support_gc_kwargs:
prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs
model = prepare_model_for_kbit_training(model, **prepare_model_kwargs)
elif getattr(args, "gradient_checkpointing", False):
# For backward compatibility with older versions of transformers
if hasattr(model, "enable_input_require_grads"):
model.enable_input_require_grads()
else:
def make_inputs_require_grad(module, input, output):
output.requires_grad_(True)
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
# get peft model with the given config
model = get_peft_model(model, peft_config)
if args.bf16 and getattr(model, "is_loaded_in_4bit", False):
peft_module_casting_to_bf16(model)
# If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager
self._peft_has_been_casted_to_bf16 = True
# For models that use gradient_checkpointing, we need to attach a hook that enables input
# to explicitly have `requires_grad=True`, otherwise training will either silently
# fail or completely fail.
elif getattr(args, "gradient_checkpointing", False):
# For backward compatibility with older versions of transformers
if hasattr(model, "enable_input_require_grads"):
model.enable_input_require_grads()
else:
def make_inputs_require_grad(module, input, output):
output.requires_grad_(True)
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
if generate_during_eval:
warnings.warn(
"You passed `generate_during_eval` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.generate_during_eval = generate_during_eval
if args.generate_during_eval and not is_wandb_available():
raise ValueError(
"`generate_during_eval=True` requires Weights and Biases to be installed."
" Please install `wandb` to resolve."
)
if is_encoder_decoder is not None:
warnings.warn(
"You passed `is_encoder_decoder` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.is_encoder_decoder = is_encoder_decoder
if model is not None:
self.is_encoder_decoder = model.config.is_encoder_decoder
elif args.is_encoder_decoder is None:
raise ValueError(
"When no model is provided, you need to pass the parameter is_encoder_decoder to the DPOTrainer/DPOConfig."
)
else:
self.is_encoder_decoder = args.is_encoder_decoder
if model is not None:
self.is_vision_model = model.config.model_type in MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.keys()
else:
warnings.warn(
"No model provided, cannot determine if it is a vision model. Setting is_vision_model to False."
)
self.is_vision_model = False
if self.is_vision_model:
self.processor = processing_class
self.processing_class = self.processor.tokenizer # tokenizer is actually a processor at this point
else:
self.processing_class = processing_class
self.is_peft_model = is_peft_available() and isinstance(model, PeftModel)
if model_adapter_name is not None:
warnings.warn(
"You passed `model_adapter_name` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.model_adapter_name = model_adapter_name
self.model_adapter_name = args.model_adapter_name
if ref_adapter_name is not None:
warnings.warn(
"You passed `ref_adapter_name` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.ref_adapter_name = ref_adapter_name
self.ref_adapter_name = args.ref_adapter_name
if reference_free:
warnings.warn(
"You passed `reference_free` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.reference_free = reference_free
self.reference_free = args.reference_free
if precompute_ref_log_probs:
warnings.warn(
"You passed `precompute_ref_log_probs` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.precompute_ref_log_probs = precompute_ref_log_probs
if ref_model:
self.ref_model = ref_model
elif self.is_peft_model or args.precompute_ref_log_probs:
# The `model` with adapters turned off will be used as the reference model
self.ref_model = None
else:
self.ref_model = create_reference_model(model)
if processing_class is None:
raise ValueError("processing_class must be specified to tokenize a DPO dataset.")
if max_length is not None:
warnings.warn(
"You passed `max_length` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.max_length = max_length
if args.max_length is None:
warnings.warn(
"`max_length` is not set in the DPOConfig's init"
" it will default to `512` by default, but you should do it yourself in the future.",
UserWarning,
)
args.max_length = 512
if max_prompt_length is not None:
warnings.warn(
"You passed `max_prompt_length` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.max_prompt_length = max_prompt_length
if args.max_prompt_length is None:
warnings.warn(
"`max_prompt_length` is not set in the DPOConfig's init"
" it will default to `128` by default, but you should do it yourself in the future.",
UserWarning,
)
args.max_prompt_length = 128
if max_target_length is not None:
warnings.warn(
"You passed `max_target_length` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.max_completion_length = max_target_length
if args.max_completion_length is None and self.is_encoder_decoder:
warnings.warn(
"When using an encoder decoder architecture, you should set `max_completion_length` in the DPOConfig's init"
" it will default to `128` by default, but you should do it yourself in the future.",
UserWarning,
)
args.max_completion_length = 128
if label_pad_token_id != -100:
warnings.warn(
"You passed `label_pad_token_id` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.label_pad_token_id = label_pad_token_id
if data_collator is None:
if args.prefix_sharing:
if args.enable_packing:
data_collator = DPOPrefixSharingPackedDataCollatorWithPadding(
max_length=args.packing_length,
pad_token_id=self.processing_class.pad_token_id,
label_pad_token_id=args.label_pad_token_id
)
else:
data_collator = DPOPrefixSharingDataCollatorWithPadding(
pad_token_id=self.processing_class.pad_token_id,
label_pad_token_id=args.label_pad_token_id,
)
else:
data_collator = DPODataCollatorWithPadding(
pad_token_id=self.processing_class.pad_token_id,
label_pad_token_id=args.label_pad_token_id,
is_encoder_decoder=self.is_encoder_decoder,
)
if args.remove_unused_columns:
args.remove_unused_columns = False
# warn users
warnings.warn(
"When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments"
" we have set it for you, but you should do it yourself in the future.",
UserWarning,
)
self.use_dpo_data_collator = True
else:
self.use_dpo_data_collator = False
if not disable_dropout:
warnings.warn(
"You passed `disable_dropout` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.disable_dropout = disable_dropout
if args.disable_dropout:
disable_dropout_in_model(model)
if self.ref_model is not None:
disable_dropout_in_model(self.ref_model)
self.max_length = args.max_length
self.generate_during_eval = args.generate_during_eval
self.label_pad_token_id = args.label_pad_token_id
if padding_value is not None:
warnings.warn(
"You passed `padding_value` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.padding_value = padding_value
self.padding_value = args.padding_value if padding_value is not None else self.processing_class.pad_token_id
self.max_prompt_length = args.max_prompt_length
if truncation_mode != "keep_end":
warnings.warn(
"You passed `truncation_mode` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.truncation_mode = truncation_mode
self.truncation_mode = args.truncation_mode
self.max_completion_length = args.max_completion_length
self.precompute_ref_log_probs = args.precompute_ref_log_probs
# Since ref_logs are precomputed on the first call to get_train/eval_dataloader
# keep track of first called to avoid computation of future calls
self._precomputed_train_ref_log_probs = False
self._precomputed_eval_ref_log_probs = False
if loss_type is not None:
warnings.warn(
"You passed `loss_type` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.loss_type = loss_type
if label_smoothing != 0:
warnings.warn(
"You passed `label_smoothing` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.label_smoothing = label_smoothing
if (
args.loss_type in ["hinge", "ipo", "bco_pair", "sppo_hard", "nca_pair", "apo_zero", "apo_down"]
and args.label_smoothing > 0
):
warnings.warn(
"You are using a loss type that does not support label smoothing. Ignoring label_smoothing parameter."
)
if args.loss_type == "kto_pair":
raise ValueError("Support for kto_pair has been removed in DPOTrainer. Please use KTOTrainer.")
if beta != 0.1:
warnings.warn(
"You passed `beta` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.beta = beta
self.beta = args.beta
self.label_smoothing = args.label_smoothing
self.loss_type = args.loss_type
self.aux_loss_enabled = getattr(model.config, "output_router_logits", False)
self.use_weighting = args.use_weighting
self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0)
if self.aux_loss_enabled and self.aux_loss_coef == 0.0:
warnings.warn(
"You set `output_router_logits` to True in the model config, but `router_aux_loss_coef` is set to 0.0,"
" meaning the auxiliary loss will not be used."
)
self._stored_metrics = defaultdict(lambda: defaultdict(list))
self.f_divergence_type = args.f_divergence_type
self.f_divergence_params = {FDivergenceConstants.ALPHA_DIVERGENCE_COEF_KEY: args.f_alpha_divergence_coef}
if dataset_num_proc is not None:
warnings.warn(
"You passed `dataset_num_proc` to the DPOTrainer, the value you passed will override the one in the `DPOConfig`."
)
args.dataset_num_proc = dataset_num_proc
self.dataset_num_proc = args.dataset_num_proc
# Compute that only on the main process for faster data processing.
# see: https://github.com/huggingface/trl/pull/1255
with PartialState().local_main_process_first():
# Extract the prompt if needed, and apply the chat template if needed
train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc)
train_dataset = train_dataset.map(
maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc
)
if eval_dataset is not None:
eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc)
eval_dataset = eval_dataset.map(
maybe_apply_chat_template,
fn_kwargs={"tokenizer": processing_class},
num_proc=args.dataset_num_proc,
)
# tokenize the dataset, lower writer batch size to avoid OOM (frequent in vision models)
fn_kwargs = {
"tokenizer": self.processing_class,
"args": args,
"processor": self.processor if self.is_vision_model else None,
"model": model if self.is_encoder_decoder else None,
}
train_dataset = train_dataset.map(
_tokenize,
fn_kwargs=fn_kwargs,
batched=True,
with_indices=True,
num_proc=self.dataset_num_proc,
writer_batch_size=10,
desc="Tokenizing train dataset",
)
if eval_dataset is not None:
eval_dataset = eval_dataset.map(
_tokenize,
fn_kwargs=fn_kwargs,
batched=True,
with_indices=True,
num_proc=self.dataset_num_proc,
writer_batch_size=10,
desc="Tokenizing eval dataset",
)
super().__init__(
model=model,
args=args,
data_collator=data_collator,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
processing_class=processing_class,
model_init=model_init,
compute_metrics=compute_metrics,
callbacks=callbacks,
optimizers=optimizers,
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
)
# Add tags for models that have been loaded with the correct transformers version
if hasattr(self.model, "add_model_tags"):
self.model.add_model_tags(self._tag_names)
if not hasattr(self, "accelerator"):
raise AttributeError(
"Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`."
)
# Deepspeed Zero-3 does not support precompute_ref_log_probs
if self.is_deepspeed_enabled:
if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs:
raise ValueError(
"You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`."
)
if self.ref_model is None:
if not (self.is_peft_model or self.precompute_ref_log_probs):
raise ValueError(
"No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`"
)
if args.sync_ref_model:
raise ValueError(
"You currently cannot use `ref_model=None` with TR-DPO method. Please provide `ref_model`."
)
else:
if self.is_deepspeed_enabled:
self.ref_model = self._prepare_deepspeed(self.ref_model)
else:
self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True)
if args.sync_ref_model:
if precompute_ref_log_probs:
raise ValueError(
"You cannot use `precompute_ref_log_probs=True` with TR-DPO method. Please set `precompute_ref_log_probs=False`."
)
self.add_callback(SyncRefModelCallback(ref_model=self.ref_model, accelerator=self.accelerator))
if self.loss_type == "bco_pair":
self.running = RunningMoments(self.accelerator)
def _prepare_deepspeed(self, model: PreTrainedModelWrapper):
# Adapted from accelerate: https://github.com/huggingface/accelerate/blob/739b135f8367becb67ffaada12fe76e3aa60fefd/src/accelerate/accelerator.py#L1473
deepspeed_plugin = self.accelerator.state.deepspeed_plugin
config_kwargs = deepcopy(deepspeed_plugin.deepspeed_config)