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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
#This is the script used to finetune the scikit-llm model.
|
| 5 |
+
#It also contains all the hyperparameters used for training and should be fully reproducible.
|
| 6 |
+
|
| 7 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 8 |
+
|
| 9 |
+
print(device)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
from datasets import load_dataset
|
| 13 |
+
from transformers import (
|
| 14 |
+
AutoModelForCausalLM,
|
| 15 |
+
AutoTokenizer,
|
| 16 |
+
BitsAndBytesConfig,
|
| 17 |
+
HfArgumentParser,
|
| 18 |
+
TrainingArguments,
|
| 19 |
+
pipeline,
|
| 20 |
+
logging,
|
| 21 |
+
LlamaTokenizerFast
|
| 22 |
+
)
|
| 23 |
+
from peft import LoraConfig, PeftModel, get_peft_model
|
| 24 |
+
from trl import SFTTrainer
|
| 25 |
+
|
| 26 |
+
# We use a previously finetuned model of Mistral, Mistral-Hermes.
|
| 27 |
+
#It already includes many instruction-based features (including the chatml syntax) that makes it easier to finetune.
|
| 28 |
+
model_name = "mistral-hermes-2.5"
|
| 29 |
+
|
| 30 |
+
torch.cuda.empty_cache()
|
| 31 |
+
|
| 32 |
+
# The name of the model.
|
| 33 |
+
new_model_name = "mistral-skikit-reference"
|
| 34 |
+
|
| 35 |
+
# The output directory where the model predictions and checkpoints will be written
|
| 36 |
+
output_dir = "./mistral-skikit-reference"
|
| 37 |
+
|
| 38 |
+
# Tensorboard logs
|
| 39 |
+
tb_log_dir = "./mistral-skikit-reference/logs"
|
| 40 |
+
|
| 41 |
+
# The number of steps. Since we chose a lower learning rate, we took on a long training (8 epochs). Could be lower.
|
| 42 |
+
max_steps = 1200
|
| 43 |
+
|
| 44 |
+
# Les paramètres importants !!
|
| 45 |
+
per_device_train_batch_size = 4 #Number of batches to send per step. Optimal given our GPU vram.
|
| 46 |
+
learning_rate = 2e-5 #The most important hyperparmater. We take a lower value as mistral-hermes is already finetuned and we want to keep the capacities.
|
| 47 |
+
max_seq_length = 4096 #Context window length. Here we are constrained by Hermes, but Mistral is up to 8128 (32k in the new version)
|
| 48 |
+
save_steps = 1000 # Automated saving of the steps.
|
| 49 |
+
lr_scheduler_type = "linear" #Learning rate scheduler. Better to decrease the learning rate for long training. I prefer linear over to cosine as it is more predictable: easier to restart training if needed.
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
#Other parameters. I don't usually tweak thoses.
|
| 53 |
+
local_rank = -1
|
| 54 |
+
per_device_eval_batch_size = 1
|
| 55 |
+
gradient_accumulation_steps = 4
|
| 56 |
+
max_grad_norm = 0.3
|
| 57 |
+
weight_decay = 0.001
|
| 58 |
+
lora_alpha = 16
|
| 59 |
+
lora_dropout = 0.1
|
| 60 |
+
lora_r = 64
|
| 61 |
+
|
| 62 |
+
# Group sequences into batches with same length (saves memory and speeds up training considerably)
|
| 63 |
+
group_by_length = True
|
| 64 |
+
|
| 65 |
+
# Activate 4-bit precision base model loading
|
| 66 |
+
#We go back to 16-bit for inference.
|
| 67 |
+
#Currently this speeds up training significantly we nearly no quality impact.
|
| 68 |
+
use_4bit = True
|
| 69 |
+
|
| 70 |
+
# Activate nested quantization for 4-bit base models
|
| 71 |
+
use_nested_quant = False
|
| 72 |
+
|
| 73 |
+
# Compute dtype for 4-bit base models
|
| 74 |
+
bnb_4bit_compute_dtype = "float16"
|
| 75 |
+
|
| 76 |
+
# Quantization type (fp4 or nf4=
|
| 77 |
+
bnb_4bit_quant_type = "nf4"
|
| 78 |
+
|
| 79 |
+
# Number of training epochs
|
| 80 |
+
#(not used in practice)
|
| 81 |
+
num_train_epochs = 1
|
| 82 |
+
|
| 83 |
+
# Enable fp16 training
|
| 84 |
+
fp16 = True
|
| 85 |
+
|
| 86 |
+
# Enable bf16 training
|
| 87 |
+
bf16 = False
|
| 88 |
+
|
| 89 |
+
# Use packing dataset creating
|
| 90 |
+
packing = False
|
| 91 |
+
|
| 92 |
+
# Enable gradient checkpointing
|
| 93 |
+
gradient_checkpointing = True
|
| 94 |
+
|
| 95 |
+
# Optimizer to use, original is paged_adamw_32bit
|
| 96 |
+
optim = "paged_adamw_32bit"
|
| 97 |
+
|
| 98 |
+
# Fraction of steps to do a warmup for
|
| 99 |
+
warmup_ratio = 0.03
|
| 100 |
+
|
| 101 |
+
# Log every X updates steps
|
| 102 |
+
logging_steps = 1
|
| 103 |
+
|
| 104 |
+
# Load the entire model on the GPU 0
|
| 105 |
+
device_map = {"": 0}
|
| 106 |
+
|
| 107 |
+
# Visualize training
|
| 108 |
+
report_to = "tensorboard"
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
#2. Loading the tokenizer
|
| 112 |
+
peft_config = LoraConfig(
|
| 113 |
+
lora_alpha=lora_alpha,
|
| 114 |
+
lora_dropout=lora_dropout,
|
| 115 |
+
r=lora_r,
|
| 116 |
+
inference_mode=False,
|
| 117 |
+
task_type="CAUSAL_LM",
|
| 118 |
+
target_modules = ["q_proj", "v_proj"]
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 122 |
+
|
| 123 |
+
# This is the fix for fp16 training
|
| 124 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 125 |
+
|
| 126 |
+
#3. Preparing the dataset.
|
| 127 |
+
#This is the part most specific to the scikit model.
|
| 128 |
+
#We take an entire conversation, as both the input and the output are part of the same string of texts.
|
| 129 |
+
from datasets import load_dataset
|
| 130 |
+
|
| 131 |
+
def format_alpaca(sample):
|
| 132 |
+
prompt = f"{sample['conversation']}"
|
| 133 |
+
return prompt
|
| 134 |
+
|
| 135 |
+
# template dataset to add prompt to each sample
|
| 136 |
+
def template_dataset(sample):
|
| 137 |
+
sample["text"] = f"{format_alpaca(sample)}{tokenizer.eos_token}"
|
| 138 |
+
return sample
|
| 139 |
+
|
| 140 |
+
# Loading the data du dataset.
|
| 141 |
+
data_files = {"train": "skikit_administration.json"}
|
| 142 |
+
dataset = load_dataset("json", data_files=data_files, split="train")
|
| 143 |
+
|
| 144 |
+
# Shuffle the dataset
|
| 145 |
+
dataset_shuffled = dataset.shuffle(seed=42)
|
| 146 |
+
|
| 147 |
+
#Dataset parsing.
|
| 148 |
+
dataset = dataset.map(template_dataset, remove_columns=list(dataset.features))
|
| 149 |
+
|
| 150 |
+
print(dataset[40])
|
| 151 |
+
|
| 152 |
+
#4. Model import
|
| 153 |
+
|
| 154 |
+
# Load tokenizer and model with QLoRA configuration
|
| 155 |
+
compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
|
| 156 |
+
|
| 157 |
+
bnb_config = BitsAndBytesConfig(
|
| 158 |
+
load_in_4bit=use_4bit,
|
| 159 |
+
bnb_4bit_quant_type=bnb_4bit_quant_type,
|
| 160 |
+
bnb_4bit_compute_dtype=compute_dtype,
|
| 161 |
+
bnb_4bit_use_double_quant=use_nested_quant,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
if compute_dtype == torch.float16 and use_4bit:
|
| 165 |
+
major, _ = torch.cuda.get_device_capability()
|
| 166 |
+
if major >= 8:
|
| 167 |
+
print("=" * 80)
|
| 168 |
+
print("Your GPU supports bfloat16, you can accelerate training with the argument --bf16")
|
| 169 |
+
print("=" * 80)
|
| 170 |
+
|
| 171 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 172 |
+
model_name,
|
| 173 |
+
device_map=device_map,
|
| 174 |
+
quantization_config=bnb_config
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
model.config.use_cache = False
|
| 178 |
+
model.config.pretraining_tp = 1
|
| 179 |
+
|
| 180 |
+
#5. Fine-tuning (actually)
|
| 181 |
+
#We pass all the hyperparmeters, and are ready to go.
|
| 182 |
+
|
| 183 |
+
torch.cuda.empty_cache()
|
| 184 |
+
|
| 185 |
+
training_arguments = TrainingArguments(
|
| 186 |
+
output_dir=output_dir,
|
| 187 |
+
per_device_train_batch_size=per_device_train_batch_size,
|
| 188 |
+
gradient_accumulation_steps=gradient_accumulation_steps,
|
| 189 |
+
gradient_checkpointing=True,
|
| 190 |
+
optim=optim,
|
| 191 |
+
save_steps=save_steps,
|
| 192 |
+
logging_steps=logging_steps,
|
| 193 |
+
learning_rate=learning_rate,
|
| 194 |
+
fp16=fp16,
|
| 195 |
+
bf16=bf16,
|
| 196 |
+
max_grad_norm=max_grad_norm,
|
| 197 |
+
max_steps=max_steps,
|
| 198 |
+
warmup_ratio=warmup_ratio,
|
| 199 |
+
group_by_length=group_by_length,
|
| 200 |
+
lr_scheduler_type=lr_scheduler_type,
|
| 201 |
+
report_to="tensorboard"
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
trainer = SFTTrainer(
|
| 205 |
+
model=model,
|
| 206 |
+
train_dataset=dataset,
|
| 207 |
+
peft_config=peft_config,
|
| 208 |
+
dataset_text_field="text",
|
| 209 |
+
max_seq_length=max_seq_length,
|
| 210 |
+
tokenizer=tokenizer,
|
| 211 |
+
args=training_arguments,
|
| 212 |
+
packing=packing
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
#Training:
|
| 216 |
+
trainer.train()
|
| 217 |
+
|
| 218 |
+
#Optionally, if we want to continue training (for instance if there was an issue):
|
| 219 |
+
#trainer.train(resume_from_checkpoint=True)
|
| 220 |
+
|
| 221 |
+
#6. Export the weights
|
| 222 |
+
model_to_save = trainer.model.module if hasattr(trainer.model, 'module') else trainer.model # Take care of distributed/parallel training
|
| 223 |
+
model_to_save.save_pretrained(new_model_name)
|
| 224 |
+
|
| 225 |
+
torch.cuda.empty_cache()
|
| 226 |
+
|
| 227 |
+
from peft import AutoPeftModelForCausalLM
|
| 228 |
+
|
| 229 |
+
model = AutoPeftModelForCausalLM.from_pretrained(new_model_name, device_map="auto", torch_dtype=torch.bfloat16)
|
| 230 |
+
model = model.merge_and_unload()
|
| 231 |
+
|
| 232 |
+
output_merged_dir = os.path.join(new_model_name, new_model_name)
|
| 233 |
+
model.save_pretrained(output_merged_dir, safe_serialization=True)
|
| 234 |
+
|
| 235 |
+
#We also save the tokenizer
|
| 236 |
+
tokenizer.save_pretrained(output_merged_dir)
|