-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathtest_sft_trainer.py
More file actions
2295 lines (1875 loc) · 100 KB
/
test_sft_trainer.py
File metadata and controls
2295 lines (1875 loc) · 100 KB
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
# Copyright 2020-2026 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 gc
import json
import pathlib
from unittest.mock import MagicMock, patch
import pytest
import torch
import transformers
from accelerate.utils.memory import release_memory
from datasets import load_dataset
from packaging.version import Version
from packaging.version import parse as parse_version
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TrainingArguments
from transformers.testing_utils import backend_empty_cache, torch_device
from transformers.utils import is_peft_available
from trl import SFTConfig, SFTTrainer
from trl.trainer.sft_trainer import DataCollatorForLanguageModeling, dft_loss
from .testing_utils import (
TrlTestCase,
ignore_warnings,
require_ampere_or_newer,
require_bitsandbytes,
require_kernels,
require_liger_kernel,
require_peft,
require_torch_accelerator,
require_torch_multi_accelerator,
require_vision,
)
if is_peft_available():
import peft
from peft import (
LoraConfig,
PeftModel,
PrefixTuningConfig,
PromptEncoderConfig,
PromptTuningConfig,
TaskType,
get_peft_model,
)
class TestDFTLoss(TrlTestCase):
def test_dft_loss(self):
batch_size = 2
seq_len = 3
vocab_size = 2
# All tokens have the same probability
logits = torch.fill(torch.empty(batch_size, seq_len, vocab_size), torch.rand(1).item())
outputs = MagicMock()
outputs.logits = logits
labels = torch.tensor([[1, 0, 0], [0, 1, -100]])
ce_loss = torch.nn.functional.cross_entropy(
logits.view(-1, vocab_size), labels.view(-1), ignore_index=-100, reduction="mean"
)
# We need to account for the logits shift operation so we don't consider the first tokens
# in each row of the batch
num_items_in_batch = 3
# Dft loss
predicted_dft_loss = dft_loss(outputs, labels, num_items_in_batch)
# If we have just two tokens in our vocab and all logits are the same,
# dft scales the ce_loss per token by 0.5. So the dft_loss should be ce_loss/2
torch.testing.assert_close(ce_loss / 2.0, predicted_dft_loss, atol=1e-4, rtol=1e-4)
class TestDataCollatorForLanguageModeling(TrlTestCase):
def test_basic_padding(self):
"""Test basic padding functionality without completion masks."""
collator = DataCollatorForLanguageModeling(pad_token_id=0)
examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]]))
torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [4, 5, -100]]))
def test_completion_mask(self):
"""Test completion mask functionality."""
collator = DataCollatorForLanguageModeling(pad_token_id=0)
examples = [
{"input_ids": [1, 2, 3], "completion_mask": [0, 1, 1]},
{"input_ids": [4, 5], "completion_mask": [0, 1]},
]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]]))
torch.testing.assert_close(result["labels"], torch.tensor([[-100, 2, 3], [-100, 5, -100]]))
def test_completion_only_loss_disabled(self):
"""Test behavior when completion_only_loss is disabled."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, completion_only_loss=False)
examples = [
{"input_ids": [1, 2, 3], "completion_mask": [0, 1, 1]},
{"input_ids": [4, 5], "completion_mask": [0, 1]},
]
result = collator(examples)
# Labels should not be masked when completion_only_loss=False
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]]))
torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [4, 5, -100]]))
def test_padding_free_mode(self):
"""Test padding-free mode where sequences are concatenated."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, padding_free=True)
examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "position_ids", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 4, 5]]))
torch.testing.assert_close(result["position_ids"], torch.tensor([[0, 1, 2, 0, 1]]))
torch.testing.assert_close(result["labels"], torch.tensor([[-100, 2, 3, -100, 5]]))
def test_padding_free_with_completion_mask(self):
"""Test padding-free mode with completion masks."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, padding_free=True)
examples = [
{"input_ids": [1, 2, 3], "completion_mask": [0, 0, 1]},
{"input_ids": [4, 5], "completion_mask": [1, 1]},
]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "position_ids", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 4, 5]]))
torch.testing.assert_close(result["position_ids"], torch.tensor([[0, 1, 2, 0, 1]]))
torch.testing.assert_close(result["labels"], torch.tensor([[-100, -100, 3, -100, 5]]))
def test_packing(self):
"""Test that when using packing with position_ids, attention_mask is dropped with fa2."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, padding_free=True)
# Simulate packed sequences with position_ids that restart (typical of BFD packing)
examples = [
{"input_ids": [1, 2, 3, 4, 5, 6], "seq_lengths": [3, 3]},
{"input_ids": [7, 8, 9, 10, 11], "seq_lengths": [4, 1]},
]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "position_ids", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]))
torch.testing.assert_close(result["position_ids"], torch.tensor([[0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 0]]))
torch.testing.assert_close(result["labels"], torch.tensor([[-100, 2, 3, -100, 5, 6, -100, 8, 9, 10, -100]]))
def test_pad_to_multiple_of(self):
"""Test padding to multiple of specified value."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, pad_to_multiple_of=4)
examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 0], [4, 5, 0, 0]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1, 0], [1, 1, 0, 0]]))
torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3, -100], [4, 5, -100, -100]]))
def test_pad_to_multiple_of_and_padding_free(self):
"""Test padding to multiple of specified value."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, padding_free=True, pad_to_multiple_of=4)
examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "position_ids", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 4, 5, 0, 0, 0]]))
torch.testing.assert_close(result["position_ids"], torch.tensor([[0, 1, 2, 0, 1, 0, 0, 0]]))
torch.testing.assert_close(result["labels"], torch.tensor([[-100, 2, 3, -100, 5, -100, -100, -100]]))
def test_custom_position_ids_but_no_padding_free(self):
"""Test that custom position_ids are ignored if padding_free is False."""
collator = DataCollatorForLanguageModeling(pad_token_id=0)
examples = [{"input_ids": [1, 2, 3], "seq_lengths": [1, 2]}, {"input_ids": [4, 5], "seq_lengths": [2]}]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]]))
torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [4, 5, -100]]))
def test_single_example(self):
"""Test collator with a single example."""
collator = DataCollatorForLanguageModeling(pad_token_id=0)
examples = [{"input_ids": [1, 2, 3, 4]}]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3, 4]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1, 1]]))
torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3, 4]]))
def test_different_pad_token_id(self):
"""Test with different pad token ID."""
collator = DataCollatorForLanguageModeling(pad_token_id=999)
examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 999]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]]))
torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [4, 5, -100]]))
def test_assistant_masks(self):
"""Test handling of assistant masks in examples."""
collator = DataCollatorForLanguageModeling(pad_token_id=0)
examples = [
{"input_ids": [1, 2, 3], "assistant_masks": [0, 1, 1]},
{"input_ids": [4, 5], "assistant_masks": [0, 1]},
]
result = collator(examples)
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]]))
torch.testing.assert_close(result["labels"], torch.tensor([[-100, 2, 3], [-100, 5, -100]]))
def test_max_length_keep_start(self):
"""Test that sequences longer than max_length are truncated from the start."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=3)
examples = [{"input_ids": [1, 2, 3, 4, 5]}, {"input_ids": [6, 7, 8]}]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [6, 7, 8]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 1]]))
torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [6, 7, 8]]))
def test_max_length_keep_end(self):
"""Test that sequences longer than max_length are truncated from the end (keeping last tokens)."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=3, truncation_mode="keep_end")
examples = [{"input_ids": [1, 2, 3, 4, 5]}, {"input_ids": [6, 7, 8]}]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[3, 4, 5], [6, 7, 8]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 1]]))
torch.testing.assert_close(result["labels"], torch.tensor([[3, 4, 5], [6, 7, 8]]))
def test_max_length_no_truncation_needed(self):
"""Test that max_length larger than sequences does not alter the output."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=10)
examples = [{"input_ids": [1, 2, 3]}, {"input_ids": [4, 5]}]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [4, 5, 0]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 0]]))
torch.testing.assert_close(result["labels"], torch.tensor([[1, 2, 3], [4, 5, -100]]))
def test_max_length_with_completion_mask(self):
"""Test that truncation is applied correctly when completion masks are present."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=3)
examples = [
{"input_ids": [1, 2, 3, 4, 5], "completion_mask": [0, 0, 1, 1, 1]},
{"input_ids": [6, 7, 8], "completion_mask": [0, 1, 1]},
]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[1, 2, 3], [6, 7, 8]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 1]]))
torch.testing.assert_close(result["labels"], torch.tensor([[-100, -100, 3], [-100, 7, 8]]))
def test_max_length_keep_end_with_completion_mask(self):
"""Test keep_end truncation with completion masks preserves the final tokens."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=3, truncation_mode="keep_end")
examples = [
{"input_ids": [1, 2, 3, 4, 5], "completion_mask": [0, 0, 1, 1, 1]},
{"input_ids": [6, 7, 8], "completion_mask": [0, 1, 1]},
]
result = collator(examples)
assert set(result.keys()) == {"input_ids", "attention_mask", "labels"}
torch.testing.assert_close(result["input_ids"], torch.tensor([[3, 4, 5], [6, 7, 8]]))
torch.testing.assert_close(result["attention_mask"], torch.tensor([[1, 1, 1], [1, 1, 1]]))
torch.testing.assert_close(result["labels"], torch.tensor([[3, 4, 5], [-100, 7, 8]]))
def test_max_length_invalid_truncation_mode(self):
"""Test that an invalid truncation_mode raises ValueError."""
collator = DataCollatorForLanguageModeling(pad_token_id=0, max_length=3, truncation_mode="invalid")
examples = [{"input_ids": [1, 2, 3, 4, 5]}]
with pytest.raises(ValueError, match="Unsupported truncation mode"):
collator(examples)
def test_single_example_single_doc(self):
batch_seq_lengths = [[5]]
result = DataCollatorForLanguageModeling.get_position_ids_from_packed_seq_lengths(batch_seq_lengths)
assert len(result) == 1
assert torch.equal(result[0], torch.arange(5))
def test_single_example_multiple_docs(self):
batch_seq_lengths = [[3, 2]]
result = DataCollatorForLanguageModeling.get_position_ids_from_packed_seq_lengths(batch_seq_lengths)
assert len(result) == 1
# First sequence: 0, 1, 2; second sequence: 0, 1
assert torch.equal(result[0], torch.tensor([0, 1, 2, 0, 1]))
def test_multiple_examples(self):
batch_seq_lengths = [[2, 2], [3]]
result = DataCollatorForLanguageModeling.get_position_ids_from_packed_seq_lengths(batch_seq_lengths)
assert len(result) == 2
assert torch.equal(result[0], torch.tensor([0, 1, 0, 1]))
assert torch.equal(result[1], torch.arange(3))
class TestSFTTrainer(TrlTestCase):
def test_init_with_training_arguments(self):
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
args = TrainingArguments(output_dir=self.tmp_dir, report_to="none")
SFTTrainer(model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=args, train_dataset=dataset)
@pytest.mark.parametrize(
"model_id",
[
"trl-internal-testing/tiny-Cohere2ForCausalLM",
pytest.param(
"trl-internal-testing/tiny-Glm4MoeForCausalLM",
marks=pytest.mark.skipif(
Version(transformers.__version__) < Version("5.0.0"),
reason="GLM4 tokenizer requires transformers>=5.0.0",
),
),
"trl-internal-testing/tiny-GptOssForCausalLM",
"trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
"trl-internal-testing/tiny-Qwen3MoeForCausalLM",
],
)
def test_train(self, model_id):
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
# Initialize the trainer
training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none")
trainer = SFTTrainer(model=model_id, args=training_args, train_dataset=dataset)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
# Special case for harmony
def test_train_gpt_oss(self):
# Get the dataset
dataset = load_dataset("trl-internal-testing/harmony", "language_modeling", split="train")
# Initialize the trainer
training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none")
trainer = SFTTrainer(
model="trl-internal-testing/tiny-GptOssForCausalLM", args=training_args, train_dataset=dataset
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
def test_train_model(self):
# Instantiate the model
model = AutoModelForCausalLM.from_pretrained(
"trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
dtype="float32",
)
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
# Initialize the trainer
training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none")
trainer = SFTTrainer(model=model, args=training_args, train_dataset=dataset)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
def test_train_dft_loss(self):
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling")
# Initialize the trainer
training_args = SFTConfig(
output_dir=self.tmp_dir,
loss_type="dft",
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
report_to="none",
eval_strategy="steps",
eval_steps=3,
)
trainer = SFTTrainer(
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
args=training_args,
train_dataset=dataset["train"],
eval_dataset=dataset["test"],
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
def test_train_moe_model_with_aux_loss(self):
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
# Initialize the trainer
training_args = SFTConfig(
output_dir=self.tmp_dir,
report_to="none",
model_init_kwargs={"output_router_logits": True},
)
trainer = SFTTrainer(
model="trl-internal-testing/tiny-Qwen3MoeForCausalLM", args=training_args, train_dataset=dataset
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss and aux loss are not None
assert trainer.state.log_history[-1]["train_loss"] is not None
assert trainer.state.log_history[-1]["aux_loss"] is not None
# Check the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
def test_train_with_formatting_func(self):
# Dummy formatting function
def formatting_prompts_func(example):
chosen, rejected = example["chosen"], example["rejected"]
return f"### Chosen: {chosen}\n### Rejected: {rejected}"
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_implicit_prompt_preference", split="train")
# Initialize the trainer
training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none")
trainer = SFTTrainer(
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
args=training_args,
train_dataset=dataset,
formatting_func=formatting_prompts_func,
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
def test_train_model_dtype(self):
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
# Initialize the trainer
training_args = SFTConfig(
output_dir=self.tmp_dir,
model_init_kwargs={"dtype": torch.float16},
learning_rate=0.1, # use higher lr because gradients are tiny and default lr can stall updates
report_to="none",
)
trainer = SFTTrainer(
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the params have changed
for n, param in previous_trainable_params.items():
# For some reasonn model.layers.0.input_layernorm.weight doesn't change in GitHub Actions but does
# locally. We ignore this parameter for now
if "layernorm" in n:
continue
new_param = trainer.model.get_parameter(n)
# Check the torch dtype
assert new_param.dtype == torch.float16
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
@require_peft
def test_train_dense_with_peft_config_lora(self):
# Get the base model parameter names
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
# Initialize the trainer
training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none")
trainer = SFTTrainer(
model=model_id,
args=training_args,
train_dataset=dataset,
peft_config=LoraConfig(),
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the peft params have changed and the base model params have not changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
if n in base_param_names: # We expect the base model parameters to be the same
torch.testing.assert_close(param, new_param), f"Parameter {n} has changed"
elif "base_layer" not in n: # We expect the peft parameters to be different (except for the base layer)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
@pytest.mark.parametrize(
"peft_type",
[
"prompt_tuning",
"prefix_tuning",
"prompt_encoder",
],
)
@require_peft
def test_train_with_peft_config_prompt_tuning(self, peft_type):
# Get the base model parameter names
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
base_param_names = [f"base_model.{n}" for n, _ in model.named_parameters()]
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
# Initialize the trainer, p-tuning doesn't support gradient checkpointing
training_args = SFTConfig(bf16=False, output_dir=self.tmp_dir, report_to="none", gradient_checkpointing=False)
if peft_type == "prompt_tuning":
peft_config = PromptTuningConfig(
task_type=TaskType.CAUSAL_LM,
num_virtual_tokens=4,
tokenizer_name_or_path="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
)
elif peft_type == "prefix_tuning":
if parse_version(peft.__version__) <= Version("0.17.1"):
pytest.xfail(
"Prefix tuning with device_map='auto' is broken in peft 0.17.1 and below. See "
"https://github.com/huggingface/peft/issues/2821"
)
peft_config = PrefixTuningConfig(
task_type=TaskType.CAUSAL_LM,
num_virtual_tokens=4,
)
elif peft_type == "prompt_encoder":
peft_config = PromptEncoderConfig(
task_type=TaskType.CAUSAL_LM,
num_virtual_tokens=4,
encoder_hidden_size=model.config.hidden_size, # This will be overwritten below
)
trainer = SFTTrainer(
model=model_id,
args=training_args,
train_dataset=dataset,
peft_config=peft_config,
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the peft params have changed and the base model params have not changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
if n in base_param_names: # We expect the base model parameters to be the same
torch.testing.assert_close(param, new_param), f"Parameter {n} has changed"
else: # We expect the peft parameters to be different
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
@require_peft
def test_train_moe_with_peft_config(self):
# Get the base model parameter names
model_id = "trl-internal-testing/tiny-GptOssForCausalLM"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
# Initialize the trainer
training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none")
trainer = SFTTrainer(
model=model_id,
args=training_args,
train_dataset=dataset,
peft_config=LoraConfig(target_parameters=["mlp.experts.down_proj", "mlp.experts.gate_up_proj"]),
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the peft params have changed and the base model params have not changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
if n in base_param_names: # We expect the base model parameters to be the same
torch.testing.assert_close(param, new_param), f"Parameter {n} has changed"
elif "base_layer" not in n: # We expect the peft parameters to be different (except for the base layer)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
@require_peft
def test_train_peft_model(self):
# Get the base model
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
# Get the base model parameter names
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
# Turn the model into a peft model
lora_config = LoraConfig()
model = get_peft_model(model, lora_config)
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
# Initialize the trainer
training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none")
trainer = SFTTrainer(model=model, args=training_args, train_dataset=dataset)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the peft params have changed and the base model params have not changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
if n in base_param_names: # We expect the base model parameters to be the same
torch.testing.assert_close(param, new_param), f"Parameter {n} has changed"
elif "base_layer" not in n: # We expect the peft parameters to be different (except for the base layer)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
# In practice, this test is the same as `test_train_dense_with_peft_config_lora`, since gradient checkpointing is
# enabled by default in `SFTTrainer`. We keep it as a regression guard: if the default ever changes, we still
# explicitly test PEFT + gradient checkpointing, which has caused issues in the past.
@require_peft
def test_train_with_peft_config_and_gradient_checkpointing(self):
# Get the base model parameter names
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
# Initialize the trainer
training_args = SFTConfig(output_dir=self.tmp_dir, gradient_checkpointing=True, report_to="none")
trainer = SFTTrainer(
model=model_id,
args=training_args,
train_dataset=dataset,
peft_config=LoraConfig(),
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the peft params have changed and the base model params have not changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
if n in base_param_names: # We expect the base model parameters to be the same
torch.testing.assert_close(param, new_param), f"Parameter {n} has changed"
elif "base_layer" not in n: # We expect the peft parameters to be different (except for the base layer)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
@pytest.mark.parametrize("use_reentrant", [True, False])
@require_peft
def test_train_with_peft_config_and_gradient_checkpointing_reentrant(self, use_reentrant):
# Get the base model parameter names
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="float32")
base_param_names = [f"base_model.model.{n}" for n, _ in model.named_parameters()]
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
# Initialize the trainer
training_args = SFTConfig(
output_dir=self.tmp_dir,
gradient_checkpointing=True,
gradient_checkpointing_kwargs={"use_reentrant": use_reentrant},
report_to="none",
)
trainer = SFTTrainer(
model=model_id,
args=training_args,
train_dataset=dataset,
peft_config=LoraConfig(),
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the peft params have changed and the base model params have not changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
if n in base_param_names: # We expect the base model parameters to be the same
torch.testing.assert_close(param, new_param), f"Parameter {n} has changed"
elif "base_layer" not in n: # We expect the peft parameters to be different (except for the base layer)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
@require_liger_kernel
def test_train_with_liger(self):
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
# Initialize the trainer
training_args = SFTConfig(output_dir=self.tmp_dir, use_liger_kernel=True, report_to="none")
trainer = SFTTrainer(
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
@require_torch_accelerator
@require_liger_kernel
def test_compute_loss_skip_logits_on_eval_without_metrics_with_liger(self):
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train[:1]")
training_args = SFTConfig(
output_dir=self.tmp_dir,
use_liger_kernel=False,
report_to="none",
max_length=8,
bf16=False,
)
trainer = SFTTrainer(
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
args=training_args,
train_dataset=dataset,
compute_metrics=None,
)
trainer.args.use_liger_kernel = True
trainer.model.eval()
captured = {}
def mock_super_compute_loss(model, inputs, return_outputs=False, num_items_in_batch=None):
captured["skip_logits"] = inputs.get("skip_logits")
dummy_loss = torch.tensor(1.0, requires_grad=True)
dummy_outputs = MagicMock()
dummy_outputs.token_accuracy = None
dummy_outputs.logits = torch.randn(1, 5, trainer.model.config.vocab_size)
return (dummy_loss, dummy_outputs)
inputs = {
"input_ids": torch.tensor([[1, 2, 3, 4, 5]]),
"labels": torch.tensor([[1, 2, 3, 4, 5]]),
"attention_mask": torch.tensor([[1, 1, 1, 1, 1]]),
}
with patch("transformers.Trainer.compute_loss", side_effect=mock_super_compute_loss):
trainer.compute_loss(trainer.model, inputs)
assert captured["skip_logits"] is True
@require_torch_accelerator
@require_liger_kernel
def test_predict_does_not_skip_logits_with_liger(self):
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train[:1]")
training_args = SFTConfig(
output_dir=self.tmp_dir,
use_liger_kernel=False,
report_to="none",
max_length=8,
bf16=False,
)
trainer = SFTTrainer(
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5",
args=training_args,
train_dataset=dataset,
compute_metrics=None,
)
trainer.args.use_liger_kernel = True
trainer.model.eval()
captured = {}
def mock_super_compute_loss(model, inputs, return_outputs=False, num_items_in_batch=None):
captured["skip_logits"] = inputs.get("skip_logits")
dummy_loss = torch.tensor(1.0, requires_grad=True)
dummy_outputs = (dummy_loss, torch.randn(1, 5, trainer.model.config.vocab_size))
return (dummy_loss, dummy_outputs)
with patch("transformers.Trainer.compute_loss", side_effect=mock_super_compute_loss):
trainer.predict(trainer.train_dataset)
assert captured["skip_logits"] is False
def test_train_with_non_chatml_conversational_data(self):
# Get the dataset
dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train")
# Rename role/content to from/value to ensure SFT works with non-chatML conversational data
def rename_fields(example: list[dict]):
return {"conversations": [{"from": m["role"], "value": m["content"]} for m in example["messages"]]}
dataset = dataset.map(rename_fields, remove_columns="messages")
# Initialize the trainer
training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none")
trainer = SFTTrainer(
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
def test_train_with_pretokenized_data(self):
# Get the dataset
model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5"
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train")
def tokenize_example(example):
return tokenizer(example["text"])
# Apply tokenization
tokenized_dataset = dataset.map(tokenize_example, remove_columns=["text"])
# Initialize the trainer
training_args = SFTConfig(output_dir=self.tmp_dir, report_to="none")
trainer = SFTTrainer(model=model_id, args=training_args, train_dataset=tokenized_dataset)
# Save the initial parameters to compare them later
previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()}
# Train the model
trainer.train()
# Check that the training loss is not None
assert trainer.state.log_history[-1]["train_loss"] is not None
# Check the params have changed
for n, param in previous_trainable_params.items():
new_param = trainer.model.get_parameter(n)
assert not torch.allclose(param, new_param), f"Parameter {n} has not changed"
def test_skip_prepare_dataset_passes_truncation_to_text_collator(self):
dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling", split="train[:2]")
training_args = SFTConfig(
output_dir=self.tmp_dir,
max_length=16,
truncation_mode="keep_end",
dataset_kwargs={"skip_prepare_dataset": True},
report_to="none",
)
trainer = SFTTrainer(
model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", args=training_args, train_dataset=dataset
)