File size: 3,934 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""
utils.py
νŒŒλΌλ―Έν„° 수 좜λ ₯, GPU λ©”λͺ¨λ¦¬ 좜λ ₯ λ“± 곡톡 μœ ν‹Έλ¦¬ν‹° λͺ¨μŒ.
"""

import os
import torch
from logger import get_logger

log = get_logger(__name__)


# ──────────────────────────────────────────────
# λͺ¨λΈ νŒŒλΌλ―Έν„° 톡계
# ──────────────────────────────────────────────

def print_param_stats(model) -> None:
    """ν•™μŠ΅ κ°€λŠ₯ / 전체 νŒŒλΌλ―Έν„° μˆ˜μ™€ λΉ„μœ¨μ„ 좜λ ₯ν•œλ‹€."""
    total      = sum(p.numel() for p in model.parameters())
    trainable  = sum(p.numel() for p in model.parameters() if p.requires_grad)
    ratio      = 100 * trainable / total if total > 0 else 0.0

    log.info("=" * 55)
    log.info(f"  Trainable parameters : {trainable:>15,}")
    log.info(f"  Total    parameters  : {total:>15,}")
    log.info(f"  Trainable ratio      : {ratio:.4f} %")
    log.info("=" * 55)


# ──────────────────────────────────────────────
# GPU λ©”λͺ¨λ¦¬
# ──────────────────────────────────────────────

def print_gpu_memory(tag: str = "") -> None:
    """ν˜„μž¬ ν”„λ‘œμ„ΈμŠ€κ°€ 점유 쀑인 GPU VRAM μ‚¬μš©λŸ‰μ„ 좜λ ₯ν•œλ‹€."""
    if not torch.cuda.is_available():
        log.info("CUDA not available β€” skipping memory report.")
        return

    for i in range(torch.cuda.device_count()):
        allocated = torch.cuda.memory_allocated(i) / 1024 ** 3
        reserved  = torch.cuda.memory_reserved(i)  / 1024 ** 3
        total_mem = torch.cuda.get_device_properties(i).total_memory / 1024 ** 3
        label     = f"[{tag}] " if tag else ""
        log.info(
            f"{label}GPU {i} ({torch.cuda.get_device_name(i)}) | "
            f"Allocated {allocated:.2f} GB / Reserved {reserved:.2f} GB / "
            f"Total {total_mem:.2f} GB"
        )


# ──────────────────────────────────────────────
# 체크포인트 탐색
# ──────────────────────────────────────────────

def find_last_checkpoint(checkpoint_dir: str) -> str | None:
    """
    HuggingFace Trainer ν˜•μ‹μ˜ checkpoint-XXXX 폴더 쀑
    μŠ€ν… λ²ˆν˜Έκ°€ κ°€μž₯ 큰 것을 λ°˜ν™˜ν•œλ‹€. μ—†μœΌλ©΄ None.
    """
    import re
    from pathlib import Path

    ckpt_root = Path(checkpoint_dir)
    if not ckpt_root.exists():
        return None

    pattern = re.compile(r"^checkpoint-(\d+)$")
    candidates = []
    for d in ckpt_root.iterdir():
        m = pattern.match(d.name)
        if m and d.is_dir():
            candidates.append((int(m.group(1)), str(d)))

    if not candidates:
        return None

    candidates.sort(key=lambda x: x[0])
    _, path = candidates[-1]
    return path


# ──────────────────────────────────────────────
# ν™˜κ²½ 정보
# ──────────────────────────────────────────────

def log_environment() -> None:
    """Python, torch, CUDA 버전과 GPU 정보λ₯Ό λ‘œκ·Έμ— 남긴닀."""
    import sys
    log.info(f"Python  : {sys.version}")
    log.info(f"PyTorch : {torch.__version__}")
    log.info(f"CUDA    : {torch.version.cuda}")
    if torch.cuda.is_available():
        for i in range(torch.cuda.device_count()):
            props = torch.cuda.get_device_properties(i)
            log.info(f"  GPU {i} : {props.name} | {props.total_memory / 1024**3:.1f} GB")
    else:
        log.warning("CUDA device not found.")