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