File size: 2,735 Bytes
458260e | 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 | """
checkpoint.py
체ν¬ν¬μΈνΈ νμ§, resume μ¬λΆ κ²°μ , νμ΅ μλ£ ν μ μ₯μ λ΄λΉνλ€.
"""
from pathlib import Path
from config import SFTConfig
from logger import get_logger
from utils import find_last_checkpoint
from qat_gguf import merge_lora_into_base
log = get_logger(__name__)
def get_resume_checkpoint(cfg: SFTConfig) -> str | None:
"""
checkpoint_dir μ μ μ₯λ κ°μ₯ μ΅κ·Ό 체ν¬ν¬μΈνΈλ₯Ό λ°ννλ€.
μμΌλ©΄ None β μ²μλΆν° νμ΅.
"""
ckpt = find_last_checkpoint(cfg.paths.checkpoint_dir)
if ckpt:
log.info(f"Resume checkpoint found : {ckpt}")
else:
log.info("No checkpoint found. Training from scratch.")
return ckpt
def save_final_model(cfg: SFTConfig, trainer) -> None:
"""
νμ΅ μλ£ ν final_model/ ν΄λμ "LoRA delta κ° λ³ν©λ ν μ λ°λ(bf16) λͺ¨λΈ"μ μ μ₯νλ€.
체ν¬ν¬μΈνΈ μ€κ° μ μ₯(QATTrainer._save)μ μ΄λν°(lora_A/B)λ§ μ μ₯νμ§λ§,
μ΅μ’
μ°μΆλ¬Όμ GGUF λ³ν(convert_hf_to_gguf.py) νμ΄νλΌμΈμ λ°λ‘ λ£μ μ μλλ‘
merge_lora_into_base λ‘ base+delta λ₯Ό μ€μ κ°μ€μΉλ‘ ν©μ³μ μΌλ° HF λͺ¨λΈ ν¬λ§·μΌλ‘ μ μ₯νλ€.
μ΄ν llama.cpp μ quantize λκ΅¬λ‘ Q4_0 μμννλ©΄ QAT λ‘ νμ΅ν delta κ° λ°μλλ€.
"""
final_dir = str(Path(cfg.paths.output_dir) / "final_model")
merge_lora_into_base(trainer.model)
trainer.model.config.use_cache = True
trainer.model.save_pretrained(final_dir)
if trainer.processing_class is not None:
trainer.processing_class.save_pretrained(final_dir)
log.info(f"Final model saved (LoRA merged, ready for GGUF conversion) : {final_dir}")
log.info(
"λ€μ λ¨κ³: llama.cpp μ convert_hf_to_gguf.py λ‘ GGUF λ³ν ν "
"quantize λκ΅¬λ‘ Q4_0 μμννμΈμ."
)
def save_training_state(cfg: SFTConfig, trainer) -> None:
"""
trainer.state (loss 곑μ , step μ λ±) λ₯Ό JSON μΌλ‘ 보쑴νλ€.
λμ€μ νμ΅ κ³‘μ μκ°νλ λΆμμ νμ© κ°λ₯.
"""
import json
state_path = Path(cfg.paths.output_dir) / "trainer_state.json"
try:
state_dict = trainer.state.__dict__
with open(state_path, "w", encoding="utf-8") as f:
# log_history λ± μ§λ ¬ν κ°λ₯ν νλͺ©λ§ μ μ₯
json.dump(
{k: v for k, v in state_dict.items()
if isinstance(v, (int, float, str, list, dict, bool, type(None)))},
f, ensure_ascii=False, indent=2
)
log.info(f"Trainer state saved : {state_path}")
except Exception as e:
log.warning(f"trainer_state μ μ₯ μ€ν¨ (무μ): {e}")
|