Update train.py
Browse files
train.py
CHANGED
|
@@ -1,164 +1,168 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import random
|
| 3 |
-
import numpy as np
|
| 4 |
-
import torch
|
| 5 |
-
from datasets import load_dataset
|
| 6 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, EarlyStoppingCallback
|
| 7 |
-
from trl import SFTTrainer, SFTConfig
|
| 8 |
-
from peft import LoraConfig
|
| 9 |
-
from transformers import BitsAndBytesConfig
|
| 10 |
-
|
| 11 |
-
#
|
| 12 |
-
BASE_MODEL = os.environ.get("BASE_MODEL", "DeepSeek-Coder-V2-Lite-Instruct")
|
| 13 |
-
OUTPUT_DIR = os.environ.get("OUTPUT_DIR", "outputs/zenith-lora")
|
| 14 |
-
DATA_PATH = os.environ.get("DATA_PATH", "data/
|
| 15 |
-
VAL_PATH = os.environ.get("VAL_PATH")
|
| 16 |
-
MAX_STEPS = int(os.environ.get("STEPS",
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
random.seed(SEED)
|
| 24 |
-
|
| 25 |
-
torch.
|
| 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 |
-
model
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
data_files = [DATA_PATH
|
| 63 |
-
print(f"Loading
|
| 64 |
-
raw_train = load_dataset("json", data_files=data_files, split="train")
|
| 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 |
-
return {"text":
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
train_ds =
|
| 96 |
-
val_ds =
|
| 97 |
-
|
| 98 |
-
train_ds = train_ds.
|
| 99 |
-
val_ds = val_ds.
|
| 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 |
-
gradient_checkpointing=True,
|
| 139 |
-
gradient_checkpointing_kwargs={"use_reentrant": False},
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
print("
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import random
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, EarlyStoppingCallback, TrainerCallback
|
| 7 |
+
from trl import SFTTrainer, SFTConfig
|
| 8 |
+
from peft import LoraConfig
|
| 9 |
+
from transformers import BitsAndBytesConfig
|
| 10 |
+
|
| 11 |
+
# ====== CONFIG ======
|
| 12 |
+
BASE_MODEL = os.environ.get("BASE_MODEL", "DeepSeek-Coder-V2-Lite-Instruct")
|
| 13 |
+
OUTPUT_DIR = os.environ.get("OUTPUT_DIR", "outputs/zenith-lora")
|
| 14 |
+
DATA_PATH = os.environ.get("DATA_PATH", "data/zenith_combined.jsonl")
|
| 15 |
+
VAL_PATH = os.environ.get("VAL_PATH")
|
| 16 |
+
MAX_STEPS = int(os.environ.get("STEPS", 300)) # ~2 hr on A100
|
| 17 |
+
SEED = int(os.environ.get("SEED", 42))
|
| 18 |
+
|
| 19 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
# ====== SEED CONTROL ======
|
| 22 |
+
random.seed(SEED)
|
| 23 |
+
np.random.seed(SEED)
|
| 24 |
+
torch.manual_seed(SEED)
|
| 25 |
+
if torch.cuda.is_available():
|
| 26 |
+
torch.cuda.manual_seed_all(SEED)
|
| 27 |
+
|
| 28 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 29 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 30 |
+
|
| 31 |
+
print(f"π Loading tokenizer and model from: {BASE_MODEL}")
|
| 32 |
+
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
|
| 33 |
+
if tokenizer.pad_token is None:
|
| 34 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 35 |
+
|
| 36 |
+
# ====== GPU PRECISION CONFIG ======
|
| 37 |
+
compute_dtype = torch.float16
|
| 38 |
+
if torch.cuda.is_available():
|
| 39 |
+
major, _ = torch.cuda.get_device_capability(0)
|
| 40 |
+
if major >= 8:
|
| 41 |
+
print("β
Using bfloat16 for Ampere+ GPU")
|
| 42 |
+
compute_dtype = torch.bfloat16
|
| 43 |
+
|
| 44 |
+
# ====== 4-BIT QUANTIZATION ======
|
| 45 |
+
bnb_config = BitsAndBytesConfig(
|
| 46 |
+
load_in_4bit=True,
|
| 47 |
+
bnb_4bit_quant_type="nf4",
|
| 48 |
+
bnb_4bit_compute_dtype=compute_dtype,
|
| 49 |
+
bnb_4bit_use_double_quant=True,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
print("βοΈ Loading model with 4-bit quantization...")
|
| 53 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 54 |
+
BASE_MODEL,
|
| 55 |
+
quantization_config=bnb_config,
|
| 56 |
+
device_map="auto",
|
| 57 |
+
trust_remote_code=True,
|
| 58 |
+
)
|
| 59 |
+
model.config.use_cache = False
|
| 60 |
+
|
| 61 |
+
# ====== DATASET LOADING ======
|
| 62 |
+
data_files = [DATA_PATH]
|
| 63 |
+
print(f"π Loading dataset: {data_files}")
|
| 64 |
+
raw_train = load_dataset("json", data_files=data_files, split="train")
|
| 65 |
+
|
| 66 |
+
if VAL_PATH and os.path.exists(VAL_PATH):
|
| 67 |
+
print(f"π Using external validation: {VAL_PATH}")
|
| 68 |
+
raw_val = load_dataset("json", data_files=VAL_PATH, split="train")
|
| 69 |
+
else:
|
| 70 |
+
split = raw_train.train_test_split(test_size=0.05, seed=SEED)
|
| 71 |
+
raw_train, raw_val = split["train"], split["test"]
|
| 72 |
+
|
| 73 |
+
MAX_SEQ_LEN = int(os.environ.get("MAX_SEQ_LEN", 2048))
|
| 74 |
+
|
| 75 |
+
def _valid(example):
|
| 76 |
+
msgs = example.get("messages")
|
| 77 |
+
if not isinstance(msgs, list) or not msgs:
|
| 78 |
+
return False
|
| 79 |
+
for m in msgs:
|
| 80 |
+
if not isinstance(m, dict) or "role" not in m or "content" not in m:
|
| 81 |
+
return False
|
| 82 |
+
return True
|
| 83 |
+
|
| 84 |
+
def _to_text(example):
|
| 85 |
+
try:
|
| 86 |
+
text = tokenizer.apply_chat_template(
|
| 87 |
+
example["messages"], tokenize=False, add_generation_prompt=False
|
| 88 |
+
)
|
| 89 |
+
return {"text": text}
|
| 90 |
+
except Exception:
|
| 91 |
+
return {"text": ""}
|
| 92 |
+
|
| 93 |
+
train_ds = raw_train.filter(_valid)
|
| 94 |
+
val_ds = raw_val.filter(_valid)
|
| 95 |
+
train_ds = train_ds.map(_to_text, remove_columns=train_ds.column_names)
|
| 96 |
+
val_ds = val_ds.map(_to_text, remove_columns=val_ds.column_names)
|
| 97 |
+
|
| 98 |
+
train_ds = train_ds.filter(lambda x: len(x.get("text", "")) > 0)
|
| 99 |
+
val_ds = val_ds.filter(lambda x: len(x.get("text", "")) > 0)
|
| 100 |
+
|
| 101 |
+
print(f"β
Training samples: {len(train_ds)}, Validation: {len(val_ds)}")
|
| 102 |
+
|
| 103 |
+
# ====== LORA CONFIG (gentle mode) ======
|
| 104 |
+
peft_config = LoraConfig(
|
| 105 |
+
r=int(os.environ.get("LORA_R", 8)),
|
| 106 |
+
lora_alpha=int(os.environ.get("LORA_ALPHA", 16)),
|
| 107 |
+
lora_dropout=float(os.environ.get("LORA_DROPOUT", 0.1)),
|
| 108 |
+
bias="none",
|
| 109 |
+
task_type="CAUSAL_LM",
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
# ====== EVAL CALLBACK ======
|
| 113 |
+
class EvalEveryCallback(TrainerCallback):
|
| 114 |
+
def __init__(self, eval_steps=100):
|
| 115 |
+
self.eval_steps = eval_steps
|
| 116 |
+
def on_step_end(self, args, state, control, **kwargs):
|
| 117 |
+
if state.global_step % self.eval_steps == 0 and state.global_step > 0:
|
| 118 |
+
control.should_evaluate = True
|
| 119 |
+
return control
|
| 120 |
+
|
| 121 |
+
# ====== TRAINING CONFIG ======
|
| 122 |
+
training_args = SFTConfig(
|
| 123 |
+
output_dir=OUTPUT_DIR,
|
| 124 |
+
max_steps=MAX_STEPS,
|
| 125 |
+
per_device_train_batch_size=int(os.environ.get("BATCH", 2)),
|
| 126 |
+
gradient_accumulation_steps=int(os.environ.get("GRAD_ACC", 2)),
|
| 127 |
+
learning_rate=float(os.environ.get("LR", 5e-5)),
|
| 128 |
+
lr_scheduler_type=os.environ.get("LR_SCHED", "cosine"),
|
| 129 |
+
warmup_ratio=float(os.environ.get("WARMUP_RATIO", 0.1)),
|
| 130 |
+
weight_decay=float(os.environ.get("WEIGHT_DECAY", 0.01)),
|
| 131 |
+
max_grad_norm=float(os.environ.get("MAX_GRAD_NORM", 1.0)),
|
| 132 |
+
logging_steps=int(os.environ.get("LOG_STEPS", 10)),
|
| 133 |
+
save_steps=int(os.environ.get("SAVE_STEPS", 50)),
|
| 134 |
+
save_total_limit=int(os.environ.get("SAVE_LIMIT", 2)),
|
| 135 |
+
fp16=torch.cuda.is_available(),
|
| 136 |
+
bf16=torch.cuda.is_available() and torch.cuda.get_device_capability(0)[0] >= 8,
|
| 137 |
+
max_seq_length=MAX_SEQ_LEN,
|
| 138 |
+
gradient_checkpointing=True,
|
| 139 |
+
gradient_checkpointing_kwargs={"use_reentrant": False},
|
| 140 |
+
dataloader_drop_last=True,
|
| 141 |
+
report_to="none",
|
| 142 |
+
seed=SEED,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# ====== TRAINER ======
|
| 146 |
+
print(f"π Starting Zenith fine-tuning for {MAX_STEPS} steps (~2h runtime)...")
|
| 147 |
+
trainer = SFTTrainer(
|
| 148 |
+
model=model,
|
| 149 |
+
tokenizer=tokenizer,
|
| 150 |
+
train_dataset=train_ds,
|
| 151 |
+
eval_dataset=val_ds,
|
| 152 |
+
peft_config=peft_config,
|
| 153 |
+
args=training_args,
|
| 154 |
+
dataset_text_field="text",
|
| 155 |
+
callbacks=[
|
| 156 |
+
EarlyStoppingCallback(early_stopping_patience=int(os.environ.get("EARLY_STOP_PATIENCE", 3))),
|
| 157 |
+
EvalEveryCallback(eval_steps=int(os.environ.get("EVAL_STEPS", 50)))
|
| 158 |
+
],
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
trainer.train()
|
| 162 |
+
|
| 163 |
+
print("πΎ Saving LoRA adapter...")
|
| 164 |
+
trainer.model.save_pretrained(OUTPUT_DIR)
|
| 165 |
+
tokenizer.save_pretrained(OUTPUT_DIR)
|
| 166 |
+
|
| 167 |
+
print(f"β
Zenith LoRA adapter saved to: {OUTPUT_DIR}")
|
| 168 |
+
print("π― Training complete under 2 hours.")
|