forked from foundation-model-stack/fms-hf-tuning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_sft_trainer.py
1509 lines (1233 loc) · 54.5 KB
/
test_sft_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
# Copyright The FMS HF Tuning Authors
#
# 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.
"""Unit Tests for SFT Trainer.
"""
# pylint: disable=too-many-lines
# Standard
from dataclasses import asdict
import copy
import json
import os
import tempfile
# Third Party
from datasets.exceptions import DatasetGenerationError, DatasetNotFoundError
from transformers.trainer_callback import TrainerCallback
import pytest
import torch
import transformers
import yaml
# First Party
from build.utils import serialize_args
from scripts.run_inference import TunedCausalLM
from tests.artifacts.predefined_data_configs import (
DATA_CONFIG_MULTIPLE_DATASETS_SAMPLING_YAML,
DATA_CONFIG_TOKENIZE_AND_APPLY_INPUT_MASKING_YAML,
)
from tests.artifacts.testdata import (
CHAT_DATA_MULTI_TURN,
CHAT_DATA_SINGLE_TURN,
CUSTOM_TOKENIZER_TINYLLAMA,
EMPTY_DATA,
MALFORMATTED_DATA,
MODEL_NAME,
TWITTER_COMPLAINTS_DATA_ARROW,
TWITTER_COMPLAINTS_DATA_DIR_JSON,
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_ARROW,
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_JSON,
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_JSONL,
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_PARQUET,
TWITTER_COMPLAINTS_DATA_JSON,
TWITTER_COMPLAINTS_DATA_JSONL,
TWITTER_COMPLAINTS_DATA_PARQUET,
TWITTER_COMPLAINTS_TOKENIZED_ARROW,
TWITTER_COMPLAINTS_TOKENIZED_JSON,
TWITTER_COMPLAINTS_TOKENIZED_JSONL,
TWITTER_COMPLAINTS_TOKENIZED_PARQUET,
)
# Local
from tuning import sft_trainer
from tuning.config import configs, peft_config
from tuning.config.tracker_configs import FileLoggingTrackerConfig
from tuning.data.data_config import (
DataConfig,
DataHandlerConfig,
DataPreProcessorConfig,
DataSetConfig,
)
from tuning.data.data_handlers import apply_dataset_formatting
MODEL_ARGS = configs.ModelArguments(
model_name_or_path=MODEL_NAME, use_flash_attn=False, torch_dtype="float32"
)
DATA_ARGS = configs.DataArguments(
training_data_path=TWITTER_COMPLAINTS_DATA_JSONL,
response_template="\n### Label:",
dataset_text_field="output",
)
TRAIN_ARGS = configs.TrainingArguments(
num_train_epochs=5,
per_device_train_batch_size=4,
per_device_eval_batch_size=4,
gradient_accumulation_steps=4,
learning_rate=0.00001,
weight_decay=0,
warmup_ratio=0.03,
lr_scheduler_type="cosine",
logging_steps=1,
include_tokens_per_second=True,
packing=False,
max_seq_length=4096,
save_strategy="epoch",
output_dir="tmp",
)
PEFT_PT_ARGS = peft_config.PromptTuningConfig(
prompt_tuning_init="RANDOM",
num_virtual_tokens=8,
prompt_tuning_init_text="hello",
)
PEFT_LORA_ARGS = peft_config.LoraConfig(r=8, lora_alpha=32, lora_dropout=0.05)
def test_resume_training_from_checkpoint():
"""
Test tuning resumes from the latest checkpoint, creating new checkpoints and the
checkpoints created before resuming tuning is not affected.
"""
with tempfile.TemporaryDirectory() as tempdir:
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
sft_trainer.train(MODEL_ARGS, DATA_ARGS, train_args, None)
_validate_training(tempdir)
# Get trainer state of latest checkpoint
init_trainer_state, _ = _get_latest_checkpoint_trainer_state(tempdir)
assert init_trainer_state is not None
# Resume training with higher epoch and same output dir
train_args.num_train_epochs += 5
sft_trainer.train(MODEL_ARGS, DATA_ARGS, train_args, None)
_validate_training(tempdir)
# Get trainer state of latest checkpoint
final_trainer_state, _ = _get_latest_checkpoint_trainer_state(tempdir)
assert final_trainer_state is not None
assert final_trainer_state["epoch"] == init_trainer_state["epoch"] + 5
assert final_trainer_state["global_step"] > init_trainer_state["global_step"]
# Check if loss of 1st epoch after first tuning is same after
# resuming tuning and not overwritten
assert len(init_trainer_state["log_history"]) > 0
init_log_history = init_trainer_state["log_history"][0]
assert init_log_history["epoch"] == 1
final_log_history = final_trainer_state["log_history"][0]
assert final_log_history["epoch"] == 1
assert init_log_history["loss"] == final_log_history["loss"]
def test_resume_training_from_checkpoint_with_flag_true():
"""
Test tuning resumes from the latest checkpoint when flag is true,
creating new checkpoints and the checkpoints created before resuming
tuning is not affected.
"""
with tempfile.TemporaryDirectory() as tempdir:
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
train_args.resume_from_checkpoint = "True"
sft_trainer.train(MODEL_ARGS, DATA_ARGS, train_args, None)
_validate_training(tempdir)
# Get trainer state of latest checkpoint
init_trainer_state, _ = _get_latest_checkpoint_trainer_state(tempdir)
assert init_trainer_state is not None
# Get Training logs
init_training_logs = _get_training_logs_by_epoch(tempdir)
# Resume training with higher epoch and same output dir
train_args.num_train_epochs += 5
sft_trainer.train(MODEL_ARGS, DATA_ARGS, train_args, None)
_validate_training(tempdir)
# Get trainer state of latest checkpoint
final_trainer_state, _ = _get_latest_checkpoint_trainer_state(tempdir)
assert final_trainer_state is not None
assert final_trainer_state["epoch"] == init_trainer_state["epoch"] + 5
assert final_trainer_state["global_step"] > init_trainer_state["global_step"]
final_training_logs = _get_training_logs_by_epoch(tempdir)
assert (
init_training_logs[0]["data"]["timestamp"]
== final_training_logs[0]["data"]["timestamp"]
)
def test_resume_training_from_checkpoint_with_flag_false():
"""
Test when setting resume_from_checkpoint=False that tuning will start from scratch.
"""
with tempfile.TemporaryDirectory() as tempdir:
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
train_args.resume_from_checkpoint = "False"
sft_trainer.train(MODEL_ARGS, DATA_ARGS, train_args, None)
_validate_training(tempdir)
# Get trainer state of latest checkpoint
init_trainer_state, _ = _get_latest_checkpoint_trainer_state(tempdir)
assert init_trainer_state is not None
# Get Training log entry for epoch 1
init_training_logs = _get_training_logs_by_epoch(tempdir, epoch=1)
assert len(init_training_logs) == 1
# Training again with higher epoch and same output dir
train_args.num_train_epochs += 5
sft_trainer.train(MODEL_ARGS, DATA_ARGS, train_args, None)
_validate_training(tempdir)
# Get Training log entry for epoch 1
final_training_logs = _get_training_logs_by_epoch(tempdir, epoch=1)
assert len(final_training_logs) == 2
def test_resume_training_from_checkpoint_with_flag_checkpoint_path_lora():
"""
Test resume checkpoint from a specified checkpoint path for LoRA tuning.
"""
with tempfile.TemporaryDirectory() as tempdir:
train_args = copy.deepcopy(TRAIN_ARGS)
lora_config = copy.deepcopy(PEFT_LORA_ARGS)
train_args.output_dir = tempdir
sft_trainer.train(MODEL_ARGS, DATA_ARGS, train_args, lora_config)
_validate_training(tempdir)
# Get trainer state and checkpoint_path of second last checkpoint
init_trainer_state, checkpoint_path = _get_latest_checkpoint_trainer_state(
tempdir, checkpoint_index=-2
)
assert init_trainer_state is not None
# Resume training with higher epoch and same output dir
train_args.num_train_epochs += 5
train_args.resume_from_checkpoint = checkpoint_path
sft_trainer.train(MODEL_ARGS, DATA_ARGS, train_args, lora_config)
_validate_training(tempdir)
# Get total_flos from trainer state of checkpoint_path and check if its same
final_trainer_state = None
trainer_state_file = os.path.join(checkpoint_path, "trainer_state.json")
with open(trainer_state_file, "r", encoding="utf-8") as f:
final_trainer_state = json.load(f)
assert final_trainer_state["total_flos"] == init_trainer_state["total_flos"]
def _get_latest_checkpoint_trainer_state(dir_path: str, checkpoint_index: int = -1):
"""
Get the trainer state from the latest or specified checkpoint directory.
The trainer state is returned along with the path to the checkpoint.
Args:
dir_path (str): The directory path where checkpoint folders are located.
checkpoint_index (int, optional): The index of the checkpoint to retrieve,
based on the checkpoint number. The default
is -1, which returns the latest checkpoint.
Returns:
trainer_state: The trainer state loaded from `trainer_state.json` in the
checkpoint directory.
last_checkpoint: The path to the checkpoint directory.
"""
trainer_state = None
last_checkpoint = None
checkpoints = [
os.path.join(dir_path, d)
for d in os.listdir(dir_path)
if d.startswith("checkpoint")
]
if checkpoints:
last_checkpoint = sorted(checkpoints, key=lambda x: int(x.split("-")[-1]))[
checkpoint_index
]
trainer_state_file = os.path.join(last_checkpoint, "trainer_state.json")
with open(trainer_state_file, "r", encoding="utf-8") as f:
trainer_state = json.load(f)
return trainer_state, last_checkpoint
def _get_training_logs_by_epoch(dir_path: str, epoch: int = None):
"""
Load and optionally filter training_logs.jsonl file.
If an epoch number is specified, the function filters the logs
and returns only the entries corresponding to the specified epoch.
Args:
dir_path (str): The directory path where the `training_logs.jsonl` file is located.
epoch (int, optional): The epoch number to filter logs by. If not specified,
all logs are returned.
Returns:
list: A list containing the training logs. If `epoch` is specified,
only logs from the specified epoch are returned; otherwise, all logs are returned.
"""
data_list = []
with open(f"{dir_path}/training_logs.jsonl", "r", encoding="utf-8") as file:
for line in file:
json_data = json.loads(line)
data_list.append(json_data)
if epoch:
mod_data_list = []
for value in data_list:
if value["data"]["epoch"] == epoch:
mod_data_list.append(value)
return mod_data_list
return data_list
def test_run_train_requires_output_dir():
"""Check fails when output dir not provided."""
updated_output_dir_train_args = copy.deepcopy(TRAIN_ARGS)
updated_output_dir_train_args.output_dir = None
with pytest.raises(TypeError):
sft_trainer.train(MODEL_ARGS, DATA_ARGS, updated_output_dir_train_args, None)
def test_run_train_fails_training_data_path_not_exist():
"""Check fails when data path not found."""
updated_data_path_args = copy.deepcopy(DATA_ARGS)
updated_data_path_args.training_data_path = "fake/path"
with pytest.raises(DatasetNotFoundError):
sft_trainer.train(MODEL_ARGS, updated_data_path_args, TRAIN_ARGS, None)
HAPPY_PATH_DUMMY_CONFIG_PATH = os.path.join(
os.path.dirname(__file__), "build", "dummy_job_config.json"
)
# Note: job_config dict gets modified during process training args
@pytest.fixture(name="job_config", scope="session")
def fixture_job_config():
with open(HAPPY_PATH_DUMMY_CONFIG_PATH, "r", encoding="utf-8") as f:
dummy_job_config_dict = json.load(f)
return dummy_job_config_dict
############################# Arg Parsing Tests #############################
def test_parse_arguments(job_config):
parser = sft_trainer.get_parser()
job_config_copy = copy.deepcopy(job_config)
(
model_args,
data_args,
training_args,
_,
tune_config,
_,
_,
_,
_,
_,
_,
_,
_,
_,
) = sft_trainer.parse_arguments(parser, job_config_copy)
assert str(model_args.torch_dtype) == "torch.bfloat16"
assert data_args.dataset_text_field == "output"
assert training_args.output_dir == "bloom-twitter"
assert tune_config is None
def test_parse_arguments_defaults(job_config):
parser = sft_trainer.get_parser()
job_config_defaults = copy.deepcopy(job_config)
assert "torch_dtype" not in job_config_defaults
assert job_config_defaults["use_flash_attn"] is False
assert "save_strategy" not in job_config_defaults
(
model_args,
_,
training_args,
_,
_,
_,
_,
_,
_,
_,
_,
_,
_,
_,
) = sft_trainer.parse_arguments(parser, job_config_defaults)
assert str(model_args.torch_dtype) == "torch.bfloat16"
assert model_args.use_flash_attn is False
assert training_args.save_strategy.value == "epoch"
def test_parse_arguments_peft_method(job_config):
parser = sft_trainer.get_parser()
job_config_pt = copy.deepcopy(job_config)
job_config_pt["peft_method"] = "pt"
_, _, _, _, tune_config, _, _, _, _, _, _, _, _, _ = sft_trainer.parse_arguments(
parser, job_config_pt
)
assert isinstance(tune_config, peft_config.PromptTuningConfig)
job_config_lora = copy.deepcopy(job_config)
job_config_lora["peft_method"] = "lora"
_, _, _, _, tune_config, _, _, _, _, _, _, _, _, _ = sft_trainer.parse_arguments(
parser, job_config_lora
)
assert isinstance(tune_config, peft_config.LoraConfig)
assert not tune_config.target_modules
assert "target_modules" not in job_config_lora
############################# Prompt Tuning Tests #############################
def test_run_causallm_pt_and_inference():
"""Check if we can bootstrap and peft tune causallm models"""
with tempfile.TemporaryDirectory() as tempdir:
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
sft_trainer.train(MODEL_ARGS, DATA_ARGS, train_args, PEFT_PT_ARGS)
# validate peft tuning configs
_validate_training(tempdir)
checkpoint_path = _get_checkpoint_path(tempdir)
adapter_config = _get_adapter_config(checkpoint_path)
_validate_adapter_config(
adapter_config, "PROMPT_TUNING", MODEL_ARGS.model_name_or_path
)
# Load the model
loaded_model = TunedCausalLM.load(checkpoint_path, MODEL_NAME)
# Run inference on the text
output_inference = loaded_model.run(
"### Text: @NortonSupport Thanks much.\n\n### Label:", max_new_tokens=50
)
assert len(output_inference) > 0
assert "### Text: @NortonSupport Thanks much.\n\n### Label:" in output_inference
def test_run_causallm_pt_and_inference_with_formatting_data():
"""Check if we can bootstrap and peft tune causallm models
This test needs the trainer to format data to a single sequence internally.
"""
with tempfile.TemporaryDirectory() as tempdir:
data_formatting_args = copy.deepcopy(DATA_ARGS)
data_formatting_args.dataset_text_field = None
data_formatting_args.data_formatter_template = (
"### Text: {{Tweet text}} \n\n### Label: {{text_label}}"
)
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
sft_trainer.train(MODEL_ARGS, data_formatting_args, train_args, PEFT_PT_ARGS)
# validate peft tuning configs
_validate_training(tempdir)
checkpoint_path = _get_checkpoint_path(tempdir)
adapter_config = _get_adapter_config(checkpoint_path)
_validate_adapter_config(
adapter_config, "PROMPT_TUNING", MODEL_ARGS.model_name_or_path
)
# Load the model
loaded_model = TunedCausalLM.load(checkpoint_path, MODEL_NAME)
# Run inference on the text
output_inference = loaded_model.run(
"### Text: @NortonSupport Thanks much.\n\n### Label:", max_new_tokens=50
)
assert len(output_inference) > 0
assert "### Text: @NortonSupport Thanks much.\n\n### Label:" in output_inference
def test_run_causallm_pt_and_inference_JSON_file_formatter():
"""Check if we can bootstrap and peft tune causallm models with JSON train file format"""
with tempfile.TemporaryDirectory() as tempdir:
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
data_args = copy.deepcopy(DATA_ARGS)
data_args.training_data_path = TWITTER_COMPLAINTS_DATA_JSON
data_args.dataset_text_field = None
data_args.data_formatter_template = (
"### Text: {{Tweet text}} \n\n### Label: {{text_label}}"
)
sft_trainer.train(MODEL_ARGS, data_args, train_args, PEFT_PT_ARGS)
# validate peft tuning configs
_validate_training(tempdir)
checkpoint_path = _get_checkpoint_path(tempdir)
adapter_config = _get_adapter_config(checkpoint_path)
_validate_adapter_config(
adapter_config, "PROMPT_TUNING", MODEL_ARGS.model_name_or_path
)
# Load the model
loaded_model = TunedCausalLM.load(checkpoint_path, MODEL_NAME)
# Run inference on the text
output_inference = loaded_model.run(
"### Text: @NortonSupport Thanks much.\n\n### Label:", max_new_tokens=50
)
assert len(output_inference) > 0
assert "### Text: @NortonSupport Thanks much.\n\n### Label:" in output_inference
def test_run_causallm_pt_init_text():
"""Check if we can bootstrap and peft tune causallm models with init text as 'TEXT'"""
with tempfile.TemporaryDirectory() as tempdir:
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
tuning_config = peft_config.PromptTuningConfig(
prompt_tuning_init="TEXT",
prompt_tuning_init_text="hello",
)
sft_trainer.train(MODEL_ARGS, DATA_ARGS, train_args, tuning_config)
# validate peft tuning configs
_validate_training(tempdir)
checkpoint_path = _get_checkpoint_path(tempdir)
adapter_config = _get_adapter_config(checkpoint_path)
_validate_adapter_config(
adapter_config, "PROMPT_TUNING", MODEL_ARGS.model_name_or_path
)
invalid_params_map = [
("num_train_epochs", 0, "num_train_epochs has to be an integer/float >= 1"),
(
"gradient_accumulation_steps",
0,
"gradient_accumulation_steps has to be an integer >= 1",
),
]
@pytest.mark.parametrize(
"param_name,param_val,exc_msg",
invalid_params_map,
ids=["num_train_epochs", "grad_acc_steps"],
)
def test_run_causallm_pt_invalid_train_params(param_name, param_val, exc_msg):
"""Check if error is raised when invalid params are used to peft tune causallm models"""
with tempfile.TemporaryDirectory() as tempdir:
invalid_params = copy.deepcopy(TRAIN_ARGS)
invalid_params.output_dir = tempdir
setattr(invalid_params, param_name, param_val)
with pytest.raises(ValueError, match=exc_msg):
sft_trainer.train(MODEL_ARGS, DATA_ARGS, invalid_params, PEFT_PT_ARGS)
@pytest.mark.parametrize(
"dataset_path",
[TWITTER_COMPLAINTS_DATA_JSONL, TWITTER_COMPLAINTS_DATA_JSON],
)
def test_run_causallm_pt_with_validation(dataset_path):
"""Check if we can bootstrap and peft tune causallm models with validation dataset"""
with tempfile.TemporaryDirectory() as tempdir:
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
train_args.eval_strategy = "epoch"
data_args = copy.deepcopy(DATA_ARGS)
data_args.validation_data_path = dataset_path
sft_trainer.train(MODEL_ARGS, data_args, train_args, PEFT_PT_ARGS)
_validate_training(tempdir, check_eval=True)
@pytest.mark.parametrize(
"dataset_path",
[TWITTER_COMPLAINTS_DATA_JSONL, TWITTER_COMPLAINTS_DATA_JSON],
)
def test_run_causallm_pt_with_validation_data_formatting(dataset_path):
"""Check if we can bootstrap and peft tune causallm models with validation dataset"""
with tempfile.TemporaryDirectory() as tempdir:
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
train_args.eval_strategy = "epoch"
data_args = copy.deepcopy(DATA_ARGS)
data_args.validation_data_path = dataset_path
data_args.dataset_text_field = None
data_args.data_formatter_template = (
"### Text: {{Tweet text}} \n\n### Label: {{text_label}}"
)
sft_trainer.train(MODEL_ARGS, data_args, train_args, PEFT_PT_ARGS)
_validate_training(tempdir, check_eval=True)
@pytest.mark.parametrize(
"dataset_path",
[TWITTER_COMPLAINTS_DATA_JSONL, TWITTER_COMPLAINTS_DATA_JSON],
)
def test_run_causallm_pt_with_custom_tokenizer(dataset_path):
"""Check if we fail when custom tokenizer not having pad token is used in prompt tuning"""
with tempfile.TemporaryDirectory() as tempdir:
train_args = copy.deepcopy(TRAIN_ARGS)
model_args = copy.deepcopy(MODEL_ARGS)
model_args.tokenizer_name_or_path = model_args.model_name_or_path
train_args.output_dir = tempdir
train_args.eval_strategy = "epoch"
data_args = copy.deepcopy(DATA_ARGS)
data_args.validation_data_path = dataset_path
with pytest.raises(ValueError):
sft_trainer.train(model_args, data_args, train_args, PEFT_PT_ARGS)
############################# Lora Tests #############################
target_modules_val_map = [
(None, ["q_proj", "v_proj"]),
(
["q_proj", "k_proj", "v_proj", "o_proj"],
["q_proj", "k_proj", "v_proj", "o_proj"],
),
(
["all-linear"],
["o_proj", "q_proj", "gate_proj", "down_proj", "k_proj", "up_proj", "v_proj"],
),
]
@pytest.mark.parametrize(
"target_modules,expected",
target_modules_val_map,
ids=["default", "custom_target_modules", "all_linear_target_modules"],
)
def test_run_causallm_lora_and_inference(request, target_modules, expected):
"""Check if we can bootstrap and lora tune causallm models"""
with tempfile.TemporaryDirectory() as tempdir:
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
base_lora_args = copy.deepcopy(PEFT_LORA_ARGS)
if "default" not in request._pyfuncitem.callspec.id:
base_lora_args.target_modules = target_modules
sft_trainer.train(MODEL_ARGS, DATA_ARGS, train_args, base_lora_args)
# validate lora tuning configs
_validate_training(tempdir)
checkpoint_path = _get_checkpoint_path(tempdir)
adapter_config = _get_adapter_config(checkpoint_path)
_validate_adapter_config(adapter_config, "LORA")
for module in expected:
assert module in adapter_config.get("target_modules")
# Load the model
loaded_model = TunedCausalLM.load(checkpoint_path, MODEL_NAME)
# Run inference on the text
output_inference = loaded_model.run(
"Simply put, the theory of relativity states that ", max_new_tokens=50
)
assert len(output_inference) > 0
assert "Simply put, the theory of relativity states that" in output_inference
def test_successful_lora_target_modules_default_from_main():
"""Check that if target_modules is not set, or set to None via JSON, the
default value by model type will be using in LoRA tuning.
The correct default target modules will be used for model type llama
and will exist in the resulting adapter_config.json.
https://github.com/huggingface/peft/blob/7b1c08d2b5e13d3c99b7d6ee83eab90e1216d4ba/
src/peft/tuners/lora/model.py#L432
"""
with tempfile.TemporaryDirectory() as tempdir:
TRAIN_KWARGS = {
**MODEL_ARGS.__dict__,
**TRAIN_ARGS.__dict__,
**DATA_ARGS.__dict__,
**PEFT_LORA_ARGS.__dict__,
**{"peft_method": "lora", "output_dir": tempdir},
}
serialized_args = serialize_args(TRAIN_KWARGS)
os.environ["SFT_TRAINER_CONFIG_JSON_ENV_VAR"] = serialized_args
sft_trainer.main()
_validate_training(tempdir)
# Calling LoRA tuning from the main results in 'added_tokens_info.json'
assert "added_tokens_info.json" in os.listdir(tempdir)
checkpoint_path = _get_checkpoint_path(tempdir)
adapter_config = _get_adapter_config(checkpoint_path)
_validate_adapter_config(adapter_config, "LORA")
assert (
"target_modules" in adapter_config
), "target_modules not found in adapter_config.json."
assert set(adapter_config.get("target_modules")) == {
"q_proj",
"v_proj",
}, "target_modules are not set to the default values."
############################# Finetuning Tests #############################
@pytest.mark.parametrize(
"dataset_path",
[
TWITTER_COMPLAINTS_DATA_JSONL,
TWITTER_COMPLAINTS_DATA_JSON,
TWITTER_COMPLAINTS_DATA_PARQUET,
TWITTER_COMPLAINTS_DATA_ARROW,
],
)
def test_run_causallm_ft_and_inference(dataset_path):
"""Check if we can bootstrap and finetune causallm models with different data formats"""
with tempfile.TemporaryDirectory() as tempdir:
data_args = copy.deepcopy(DATA_ARGS)
data_args.training_data_path = dataset_path
_test_run_causallm_ft(TRAIN_ARGS, MODEL_ARGS, data_args, tempdir)
_test_run_inference(checkpoint_path=_get_checkpoint_path(tempdir))
def test_run_causallm_ft_save_with_save_model_dir_save_strategy_no():
"""Check if we can bootstrap and finetune causallm model with save_model_dir
and save_strategy=no. Verify no checkpoints created and can save model.
"""
with tempfile.TemporaryDirectory() as tempdir:
save_model_args = copy.deepcopy(TRAIN_ARGS)
save_model_args.save_strategy = "no"
save_model_args.output_dir = tempdir
trainer, _ = sft_trainer.train(MODEL_ARGS, DATA_ARGS, save_model_args, None)
logs_path = os.path.join(
tempdir, FileLoggingTrackerConfig.training_logs_filename
)
_validate_logfile(logs_path)
# validate that no checkpoints created
assert not any(x.startswith("checkpoint-") for x in os.listdir(tempdir))
sft_trainer.save(tempdir, trainer, "debug")
assert any(x.endswith(".safetensors") for x in os.listdir(tempdir))
_test_run_inference(checkpoint_path=tempdir)
@pytest.mark.parametrize(
"dataset_path",
[
TWITTER_COMPLAINTS_TOKENIZED_JSONL,
TWITTER_COMPLAINTS_TOKENIZED_JSON,
TWITTER_COMPLAINTS_TOKENIZED_PARQUET,
TWITTER_COMPLAINTS_TOKENIZED_ARROW,
],
)
def test_run_causallm_ft_pretokenized(dataset_path):
"""Check if we can bootstrap and finetune causallm models using pretokenized data"""
with tempfile.TemporaryDirectory() as tempdir:
data_formatting_args = copy.deepcopy(DATA_ARGS)
# below args not needed for pretokenized data
data_formatting_args.data_formatter_template = None
data_formatting_args.dataset_text_field = None
data_formatting_args.response_template = None
# update the training data path to tokenized data
data_formatting_args.training_data_path = dataset_path
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
sft_trainer.train(MODEL_ARGS, data_formatting_args, train_args)
# validate full ft configs
_validate_training(tempdir)
checkpoint_path = _get_checkpoint_path(tempdir)
# Load the model
loaded_model = TunedCausalLM.load(checkpoint_path, MODEL_NAME)
# Run inference on the text
output_inference = loaded_model.run(
"### Text: @NortonSupport Thanks much.\n\n### Label:", max_new_tokens=50
)
assert len(output_inference) > 0
assert "### Text: @NortonSupport Thanks much.\n\n### Label:" in output_inference
@pytest.mark.parametrize(
"datafiles, datasetconfigname",
[
(
[TWITTER_COMPLAINTS_DATA_DIR_JSON],
DATA_CONFIG_TOKENIZE_AND_APPLY_INPUT_MASKING_YAML,
),
(
[
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_JSON,
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_JSON,
],
DATA_CONFIG_MULTIPLE_DATASETS_SAMPLING_YAML,
),
(
[
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_JSON,
TWITTER_COMPLAINTS_DATA_DIR_JSON,
],
DATA_CONFIG_MULTIPLE_DATASETS_SAMPLING_YAML,
),
(
[
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_JSONL,
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_JSONL,
],
DATA_CONFIG_MULTIPLE_DATASETS_SAMPLING_YAML,
),
(
[
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_ARROW,
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_ARROW,
],
DATA_CONFIG_MULTIPLE_DATASETS_SAMPLING_YAML,
),
(
[
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_PARQUET,
TWITTER_COMPLAINTS_DATA_INPUT_OUTPUT_PARQUET,
],
DATA_CONFIG_MULTIPLE_DATASETS_SAMPLING_YAML,
),
],
)
def test_run_causallm_ft_and_inference_with_multiple_dataset(
datasetconfigname, datafiles
):
"""Check if we can finetune causallm models using multiple datasets with multiple files"""
with tempfile.TemporaryDirectory() as tempdir:
data_formatting_args = copy.deepcopy(DATA_ARGS)
# set training_data_path and response_template to none
data_formatting_args.response_template = None
data_formatting_args.training_data_path = None
# add data_paths in data_config file
with tempfile.NamedTemporaryFile(
"w", delete=False, suffix=".yaml"
) as temp_yaml_file:
with open(datasetconfigname, "r", encoding="utf-8") as f:
data = yaml.safe_load(f)
datasets = data["datasets"]
for _, d in enumerate(datasets):
d["data_paths"] = datafiles
yaml.dump(data, temp_yaml_file)
data_formatting_args.data_config_path = temp_yaml_file.name
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
sft_trainer.train(MODEL_ARGS, data_formatting_args, train_args)
# validate full ft configs
_validate_training(tempdir)
_, checkpoint_path = _get_latest_checkpoint_trainer_state(tempdir)
# Load the model
loaded_model = TunedCausalLM.load(checkpoint_path, MODEL_NAME)
# Run inference on the text
output_inference = loaded_model.run(
"### Text: @NortonSupport Thanks much.\n\n### Label:", max_new_tokens=50
)
assert len(output_inference) > 0
assert "### Text: @NortonSupport Thanks much.\n\n### Label:" in output_inference
@pytest.mark.parametrize(
"dataset_path",
[CHAT_DATA_SINGLE_TURN, CHAT_DATA_MULTI_TURN],
)
def test_run_chat_style_ft(dataset_path):
"""Check if we can perform an e2e run with chat template and multi turn chat training."""
with tempfile.TemporaryDirectory() as tempdir:
data_args = copy.deepcopy(DATA_ARGS)
data_args.training_data_path = dataset_path
data_args.chat_template = "{% for message in messages['messages'] %}\
{% if message['role'] == 'user' %}{{ '<|user|>\n' + message['content'] + eos_token }}\
{% elif message['role'] == 'system' %}{{ '<|system|>\n' + message['content'] + eos_token }}\
{% elif message['role'] == 'assistant' %}{{ '<|assistant|>\n' + message['content'] + eos_token }}\
{% endif %}\
{% if loop.last and add_generation_prompt %}{{ '<|assistant|>' }}\
{% endif %}\
{% endfor %}"
data_args.response_template = "<|assistant|>"
data_args.instruction_template = "<|user|>"
model_args = copy.deepcopy(MODEL_ARGS)
model_args.tokenizer_name_or_path = CUSTOM_TOKENIZER_TINYLLAMA
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
sft_trainer.train(model_args, data_args, train_args)
# validate the configs
_validate_training(tempdir)
checkpoint_path = _get_checkpoint_path(tempdir)
# Load the model
loaded_model = TunedCausalLM.load(checkpoint_path, MODEL_NAME)
# Run inference on the text
output_inference = loaded_model.run(
'<|user|>\nProvide two rhyming words for the word "love"\n\
<nopace></s><|assistant|>',
max_new_tokens=50,
)
assert len(output_inference) > 0
assert 'Provide two rhyming words for the word "love"' in output_inference
@pytest.mark.parametrize(
"datafiles, dataconfigfile",
[
(
[CHAT_DATA_SINGLE_TURN, CHAT_DATA_MULTI_TURN, CHAT_DATA_SINGLE_TURN],
DATA_CONFIG_MULTIPLE_DATASETS_SAMPLING_YAML,
)
],
)
def test_run_chat_style_ft_using_dataconfig(datafiles, dataconfigfile):
"""Check if we can perform an e2e run with chat template
and multi turn chat training using data config."""
with tempfile.TemporaryDirectory() as tempdir:
data_args = copy.deepcopy(DATA_ARGS)
data_args.chat_template = "{% for message in messages['messages'] %}\
{% if message['role'] == 'user' %}{{ '<|user|>\n' + message['content'] + eos_token }}\
{% elif message['role'] == 'system' %}{{ '<|system|>\n' + message['content'] + eos_token }}\
{% elif message['role'] == 'assistant' %}{{ '<|assistant|>\n' + message['content'] + eos_token }}\
{% endif %}\
{% if loop.last and add_generation_prompt %}{{ '<|assistant|>' }}\
{% endif %}\
{% endfor %}"
data_args.response_template = "<|assistant|>"
data_args.instruction_template = "<|user|>"
data_args.dataset_text_field = "new_formatted_field"
handler_kwargs = {"dataset_text_field": data_args.dataset_text_field}
kwargs = {
"fn_kwargs": handler_kwargs,
"batched": False,
"remove_columns": "all",
}
handler_config = DataHandlerConfig(
name="apply_tokenizer_chat_template", arguments=kwargs
)
model_args = copy.deepcopy(MODEL_ARGS)
model_args.tokenizer_name_or_path = CUSTOM_TOKENIZER_TINYLLAMA
train_args = copy.deepcopy(TRAIN_ARGS)
train_args.output_dir = tempdir
with tempfile.NamedTemporaryFile(
"w", delete=False, suffix=".yaml"
) as temp_yaml_file:
with open(dataconfigfile, "r", encoding="utf-8") as f:
data = yaml.safe_load(f)
datasets = data["datasets"]
for i, d in enumerate(datasets):
d["data_paths"] = [datafiles[i]]
# Basic chat datasets don't need data handling
d["data_handlers"] = [asdict(handler_config)]
yaml.dump(data, temp_yaml_file)
data_args.data_config_path = temp_yaml_file.name
sft_trainer.train(model_args, data_args, train_args)
# validate the configs
_validate_training(tempdir)
checkpoint_path = _get_checkpoint_path(tempdir)
# Load the model
loaded_model = TunedCausalLM.load(checkpoint_path, MODEL_NAME)
# Run inference on the text
output_inference = loaded_model.run(
'<|user|>\nProvide two rhyming words for the word "love"\n\
<nopace></s><|assistant|>',
max_new_tokens=50,
)