File size: 7,343 Bytes
9fc3b3a | 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 | """
trainer_builder.py
TrainingArguments μ Trainer λ₯Ό ꡬμ±νμ¬ λ°ννλ€.
"""
import json
import os
import time
import torch
from transformers import Trainer, TrainingArguments, TrainerCallback
from config import CPTConfig
from dataset_loader import CPTDataCollator
from logger import get_logger
from qat_gguf import get_lora_state_dict, load_lora_state_dict, set_quant_enabled
log = get_logger(__name__)
QAT_ADAPTER_FILENAME = "qat_lora_adapter.pt"
QAT_META_FILENAME = "qat_meta.json"
class QuantWarmupCallback(TrainerCallback):
"""
νμ΅ μμ ν quant_warmup_steps μ€ν
κΉμ§λ fake-quant λ₯Ό λκ³
μμ LoRA λ‘λ§ μ μμν¨ λ€, κ·Έ μμ λΆν° GGUF Q4_0 fake-quant λ₯Ό μΌ λ€.
"""
def __init__(self, warmup_steps: int, enabled: bool):
self.warmup_steps = warmup_steps
self.enabled = enabled
self._activated = False
def on_step_begin(self, args, state, control, model=None, **kwargs):
if not self.enabled or self._activated:
return
if state.global_step >= self.warmup_steps:
set_quant_enabled(model, True)
self._activated = True
log.info(f"QAT warmup μ’
λ£ (step {state.global_step}) β fake-quant νμ±ν.")
class QATTrainer(Trainer):
"""
HF Trainer λ κΈ°λ³Έμ μΌλ‘ λ§€ save_steps λ§λ€ model.save_pretrained() λ₯Ό νΈμΆν΄μ
μ 체 λͺ¨λΈμ ν΅μ§Έλ‘ μ μ₯νλ€. base weight κ° frozen μ΄κ³ λ³κ²½λμ§ μμΌλ―λ‘
μ΄λ λΆνμν λμ€ν¬/μκ° λλΉλ€. μ¬κΈ°μλ LoRA νλΌλ―Έν°(lora_A, lora_B)λ§
λ³λ νμΌλ‘ μ μ₯/볡μνλλ‘ μ€λ²λΌμ΄λνλ€.
"""
def __init__(self, *args, qat_meta: dict = None, **kwargs):
super().__init__(*args, **kwargs)
self._qat_meta = qat_meta or {}
def _save(self, output_dir: str = None, state_dict=None):
output_dir = output_dir or self.args.output_dir
os.makedirs(output_dir, exist_ok=True)
lora_sd = get_lora_state_dict(self.model)
torch.save(lora_sd, os.path.join(output_dir, QAT_ADAPTER_FILENAME))
with open(os.path.join(output_dir, QAT_META_FILENAME), "w", encoding="utf-8") as f:
json.dump(self._qat_meta, f, ensure_ascii=False, indent=2)
# ν ν¬λμ΄μ λ κ·Έλλ‘ μ μ₯ (μ©λ μμ)
if self.processing_class is not None:
self.processing_class.save_pretrained(output_dir)
log.info(f"QAT LoRA μ΄λν° μ μ₯ μλ£: {output_dir} ({len(lora_sd)}κ° ν
μ)")
def _load_from_checkpoint(self, resume_from_checkpoint, model=None):
model = model if model is not None else self.model
adapter_path = os.path.join(resume_from_checkpoint, QAT_ADAPTER_FILENAME)
if not os.path.exists(adapter_path):
log.warning(
f"체ν¬ν¬μΈνΈμ {QAT_ADAPTER_FILENAME} μ΄ μμ΅λλ€ β λ‘λλ₯Ό 건λλλλ€: {resume_from_checkpoint}"
)
return
lora_sd = torch.load(adapter_path, map_location="cpu")
load_lora_state_dict(model, lora_sd)
log.info(f"QAT LoRA μ΄λν° λ³΅μ μλ£: {resume_from_checkpoint}")
class ProgressCallback(TrainerCallback):
"""λ§€ step λ§λ€ μ§ν μν©μ μ½μμ μΆλ ₯νλ μ½λ°±."""
def __init__(self, total_steps: int):
self.total_steps = total_steps
self.step_start = None
def on_step_begin(self, args, state, control, **kwargs):
self.step_start = time.time()
def on_step_end(self, args, state, control, **kwargs):
elapsed = time.time() - self.step_start if self.step_start else 0
current = state.global_step
total = self.total_steps
loss_str = "-.----"
if state.log_history:
last = state.log_history[-1]
if "loss" in last:
loss_str = f"{last['loss']:.4f}"
vram_str = ""
if torch.cuda.is_available():
alloc = torch.cuda.memory_allocated(0) / 1024 ** 3
vram_str = f" | VRAM {alloc:.1f}GB"
pct = 100 * current / total if total > 0 else 0
bar_len = 20
filled = int(bar_len * current / total) if total > 0 else 0
bar = "β" * filled + "β" * (bar_len - filled)
print(
f"[{bar}] {current}/{total} ({pct:.1f}%)"
f" | loss {loss_str}"
f" | {elapsed:.1f}s/step"
f"{vram_str}"
)
def on_train_end(self, args, state, control, **kwargs):
print("Training complete.")
def build_trainer(
cfg: CPTConfig,
model,
tokenizer,
train_dataset,
resume_from: str | None = None,
) -> Trainer:
t = cfg.training
training_args = TrainingArguments(
output_dir=cfg.paths.output_dir,
num_train_epochs=t.num_train_epochs,
max_steps=t.max_steps,
per_device_train_batch_size=t.per_device_train_batch_size,
gradient_accumulation_steps=t.gradient_accumulation_steps,
learning_rate=t.learning_rate,
lr_scheduler_type=t.lr_scheduler_type,
warmup_ratio=t.warmup_ratio,
weight_decay=t.weight_decay,
optim=t.optim,
bf16=t.bf16,
fp16=t.fp16,
tf32=t.tf32,
gradient_checkpointing=t.gradient_checkpointing,
logging_dir=cfg.paths.output_dir + "/logs",
logging_steps=t.logging_steps,
report_to=t.report_to,
save_steps=t.save_steps,
save_total_limit=t.save_total_limit,
save_strategy="steps",
seed=t.seed,
data_seed=t.seed,
dataloader_num_workers=t.dataloader_num_workers,
ddp_find_unused_parameters=t.ddp_find_unused_parameters,
eval_strategy="no", # evaluation_strategy μμ λ³κ²½
disable_tqdm=True, # tqdm λκ³ μ»€μ€ν
μ½λ°±λ§ μ¬μ©
remove_unused_columns=False,
)
collator = CPTDataCollator(
pad_token_id=tokenizer.pad_token_id,
max_seq_length=t.max_seq_length,
)
steps_per_epoch = len(train_dataset) // t.per_device_train_batch_size
if t.max_steps > 0:
total_steps = t.max_steps
else:
total_steps = steps_per_epoch * t.num_train_epochs
qat_cfg = cfg.qat
callbacks = [ProgressCallback(total_steps=total_steps)]
if qat_cfg.enabled and qat_cfg.quant_warmup_steps > 0:
callbacks.append(QuantWarmupCallback(
warmup_steps=qat_cfg.quant_warmup_steps,
enabled=qat_cfg.enabled,
))
qat_meta = {
"quant_target": "gguf_q4_0",
"block_size": qat_cfg.block_size,
"target_modules": qat_cfg.target_modules,
"lora_r": cfg.lora.r,
"lora_alpha": cfg.lora.lora_alpha,
"lora_dropout": cfg.lora.lora_dropout,
}
trainer = QATTrainer(
model=model,
args=training_args,
train_dataset=train_dataset,
data_collator=collator,
processing_class=tokenizer, # tokenizer μμ λ³κ²½
callbacks=callbacks,
qat_meta=qat_meta,
)
if resume_from:
log.info(f"Resume from checkpoint: {resume_from}")
log.info(
f"Trainer built. Total steps: {total_steps} | "
f"QAT enabled: {qat_cfg.enabled} | warmup_steps: {qat_cfg.quant_warmup_steps}"
)
return trainer
|