cpt_aqt / utils.py
starcrow's picture
Upload folder using huggingface_hub
9fc3b3a verified
Raw History Blame Contribute Delete
3.93 kB
"""
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.")