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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from transformers import (
|
| 4 |
+
AutoModelForCausalLM,
|
| 5 |
+
AutoTokenizer,
|
| 6 |
+
DataCollatorForLanguageModeling,
|
| 7 |
+
BitsAndBytesConfig
|
| 8 |
+
)
|
| 9 |
+
from datasets import load_dataset
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
from galore_torch import GaLoreAdamW8bit
|
| 12 |
+
import torch.amp as amp
|
| 13 |
+
from torch.utils.data import DataLoader
|
| 14 |
+
from torch.optim.lr_scheduler import CosineAnnealingWarmRestarts
|
| 15 |
+
import gc
|
| 16 |
+
import os
|
| 17 |
+
import json
|
| 18 |
+
import shutil
|
| 19 |
+
import argparse
|
| 20 |
+
|
| 21 |
+
def save_training_state(checkpoint_dir, step, epoch, optimizer_state, scheduler_state):
|
| 22 |
+
"""Save training progress, optimizer and scheduler state"""
|
| 23 |
+
state = {
|
| 24 |
+
'step': step,
|
| 25 |
+
'epoch': epoch,
|
| 26 |
+
'optimizer_state': optimizer_state,
|
| 27 |
+
'scheduler_state': scheduler_state
|
| 28 |
+
}
|
| 29 |
+
with open(os.path.join(checkpoint_dir, 'training_state.json'), 'w') as f:
|
| 30 |
+
json.dump(state, f)
|
| 31 |
+
|
| 32 |
+
def load_training_state(checkpoint_dir):
|
| 33 |
+
"""Load training progress, optimizer and scheduler state"""
|
| 34 |
+
state_path = os.path.join(checkpoint_dir, 'training_state.json')
|
| 35 |
+
if os.path.exists(state_path):
|
| 36 |
+
with open(state_path, 'r') as f:
|
| 37 |
+
return json.load(f)
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
def main():
|
| 41 |
+
# Set the number of epochs here
|
| 42 |
+
num_epochs = 1 # Change this value to your desired number of epochs
|
| 43 |
+
|
| 44 |
+
# Training configuration
|
| 45 |
+
save_interval = 100000000000000000 # Change this number to save checkpoint at specified step during training
|
| 46 |
+
checkpoint_dir = "C:/Path/to/AI/Model/Checkpoint"
|
| 47 |
+
keep_last_checkpoints = 3
|
| 48 |
+
|
| 49 |
+
# Initialize starting point
|
| 50 |
+
start_step = 0
|
| 51 |
+
start_epoch = 0
|
| 52 |
+
|
| 53 |
+
# Load the tokenizer and model
|
| 54 |
+
model_path = "C:/Path/to/Input/AI/Model"
|
| 55 |
+
os.makedirs(checkpoint_dir, exist_ok=True)
|
| 56 |
+
|
| 57 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 58 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 59 |
+
|
| 60 |
+
# Modified 8-bit configuration
|
| 61 |
+
bnb_config = BitsAndBytesConfig(
|
| 62 |
+
load_in_8bit=True,
|
| 63 |
+
bnb_4bit_compute_dtype=torch.float16
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 67 |
+
model_path,
|
| 68 |
+
quantization_config=bnb_config,
|
| 69 |
+
torch_dtype=torch.float16,
|
| 70 |
+
low_cpu_mem_usage=True,
|
| 71 |
+
device_map={"": 0}
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# Dataset preparation
|
| 75 |
+
cache_dir = "C:/Path/to/Cache/Location"
|
| 76 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 77 |
+
|
| 78 |
+
dataset = load_dataset(
|
| 79 |
+
"json",
|
| 80 |
+
data_files="C:/Path/to/Training/Dataset.json",
|
| 81 |
+
split="train",
|
| 82 |
+
cache_dir=cache_dir
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def preprocess(example):
|
| 86 |
+
formatted_text = (
|
| 87 |
+
f"<|im_start|>system\n\n"
|
| 88 |
+
f"{example['instruction']}<|im_end|>\n"
|
| 89 |
+
f"<|im_start|>user\n\n"
|
| 90 |
+
f"{example['input']}<|im_end|>\n"
|
| 91 |
+
f"<|im_start|>assistant\n\n"
|
| 92 |
+
f"{example['output']}<|im_end|>"
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
tokenized = tokenizer(
|
| 96 |
+
formatted_text,
|
| 97 |
+
truncation=True,
|
| 98 |
+
max_length=2048,
|
| 99 |
+
padding='max_length',
|
| 100 |
+
return_tensors=None
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
tokenized['labels'] = tokenized['input_ids'].copy()
|
| 104 |
+
return tokenized
|
| 105 |
+
|
| 106 |
+
tokenized_dataset = dataset.map(
|
| 107 |
+
preprocess,
|
| 108 |
+
batched=True,
|
| 109 |
+
batch_size=100,
|
| 110 |
+
num_proc=12,
|
| 111 |
+
remove_columns=dataset.column_names,
|
| 112 |
+
cache_file_name=os.path.join(cache_dir, "processed_dataset.arrow")
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
data_collator = DataCollatorForLanguageModeling(
|
| 116 |
+
tokenizer=tokenizer,
|
| 117 |
+
mlm=False
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
batch_size = 4000
|
| 121 |
+
train_dataloader = DataLoader(
|
| 122 |
+
tokenized_dataset,
|
| 123 |
+
batch_size=batch_size,
|
| 124 |
+
shuffle=True,
|
| 125 |
+
num_workers=3,
|
| 126 |
+
pin_memory=True,
|
| 127 |
+
collate_fn=data_collator
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# Optimizer setup
|
| 131 |
+
accumulation_steps = 20
|
| 132 |
+
galore_params = []
|
| 133 |
+
target_modules_list = ["attn", "mlp"]
|
| 134 |
+
|
| 135 |
+
for module_name, module in model.named_modules():
|
| 136 |
+
if not isinstance(module, nn.Linear):
|
| 137 |
+
continue
|
| 138 |
+
if not any(target_key in module_name for target_key in target_modules_list):
|
| 139 |
+
continue
|
| 140 |
+
module.weight.data = module.weight.data.to(torch.float16)
|
| 141 |
+
galore_params.append(module.weight)
|
| 142 |
+
|
| 143 |
+
id_galore_params = [id(p) for p in galore_params]
|
| 144 |
+
regular_params = [p for p in model.parameters() if id(p) not in id_galore_params]
|
| 145 |
+
|
| 146 |
+
for param in regular_params:
|
| 147 |
+
if param.requires_grad:
|
| 148 |
+
param.data = param.data.to(torch.float16)
|
| 149 |
+
|
| 150 |
+
param_groups = [
|
| 151 |
+
{'params': regular_params},
|
| 152 |
+
{
|
| 153 |
+
'params': galore_params,
|
| 154 |
+
'rank': 64,
|
| 155 |
+
'update_proj_gap': 200,
|
| 156 |
+
'scale': 0.25,
|
| 157 |
+
'proj_type': 'std'
|
| 158 |
+
}
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
optimizer = GaLoreAdamW8bit(param_groups, lr=3e-4)
|
| 162 |
+
|
| 163 |
+
# Calculate scheduler parameters
|
| 164 |
+
total_training_steps = len(train_dataloader)
|
| 165 |
+
first_cycle_steps = int(total_training_steps * 0.1) # First cycle is 10% of total steps
|
| 166 |
+
|
| 167 |
+
# Initialize the cosine scheduler with warm restarts
|
| 168 |
+
scheduler = CosineAnnealingWarmRestarts(
|
| 169 |
+
optimizer,
|
| 170 |
+
T_0=first_cycle_steps, # Length of first cycle
|
| 171 |
+
T_mult=2, # Each cycle is 1.5x longer than the last
|
| 172 |
+
eta_min=1e-6 # Minimum learning rate
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
# Training loop
|
| 176 |
+
model.train()
|
| 177 |
+
total_steps = len(train_dataloader)
|
| 178 |
+
prev_avg_loss = 0 # Initialize for moving average calculation
|
| 179 |
+
|
| 180 |
+
for epoch in range(start_epoch, num_epochs):
|
| 181 |
+
running_loss = 0.0
|
| 182 |
+
optimizer.zero_grad()
|
| 183 |
+
|
| 184 |
+
progress_bar = tqdm(enumerate(train_dataloader), total=total_steps, initial=start_step)
|
| 185 |
+
|
| 186 |
+
for step, batch in progress_bar:
|
| 187 |
+
if step < start_step:
|
| 188 |
+
continue
|
| 189 |
+
|
| 190 |
+
# Process batch
|
| 191 |
+
inputs = {
|
| 192 |
+
k: v.view(-1, v.size(-1)).cuda(non_blocking=True) if isinstance(v, torch.Tensor) else v
|
| 193 |
+
for k, v in batch.items()
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
if 'attention_mask' not in inputs:
|
| 197 |
+
inputs['attention_mask'] = torch.ones_like(inputs['input_ids'])
|
| 198 |
+
|
| 199 |
+
# Forward and backward passes
|
| 200 |
+
outputs = model(**inputs)
|
| 201 |
+
loss = outputs.loss / accumulation_steps
|
| 202 |
+
loss.backward()
|
| 203 |
+
|
| 204 |
+
running_loss += loss.item()
|
| 205 |
+
|
| 206 |
+
if (step + 1) % accumulation_steps == 0:
|
| 207 |
+
# Clip gradients
|
| 208 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 209 |
+
|
| 210 |
+
optimizer.step()
|
| 211 |
+
scheduler.step() # Update learning rate
|
| 212 |
+
optimizer.zero_grad()
|
| 213 |
+
|
| 214 |
+
# Calculate metrics for progress bar
|
| 215 |
+
current_lr = scheduler.get_last_lr()[0] # Get current learning rate
|
| 216 |
+
current_loss = running_loss
|
| 217 |
+
avg_loss = current_loss if step == 0 else (current_loss * 0.1 + prev_avg_loss * 0.9)
|
| 218 |
+
prev_avg_loss = avg_loss
|
| 219 |
+
|
| 220 |
+
progress_bar.set_postfix({
|
| 221 |
+
'epoch': epoch + 1,
|
| 222 |
+
'loss': f'{current_loss:.4f}',
|
| 223 |
+
'avg_loss': f'{avg_loss:.4f}',
|
| 224 |
+
'lr': f'{current_lr:.2e}',
|
| 225 |
+
'step': f'{step}/{total_steps}'
|
| 226 |
+
})
|
| 227 |
+
|
| 228 |
+
running_loss = 0.0
|
| 229 |
+
|
| 230 |
+
# Save checkpoint
|
| 231 |
+
if step > 0 and step % save_interval == 0:
|
| 232 |
+
checkpoint_path = f"{checkpoint_dir}/checkpoint-{step}"
|
| 233 |
+
model.save_pretrained(checkpoint_path)
|
| 234 |
+
|
| 235 |
+
save_training_state(
|
| 236 |
+
checkpoint_path,
|
| 237 |
+
step,
|
| 238 |
+
epoch,
|
| 239 |
+
optimizer.state_dict(),
|
| 240 |
+
scheduler.state_dict()
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
# Remove old checkpoints
|
| 244 |
+
checkpoints = sorted([d for d in os.listdir(checkpoint_dir)
|
| 245 |
+
if d.startswith('checkpoint-')])
|
| 246 |
+
while len(checkpoints) > keep_last_checkpoints:
|
| 247 |
+
oldest_checkpoint = checkpoints.pop(0)
|
| 248 |
+
shutil.rmtree(os.path.join(checkpoint_dir, oldest_checkpoint))
|
| 249 |
+
|
| 250 |
+
# Memory cleanup
|
| 251 |
+
if step % 100 == 0:
|
| 252 |
+
gc.collect()
|
| 253 |
+
torch.cuda.empty_cache()
|
| 254 |
+
|
| 255 |
+
progress_bar.close()
|
| 256 |
+
|
| 257 |
+
# Save final model
|
| 258 |
+
final_path = "C:/Path/to/AI/Model/Final/Output"
|
| 259 |
+
model.save_pretrained(final_path)
|
| 260 |
+
tokenizer.save_pretrained(final_path)
|
| 261 |
+
|
| 262 |
+
save_training_state(
|
| 263 |
+
final_path,
|
| 264 |
+
total_steps,
|
| 265 |
+
epoch,
|
| 266 |
+
optimizer.state_dict(),
|
| 267 |
+
scheduler.state_dict()
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
if __name__ == "__main__":
|
| 271 |
+
main()
|