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}")