deployment issue
Browse files- sample_finetune.py +213 -213
sample_finetune.py
CHANGED
@@ -1,214 +1,214 @@
|
|
1 |
-
import sys
|
2 |
-
import logging
|
3 |
-
|
4 |
-
import datasets
|
5 |
-
from datasets import load_dataset
|
6 |
-
from peft import LoraConfig
|
7 |
-
import torch
|
8 |
-
import transformers
|
9 |
-
from trl import SFTTrainer
|
10 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, BitsAndBytesConfig
|
11 |
-
|
12 |
-
"""
|
13 |
-
A simple example on using SFTTrainer and Accelerate to finetune Phi-3 models. For
|
14 |
-
a more advanced example, please follow HF alignment-handbook/scripts/run_sft.py.
|
15 |
-
This example has utilized DeepSpeed ZeRO3 offload to reduce the memory usage. The
|
16 |
-
script can be run on V100 or later generation GPUs. Here are some suggestions on
|
17 |
-
futher reducing memory consumption:
|
18 |
-
- reduce batch size
|
19 |
-
- decrease lora dimension
|
20 |
-
- restrict lora target modules
|
21 |
-
Please follow these steps to run the script:
|
22 |
-
1. Install dependencies:
|
23 |
-
conda install -c conda-forge accelerate
|
24 |
-
pip3 install -i https://pypi.org/simple/ bitsandbytes
|
25 |
-
pip3 install peft transformers trl datasets
|
26 |
-
pip3 install deepspeed
|
27 |
-
2. Setup accelerate and deepspeed config based on the machine used:
|
28 |
-
accelerate config
|
29 |
-
Here is a sample config for deepspeed zero3:
|
30 |
-
compute_environment: LOCAL_MACHINE
|
31 |
-
debug: false
|
32 |
-
deepspeed_config:
|
33 |
-
gradient_accumulation_steps: 1
|
34 |
-
offload_optimizer_device: none
|
35 |
-
offload_param_device: none
|
36 |
-
zero3_init_flag: true
|
37 |
-
zero3_save_16bit_model: true
|
38 |
-
zero_stage: 3
|
39 |
-
distributed_type: DEEPSPEED
|
40 |
-
downcast_bf16: 'no'
|
41 |
-
enable_cpu_affinity: false
|
42 |
-
machine_rank: 0
|
43 |
-
main_training_function: main
|
44 |
-
mixed_precision: bf16
|
45 |
-
num_machines: 1
|
46 |
-
num_processes: 4
|
47 |
-
rdzv_backend: static
|
48 |
-
same_network: true
|
49 |
-
tpu_env: []
|
50 |
-
tpu_use_cluster: false
|
51 |
-
tpu_use_sudo: false
|
52 |
-
use_cpu: false
|
53 |
-
3. check accelerate config:
|
54 |
-
accelerate env
|
55 |
-
4. Run the code:
|
56 |
-
accelerate launch sample_finetune.py
|
57 |
-
"""
|
58 |
-
|
59 |
-
logger = logging.getLogger(__name__)
|
60 |
-
|
61 |
-
|
62 |
-
###################
|
63 |
-
# Hyper-parameters
|
64 |
-
###################
|
65 |
-
training_config = {
|
66 |
-
"bf16": True,
|
67 |
-
"do_eval": False,
|
68 |
-
"learning_rate": 5.0e-06,
|
69 |
-
"log_level": "info",
|
70 |
-
"logging_steps": 20,
|
71 |
-
"logging_strategy": "steps",
|
72 |
-
"lr_scheduler_type": "cosine",
|
73 |
-
"num_train_epochs": 1,
|
74 |
-
"max_steps": -1,
|
75 |
-
"output_dir": "./checkpoint_dir",
|
76 |
-
"overwrite_output_dir": True,
|
77 |
-
"per_device_eval_batch_size": 4,
|
78 |
-
"per_device_train_batch_size": 4,
|
79 |
-
"remove_unused_columns": True,
|
80 |
-
"save_steps": 100,
|
81 |
-
"save_total_limit": 1,
|
82 |
-
"seed": 0,
|
83 |
-
"gradient_checkpointing": True,
|
84 |
-
"gradient_checkpointing_kwargs":{"use_reentrant": False},
|
85 |
-
"gradient_accumulation_steps": 1,
|
86 |
-
"warmup_ratio": 0.2,
|
87 |
-
}
|
88 |
-
|
89 |
-
peft_config = {
|
90 |
-
"r": 16,
|
91 |
-
"lora_alpha": 32,
|
92 |
-
"lora_dropout": 0.05,
|
93 |
-
"bias": "none",
|
94 |
-
"task_type": "CAUSAL_LM",
|
95 |
-
"target_modules": "all-linear",
|
96 |
-
"modules_to_save": None,
|
97 |
-
}
|
98 |
-
train_conf = TrainingArguments(**training_config)
|
99 |
-
peft_conf = LoraConfig(**peft_config)
|
100 |
-
|
101 |
-
|
102 |
-
###############
|
103 |
-
# Setup logging
|
104 |
-
###############
|
105 |
-
logging.basicConfig(
|
106 |
-
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
107 |
-
datefmt="%Y-%m-%d %H:%M:%S",
|
108 |
-
handlers=[logging.StreamHandler(sys.stdout)],
|
109 |
-
)
|
110 |
-
log_level = train_conf.get_process_log_level()
|
111 |
-
logger.setLevel(log_level)
|
112 |
-
datasets.utils.logging.set_verbosity(log_level)
|
113 |
-
transformers.utils.logging.set_verbosity(log_level)
|
114 |
-
transformers.utils.logging.enable_default_handler()
|
115 |
-
transformers.utils.logging.enable_explicit_format()
|
116 |
-
|
117 |
-
# Log on each process a small summary
|
118 |
-
logger.warning(
|
119 |
-
f"Process rank: {train_conf.local_rank}, device: {train_conf.device}, n_gpu: {train_conf.n_gpu}"
|
120 |
-
+ f" distributed training: {bool(train_conf.local_rank != -1)}, 16-bits training: {train_conf.fp16}"
|
121 |
-
)
|
122 |
-
logger.info(f"Training/evaluation parameters {train_conf}")
|
123 |
-
logger.info(f"PEFT parameters {peft_conf}")
|
124 |
-
|
125 |
-
|
126 |
-
################
|
127 |
-
# Model Loading
|
128 |
-
################
|
129 |
-
# checkpoint_path = "microsoft/Phi-3-mini-4k-instruct"
|
130 |
-
checkpoint_path = "microsoft/Phi-3-mini-128k-instruct"
|
131 |
-
model_kwargs = dict(
|
132 |
-
use_cache=False,
|
133 |
-
trust_remote_code=True,
|
134 |
-
attn_implementation="flash_attention_2", # loading the model with flash-attenstion support
|
135 |
-
torch_dtype=torch.bfloat16,
|
136 |
-
device_map=None
|
137 |
-
)
|
138 |
-
model = AutoModelForCausalLM.from_pretrained(checkpoint_path, **model_kwargs)
|
139 |
-
tokenizer = AutoTokenizer.from_pretrained(checkpoint_path)
|
140 |
-
tokenizer.model_max_length = 2048
|
141 |
-
tokenizer.pad_token = tokenizer.unk_token # use unk rather than eos token to prevent endless generation
|
142 |
-
tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token)
|
143 |
-
tokenizer.padding_side = 'right'
|
144 |
-
|
145 |
-
|
146 |
-
##################
|
147 |
-
# Data Processing
|
148 |
-
##################
|
149 |
-
def apply_chat_template(
|
150 |
-
example,
|
151 |
-
tokenizer,
|
152 |
-
):
|
153 |
-
messages = example["messages"]
|
154 |
-
example["text"] = tokenizer.apply_chat_template(
|
155 |
-
messages, tokenize=False, add_generation_prompt=False)
|
156 |
-
return example
|
157 |
-
|
158 |
-
raw_dataset = load_dataset("HuggingFaceH4/ultrachat_200k")
|
159 |
-
train_dataset = raw_dataset["train_sft"]
|
160 |
-
test_dataset = raw_dataset["test_sft"]
|
161 |
-
column_names = list(train_dataset.features)
|
162 |
-
|
163 |
-
processed_train_dataset = train_dataset.map(
|
164 |
-
apply_chat_template,
|
165 |
-
fn_kwargs={"tokenizer": tokenizer},
|
166 |
-
num_proc=10,
|
167 |
-
remove_columns=column_names,
|
168 |
-
desc="Applying chat template to train_sft",
|
169 |
-
)
|
170 |
-
|
171 |
-
processed_test_dataset = test_dataset.map(
|
172 |
-
apply_chat_template,
|
173 |
-
fn_kwargs={"tokenizer": tokenizer},
|
174 |
-
num_proc=10,
|
175 |
-
remove_columns=column_names,
|
176 |
-
desc="Applying chat template to test_sft",
|
177 |
-
)
|
178 |
-
|
179 |
-
|
180 |
-
###########
|
181 |
-
# Training
|
182 |
-
###########
|
183 |
-
trainer = SFTTrainer(
|
184 |
-
model=model,
|
185 |
-
args=train_conf,
|
186 |
-
peft_config=peft_conf,
|
187 |
-
train_dataset=processed_train_dataset,
|
188 |
-
eval_dataset=processed_test_dataset,
|
189 |
-
max_seq_length=2048,
|
190 |
-
dataset_text_field="text",
|
191 |
-
tokenizer=tokenizer,
|
192 |
-
packing=True
|
193 |
-
)
|
194 |
-
train_result = trainer.train()
|
195 |
-
metrics = train_result.metrics
|
196 |
-
trainer.log_metrics("train", metrics)
|
197 |
-
trainer.save_metrics("train", metrics)
|
198 |
-
trainer.save_state()
|
199 |
-
|
200 |
-
|
201 |
-
#############
|
202 |
-
# Evaluation
|
203 |
-
#############
|
204 |
-
tokenizer.padding_side = 'left'
|
205 |
-
metrics = trainer.evaluate()
|
206 |
-
metrics["eval_samples"] = len(processed_test_dataset)
|
207 |
-
trainer.log_metrics("eval", metrics)
|
208 |
-
trainer.save_metrics("eval", metrics)
|
209 |
-
|
210 |
-
|
211 |
-
# ############
|
212 |
-
# # Save model
|
213 |
-
# ############
|
214 |
trainer.save_model(train_conf.output_dir)
|
|
|
1 |
+
import sys
|
2 |
+
import logging
|
3 |
+
|
4 |
+
import datasets
|
5 |
+
from datasets import load_dataset
|
6 |
+
from peft import LoraConfig
|
7 |
+
import torch
|
8 |
+
import transformers
|
9 |
+
from trl import SFTTrainer
|
10 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, BitsAndBytesConfig
|
11 |
+
|
12 |
+
"""
|
13 |
+
A simple example on using SFTTrainer and Accelerate to finetune Phi-3 models. For
|
14 |
+
a more advanced example, please follow HF alignment-handbook/scripts/run_sft.py.
|
15 |
+
This example has utilized DeepSpeed ZeRO3 offload to reduce the memory usage. The
|
16 |
+
script can be run on V100 or later generation GPUs. Here are some suggestions on
|
17 |
+
futher reducing memory consumption:
|
18 |
+
- reduce batch size
|
19 |
+
- decrease lora dimension
|
20 |
+
- restrict lora target modules
|
21 |
+
Please follow these steps to run the script:
|
22 |
+
1. Install dependencies:
|
23 |
+
conda install -c conda-forge accelerate
|
24 |
+
pip3 install -i https://pypi.org/simple/ bitsandbytes
|
25 |
+
pip3 install peft transformers trl datasets
|
26 |
+
pip3 install deepspeed
|
27 |
+
2. Setup accelerate and deepspeed config based on the machine used:
|
28 |
+
accelerate config
|
29 |
+
Here is a sample config for deepspeed zero3:
|
30 |
+
compute_environment: LOCAL_MACHINE
|
31 |
+
debug: false
|
32 |
+
deepspeed_config:
|
33 |
+
gradient_accumulation_steps: 1
|
34 |
+
offload_optimizer_device: none
|
35 |
+
offload_param_device: none
|
36 |
+
zero3_init_flag: true
|
37 |
+
zero3_save_16bit_model: true
|
38 |
+
zero_stage: 3
|
39 |
+
distributed_type: DEEPSPEED
|
40 |
+
downcast_bf16: 'no'
|
41 |
+
enable_cpu_affinity: false
|
42 |
+
machine_rank: 0
|
43 |
+
main_training_function: main
|
44 |
+
mixed_precision: bf16
|
45 |
+
num_machines: 1
|
46 |
+
num_processes: 4
|
47 |
+
rdzv_backend: static
|
48 |
+
same_network: true
|
49 |
+
tpu_env: []
|
50 |
+
tpu_use_cluster: false
|
51 |
+
tpu_use_sudo: false
|
52 |
+
use_cpu: false
|
53 |
+
3. check accelerate config:
|
54 |
+
accelerate env
|
55 |
+
4. Run the code:
|
56 |
+
accelerate launch sample_finetune.py
|
57 |
+
"""
|
58 |
+
|
59 |
+
logger = logging.getLogger(__name__)
|
60 |
+
|
61 |
+
|
62 |
+
###################
|
63 |
+
# Hyper-parameters
|
64 |
+
###################
|
65 |
+
training_config = {
|
66 |
+
"bf16": True,
|
67 |
+
"do_eval": False,
|
68 |
+
"learning_rate": 5.0e-06,
|
69 |
+
"log_level": "info",
|
70 |
+
"logging_steps": 20,
|
71 |
+
"logging_strategy": "steps",
|
72 |
+
"lr_scheduler_type": "cosine",
|
73 |
+
"num_train_epochs": 1,
|
74 |
+
"max_steps": -1,
|
75 |
+
"output_dir": "./checkpoint_dir",
|
76 |
+
"overwrite_output_dir": True,
|
77 |
+
"per_device_eval_batch_size": 4,
|
78 |
+
"per_device_train_batch_size": 4,
|
79 |
+
"remove_unused_columns": True,
|
80 |
+
"save_steps": 100,
|
81 |
+
"save_total_limit": 1,
|
82 |
+
"seed": 0,
|
83 |
+
"gradient_checkpointing": True,
|
84 |
+
"gradient_checkpointing_kwargs":{"use_reentrant": False},
|
85 |
+
"gradient_accumulation_steps": 1,
|
86 |
+
"warmup_ratio": 0.2,
|
87 |
+
}
|
88 |
+
|
89 |
+
peft_config = {
|
90 |
+
"r": 16,
|
91 |
+
"lora_alpha": 32,
|
92 |
+
"lora_dropout": 0.05,
|
93 |
+
"bias": "none",
|
94 |
+
"task_type": "CAUSAL_LM",
|
95 |
+
"target_modules": "all-linear",
|
96 |
+
"modules_to_save": None,
|
97 |
+
}
|
98 |
+
train_conf = TrainingArguments(**training_config)
|
99 |
+
peft_conf = LoraConfig(**peft_config)
|
100 |
+
|
101 |
+
|
102 |
+
###############
|
103 |
+
# Setup logging
|
104 |
+
###############
|
105 |
+
logging.basicConfig(
|
106 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
107 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
108 |
+
handlers=[logging.StreamHandler(sys.stdout)],
|
109 |
+
)
|
110 |
+
log_level = train_conf.get_process_log_level()
|
111 |
+
logger.setLevel(log_level)
|
112 |
+
datasets.utils.logging.set_verbosity(log_level)
|
113 |
+
transformers.utils.logging.set_verbosity(log_level)
|
114 |
+
transformers.utils.logging.enable_default_handler()
|
115 |
+
transformers.utils.logging.enable_explicit_format()
|
116 |
+
|
117 |
+
# Log on each process a small summary
|
118 |
+
logger.warning(
|
119 |
+
f"Process rank: {train_conf.local_rank}, device: {train_conf.device}, n_gpu: {train_conf.n_gpu}"
|
120 |
+
+ f" distributed training: {bool(train_conf.local_rank != -1)}, 16-bits training: {train_conf.fp16}"
|
121 |
+
)
|
122 |
+
logger.info(f"Training/evaluation parameters {train_conf}")
|
123 |
+
logger.info(f"PEFT parameters {peft_conf}")
|
124 |
+
|
125 |
+
|
126 |
+
################
|
127 |
+
# Model Loading
|
128 |
+
################
|
129 |
+
# checkpoint_path = "microsoft/Phi-3-mini-4k-instruct"
|
130 |
+
checkpoint_path = "microsoft/Phi-3-mini-128k-instruct"
|
131 |
+
model_kwargs = dict(
|
132 |
+
use_cache=False,
|
133 |
+
trust_remote_code=True,
|
134 |
+
attn_implementation="flash_attention_2", # loading the model with flash-attenstion support
|
135 |
+
torch_dtype=torch.bfloat16,
|
136 |
+
device_map=None
|
137 |
+
)
|
138 |
+
model = AutoModelForCausalLM.from_pretrained(checkpoint_path, **model_kwargs, trust_remote_code=True)
|
139 |
+
tokenizer = AutoTokenizer.from_pretrained(checkpoint_path)
|
140 |
+
tokenizer.model_max_length = 2048
|
141 |
+
tokenizer.pad_token = tokenizer.unk_token # use unk rather than eos token to prevent endless generation
|
142 |
+
tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids(tokenizer.pad_token)
|
143 |
+
tokenizer.padding_side = 'right'
|
144 |
+
|
145 |
+
|
146 |
+
##################
|
147 |
+
# Data Processing
|
148 |
+
##################
|
149 |
+
def apply_chat_template(
|
150 |
+
example,
|
151 |
+
tokenizer,
|
152 |
+
):
|
153 |
+
messages = example["messages"]
|
154 |
+
example["text"] = tokenizer.apply_chat_template(
|
155 |
+
messages, tokenize=False, add_generation_prompt=False)
|
156 |
+
return example
|
157 |
+
|
158 |
+
raw_dataset = load_dataset("HuggingFaceH4/ultrachat_200k")
|
159 |
+
train_dataset = raw_dataset["train_sft"]
|
160 |
+
test_dataset = raw_dataset["test_sft"]
|
161 |
+
column_names = list(train_dataset.features)
|
162 |
+
|
163 |
+
processed_train_dataset = train_dataset.map(
|
164 |
+
apply_chat_template,
|
165 |
+
fn_kwargs={"tokenizer": tokenizer},
|
166 |
+
num_proc=10,
|
167 |
+
remove_columns=column_names,
|
168 |
+
desc="Applying chat template to train_sft",
|
169 |
+
)
|
170 |
+
|
171 |
+
processed_test_dataset = test_dataset.map(
|
172 |
+
apply_chat_template,
|
173 |
+
fn_kwargs={"tokenizer": tokenizer},
|
174 |
+
num_proc=10,
|
175 |
+
remove_columns=column_names,
|
176 |
+
desc="Applying chat template to test_sft",
|
177 |
+
)
|
178 |
+
|
179 |
+
|
180 |
+
###########
|
181 |
+
# Training
|
182 |
+
###########
|
183 |
+
trainer = SFTTrainer(
|
184 |
+
model=model,
|
185 |
+
args=train_conf,
|
186 |
+
peft_config=peft_conf,
|
187 |
+
train_dataset=processed_train_dataset,
|
188 |
+
eval_dataset=processed_test_dataset,
|
189 |
+
max_seq_length=2048,
|
190 |
+
dataset_text_field="text",
|
191 |
+
tokenizer=tokenizer,
|
192 |
+
packing=True
|
193 |
+
)
|
194 |
+
train_result = trainer.train()
|
195 |
+
metrics = train_result.metrics
|
196 |
+
trainer.log_metrics("train", metrics)
|
197 |
+
trainer.save_metrics("train", metrics)
|
198 |
+
trainer.save_state()
|
199 |
+
|
200 |
+
|
201 |
+
#############
|
202 |
+
# Evaluation
|
203 |
+
#############
|
204 |
+
tokenizer.padding_side = 'left'
|
205 |
+
metrics = trainer.evaluate()
|
206 |
+
metrics["eval_samples"] = len(processed_test_dataset)
|
207 |
+
trainer.log_metrics("eval", metrics)
|
208 |
+
trainer.save_metrics("eval", metrics)
|
209 |
+
|
210 |
+
|
211 |
+
# ############
|
212 |
+
# # Save model
|
213 |
+
# ############
|
214 |
trainer.save_model(train_conf.output_dir)
|