Run this model with HF Jobs
Run dllwa/gemma4-form-report-lora on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/dllwa/gemma4-form-report-lora. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/dllwa/gemma4-form-report-lora on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use dllwa/gemma4-form-report-lora with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use dllwa/gemma4-form-report-lora with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("google/gemma-4-31B-it") model = PeftModel.from_pretrained(base_model, "dllwa/gemma4-form-report-lora") - Notebooks
- Google Colab
- Kaggle
File size: 26,793 Bytes
3ca95cd | 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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 | #!/usr/bin/env python3
"""ํ์คํฌ๋ณ LoRA ์ด๋ํฐ ํ์ต (Gemma 4 + peft).
์ด ์คํฌ๋ฆฝํธ๋ **ํ์คํฌ๊ฐ ๋ฐ๋์ด๋ ๊ทธ๋๋ก ์ด๋ค.** ๋ฐ๋๋ ๊ฒ์ config์ ๋ฐ์ดํฐ๋ฟ์ด๋ค.
(docs/01_METHODOLOGY.md "์คํ ๊ด๋ฆฌ ๊ท์น" โ ์ฝ๋๋ ํ ๋ฒ, config๋ง ๊ฐ์๋ผ์ด๋ค)
์ trl.SFTTrainer ๋ฅผ ์ฐ์ง ์๋๊ฐ:
์๋ฒ ํ๊ฒฝ์ trl 0.11.4 ๋ `liger_kernel` ์์กด์ฑ์ด ์์ด ์ํฌํธ ์์ฒด๊ฐ ์คํจํ๋ค.
๊ณต์ฉ ์๋ฒ์ ํจํค์ง๋ฅผ ์๋ก ์ค์นํ์ง ์๋๋ค๋ ์์น(D-008, D-013)์ ๋ฐ๋ผ,
33์ผ์งธ ๋ฌด์ค๋จ ๋์ ์ค์ธ ๊ธฐ์กด ํ์ต ์คํฌ๋ฆฝํธ์ ๊ฐ์ ๊ฒฝ๋ก
(transformers.Trainer + peft)๋ก ๊ตฌํํ๋ค.
โ ๋ฉ๋ชจ๋ฆฌ ์ํ์ ๋ฐ๋์ ๊ฑด๋ค:
์ด GPU๋ ๊ณต์ฉ์ด๋ฉฐ ๋ฐ๋ฉ ๋ฐฉ์ง์ฉ vLLM(์ฅ๋น 72GB)๊ณผ LoRA burst(์ฅ๋น ~38GB)๊ฐ
ํจ๊ป ๋๋ค. ์ํ์ ๊ฑธ์ง ์์ผ๋ฉด ์ฐ๋ฆฌ๊ฐ ๊ทธ๋ค์ OOM์ผ๋ก ์ฃฝ์ผ ์ ์๋ค.
์ํ์ ๊ฑธ๋ฉด ์ด๊ณผ ์ **์ฐ๋ฆฌ ํ๋ก์ธ์ค๋ง** ์ฃฝ๋๋ค. (docs/06_ENVIRONMENT_ANALYSIS.md C-5)
"""
import argparse
import json
import math
import os
import random
import subprocess
import sys
from dataclasses import dataclass
from typing import Any
import torch
from peft import LoraConfig, get_peft_model
from torch.utils.data import Dataset
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
Trainer,
TrainingArguments,
set_seed,
)
from transformers.loss.loss_utils import ForCausalLMLoss
# ์ง๋จ์ฉ ํ
โ ๊ฐ์ค์น ์ ์ฌ ์ค๋ ๋ ์๋ฅผ ๋ฎ์ด์ด๋ค. ํ์์๋ ์๋ฌด ์ผ๋ ์ ํ๋ค.
# `transformers/core_model_loading.py:984` ์ `GLOBAL_WORKERS = min(4, cpu_count)` ๋
# ํ๋์ฝ๋ฉ์ด๋ผ ํ๊ฒฝ๋ณ์๋ก ๋ชป ๋๋ค(08 9์ ). DDP ์๋ ์๋ฌ๊ฐ "์ค๋ ๋ 4๊ฐ๊ฐ ๋์์
# CUDA ์ปจํ
์คํธ๋ฅผ ๋ง๋ค๋ฉฐ ๊ฒฝํฉํ๋ค"๋ ๊ฐ์ค์ ๊ฒ์ธ์ง ๊ฐ๋ฅด๋ ค๋ฉด ์ด๊ฑธ 1๋ก ๋ฎ์ถฐ๋ด์ผ ํ๋ค.
# scripts/diag_ddp.sh ์ ์ฉ. ๋ณธ ํ์ต์์๋ ์ค์ ํ์ง ์๋๋ค.
if os.environ.get("LORA_LOAD_WORKERS"):
import transformers.core_model_loading as _cml
_cml.GLOBAL_WORKERS = int(os.environ["LORA_LOAD_WORKERS"])
print(f"[์ง๋จ] ๊ฐ์ค์น ์ ์ฌ ์ค๋ ๋ = {_cml.GLOBAL_WORKERS} (๊ธฐ๋ณธ 4)")
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from common.gpu_guard import (BURST_LOCK, BURST_SAFE_GIB, # noqa: E402,F401
_ancestor_holds_burst_lock, require_burst_lock_if_needed)
from common.chat_format import ( # noqa: E402
build_prompt_and_full, build_user_turn, derive_answer_suffix,
detect_system_support, encode_no_special,
)
# ---------------------------------------------------------------- ๋ฐ์ดํฐ
class JsonlSFTDataset(Dataset):
"""jsonl(instruction/input/output)์ ๋ํ ํ์์ผ๋ก ํ ํฌ๋์ด์ฆํ๋ค.
์์ค์ **model(assistant) ํํธ์๋ง** ๊ฑด๋ค. ์ง๋ฌธ๊น์ง ํ์ต์ํค๋ฉด
๋ชจ๋ธ์ด ๋ต๋ณ ๋์ ์ง๋ฌธ์ ๋ฐ๋ผ ์ฐ๊ธฐ ์์ํ๋ค.
๊ตฌํ: ํ๋กฌํํธ๋ง ํ ํฌ๋์ด์ฆํ ๊ธธ์ด๋งํผ labels๋ฅผ -100์ผ๋ก ๋ฎ๋๋ค.
ํ ํฌ๋์ด์ ์ chat template์ ๊ทธ๋๋ก ์ฐ๋ฏ๋ก ํน์ํ ํฐ์ ์์ผ๋ก ์ ์ง ์๋๋ค
(ํ๋์ฝ๋ฉํ๋ฉด ๋ชจ๋ธ์ด ํ์ตํ ํ์๊ณผ ์ด๊ธ๋ ์ฑ๋ฅ์ด ์กฐ์ฉํ ๋ง๊ฐ์ง๋ค).
"""
def __init__(self, path, tokenizer, max_len, system=None, supports_system=True):
self.tok = tokenizer
self.max_len = max_len
self.system = system
self.supports_system = supports_system
# ์ ๋ต ๋ค ์ข
๋ฃ ํ์์ ํ
ํ๋ฆฟ์์ ๋ฝ์๋๋ค (ํ๋์ฝ๋ฉ ๊ธ์ง, N-002)
self.answer_suffix = derive_answer_suffix(tokenizer)
self.rows = []
with open(path, encoding="utf-8") as f:
for line in f:
d = json.loads(line)
if d.get("instruction") and d.get("output"):
self.rows.append(d)
def __len__(self):
return len(self.rows)
def __getitem__(self, i):
d = self.rows[i]
# ํ๊ฐ ์ฝ๋์ **๊ฐ์ ํจ์**๋ฅผ ์ด๋ค. ๋ณต์ฌํด๋๋ฉด ํ์ชฝ๋ง ๊ณ ์ณ์ง๋ ์๊ฐ
# ํ์ต/์ถ๋ก ํ์์ด ์ด๊ธ๋๊ณ , ๊ทธ๊ฑด ์๋ฌ ์์ด ์ฑ๋ฅ๋ง ๋จ์ด๋จ๋ฆฐ๋ค. (N-002)
msgs, answer = build_user_turn(d, self.system, self.supports_system)
prompt_text, full_text = build_prompt_and_full(
self.tok, msgs, answer, self.answer_suffix)
prompt_ids = encode_no_special(self.tok, prompt_text)
full_ids = encode_no_special(self.tok, full_text)
# ํ๋กฌํํธ๊ฐ ์ ์ฒด์ ์ ๋์ฌ๊ฐ ์๋๋ฉด ๋ง์คํน์ด ์๋ฑํ ๊ตฌ๊ฐ์ ๋ฎ๋๋ค.
# ์กฐ์ฉํ ์๋ชป ํ์ต๋๋๋ ์ฌ๊ธฐ์ ๋ฉ์ถ๋ ํธ์ด ๋ซ๋ค.
if full_ids[: len(prompt_ids)] != prompt_ids:
raise RuntimeError(
"ํ๋กฌํํธ๊ฐ ์ ์ฒด ์ํ์ค์ ์ ๋์ฌ๊ฐ ์๋๋ค โ ๋ํ ํ
ํ๋ฆฟ ์ฒ๋ฆฌ๊ฐ ์ด๊ธ๋ฌ๋ค.\n"
f" prompt: {prompt_text[-120:]!r}\n full: {full_text[-120:]!r}"
)
full_ids = full_ids[: self.max_len]
labels = list(full_ids)
for j in range(min(len(prompt_ids), len(labels))):
labels[j] = -100 # ํ๋กฌํํธ ๊ตฌ๊ฐ์ ์์ค์์ ์ ์ธ
return {"input_ids": full_ids, "labels": labels}
@dataclass
class PadCollator:
"""๋ฐฐ์น ์์์ ๊ฐ์ฅ ๊ธด ๊ฒ์ ๋ง์ถฐ ์ค๋ฅธ์ชฝ ํจ๋ฉํ๋ค."""
pad_token_id: int
def __call__(self, features: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
maxlen = max(len(f["input_ids"]) for f in features)
input_ids, labels, attn = [], [], []
for f in features:
n = maxlen - len(f["input_ids"])
input_ids.append(f["input_ids"] + [self.pad_token_id] * n)
labels.append(f["labels"] + [-100] * n) # ํจ๋ฉ์ ์์ค์์ ์ ์ธ
attn.append([1] * len(f["input_ids"]) + [0] * n)
return {
"input_ids": torch.tensor(input_ids, dtype=torch.long),
"labels": torch.tensor(labels, dtype=torch.long),
"attention_mask": torch.tensor(attn, dtype=torch.long),
}
# ------------------------------------------------------- ์์ค ์ ๊ทํ (N-031)
def token_mean_loss(outputs, labels, num_items_in_batch=None):
"""๋์ ๊ตฌ๊ฐ **์ ์ฒด์ ์ ๋ต ํ ํฐ ์**๋ก ๋๋๋ค โ ๋ชจ๋ ํ ํฐ์ด ๋๋ฑํ ํ ํ.
**์ ํ์ํ๊ฐ.** `Gemma4UnifiedForConditionalGeneration.accepts_loss_kwargs`
๊ฐ `False` ๋ผ์, ์ด๊ฑธ ์ ๋๊ธฐ๋ฉด `Trainer` ๊ฐ ํ ํฐ์ ์ธ์ง๋ ์๊ณ
`loss / grad_accum` ์ผ๋ก **๋ง์ดํฌ๋ก๋ฐฐ์น ๊ฐ์**๋งํผ ๋๋๋ค. ๊ทธ๋ฌ๋ฉด ํ ํฐ ์๊ฐ
์ ์ ๋ง์ดํฌ๋ก๋ฐฐ์น์ ํ ํฐ์ด ๊ณผ๋ํ๊ฐ๋๋ค โ ์งง์ ์ ๋ต์ด ์ต๋ 2.3๋ฐฐ ๋ฌด๊ฒ๊ฒ
ํ์ต๋๋ค(`09_loss_normalization.md` 8์ ). **์๋ฌ๋ ์ ๋๋ค.**
`compute_loss_func` ํ๋๋ก `Trainer` ์ ๋ ๊ฐ๋๊ฐ ๋์์ ํ๋ฆฐ๋ค:
ํ ํฐ์ ์ธ๊ฒ ๋ง๋ค๊ณ (`_get_num_items_in_batch`), ์ ๋๋์
๋ ๊ฑด๋๋ด๋ค
(`training_step`). ๋ชจ๋ธ ํด๋์ค๋ฅผ ๊ฑด๋๋ฆฌ์ง ์๋๋ค.
โ ๏ธ **`fixed_cross_entropy` ๋ฅผ ์ง์ ๋ถ๋ฅด๋ฉด ์ ๋๋ค.** `compute_loss_func` ์
๋๊ธฐ๋ฉด `Trainer` ๊ฐ `labels` ๋ฅผ `inputs` ์์ **pop** ํด์ ๋ชจ๋ธ์ ์ ๋๊ธฐ๋ฏ๋ก
(`trainer.py` `compute_loss`), ์ฌ๊ธฐ ์ค๋ ๋ผ๋ฒจ์ **์ํํธ๋์ง ์์ ์๋ณธ**์ด๊ณ
๋ก์ง์ `[B, L, V]` ๋ค. ๊ทธ๋๋ก ํ์ฐ๋ฉด ํ์ ๋ถ์ผ์น๋ก ์ฃฝ๊ฑฐ๋, flatten ํ๋ฉด
**"ํ์ฌ ํ ํฐ ๋งํ๊ธฐ"๋ฅผ ์กฐ์ฉํ ํ์ตํ๋ค.**
`ForCausalLMLoss` ๊ฐ ์ํํธยทflattenยท๋๋์
์ ๋ชจ๋ ํ๋ค.
โ ๏ธ **DDP ๋ก ๊ฐ๋ฉด** `TrainingArguments(average_tokens_across_devices=True)` ๊ฐ
์ถ๊ฐ๋ก ํ์ํ๋ค โ rank ๋ณ ํ ํฐ ์๋ฅผ gather ํด ํฉ์ณ์ผ ๋ถ๋ชจ๊ฐ ์ ์ญ์ด ๋๋ค.
์ง๊ธ(๋ชจ๋ธ ๋ณ๋ ฌ, ๋จ์ผ ํ๋ก์ธ์ค)์ ๋ถํ์ํ๋ค.
"""
return ForCausalLMLoss(
outputs.logits, labels,
vocab_size=outputs.logits.size(-1),
num_items_in_batch=num_items_in_batch,
)
# ---------------------------------------------------------------- ์ ํธ
def git_commit_hash() -> str:
"""์ฌํ์ฑ์ ์ํด ์ง๊ธ ์ฝ๋์ ์ปค๋ฐ ํด์๋ฅผ ๊ธฐ๋กํ๋ค.
ํ์ต์ **์๋ฒ์์ ๋์ง๋ง ์๋ฒ ๋๋ ํ ๋ฆฌ๋ git ์ ์ฅ์๊ฐ ์๋๋ค**(A ๋ฐฉ์ โ
๋ก์ปฌ์์ ์ปค๋ฐํ๊ณ rsync๋ก ์ฝ๋๋ง ๋ณด๋ธ๋ค). ๊ทธ๋์ `git rev-parse` ๋ ์๋ฒ์์
ํญ์ ์คํจํ๊ณ , ์ค์ ๋ก ์ฒซ ์ค๋ชจํฌ ํ
์คํธ์ run_card์ `(git ์ ๋ณด ์์)` ์ด
์ฐํ๋ค. ๊ทธ๋ฌ๋ฉด "์ด ์ด๋ํฐ๋ ์ด๋ ์ฝ๋๋ก ๋ง๋ค์๋๊ฐ"์ ๋ตํ ์ ์๋ค.
โ `scripts/sync_to_server.sh` ๊ฐ ๋๊ธฐํํ ๋ ์ ์ฅ์ ๋ฃจํธ์ `.commit_hash` ๋ฅผ
์จ ๋๋ค. git ์ด ์ ๋๋ ๊ณณ์์๋ ๊ทธ ํ์ผ์ ์ฝ๋๋ค.
"""
here = os.path.dirname(os.path.abspath(__file__))
repo_root = os.path.abspath(os.path.join(here, "..", ".."))
try:
out = subprocess.run(["git", "-C", here, "rev-parse", "--short", "HEAD"],
capture_output=True, text=True, timeout=10)
if out.returncode == 0 and out.stdout.strip():
return out.stdout.strip()
except Exception:
pass
stamp = os.path.join(repo_root, ".commit_hash")
try:
with open(stamp, encoding="utf-8") as f:
v = f.read().strip()
if v:
return v
except OSError:
pass
return "(git ์ ๋ณด ์์)"
# โ burst ๋ฝ ๊ฐ๋๋ `src/common/gpu_guard.py` ๋ก ์ฎ๊ฒผ๋ค (2026-08-14).
# ํ๊ฐ(`src/eval/generate.py`)๋ ๊ฐ์ ๊ฐ๋๋ฅผ ํต๊ณผํด์ผ ํ๋๋ฐ ๊ทธ์ชฝ์ ์์๋ค โ
# D-022 ๋ "GPU ์ฐ๋ ์์
์ ๋ถ"์ธ๋ฐ ์ฝ๋๋ ํ์ต์๋ง ๋ถ์ด ์์๋ค.
# (์์๋ฅผ ๋ ํ์ผ์ ๋ณต์ ํ๋ฉด ๊ฐ๋ผ์ง๋ค โ ๊ทธ๋์ ํ ๊ณณ์ ๋๋ค.)
def cap_gpu_memory(fraction: float, single_device: bool = False):
"""โ ๊ณต์ฉ GPU ๋ณดํธ โ ์ฐ๋ฆฌ ํ๋ก์ธ์ค์ ๋ฉ๋ชจ๋ฆฌ ์ํ์ ๊ฑด๋ค.
๋งจ ๋จผ์ `set_device` ๋ก ์ด ํ๋ก์ธ์ค์ ์นด๋๋ฅผ ๋ชป ๋ฐ๋๋ค. ๊ทธ๋ฌ์ง ์์ผ๋ฉด
DDP ์์ `CUDA driver error: initialization error` ๊ฐ ๊ฐํ์ ์ผ๋ก ๋ฌ๋ค โ
transformers ๊ฐ ๊ฐ์ค์น๋ฅผ **์ฌ๋ฌ ์ค๋ ๋๋ก** ์ฌ๋ฆฌ๋๋ฐ, ๊ทธ ์์ ์ CUDA
์ปจํ
์คํธ๊ฐ ํ์ ๋ผ ์์ง ์์ผ๋ฉด ์ค๋ ๋๋ค์ด ๋์์ ์ด๊ธฐํํ๋ฉฐ ์ถฉ๋ํ๋ค.
(์คํจ ๋น๋๋ **[๋ฏธ๊ฒ์ฆ]** โ ์คํ ์ด๋ ฅ์ ์๊ฐ๋ณ๋ก ์ฌ๊ตฌ์ฑํ์ง ์์๋ค. ์ฑ๊ณตํ๊ธฐ๋ ํด์ ๋ ์ํํ ์ข
๋ฅ์ ๋ฒ๊ทธ๋ค)
"""
local_rank = int(os.environ.get("LOCAL_RANK", 0))
if torch.cuda.is_available():
torch.cuda.set_device(local_rank)
# ์๊ธฐ๊ฐ ์ฐ๋ ์นด๋์๋ง ๊ฑด๋ค. ์ ์นด๋๋ฅผ ๋๋ฉด DDP ์์ rank0 ์ด GPU1 ์๋,
# rank1 ์ด GPU0 ์๋ **์ฐ์ง๋ ์์ CUDA ์ปจํ
์คํธ**๋ฅผ ๋ง๋ ๋ค โ ์นด๋๋น 518MiB ๋ฅผ
# ๊ทธ๋ฅ ๋ฒ๋ฆฌ๋ ๋ฐ๋ค, ๊ทธ ๊ต์ฐจ ์ด๊ธฐํ๊ฐ ์ ๊ฒฝํฉ์ ์์ธ์ด์๋ค.
devices = [local_rank] if single_device else list(range(torch.cuda.device_count()))
if fraction and fraction > 0:
for i in devices:
torch.cuda.set_per_process_memory_fraction(fraction, i)
total = torch.cuda.get_device_properties(local_rank).total_memory / 1024**3
print(f"[mem] GPU{devices} ์ํ {fraction:.0%} โ {total * fraction:.1f}GiB "
f"(์ด๊ณผ ์ ์ฐ๋ฆฌ ํ๋ก์ธ์ค๋ง OOM โ vLLM ์์ )")
else:
print("[mem] โ ๏ธ ์ํ ์์ โ ๊ณต์ฉ ์๋ฒ์์๋ ์ํํ๋ค. --mem_fraction ์ ์ง์ ํ๋ผ.")
# ---------------------------------------------------------------- ๋ฉ์ธ
def main():
p = argparse.ArgumentParser()
p.add_argument("--model", required=True, help="HF ๋ชจ๋ธ ID ๋๋ ๋ก์ปฌ ๊ฒฝ๋ก")
p.add_argument("--train", required=True, help="ํ์ต jsonl")
p.add_argument("--val", default=None, help="๊ฒ์ฆ jsonl")
p.add_argument("--output", required=True, help="์ด๋ํฐ ์ ์ฅ ๊ฒฝ๋ก")
p.add_argument("--task", default="qa", help="run_card ๊ธฐ๋ก์ฉ ํ์คํฌ๋ช
")
p.add_argument("--lora_r", type=int, default=16)
p.add_argument("--lora_alpha", type=int, default=32)
p.add_argument("--lora_dropout", type=float, default=0.05)
p.add_argument("--target_modules", default="all-linear",
help="'all-linear' ๋๋ ์ผํ๊ตฌ๋ถ ๋ชจ๋๋ช
")
p.add_argument("--max_len", type=int, default=1024)
p.add_argument("--batch", type=int, default=4)
p.add_argument("--grad_accum", type=int, default=4)
p.add_argument("--lr", type=float, default=2e-4)
p.add_argument("--epochs", type=float, default=1.0)
p.add_argument("--max_steps", type=int, default=-1)
p.add_argument("--warmup_ratio", type=float, default=0.03)
p.add_argument("--logging_steps", type=int, default=20)
p.add_argument("--eval_steps", type=int, default=200)
p.add_argument("--save_steps", type=int, default=500)
p.add_argument("--per_epoch", action="store_true",
help="์ํญ ๋จ์ ์ ์ฅยทํ๊ฐ(11์ฐจ~, ์ ์์ ์๊ฑด: ์ํญ ์ฒดํฌํฌ์ธํธ๋ณ ํ๊ฐโ์ต์ ์ ํ). "
"์ฒดํฌํฌ์ธํธ๊ฐ ์ํญ ์๋งํผ ๋จ๋๋ค(save_total_limit ํด์ ).")
p.add_argument("--mem_fraction", type=float, default=0.19,
help="โ GPU๋น ๋ฉ๋ชจ๋ฆฌ ์ํ ๋น์จ. ๊ณต์ฉ ์๋ฒ์ด๋ฏ๋ก ๋ฐ๋์ ๊ฑด๋ค.")
p.add_argument("--system", default=None, help="system ํ๋กฌํํธ(์ ํ)")
p.add_argument("--seed", type=int, default=42)
p.add_argument("--limit", type=int, default=0, help="์ค๋ชจํฌ ํ
์คํธ์ฉ ์ํ ์ ์ ํ")
p.add_argument("--val_max", type=int, default=0,
help="ํ์ต ์ค ๊ฒ์ฆ์ ์ธ val ์ต๋ ๊ฑด์(0=์ ๋). "
"ํ์ต ์ค eval_loss๋ ์ถ์ธ ํ์ธ์ฉ์ด๋ฏ๋ก ์ ๋์ด ํ์ ์๋ค.")
# --- ๋ฉ๋ชจ๋ฆฌ ๋ฐฐ์น ์คํ์ฉ (N-028) -------------------------------------
p.add_argument("--load_4bit", action="store_true",
help="QLoRA. ๊ฐ์ค์น๋ฅผ 4bit๋ก ๋ค์ด ์ฅ๋น footprint๋ฅผ ์ค์ธ๋ค. "
"ํ ์ฅ์ ๋ชจ๋ธ ์ ์ฒด๊ฐ ๋ค์ด๊ฐ๋ฉด ๋ฐ์ดํฐ ๋ณ๋ ฌ(DDP)์ด ๊ฐ๋ฅํด์ง๋ค.")
p.add_argument("--device_map", default="auto",
help="'auto'=์ธต์ ์ฌ๋ฌ ์ฅ์ ์ชผ๊ฐฌ(๋ชจ๋ธ ๋ณ๋ ฌ, ํ ์ฅ์ฉ ์์ฐจ ์คํ). "
"'single'=๋ณด์ด๋ ์ฒซ ์ฅ์ ์ ๋ถ ์ฌ๋ฆผ(DDP์ ์ ์ ).")
p.add_argument("--attn", default="eager",
help="์ดํ
์
๊ตฌํ. 'eager'=์์ (๋๋ฆฌ๊ณ ์ดํ
์
ํ๋ ฌ์ ํต์งธ๋ก ๋ง๋ ๋ค), "
"'sdpa'=torch ๋ด์ฅ ์ปค๋(ํ๋ ฌ์ ์ ๋ง๋ ๋ค). โ ๏ธ **์ฐ๋ฆฌ ํ๊ฒฝ์์ ํจ๊ณผ ์์๋ค** โ 2.238 vs 2.285, ๋ฉ๋ชจ๋ฆฌ ๋์ผ. ๋ณ๋ชฉ์ด ์ดํ
์
์ด ์๋๋ผ ๋ก์ง์ด๋ค(N-017 ๊ธฐ๊ฐ).")
p.add_argument("--no_grad_ckpt", action="store_true",
help="gradient checkpointing ํด์ . ๋ฉ๋ชจ๋ฆฌโ ์๋โ. "
"โ ๏ธ '20~40%% ๋นจ๋ผ์ง๋ค'๋ [๋ฏธ๊ฒ์ฆ] ํต๋
์ด๊ณ ์ฐ๋ฆฌ ํ๊ฒฝ์์ ์ฐ ์ ์ด ์๋ค(N-006).")
p.add_argument("--resume_from_checkpoint", default=None,
help="์ฒดํฌํฌ์ธํธ์์ ์ด์ด์ ํ์ตํ๋ค. ๊ฒฝ๋ก๋ฅผ ์ฃผ๊ฑฐ๋ `auto` ๋ก "
"`--output` ์์ ๊ฐ์ฅ ์ต๊ทผ checkpoint-* ๋ฅผ ์ฐพ๋๋ค.\n"
"โ ๏ธ 2026-08-21 ์ ์ค. ๊ทธ ์ ์๋ **์ด ๊ธฐ๋ฅ์ด ์์ ์์๋ค** โ "
"`02_PROGRESS` ๊ฐ '์ฒดํฌํฌ์ธํธ๋ก ์ด์ด๋ถ์ผ ์ ์๋ค'๊ณ ์ ์ด๋์ง๋ง "
"`trainer.train()` ์ ์ธ์ ์์ด ๋ถ๋ฅด๊ณ ์์ด ์ฌ์ค์ด ์๋์๋ค. "
"7์๊ฐ์ง๋ฆฌ ํ์ต์ ๋ณดํ์ด ์๋ ์ํ์๋ค.")
p.add_argument("--legacy_loss_norm", action="store_true",
help="โ ๏ธ ์ ์์ค ์ ๊ทํ(๋ง์ดํฌ๋ก๋ฐฐ์น ๊ฐ์๋ก ๋๋)๋ก ๋๋๋ฆฐ๋ค. "
"๊ธธ์ด ํธํฅ์ด ์๊ธด๋ค(N-031). **ํธํฅ ํฌ๊ธฐ๋ฅผ ์ฌ๋ ๋์กฐ ์คํ ์ ์ฉ.**")
args = p.parse_args()
set_seed(args.seed)
random.seed(args.seed)
require_burst_lock_if_needed(args.mem_fraction) # โ ๋ฝ ์์ด ๋์ ์ํ์ด๋ฉด ์ฌ๊ธฐ์ ์ค๋จ (D-022, N-032)
cap_gpu_memory(args.mem_fraction, single_device=(args.device_map == "single"))
print(f"[๋ชจ๋ธ] {args.model}")
tok = AutoTokenizer.from_pretrained(args.model)
if tok.pad_token_id is None:
tok.pad_token = tok.eos_token
supports_system = detect_system_support(tok)
print(f"[ํ
ํ๋ฆฟ] system ๋กค ์ง์: {supports_system}"
+ ("" if supports_system else " โ system์ ์ฒซ user ํด์ ์ ์ด ๋ฃ๋๋ค"))
# device_map="auto" ๋ ์ธต์ ์ฌ๋ฌ ์ฅ์ ์ชผ๊ฐ ์น๋๋ค(= ๋ชจ๋ธ ๋ณ๋ ฌ).
# ๋ ์ฅ์ ์ฐ์ง๋ง **ํ ์ฅ์ฉ ์์ฐจ๋ก** ๋๋ค โ ํ ์ฅ์ด ๊ณ์ฐํ ๋ ๋ค๋ฅธ ์ฅ์ ๋
ผ๋ค.
# ์ง์ง ๋ณ๋ ฌ(DDP)์ ํ๋ ค๋ฉด ํ ์ฅ์ ๋ชจ๋ธ **์ ์ฒด**๊ฐ ๋ค์ด๊ฐ์ผ ํ๋ค. (N-028)
# DDP(torchrun)๋ก ๋์ฐ๋ฉด ํ๋ก์ธ์ค๋ง๋ค ์๊ธฐ ์นด๋๋ฅผ ์ก์์ผ ํ๋ค. ์ ๋ถ 0๋ฒ์
# ์ก์ผ๋ฉด ํ ์ฅ์ ๋ ์ฌ๋ณธ์ด ์ฌ๋ผ๊ฐ OOM ๋๊ณ , ๋๋จธ์ง ํ ์ฅ์ ๋
ผ๋ค.
local_rank = int(os.environ.get("LOCAL_RANK", 0))
dm = {"": local_rank} if args.device_map == "single" else args.device_map
load_kw = dict(dtype=torch.bfloat16, device_map=dm, attn_implementation=args.attn)
if args.load_4bit:
from transformers import BitsAndBytesConfig
load_kw["quantization_config"] = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4", # ์ ๊ท๋ถํฌ ๊ฐ์ค์น์ ๋ง์ถ 4bit ํํ
bnb_4bit_compute_dtype=torch.bfloat16, # ๊ณ์ฐ์ bf16์ผ๋ก ๋๋๋ ค์ ํ๋ค
bnb_4bit_use_double_quant=True, # ์์ํ ์์๊น์ง ํ ๋ฒ ๋ ์์ถ
)
print("[๋ชจ๋ธ] 4bit(nf4) ๋ก๋ โ ๊ฐ์ค์น footprint๋ฅผ ์ค์ฌ ํ ์ฅ์ ๋ด๋๋ค")
model = AutoModelForCausalLM.from_pretrained(args.model, **load_kw)
if args.load_4bit:
# 4bit ๊ฐ์ค์น๋ ํ์ต ๋์์ด ์๋๋ค. ์
๋ ฅ์ grad๊ฐ ํ๋ฅด๋๋ก ์ค๋นํด์ค์ผ
# LoRA ์ธต๊น์ง ์ญ์ ํ๊ฐ ๋ฟ๋๋ค.
from peft import prepare_model_for_kbit_training
model = prepare_model_for_kbit_training(
model, use_gradient_checkpointing=not args.no_grad_ckpt)
model.config.use_cache = False # ํ์ต ์ค์ ์บ์ ๋(๋ฉ๋ชจ๋ฆฌ ์ ์ฝ)
if not args.no_grad_ckpt:
model.gradient_checkpointing_enable()
model.enable_input_require_grads() # peft + gradient checkpointing ํ์
tm = args.target_modules
lora_cfg = LoraConfig(
r=args.lora_r,
lora_alpha=args.lora_alpha,
lora_dropout=args.lora_dropout,
bias="none",
task_type="CAUSAL_LM",
target_modules=tm if tm == "all-linear" else [s.strip() for s in tm.split(",")],
)
model = get_peft_model(model, lora_cfg)
model.print_trainable_parameters()
ds_train = JsonlSFTDataset(args.train, tok, args.max_len, args.system, supports_system)
ds_val = (JsonlSFTDataset(args.val, tok, args.max_len, args.system, supports_system)
if args.val else None)
if args.limit:
ds_train.rows = ds_train.rows[: args.limit]
if ds_val:
ds_val.rows = ds_val.rows[: max(8, args.limit // 10)]
elif args.val_max and ds_val and len(ds_val.rows) > args.val_max:
# ์์์ ์๋ฅด์ง ์๊ณ ๋ฌด์์๋ก ๋ฝ๋๋ค. jsonl ์ด ์๋ณธ ์์๋ฅผ ์ ์งํ๊ณ ์์ด
# ์๋ถ๋ถ๋ง ์ฐ๋ฉด ํน์ ๋ฌธ์ยท์ฃผ์ ์ ์น์ฐ์น๋ค. seed ๊ณ ์ ์ด๋ผ ์ฌํ๋๋ค.
ds_val.rows = random.Random(args.seed).sample(ds_val.rows, args.val_max)
print(f"[๊ฒ์ฆ] ํ์ต ์ค eval ์ ๋ฌด์์ {args.val_max:,}๊ฑด์ผ๋ก ํ๋ค "
f"(์ถ์ธ ํ์ธ์ฉ โ ์ต์ข
ํ๊ฐ๋ generate.py ๋ก ์ ๋ ๋ณ๋ ์ํ)")
print(f"[๋ฐ์ดํฐ] train {len(ds_train):,}" + (f" / val {len(ds_val):,}" if ds_val else ""))
os.makedirs(args.output, exist_ok=True)
targs = TrainingArguments(
output_dir=args.output,
per_device_train_batch_size=args.batch,
per_device_eval_batch_size=args.batch,
gradient_accumulation_steps=args.grad_accum,
learning_rate=args.lr,
num_train_epochs=args.epochs,
max_steps=args.max_steps,
warmup_ratio=args.warmup_ratio,
lr_scheduler_type="cosine",
bf16=True,
logging_steps=args.logging_steps,
eval_strategy=("epoch" if args.per_epoch else "steps") if ds_val else "no",
eval_steps=args.eval_steps,
save_strategy="epoch" if args.per_epoch else "steps",
save_steps=args.save_steps,
save_total_limit=None if args.per_epoch else 2,
report_to=[], # ์ธ๋ถ ์ถ์ ๋๊ตฌ ์ ์ (md๋ก ๊ธฐ๋ก)
gradient_checkpointing=not args.no_grad_ckpt,
seed=args.seed,
)
trainer = Trainer(
model=model,
args=targs,
train_dataset=ds_train,
eval_dataset=ds_val,
data_collator=PadCollator(tok.pad_token_id),
# N-031: ์ด๊ฒ ์์ผ๋ฉด ๋ง์ดํฌ๋ก๋ฐฐ์น ๊ฐ์๋ก ๋๋ ๊ธธ์ด ํธํฅ์ด ์๊ธด๋ค.
# ๊ฒ์ฆ ๋๊ตฌ: src/train/verify_loss_normalization.py
compute_loss_func=None if args.legacy_loss_norm else token_mean_loss,
)
if args.legacy_loss_norm:
print("[์์ค] โ ๏ธ ์ ์ ๊ทํ(๋ง์ดํฌ๋ก๋ฐฐ์น ๊ฐ์๋ก ๋๋)๋ก ๋๋ค โ "
"๊ธธ์ด ํธํฅ์ด ์๋ค. ๋น๊ต ์คํ์ฉ์ด ์๋๋ฉด ์ฐ์ง ๋ง๋ผ. (N-031)")
else:
print("[์์ค] ๋์ ๊ตฌ๊ฐ ์ ์ฒด ํ ํฐ ์๋ก ์ ๊ทํํ๋ค (compute_loss_func, N-031)")
# โโ resume ๊ฒฝ๋ก ๊ฒฐ์ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
resume = args.resume_from_checkpoint
if resume == "auto":
cks = [d for d in os.listdir(args.output)
if d.startswith("checkpoint-") and
os.path.isdir(os.path.join(args.output, d))] if os.path.isdir(args.output) else []
if cks:
# `checkpoint-1500` ์ด `checkpoint-500` ๋ณด๋ค ๋ค๋ค โ **๋ฌธ์์ด ์ ๋ ฌ์ด๋ฉด ํ๋ฆฐ๋ค.**
resume = os.path.join(args.output,
max(cks, key=lambda d: int(d.split("-")[1])))
else:
resume = None
print("[์ฌ๊ฐ] `auto` ์ธ๋ฐ ์ฒดํฌํฌ์ธํธ๊ฐ ์๋ค โ ์ฒ์๋ถํฐ ์์ํ๋ค")
if resume:
if not os.path.isdir(resume):
raise SystemExit(f"[์ค๋จ] ์ฒดํฌํฌ์ธํธ๋ฅผ ๋ชป ์ฐพ์๋ค: {resume}")
print(f"[์ฌ๊ฐ] {resume} ์์ ์ด์ด์ ํ์ตํ๋ค")
print("[ํ์ต] ์์")
torch.cuda.reset_peak_memory_stats()
result = trainer.train(resume_from_checkpoint=resume)
# ํผํฌ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๊ธฐ๋กํ๋ค. ์ํ(mem_fraction)์ ์ผ๋ง๋ ๋ถ์ด ์์๋์ง ๋ชจ๋ฅด๋ฉด
# "์ด ์ค์ ์ด ์์ฌ์์ฌํ๋์ง ์ฌ์ ๋ก์ ๋์ง"๋ฅผ ๋์ค์ ์ ์ ์๋ค.
# (์ค์ ๋ก batch=4 ๋ ์ต์ฅ ์ํ ๋ฐฐ์น์์ ์์ค ๊ณ์ฐ ์ค OOM ๋ฌ๋ค โ N-026)
peak = {}
cap_gib = torch.cuda.get_device_properties(0).total_memory / 1024**3 * args.mem_fraction
for i in range(torch.cuda.device_count()):
gib = torch.cuda.max_memory_allocated(i) / 1024**3
# โ ๏ธ allocated ๋ "ํ
์์ ์ค์ ๋ก ์ด ์"์ด๋ค. ์นด๋๊ฐ ๋ณด๋ ๊ฐ(nvidia-smi)์
# ํ ๋น์๊ฐ ๋ฏธ๋ฆฌ ์ก์๋ ์๋น๋ถ๊น์ง ํฌํจํ reserved ๋ค. ์์ฐ์ ๋ฐ์ง ๋
# ๋ด์ผ ํ๋ ๊ฑด reserved ์ชฝ์ด๋ค โ allocated ๋ง ๋ณด๋ฉด ๊ณผ์ํ๊ฐํ๋ค.
res = torch.cuda.max_memory_reserved(i) / 1024**3
peak[f"gpu{i}_peak_gib"] = round(gib, 2)
peak[f"gpu{i}_reserved_gib"] = round(res, 2)
print(f"[mem] GPU{i} ํ ๋น {gib:.2f}GiB / ์์ฝ {res:.2f}GiB "
f"/ ์ํ {cap_gib:.1f}GiB (์์ฝ ๊ธฐ์ค {res / cap_gib:.0%})")
peak["cap_gib"] = round(cap_gib, 2)
# โ DDP ์์๋ **rank 0 ๋ง ์ด๋ค.** ์ ๊ทธ๋ฌ๋ฉด ๋ ํ๋ก์ธ์ค๊ฐ ๊ฐ์ ๊ฒฝ๋ก์ ์ด๋ํฐ์
# run_card.json ์ ๋์์ ์จ์ ํ์ผ์ด ์์ธ๋ค(`save_pretrained` ๋ ์์์ ์ด์ง ์๋ค).
# LoRA ๊ฐ์ค์น๋ ๊ธฐ์ธ๊ธฐ ๋๊ธฐํ๋ก rank ๋ง๋ค ๊ฐ์ผ๋ฏ๋ก ํ๋๋ง ์ฐ๋ฉด ์ถฉ๋ถํ๋ค.
# ๋จ์ผ ํ๋ก์ธ์ค(๋ชจ๋ธ ๋ณ๋ ฌ)์์๋ `is_world_process_zero()` ๊ฐ ํญ์ True ๋ผ ๋ฌดํดํ๋ค.
# โ ๏ธ ๋ฉ๋ชจ๋ฆฌ๋ **rank ๋ง๋ค ์๊ธฐ ์นด๋๋ง** ๋ณธ๋ค โ `ddp_launch.sh` ๊ฐ ์นด๋๋ฅผ ํ๋๋ง
# ๋
ธ์ถํ๋ฏ๋ก rank1 ์ "GPU0" ์ ๋ฌผ๋ฆฌ์ ์ผ๋ก GPU1 ์ด๋ค. ๋ ์ฅ์ ๋ค ๋ณด๋ ค๋ฉด
# `torchrun --tee 3` ์ผ๋ก rank ๋ณ ์ถ๋ ฅ์ ๋ด์ผ ํ๋ค.
if not trainer.is_world_process_zero():
# `ddp_launch.sh` ๊ฐ LOCAL_RANK ๋ฅผ 0 ์ผ๋ก ๋ฎ์ด์ฐ๋ฏ๋ก(์นด๋ ๊ฒฉ๋ฆฌ) ์ง์ง ์๋ฒ์ RANK ๋ค.
print(f"[mem] (rank{os.environ.get('RANK', '?')} ์ ์ ์ฅํ์ง ์๋๋ค "
f"โ ์ [mem] ์ ์ด rank ๊ฐ ์ฅ ์นด๋์ ๊ฐ์ด๋ค)")
return 0
adapter_dir = os.path.join(args.output, "adapter")
model.save_pretrained(adapter_dir)
tok.save_pretrained(adapter_dir)
print(f"[์ ์ฅ] ์ด๋ํฐ โ {adapter_dir}")
# ์คํ ์นด๋ โ ์ด ์ด๋ํฐ๊ฐ ๋ฌด์์ผ๋ก ์ด๋ป๊ฒ ๋ง๋ค์ด์ก๋์ง
card = {
"task": args.task,
"base_model": args.model,
"git_commit": git_commit_hash(),
"data": {"train": args.train, "val": args.val,
"n_train": len(ds_train), "n_val": len(ds_val) if ds_val else 0,
"val_max": args.val_max},
"lora": {"r": args.lora_r, "alpha": args.lora_alpha,
"dropout": args.lora_dropout, "target_modules": args.target_modules},
"train": {"max_len": args.max_len, "batch": args.batch,
"grad_accum": args.grad_accum, "lr": args.lr,
"epochs": args.epochs, "max_steps": args.max_steps,
"seed": args.seed},
"resumed_from": resume,
"mem_fraction": args.mem_fraction,
"load_4bit": args.load_4bit,
"device_map": args.device_map,
"grad_checkpointing": not args.no_grad_ckpt,
"peak_memory": peak,
"attn": args.attn,
"alloc_conf": os.environ.get("PYTORCH_CUDA_ALLOC_CONF", "(๊ธฐ๋ณธ๊ฐ)"),
"metrics": {k: v for k, v in result.metrics.items()},
"log_history": trainer.state.log_history,
}
with open(os.path.join(args.output, "run_card.json"), "w", encoding="utf-8") as f:
json.dump(card, f, ensure_ascii=False, indent=2)
print(f"[์ ์ฅ] ์คํ ์นด๋ โ {args.output}/run_card.json")
print(f"[์๋ฃ] train_loss={result.metrics.get('train_loss')}")
if __name__ == "__main__":
sys.exit(main())
|