Upload folder using huggingface_hub

#39
source/train/__init__.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ train — LLM pretraining package.
3
+
4
+ Public API:
5
+ TrainConfig : Dataclass of training hyper-parameters.
6
+ Trainer : Core training loop with gradient accumulation, AMP, and logging.
7
+
8
+ Utility functions (re-exported from train.utils):
9
+ get_cosine_schedule_with_warmup
10
+ save_checkpoint
11
+ load_checkpoint
12
+ get_grad_norm
13
+ setup_ddp
14
+ cleanup_ddp
15
+ is_main_process
16
+ """
17
+
18
+ from train.trainer import TrainConfig, Trainer
19
+ from train.utils import (
20
+ cleanup_ddp,
21
+ get_cosine_schedule_with_warmup,
22
+ get_grad_norm,
23
+ is_main_process,
24
+ load_checkpoint,
25
+ save_checkpoint,
26
+ setup_ddp,
27
+ )
28
+
29
+ __all__ = [
30
+ # Core classes
31
+ "TrainConfig",
32
+ "Trainer",
33
+ # Utility functions
34
+ "get_cosine_schedule_with_warmup",
35
+ "save_checkpoint",
36
+ "load_checkpoint",
37
+ "get_grad_norm",
38
+ "setup_ddp",
39
+ "cleanup_ddp",
40
+ "is_main_process",
41
+ ]
source/train/orpo.py ADDED
@@ -0,0 +1,586 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ORPO (Odds Ratio Preference Optimization) training script.
3
+ Uses TRL 0.29.0 ORPOTrainer/ORPOConfig (trl.experimental.orpo).
4
+ Optimized for 8x NVIDIA B200 GPUs (183GB VRAM each, ~1.47TB total).
5
+
6
+ Usage:
7
+ # Full training (8 GPU DDP)
8
+ torchrun --nproc_per_node=8 train/orpo.py \
9
+ --config configs/korean_3b_orpo.yaml
10
+
11
+ # Quick test (200 steps)
12
+ python train/orpo.py --config configs/korean_3b_orpo.yaml --max_steps 200
13
+
14
+ # Single GPU test
15
+ python train/orpo.py --config configs/korean_3b_orpo.yaml --device cuda:0
16
+
17
+ Prerequisites:
18
+ pip install trl==0.29.0 transformers accelerate peft datasets
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import datetime
25
+ import json
26
+ import logging
27
+ import os
28
+ import signal as _signal_mod
29
+ import sys
30
+ import time
31
+ import traceback
32
+ from pathlib import Path
33
+
34
+ import torch
35
+ from datasets import Dataset, load_dataset
36
+ from transformers import (
37
+ AutoModelForCausalLM,
38
+ AutoTokenizer,
39
+ EarlyStoppingCallback,
40
+ TrainerCallback,
41
+ )
42
+
43
+ # TRL imports -- ORPOTrainer/ORPOConfig (TRL 0.29.0, experimental path)
44
+ try:
45
+ from trl.experimental.orpo import ORPOConfig, ORPOTrainer
46
+ except ImportError:
47
+ print("ERROR: trl not installed or outdated. Run: pip install trl==0.29.0")
48
+ sys.exit(1)
49
+
50
+ # Telegram notifications
51
+ try:
52
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
53
+ from scripts.telegram_notify import send_telegram_safe
54
+ HAS_TELEGRAM = True
55
+ except ImportError:
56
+ HAS_TELEGRAM = False
57
+ def send_telegram_safe(msg, **kw): return False
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # Logging setup
61
+ # ---------------------------------------------------------------------------
62
+ logging.basicConfig(
63
+ level=logging.INFO,
64
+ format="%(asctime)s [%(levelname)s] %(message)s",
65
+ datefmt="%Y-%m-%d %H:%M:%S",
66
+ )
67
+ log = logging.getLogger("orpo")
68
+
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # Custom callback for detailed monitoring
72
+ # ---------------------------------------------------------------------------
73
+ class ORPOMonitorCallback(TrainerCallback):
74
+ """Monitors ORPO-specific metrics and sends alerts on anomalies."""
75
+
76
+ def __init__(self, alert_fn=send_telegram_safe):
77
+ self.alert_fn = alert_fn
78
+ self.start_time = None
79
+ self.last_eval_loss = None
80
+ self.eval_loss_increases = 0
81
+ self.negative_margin_streak = 0
82
+
83
+ def on_train_begin(self, args, state, control, **kwargs):
84
+ self.start_time = time.time()
85
+ log.info("ORPO training begin -- monitoring active")
86
+
87
+ def on_log(self, args, state, control, logs=None, **kwargs):
88
+ if logs is None:
89
+ return
90
+ step = state.global_step
91
+
92
+ # Monitor rewards/margins
93
+ margin = logs.get("rewards/margins")
94
+ if margin is not None:
95
+ if margin < 0:
96
+ self.negative_margin_streak += 1
97
+ if self.negative_margin_streak >= 10:
98
+ msg = (f"[ORPO ALERT] rewards/margins negative for "
99
+ f"{self.negative_margin_streak} consecutive logs at step {step} "
100
+ f"(margin={margin:.4f})")
101
+ log.warning(msg)
102
+ self.alert_fn(msg)
103
+ else:
104
+ self.negative_margin_streak = 0
105
+
106
+ # Log key metrics every logging step
107
+ loss = logs.get("loss")
108
+ chosen = logs.get("rewards/chosen")
109
+ rejected = logs.get("rewards/rejected")
110
+ if loss is not None:
111
+ elapsed = time.time() - self.start_time if self.start_time else 0
112
+ log.info(
113
+ f"step={step} loss={loss:.4f} "
114
+ f"margin={margin if margin is not None else 'N/A'} "
115
+ f"chosen={chosen if chosen is not None else 'N/A'} "
116
+ f"rejected={rejected if rejected is not None else 'N/A'} "
117
+ f"elapsed={elapsed/3600:.1f}h"
118
+ )
119
+
120
+ # Check for NaN/Inf
121
+ if loss is not None and (not isinstance(loss, (int, float)) or loss != loss):
122
+ msg = f"[ORPO CRITICAL] NaN/Inf loss detected at step {step}!"
123
+ log.error(msg)
124
+ self.alert_fn(msg)
125
+
126
+ def on_evaluate(self, args, state, control, metrics=None, **kwargs):
127
+ if metrics is None:
128
+ return
129
+ eval_loss = metrics.get("eval_loss")
130
+ step = state.global_step
131
+
132
+ if eval_loss is not None:
133
+ log.info(f"[EVAL] step={step} eval_loss={eval_loss:.4f}")
134
+ if self.last_eval_loss is not None and eval_loss > self.last_eval_loss:
135
+ self.eval_loss_increases += 1
136
+ log.warning(
137
+ f"[EVAL] eval_loss increased: {self.last_eval_loss:.4f} -> {eval_loss:.4f} "
138
+ f"({self.eval_loss_increases}/3 before early stop)"
139
+ )
140
+ else:
141
+ self.eval_loss_increases = 0
142
+ self.last_eval_loss = eval_loss
143
+
144
+ def on_train_end(self, args, state, control, **kwargs):
145
+ elapsed = time.time() - self.start_time if self.start_time else 0
146
+ log.info(f"ORPO training ended -- total time: {elapsed/3600:.2f}h, "
147
+ f"total steps: {state.global_step}")
148
+
149
+ def on_save(self, args, state, control, **kwargs):
150
+ log.info(f"Checkpoint saved at step {state.global_step}")
151
+
152
+
153
+ class VRAMMonitorCallback(TrainerCallback):
154
+ """Measures peak VRAM usage across all GPUs during training."""
155
+
156
+ def on_train_begin(self, args, state, control, **kwargs):
157
+ if torch.cuda.is_available():
158
+ for i in range(torch.cuda.device_count()):
159
+ torch.cuda.reset_peak_memory_stats(i)
160
+ log.info("[VRAM] Peak memory stats reset for all GPUs")
161
+
162
+ def on_train_end(self, args, state, control, **kwargs):
163
+ if torch.cuda.is_available():
164
+ for i in range(torch.cuda.device_count()):
165
+ peak_mb = torch.cuda.max_memory_allocated(i) / (1024**2)
166
+ log.info(f"[VRAM] GPU {i} peak: {peak_mb:.0f} MiB")
167
+
168
+
169
+ def load_hf_preference_dataset(dataset_name: str, token: str | None = None) -> Dataset:
170
+ """Load and normalize a HuggingFace preference dataset to {prompt, chosen, rejected}."""
171
+ ds = load_dataset(dataset_name, split="train", token=token)
172
+
173
+ # kuotient/orca-math-korean-dpo-pairs format: {system, question, chosen, rejected}
174
+ if "question" in ds.column_names and "chosen" in ds.column_names:
175
+ def normalize(example):
176
+ prompt = example.get("system", "") + "\n" + example["question"]
177
+ return {"prompt": prompt.strip(), "chosen": example["chosen"], "rejected": example["rejected"]}
178
+ return ds.map(normalize, remove_columns=ds.column_names)
179
+
180
+ # nayohan/preference-collection-ko-full format: {response_A, response_B, orig_preference}
181
+ if "orig_preference" in ds.column_names:
182
+ def normalize_pref(example):
183
+ prompt = example.get("orig_instruction", example.get("instruction", ""))
184
+ if example["orig_preference"] == "B":
185
+ return {"prompt": prompt, "chosen": example["orig_response_B"], "rejected": example["orig_response_A"]}
186
+ else:
187
+ return {"prompt": prompt, "chosen": example["orig_response_A"], "rejected": example["orig_response_B"]}
188
+ return ds.map(normalize_pref, remove_columns=ds.column_names)
189
+
190
+ # Already in {prompt, chosen, rejected} format
191
+ if all(c in ds.column_names for c in ["prompt", "chosen", "rejected"]):
192
+ return ds
193
+
194
+ raise ValueError(f"Unknown dataset format. Columns: {ds.column_names}")
195
+
196
+
197
+ def load_custom_jsonl(path: str) -> Dataset:
198
+ """Load custom JSONL with {prompt, chosen, rejected} fields."""
199
+ data = []
200
+ with open(path) as f:
201
+ for line in f:
202
+ data.append(json.loads(line))
203
+ return Dataset.from_list(data)
204
+
205
+
206
+ def load_yaml_config(path: str) -> dict:
207
+ """Load YAML config and return as dict."""
208
+ import yaml
209
+ with open(path) as f:
210
+ return yaml.safe_load(f)
211
+
212
+
213
+ def main():
214
+ parser = argparse.ArgumentParser(description="ORPO Training (TRL 0.29.0 -- 8xB200 optimized)")
215
+ parser.add_argument("--config", type=str, default=None, help="YAML config file path")
216
+ parser.add_argument("--model_path", type=str, default=None, help="HF format model path")
217
+ parser.add_argument("--dataset", type=str, default="kuotient/orca-math-korean-dpo-pairs")
218
+ parser.add_argument("--custom_data_path", type=str, default=None, help="Custom JSONL preference data")
219
+ parser.add_argument("--output_dir", type=str, default="checkpoints/korean_3b_orpo")
220
+ parser.add_argument("--hf_token", type=str, default=None)
221
+ parser.add_argument("--epochs", type=int, default=3)
222
+ parser.add_argument("--lr", type=float, default=5e-6)
223
+ parser.add_argument("--beta", type=float, default=0.1, help="ORPO beta (odds ratio weight)")
224
+ parser.add_argument("--batch_size", type=int, default=4)
225
+ parser.add_argument("--gradient_accumulation_steps", type=int, default=4)
226
+ parser.add_argument("--max_length", type=int, default=1536)
227
+ parser.add_argument("--bf16", action="store_true", default=True)
228
+ parser.add_argument("--weight_decay", type=float, default=0.01)
229
+ parser.add_argument("--eval_split_ratio", type=float, default=0.05, help="Fraction of data for eval")
230
+ parser.add_argument("--eval_steps", type=int, default=500)
231
+ parser.add_argument("--early_stopping_patience", type=int, default=3)
232
+ parser.add_argument("--max_steps", type=int, default=-1, help="Override max steps (for quick test)")
233
+ parser.add_argument("--seed", type=int, default=42)
234
+ parser.add_argument("--save_total_limit", type=int, default=5)
235
+ parser.add_argument("--warmup_ratio", type=float, default=0.05)
236
+ parser.add_argument("--lr_scheduler_type", type=str, default="cosine")
237
+ parser.add_argument("--logging_steps", type=int, default=10)
238
+ parser.add_argument("--save_steps", type=int, default=500)
239
+ parser.add_argument("--gradient_checkpointing", action="store_true", default=True)
240
+ parser.add_argument("--report_to", type=str, default="none")
241
+ parser.add_argument("--dataset_num_proc", type=int, default=8,
242
+ help="Number of processes for parallel tokenization in ORPOTrainer")
243
+ parser.add_argument("--dataloader_num_workers", type=int, default=4,
244
+ help="Number of dataloader worker processes")
245
+ parser.add_argument("--no_load_best", action="store_true", default=False,
246
+ help="Disable load_best_model_at_end (for sweep/quick tests)")
247
+ parser.add_argument("--max_samples", type=int, default=0,
248
+ help="Limit dataset size (0=use all, >0=subset for benchmarking)")
249
+ parser.add_argument("--skip_filter", action="store_true", default=False,
250
+ help="Skip NaN-prevention filter (for benchmarking only)")
251
+ args = parser.parse_args()
252
+
253
+ # Override CLI defaults with YAML config values
254
+ if args.config:
255
+ cfg = load_yaml_config(args.config)
256
+ for key, value in cfg.items():
257
+ if hasattr(args, key):
258
+ setattr(args, key, value)
259
+
260
+ if not args.model_path:
261
+ parser.error("--model_path is required (or set model_path in YAML config)")
262
+
263
+ # Log all resolved config
264
+ local_rank = int(os.environ.get("LOCAL_RANK", 0))
265
+ is_main = local_rank == 0
266
+ if is_main:
267
+ log.info("=" * 70)
268
+ log.info("ORPO Training Configuration (8xB200 optimized)")
269
+ log.info("=" * 70)
270
+ for k, v in sorted(vars(args).items()):
271
+ log.info(f" {k}: {v}")
272
+ log.info("=" * 70)
273
+
274
+ # GPU info
275
+ if torch.cuda.is_available():
276
+ for i in range(torch.cuda.device_count()):
277
+ mem = torch.cuda.get_device_properties(i).total_memory / 1e9
278
+ log.info(f" GPU {i}: {torch.cuda.get_device_name(i)} ({mem:.1f} GB)")
279
+
280
+ # Validate paths
281
+ if not Path(args.model_path).exists():
282
+ raise FileNotFoundError(f"Model path not found: {args.model_path}")
283
+ if args.custom_data_path and not Path(args.custom_data_path).exists():
284
+ raise FileNotFoundError(f"Data path not found: {args.custom_data_path}")
285
+
286
+ # NCCL/DDP environment diagnostics
287
+ if is_main:
288
+ log.info("--- DDP/NCCL Environment ---")
289
+ for env_key in ["RANK", "WORLD_SIZE", "LOCAL_RANK", "MASTER_ADDR", "MASTER_PORT",
290
+ "NCCL_IB_DISABLE", "NCCL_BUFFSIZE", "NCCL_P2P_LEVEL",
291
+ "OMP_NUM_THREADS", "PYTORCH_CUDA_ALLOC_CONF"]:
292
+ log.info(f" {env_key}={os.environ.get(env_key, '(not set)')}")
293
+ log.info(f" torch.distributed.is_available={torch.distributed.is_available()}")
294
+ if torch.distributed.is_initialized():
295
+ log.info(f" world_size={torch.distributed.get_world_size()}, "
296
+ f"rank={torch.distributed.get_rank()}")
297
+
298
+ # Load model (bfloat16 + flash_attention_2 for B200)
299
+ log.info(f"Loading model from {args.model_path}...")
300
+ t0 = time.time()
301
+ try:
302
+ model = AutoModelForCausalLM.from_pretrained(
303
+ args.model_path,
304
+ torch_dtype=torch.bfloat16,
305
+ attn_implementation="flash_attention_2",
306
+ )
307
+ except Exception as e:
308
+ log.error(f"Model loading failed: {e}")
309
+ send_telegram_safe(f"[ORPO FATAL] Model load failed: {e}")
310
+ raise
311
+ tokenizer = AutoTokenizer.from_pretrained(args.model_path)
312
+ if tokenizer.pad_token is None:
313
+ tokenizer.pad_token = tokenizer.eos_token
314
+ if is_main:
315
+ n_params = sum(p.numel() for p in model.parameters())
316
+ log.info(f"Model loaded: {n_params:,} params in {time.time()-t0:.1f}s")
317
+ log.info(f"Tokenizer: vocab_size={tokenizer.vocab_size}, "
318
+ f"pad_token='{tokenizer.pad_token}', eos_token='{tokenizer.eos_token}'")
319
+
320
+ # Load dataset
321
+ t0 = time.time()
322
+ try:
323
+ if args.custom_data_path:
324
+ log.info(f"Loading custom data from {args.custom_data_path}...")
325
+ fsize_mb = Path(args.custom_data_path).stat().st_size / 1e6
326
+ log.info(f" File size: {fsize_mb:.1f} MB")
327
+ dataset = load_custom_jsonl(args.custom_data_path)
328
+ else:
329
+ log.info(f"Loading dataset {args.dataset}...")
330
+ dataset = load_hf_preference_dataset(args.dataset, token=args.hf_token)
331
+ except Exception as e:
332
+ log.error(f"Dataset loading failed: {e}")
333
+ send_telegram_safe(f"[ORPO FATAL] Data load failed: {e}")
334
+ raise
335
+
336
+ # Subset for benchmarking (skip tokenization bottleneck)
337
+ if args.max_samples > 0 and len(dataset) > args.max_samples:
338
+ dataset = dataset.select(range(args.max_samples))
339
+ if is_main:
340
+ log.info(f"[BENCH] Dataset subset: {args.max_samples:,} samples")
341
+
342
+ if is_main:
343
+ log.info(f"Dataset loaded: {len(dataset)} pairs in {time.time()-t0:.1f}s")
344
+ # Data quality check
345
+ sample = dataset[0]
346
+ log.info(f"Sample keys: {list(sample.keys())}")
347
+ for key in ["prompt", "chosen", "rejected"]:
348
+ if key not in sample:
349
+ raise ValueError(f"Dataset missing required column: {key}")
350
+ val = sample[key]
351
+ log.info(f" {key}: {str(val)[:100]}...")
352
+
353
+ # Length distribution check (sample first 1000)
354
+ sample_size = min(1000, len(dataset))
355
+ lengths = [len(str(dataset[i]["prompt"])) + max(len(str(dataset[i]["chosen"])),
356
+ len(str(dataset[i]["rejected"]))) for i in range(sample_size)]
357
+ avg_len = sum(lengths) / len(lengths)
358
+ max_len = max(lengths)
359
+ log.info(f" Char lengths (sample {sample_size}): avg={avg_len:.0f}, max={max_len}")
360
+
361
+ # Filter out samples where prompt is too long for the response to fit in max_length.
362
+ # Without this, samples with 0 response tokens cause NaN in ORPO log-probability computation
363
+ # (division by zero in average_log_prob when loss_mask is all-zero).
364
+ # Also catches TRL truncation bug: tokenize_row uses longer_response_length = max(chosen_len, rejected_len)
365
+ # and truncates BOTH responses to [:max_length - longer_response_length]. When longer >= max_length,
366
+ # the shorter response becomes EMPTY → NaN.
367
+ if args.skip_filter:
368
+ if is_main:
369
+ log.info("[BENCH] Skipping NaN-prevention filter (--skip_filter)")
370
+ else:
371
+ pre_filter = len(dataset)
372
+ def _has_response_room(example):
373
+ prompt_tok_len = len(tokenizer.encode(example["prompt"], add_special_tokens=False))
374
+ chosen_tok_len = len(tokenizer.encode(example["chosen"], add_special_tokens=False))
375
+ rejected_tok_len = len(tokenizer.encode(example["rejected"], add_special_tokens=False))
376
+
377
+ # 1. Prompt must leave room for at least 16 response tokens
378
+ if prompt_tok_len + 16 > args.max_length:
379
+ return False
380
+
381
+ # 2. Each response independently must fit with prompt
382
+ # (TRL adds BOS/EOS, so use +2 margin)
383
+ if prompt_tok_len + chosen_tok_len + 2 > args.max_length * 2:
384
+ return False # extremely long, will cause issues
385
+ if prompt_tok_len + rejected_tok_len + 2 > args.max_length * 2:
386
+ return False
387
+
388
+ # 3. The longer response must not exceed max_length alone
389
+ # (TRL bug: both responses truncated by max(chosen_len, rejected_len))
390
+ longer = max(chosen_tok_len, rejected_tok_len)
391
+ if longer >= args.max_length:
392
+ return False
393
+
394
+ return True
395
+ dataset = dataset.filter(_has_response_room, num_proc=min(args.dataset_num_proc, 32) if is_main else 1)
396
+ if is_main:
397
+ log.info(f"Filtered: {pre_filter:,} -> {len(dataset):,} "
398
+ f"(removed {pre_filter - len(dataset):,} samples with prompt > max_length-16 or TRL truncation risk)")
399
+
400
+ # Train/eval split
401
+ split = dataset.train_test_split(test_size=args.eval_split_ratio, seed=args.seed)
402
+ train_dataset = split["train"]
403
+ eval_dataset = split["test"]
404
+ log.info(f"Train: {len(train_dataset):,}, Eval: {len(eval_dataset):,}")
405
+
406
+ # Compute training stats for warmup_steps calculation
407
+ n_gpus = max(torch.cuda.device_count(), 1) if torch.cuda.is_available() else 1
408
+ eff_batch = args.batch_size * args.gradient_accumulation_steps * n_gpus
409
+ steps_per_epoch = len(train_dataset) // eff_batch
410
+ total_steps = args.max_steps if args.max_steps > 0 else steps_per_epoch * args.epochs
411
+ computed_warmup_steps = int(total_steps * args.warmup_ratio)
412
+ if is_main:
413
+ log.info(f"Training plan: eff_batch={eff_batch}, steps/epoch={steps_per_epoch:,}, "
414
+ f"total={total_steps:,}, warmup={computed_warmup_steps}")
415
+
416
+ # DDP tokenization strategy:
417
+ # TRL ORPOTrainer uses main_process_first() — rank 0 tokenizes first, then ranks 1-7.
418
+ # With multiprocessing (num_proc>1), ranks 1-7 all spawn workers simultaneously,
419
+ # causing CPU/memory oversubscription (e.g. 7 ranks × 8 workers = 56 processes).
420
+ # Fix: rank 0 uses full num_proc for speed, other ranks use 1 (should hit cache).
421
+ world_size = int(os.environ.get("WORLD_SIZE", 1))
422
+ if world_size > 1:
423
+ effective_num_proc = args.dataset_num_proc if is_main else 1
424
+ if is_main:
425
+ log.info(f"DDP tokenization: rank 0 uses num_proc={args.dataset_num_proc}, "
426
+ f"other {world_size-1} ranks use num_proc=1 (cache)")
427
+ else:
428
+ effective_num_proc = args.dataset_num_proc
429
+
430
+ # ORPOConfig (TRL 0.29.0) -- optimized for 8x B200
431
+ orpo_config = ORPOConfig(
432
+ output_dir=args.output_dir,
433
+ num_train_epochs=args.epochs,
434
+ per_device_train_batch_size=args.batch_size,
435
+ per_device_eval_batch_size=args.batch_size,
436
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
437
+ learning_rate=args.lr,
438
+ beta=args.beta,
439
+ lr_scheduler_type=args.lr_scheduler_type,
440
+ warmup_steps=computed_warmup_steps,
441
+ weight_decay=args.weight_decay,
442
+ bf16=args.bf16,
443
+ logging_steps=args.logging_steps,
444
+ save_steps=args.save_steps,
445
+ save_total_limit=args.save_total_limit,
446
+ max_length=args.max_length,
447
+ gradient_checkpointing=args.gradient_checkpointing,
448
+ report_to=args.report_to,
449
+ remove_unused_columns=False,
450
+ eval_strategy="steps",
451
+ eval_steps=args.eval_steps,
452
+ metric_for_best_model="eval_loss" if not args.no_load_best else None,
453
+ load_best_model_at_end=not args.no_load_best,
454
+ greater_is_better=False if not args.no_load_best else None,
455
+ max_steps=args.max_steps,
456
+ seed=args.seed,
457
+ # B200 hardware optimizations
458
+ dataloader_num_workers=args.dataloader_num_workers,
459
+ dataloader_pin_memory=True,
460
+ ddp_find_unused_parameters=False,
461
+ ddp_timeout=7200, # 2h — tokenization takes ~30min on 683K samples
462
+ dataset_num_proc=effective_num_proc,
463
+ )
464
+
465
+ # ORPOTrainer (no reference model needed)
466
+ log.info("Initializing ORPOTrainer (tokenization will happen here — may take a while)...")
467
+ t0 = time.time()
468
+ monitor = ORPOMonitorCallback()
469
+ try:
470
+ trainer = ORPOTrainer(
471
+ model=model,
472
+ args=orpo_config,
473
+ train_dataset=train_dataset,
474
+ eval_dataset=eval_dataset,
475
+ processing_class=tokenizer,
476
+ callbacks=[cb for cb in [
477
+ EarlyStoppingCallback(early_stopping_patience=args.early_stopping_patience)
478
+ if not args.no_load_best else None,
479
+ monitor,
480
+ VRAMMonitorCallback(),
481
+ ] if cb is not None],
482
+ )
483
+ except Exception as e:
484
+ log.error(f"ORPOTrainer init failed: {e}\n{traceback.format_exc()}")
485
+ send_telegram_safe(f"[ORPO FATAL] Trainer init failed: {e}")
486
+ raise
487
+ if is_main:
488
+ log.info(f"ORPOTrainer initialized in {time.time()-t0:.1f}s "
489
+ f"(dataset_num_proc={args.dataset_num_proc})")
490
+
491
+ # SIGHUP/SIGTERM defense -- graceful shutdown with emergency checkpoint
492
+ def _graceful_shutdown_handler(signum, frame):
493
+ sig_name = _signal_mod.Signals(signum).name
494
+ log.warning(f"Received {sig_name}. Saving emergency checkpoint...")
495
+ try:
496
+ emergency_path = os.path.join(args.output_dir, "emergency_checkpoint")
497
+ trainer.save_model(emergency_path)
498
+ log.info(f"Emergency checkpoint saved to {emergency_path}")
499
+ send_telegram_safe(
500
+ f"[ORPO] Signal {sig_name} received at step {trainer.state.global_step}. "
501
+ f"Emergency checkpoint saved."
502
+ )
503
+ except Exception as e:
504
+ log.error(f"Emergency save failed: {e}")
505
+ send_telegram_safe(f"[ORPO] Emergency save FAILED after {sig_name}: {e}")
506
+ sys.exit(1)
507
+
508
+ for _sig in (_signal_mod.SIGHUP, _signal_mod.SIGTERM):
509
+ _signal_mod.signal(_sig, _graceful_shutdown_handler)
510
+
511
+ # Pre-training VRAM report
512
+ if is_main and torch.cuda.is_available():
513
+ torch.cuda.reset_peak_memory_stats()
514
+ alloc = torch.cuda.memory_allocated() / 1e9
515
+ reserved = torch.cuda.memory_reserved() / 1e9
516
+ log.info(f"Pre-train VRAM: allocated={alloc:.1f}GB, reserved={reserved:.1f}GB")
517
+
518
+ start_msg = (
519
+ f"[ORPO] Training started\n"
520
+ f" model: {args.model_path}\n"
521
+ f" beta: {args.beta}, lr: {args.lr}\n"
522
+ f" train: {len(train_dataset):,}, eval: {len(eval_dataset):,}\n"
523
+ f" eff_batch: {eff_batch}, steps/epoch: {steps_per_epoch:,}, total: {total_steps:,}\n"
524
+ f" warmup: {computed_warmup_steps} steps ({args.warmup_ratio*100:.0f}%)\n"
525
+ f" max_length: {args.max_length}, max_steps: {args.max_steps}\n"
526
+ f" dataset_num_proc: {args.dataset_num_proc}, dl_workers: {args.dataloader_num_workers}"
527
+ )
528
+ log.info(start_msg.replace("[ORPO] ", ""))
529
+ send_telegram_safe(start_msg)
530
+
531
+ try:
532
+ trainer.train()
533
+
534
+ # Post-training VRAM report
535
+ if is_main and torch.cuda.is_available():
536
+ peak = torch.cuda.max_memory_allocated() / 1e9
537
+ log.info(f"Peak VRAM usage: {peak:.1f}GB")
538
+
539
+ trainer.save_model(args.output_dir)
540
+ log.info(f"Model saved to {args.output_dir}")
541
+
542
+ # Extract final metrics
543
+ final_metrics = {}
544
+ for entry in reversed(trainer.state.log_history):
545
+ if "loss" in entry and "loss" not in final_metrics:
546
+ final_metrics["loss"] = entry["loss"]
547
+ if "eval_loss" in entry and "eval_loss" not in final_metrics:
548
+ final_metrics["eval_loss"] = entry["eval_loss"]
549
+ if "rewards/margins" in entry and "rewards/margins" not in final_metrics:
550
+ final_metrics["rewards/margins"] = entry["rewards/margins"]
551
+ if len(final_metrics) >= 3:
552
+ break
553
+
554
+ done_msg = (
555
+ f"[ORPO] Training complete!\n"
556
+ f" output: {args.output_dir}\n"
557
+ f" steps: {trainer.state.global_step}\n"
558
+ f" final loss: {final_metrics.get('loss', 'N/A')}\n"
559
+ f" final eval_loss: {final_metrics.get('eval_loss', 'N/A')}\n"
560
+ f" final margins: {final_metrics.get('rewards/margins', 'N/A')}"
561
+ )
562
+ log.info(done_msg.replace("[ORPO] ", ""))
563
+ send_telegram_safe(done_msg)
564
+
565
+ except KeyboardInterrupt:
566
+ log.warning("Training interrupted by user (KeyboardInterrupt)")
567
+ send_telegram_safe(f"[ORPO] Training interrupted at step {trainer.state.global_step}")
568
+ trainer.save_model(os.path.join(args.output_dir, "interrupted_checkpoint"))
569
+ log.info("Interrupted checkpoint saved.")
570
+
571
+ except Exception as e:
572
+ tb = traceback.format_exc()
573
+ error_msg = f"[ORPO] Training FAILED at step {trainer.state.global_step}: {e}"
574
+ log.error(f"{error_msg}\n{tb}")
575
+ send_telegram_safe(f"{error_msg}\n{tb[:500]}")
576
+ # Try emergency save
577
+ try:
578
+ trainer.save_model(os.path.join(args.output_dir, "error_checkpoint"))
579
+ log.info("Error checkpoint saved.")
580
+ except Exception:
581
+ log.error("Error checkpoint save also failed.")
582
+ raise
583
+
584
+
585
+ if __name__ == "__main__":
586
+ main()
source/train/pretrain.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ train/pretrain.py — Main pretraining entry point.
3
+
4
+ Launch single-GPU:
5
+ python train/pretrain.py --config configs/small.yaml --train_data data/train.bin
6
+
7
+ Launch multi-GPU with torchrun:
8
+ torchrun --nproc_per_node=8 train/pretrain.py --config configs/small.yaml \
9
+ --train_data data/train.bin
10
+
11
+ The script auto-detects whether it is running inside a torchrun launch by
12
+ checking for the RANK environment variable.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import os
19
+ import random
20
+ import signal
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ import numpy as np
25
+ import torch
26
+ from torch.utils.data import DataLoader, DistributedSampler, RandomSampler
27
+
28
+ # B200 Tensor Core 최대 활용: TF32 matmul + cuDNN
29
+ torch.backends.cuda.matmul.allow_tf32 = True
30
+ torch.backends.cudnn.allow_tf32 = True
31
+ torch.backends.cudnn.benchmark = True # fixed seq_len=4096 → safe to auto-tune
32
+ torch.set_float32_matmul_precision("high") # TF32 precision for fp32 matmul
33
+
34
+ # Allow imports from the project root regardless of working directory.
35
+ _PROJECT_ROOT = Path(__file__).resolve().parent.parent
36
+ if str(_PROJECT_ROOT) not in sys.path:
37
+ sys.path.insert(0, str(_PROJECT_ROOT))
38
+
39
+ from data import PackedDataset
40
+ from model import LLM, LMConfig
41
+ from train.trainer import TrainConfig, Trainer
42
+ from train.utils import (
43
+ cleanup_ddp,
44
+ get_cosine_schedule_with_warmup,
45
+ is_main_process,
46
+ load_checkpoint,
47
+ setup_ddp,
48
+ )
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Optional TransformerEngine import (FP8 support)
52
+ # ---------------------------------------------------------------------------
53
+ try:
54
+ import transformer_engine.pytorch as te # type: ignore[import]
55
+ HAS_TE = True
56
+ except ImportError:
57
+ te = None # type: ignore[assignment]
58
+ HAS_TE = False
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Argument parsing
63
+ # ---------------------------------------------------------------------------
64
+
65
+
66
+ def parse_args() -> argparse.Namespace:
67
+ parser = argparse.ArgumentParser(
68
+ description="Pretrain a decoder-only LLM.",
69
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
70
+ )
71
+
72
+ # Paths
73
+ parser.add_argument(
74
+ "--config",
75
+ type=Path,
76
+ default=Path("configs/small.yaml"),
77
+ help="Path to the LMConfig YAML file.",
78
+ )
79
+ parser.add_argument(
80
+ "--train_data",
81
+ type=Path,
82
+ required=True,
83
+ help="Path to the training data .bin file (numpy uint16 memmap).",
84
+ )
85
+ parser.add_argument(
86
+ "--val_data",
87
+ type=Path,
88
+ default=None,
89
+ help="Optional path to validation data .bin file.",
90
+ )
91
+ parser.add_argument(
92
+ "--checkpoint_dir",
93
+ type=Path,
94
+ default=Path("checkpoints"),
95
+ help="Root directory for saving checkpoints.",
96
+ )
97
+ parser.add_argument(
98
+ "--resume",
99
+ type=Path,
100
+ default=None,
101
+ help="Path to a checkpoint directory to resume training from.",
102
+ )
103
+
104
+ # Training hyper-parameters
105
+ parser.add_argument(
106
+ "--max_steps",
107
+ type=int,
108
+ default=None,
109
+ help="Override the number of optimiser steps (default: TrainConfig.max_steps).",
110
+ )
111
+ parser.add_argument(
112
+ "--batch_size",
113
+ type=int,
114
+ default=8,
115
+ help="Per-GPU micro-batch size.",
116
+ )
117
+ parser.add_argument(
118
+ "--lr",
119
+ type=float,
120
+ default=3e-4,
121
+ help="Peak learning rate.",
122
+ )
123
+ parser.add_argument(
124
+ "--weight_decay",
125
+ type=float,
126
+ default=0.1,
127
+ help="AdamW weight decay coefficient.",
128
+ )
129
+ parser.add_argument(
130
+ "--warmup_steps",
131
+ type=int,
132
+ default=2000,
133
+ help="Number of linear warmup steps.",
134
+ )
135
+ parser.add_argument(
136
+ "--grad_accum",
137
+ type=int,
138
+ default=1,
139
+ help="Gradient accumulation steps.",
140
+ )
141
+ parser.add_argument(
142
+ "--seed",
143
+ type=int,
144
+ default=42,
145
+ help="Base random seed (rank offset is added automatically).",
146
+ )
147
+ parser.add_argument(
148
+ "--log_file",
149
+ type=Path,
150
+ default=None,
151
+ help="Path to a text file for structured training logs (rank-0 only). "
152
+ "If omitted, logs go only to stdout.",
153
+ )
154
+ parser.add_argument(
155
+ "--use_fp8",
156
+ action="store_true",
157
+ default=False,
158
+ help="Enable TransformerEngine FP8 training (overrides config; requires B200/H100).",
159
+ )
160
+
161
+ return parser.parse_args()
162
+
163
+
164
+ # ---------------------------------------------------------------------------
165
+ # Seed helper
166
+ # ---------------------------------------------------------------------------
167
+
168
+
169
+ def set_seed(seed: int) -> None:
170
+ """Set deterministic seeds for Python, NumPy, and PyTorch."""
171
+ random.seed(seed)
172
+ np.random.seed(seed)
173
+ torch.manual_seed(seed)
174
+ torch.cuda.manual_seed_all(seed)
175
+
176
+
177
+ # ---------------------------------------------------------------------------
178
+ # Optimizer parameter groups
179
+ # ---------------------------------------------------------------------------
180
+
181
+
182
+ def build_optimizer_param_groups(
183
+ model: torch.nn.Module,
184
+ weight_decay: float,
185
+ ) -> list[dict]:
186
+ """
187
+ Split parameters into two groups:
188
+ - decay group : weight tensors with ndim >= 2
189
+ - no-decay group: bias, LayerNorm/RMSNorm weights, and embedding weights
190
+
191
+ This follows standard practice (e.g. GPT-style training).
192
+ """
193
+ decay_params: list[torch.nn.Parameter] = []
194
+ no_decay_params: list[torch.nn.Parameter] = []
195
+
196
+ # Names of module types whose parameters should never be decayed.
197
+ no_decay_module_types = (
198
+ torch.nn.Embedding,
199
+ torch.nn.LayerNorm,
200
+ )
201
+ # Also skip any parameter whose name ends with '.bias' or 'norm'.
202
+ # Mamba-2 SSM parameters that should never be decayed
203
+ no_decay_name_suffixes = ("bias", "A_log", "D", "dt_bias")
204
+
205
+ # Collect module-level exclusions.
206
+ no_decay_module_params: set[int] = set()
207
+ for module in model.modules():
208
+ if isinstance(module, no_decay_module_types):
209
+ for param in module.parameters(recurse=False):
210
+ no_decay_module_params.add(id(param))
211
+
212
+ seen: set[int] = set()
213
+ for name, param in model.named_parameters():
214
+ if not param.requires_grad:
215
+ continue
216
+ if id(param) in seen:
217
+ continue
218
+ seen.add(id(param))
219
+
220
+ if (
221
+ id(param) in no_decay_module_params
222
+ or any(name.endswith(sfx) for sfx in no_decay_name_suffixes)
223
+ or param.ndim < 2
224
+ ):
225
+ no_decay_params.append(param)
226
+ else:
227
+ decay_params.append(param)
228
+
229
+ return [
230
+ {"params": decay_params, "weight_decay": weight_decay},
231
+ {"params": no_decay_params, "weight_decay": 0.0},
232
+ ]
233
+
234
+
235
+ # ---------------------------------------------------------------------------
236
+ # Main
237
+ # ---------------------------------------------------------------------------
238
+
239
+
240
+ def main() -> None:
241
+ args = parse_args()
242
+
243
+ # ---- Distributed setup -------------------------------------------------
244
+ is_ddp = "RANK" in os.environ
245
+ rank = 0
246
+ local_rank = 0
247
+ world_size = 1
248
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
249
+
250
+ if is_ddp:
251
+ rank, local_rank, world_size, device = setup_ddp()
252
+
253
+ # Per-rank seed so data shuffling differs across replicas.
254
+ set_seed(args.seed + rank)
255
+
256
+ # ---- NUMA affinity for optimal GPU↔CPU memory locality ---------------
257
+ # B200 topology: GPU 0-3 → NUMA node 0 (cores 0-35)
258
+ # GPU 4-7 → NUMA node 1 (cores 36-71)
259
+ # Without pinning, 5/8 ranks end up on wrong NUMA → 3.2x memory latency.
260
+ try:
261
+ if local_rank < 4:
262
+ os.sched_setaffinity(0, set(range(0, 36))) # NUMA node 0
263
+ else:
264
+ os.sched_setaffinity(0, set(range(36, 72))) # NUMA node 1
265
+ if is_main_process():
266
+ print(f"NUMA affinity: rank {rank} (GPU {local_rank}) → "
267
+ f"{'NUMA0 cores 0-35' if local_rank < 4 else 'NUMA1 cores 36-71'}")
268
+ except (AttributeError, OSError) as e:
269
+ if is_main_process():
270
+ print(f"[WARN] NUMA affinity failed: {e}")
271
+
272
+ # ---- Model -------------------------------------------------------------
273
+ if not args.config.exists():
274
+ raise FileNotFoundError(f"Config file not found: {args.config}")
275
+
276
+ lm_config = LMConfig.from_yaml(args.config)
277
+
278
+ # CLI --use_fp8 flag overrides whatever the config file says.
279
+ if args.use_fp8:
280
+ lm_config.use_fp8 = True
281
+
282
+ # FP8 alignment check: (batch_size × seq_len) must be divisible by 8.
283
+ if lm_config.use_fp8 and (args.batch_size * lm_config.max_seq_len) % 8 != 0:
284
+ raise ValueError(
285
+ f"FP8: batch_size × max_seq_len = {args.batch_size} × {lm_config.max_seq_len} "
286
+ f"= {args.batch_size * lm_config.max_seq_len} must be divisible by 8."
287
+ )
288
+
289
+ # Note: fp8_model_init() is intentionally omitted — MXFP8Tensor weights are
290
+ # incompatible with DDP's _broadcast_coalesced during multi-GPU init.
291
+ # Weights remain in float32; TE quantizes on-the-fly inside fp8_autocast.
292
+ model = LLM(lm_config).to(device)
293
+
294
+ if is_main_process():
295
+ total_params = sum(p.numel() for p in model.parameters())
296
+ print(f"Model parameters: {total_params:,}")
297
+ print(f"LMConfig: {lm_config}")
298
+
299
+ # ---- Wrap in DDP -------------------------------------------------------
300
+ if is_ddp:
301
+ from torch.nn.parallel import DistributedDataParallel as DDP
302
+
303
+ model = DDP(
304
+ model,
305
+ device_ids=[local_rank],
306
+ output_device=local_rank,
307
+ gradient_as_bucket_view=True, # zero-copy gradient → NCCL buffer
308
+ bucket_cap_mb=800, # larger buckets for NVLS (was 400)
309
+ find_unused_parameters=False, # fixed graph, no traversal overhead
310
+ # NOTE: static_graph=True 제거 — TE FP8 레이어의 동적 autograd hooks와 충돌
311
+ )
312
+
313
+ # ---- Dataset & DataLoader ----------------------------------------------
314
+ # PackedDataset: non-overlapping stride=seq_len windows.
315
+ # Avoids 600M random-index mmap accesses from stride-1 TextDataset.
316
+ train_dataset = PackedDataset(args.train_data, seq_len=lm_config.max_seq_len)
317
+
318
+ if is_ddp:
319
+ train_sampler: DistributedSampler | RandomSampler = DistributedSampler(
320
+ train_dataset,
321
+ num_replicas=world_size,
322
+ rank=rank,
323
+ shuffle=True,
324
+ seed=args.seed,
325
+ )
326
+ shuffle = False
327
+ else:
328
+ train_sampler = RandomSampler(train_dataset)
329
+ shuffle = False # Sampler is provided; DataLoader must not also shuffle.
330
+
331
+ train_loader = DataLoader(
332
+ train_dataset,
333
+ batch_size=args.batch_size,
334
+ sampler=train_sampler,
335
+ num_workers=6, # 6×8=48 workers, fits 72-core budget with OMP=4
336
+ pin_memory=True,
337
+ drop_last=True,
338
+ prefetch_factor=4, # deeper pipeline for larger worker pool
339
+ persistent_workers=True, # keep workers alive across epochs — eliminates respawn stall
340
+ )
341
+
342
+ # ---- Optimizer ---------------------------------------------------------
343
+ param_groups = build_optimizer_param_groups(
344
+ getattr(model, "module", model), args.weight_decay
345
+ )
346
+ optimizer = torch.optim.AdamW(
347
+ param_groups,
348
+ lr=args.lr,
349
+ betas=(0.9, 0.95),
350
+ eps=1e-8,
351
+ fused=torch.cuda.is_available(), # Use fused kernel when on CUDA.
352
+ )
353
+
354
+ # ---- LR Scheduler ------------------------------------------------------
355
+ train_config = TrainConfig(
356
+ checkpoint_dir=str(args.checkpoint_dir),
357
+ grad_accum_steps=args.grad_accum,
358
+ use_fp8=lm_config.use_fp8,
359
+ log_file=str(args.log_file) if args.log_file is not None else None,
360
+ )
361
+ if args.max_steps is not None:
362
+ train_config.max_steps = args.max_steps
363
+
364
+ scheduler = get_cosine_schedule_with_warmup(
365
+ optimizer=optimizer,
366
+ warmup_steps=args.warmup_steps,
367
+ total_steps=train_config.max_steps,
368
+ )
369
+
370
+ # ---- Resume from checkpoint --------------------------------------------
371
+ start_step = 0
372
+ if args.resume is not None:
373
+ if not args.resume.exists():
374
+ raise FileNotFoundError(f"Checkpoint path not found: {args.resume}")
375
+ start_step, resume_loss = load_checkpoint(
376
+ path=args.resume,
377
+ model=model,
378
+ optimizer=optimizer,
379
+ scheduler=scheduler,
380
+ )
381
+ if is_main_process():
382
+ print(f"Resumed from {args.resume} at step {start_step} (loss={resume_loss:.4f})")
383
+
384
+ # ---- Checkpoint directory ----------------------------------------------
385
+ args.checkpoint_dir.mkdir(parents=True, exist_ok=True)
386
+
387
+ # ---- Trainer -----------------------------------------------------------
388
+ trainer = Trainer(
389
+ model=model,
390
+ train_loader=train_loader,
391
+ optimizer=optimizer,
392
+ scheduler=scheduler,
393
+ config=train_config,
394
+ device=device,
395
+ rank=rank,
396
+ sampler=train_sampler if is_ddp else None,
397
+ )
398
+
399
+ # ---- Signal handlers for graceful shutdown ----------------------------
400
+ # SIGHUP: SSH 세션 끊김 시 발생 → 이전에 학습을 죽인 주범
401
+ # SIGTERM: kill 명령 또는 시스템 종료 시 발생
402
+ # 핸들러가 trainer.request_shutdown()을 호출하면, 학습 루프가
403
+ # 현재 step 완료 후 비상 체크포인트를 저장하고 깨끗하게 종료합니다.
404
+ _trainer_ref = trainer
405
+
406
+ def _graceful_shutdown_handler(signum, frame):
407
+ sig_name = signal.Signals(signum).name
408
+ if is_main_process():
409
+ import datetime as _dt
410
+ ts = _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
411
+ msg = (
412
+ f"[{ts}] [SIGNAL] Received {sig_name} (signum={signum}). "
413
+ f"Initiating graceful shutdown..."
414
+ )
415
+ print(f"\n{msg}")
416
+ # 로그 파일에도 즉시 기록 (시그널 핸들러 내에서 안전하게)
417
+ if args.log_file is not None:
418
+ try:
419
+ with open(args.log_file, "a", encoding="utf-8") as f:
420
+ f.write(msg + "\n")
421
+ except Exception:
422
+ pass # 시그널 핸들러 내에서는 예외 무시
423
+ _trainer_ref.request_shutdown(sig_name)
424
+
425
+ for _sig in (signal.SIGHUP, signal.SIGTERM):
426
+ signal.signal(_sig, _graceful_shutdown_handler)
427
+
428
+ if is_main_process():
429
+ import datetime
430
+ eff_tokens_per_step = args.batch_size * lm_config.max_seq_len * args.grad_accum * world_size
431
+ nccl_debug = os.environ.get("NCCL_DEBUG", "not set")
432
+ omp_threads = os.environ.get("OMP_NUM_THREADS", "not set")
433
+ print(
434
+ f"\n{'='*70}\n"
435
+ f" LLM Pretraining — {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
436
+ f"{'='*70}\n"
437
+ f" model : {lm_config.num_params:,} params | "
438
+ f"d_model={lm_config.d_model} n_layers={lm_config.n_layers}\n"
439
+ f" precision : {'FP8 (MXFP8BlockScaling)' if lm_config.use_fp8 else 'BF16'}\n"
440
+ f" GPUs : {world_size} | batch/GPU={args.batch_size} "
441
+ f"grad_accum={args.grad_accum}\n"
442
+ f" eff_batch : {args.batch_size * args.grad_accum * world_size} seqs "
443
+ f"= {eff_tokens_per_step:,} tok/step\n"
444
+ f" max_steps : {train_config.max_steps:,} "
445
+ f"({train_config.max_steps * eff_tokens_per_step / 1e9:.1f}B tokens total)\n"
446
+ f" data : {args.train_data}\n"
447
+ f" ckpt_dir : {args.checkpoint_dir}\n"
448
+ f" env : OMP_NUM_THREADS={omp_threads} NCCL_DEBUG={nccl_debug}\n"
449
+ f"{'='*70}\n"
450
+ )
451
+
452
+ try:
453
+ trainer.train(start_step=start_step)
454
+ # 학습 완료 또는 graceful shutdown 후 상태 출력
455
+ if is_main_process():
456
+ if trainer._shutdown_requested:
457
+ print(
458
+ f"\n[INFO] Training gracefully shut down via {trainer._shutdown_signal}. "
459
+ f"Emergency checkpoint saved. Resume with same command."
460
+ )
461
+ else:
462
+ print("\n[INFO] Training completed successfully.")
463
+ except KeyboardInterrupt:
464
+ if is_main_process():
465
+ print("\n[INFO] Training interrupted by user (KeyboardInterrupt).")
466
+ except Exception as e:
467
+ import traceback
468
+ if is_main_process():
469
+ tb = traceback.format_exc()
470
+ print(f"\n[ERROR] Training failed at rank {rank}:\n{tb}")
471
+ # log_file에도 기록
472
+ if args.log_file is not None:
473
+ with open(args.log_file, "a", encoding="utf-8") as f:
474
+ import datetime
475
+ f.write(f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] [FATAL] {tb}\n")
476
+ raise
477
+ finally:
478
+ if is_ddp:
479
+ cleanup_ddp()
480
+
481
+ # Note: DDP cleanup is handled in the try/finally block above.
482
+
483
+
484
+ if __name__ == "__main__":
485
+ main()
source/train/sft.py ADDED
@@ -0,0 +1,1062 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ train/sft.py — Supervised Fine-Tuning (SFT) entry point.
3
+
4
+ Loads a pretrained checkpoint and fine-tunes it on instruction/conversation
5
+ data using SFTDataset, which masks prompt tokens with ignore_index=-1 so only
6
+ the assistant response tokens contribute to the loss.
7
+
8
+ Launch single-GPU:
9
+ python train/sft.py \\
10
+ --base_checkpoint checkpoints/korean_1b_fp8_run1/checkpoint-0034000 \\
11
+ --sft_data data/sft/train.jsonl \\
12
+ --device cuda:0
13
+
14
+ Launch multi-GPU (DDP via torchrun):
15
+ torchrun --nproc_per_node=8 train/sft.py \\
16
+ --base_checkpoint checkpoints/korean_1b_fp8_run1/checkpoint-0034000 \\
17
+ --sft_data data/sft/train.jsonl
18
+
19
+ KEY DIFFERENCES from pretrain.py:
20
+ - Loads weights from a pretrained checkpoint via LLM.from_pretrained()
21
+ - Uses SFTDataset (JSONL instruction data) instead of PackedDataset
22
+ - Lower default learning rate (2e-5 vs 2e-4)
23
+ - Fewer default steps (3000 vs 100000)
24
+ - Copies tokenizer.json to checkpoint_dir for easy deployment
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import os
31
+ import random
32
+ import signal
33
+ import shutil
34
+ import sys
35
+ from pathlib import Path
36
+
37
+ import numpy as np
38
+ import torch
39
+ import torch.nn.functional as F
40
+ from torch.utils.data import DataLoader, DistributedSampler, RandomSampler
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # Data Mixing: Interleave SFT + Pretrain batches for forgetting prevention
44
+ # ---------------------------------------------------------------------------
45
+
46
+
47
+ class MixingDataLoader:
48
+ """
49
+ Wraps two DataLoaders and yields batches from one or the other
50
+ based on a probability ratio.
51
+
52
+ With ``pretrain_ratio=0.3``, 30% of batches come from the pretrain
53
+ loader and 70% from the SFT loader. Both loaders cycle infinitely.
54
+
55
+ This is duck-type compatible with DataLoader for the Trainer's needs:
56
+ - ``__iter__`` yields batches
57
+ - ``__len__`` returns the SFT loader length (used for epoch estimation)
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ sft_loader: DataLoader,
63
+ pretrain_loader: DataLoader,
64
+ pretrain_ratio: float = 0.3,
65
+ sft_sampler: DistributedSampler | RandomSampler | None = None,
66
+ pretrain_sampler: DistributedSampler | RandomSampler | None = None,
67
+ ) -> None:
68
+ self.sft_loader = sft_loader
69
+ self.pretrain_loader = pretrain_loader
70
+ self.pretrain_ratio = pretrain_ratio
71
+ self.sft_sampler = sft_sampler
72
+ self.pretrain_sampler = pretrain_sampler
73
+ self._epoch = 0
74
+
75
+ def __len__(self) -> int:
76
+ return len(self.sft_loader)
77
+
78
+ def __iter__(self):
79
+ sft_iter = iter(self.sft_loader)
80
+ pt_iter = iter(self.pretrain_loader)
81
+
82
+ while True:
83
+ use_pretrain = random.random() < self.pretrain_ratio
84
+ try:
85
+ if use_pretrain:
86
+ batch = next(pt_iter)
87
+ else:
88
+ batch = next(sft_iter)
89
+ except StopIteration:
90
+ # Whichever exhausted, restart it
91
+ if use_pretrain:
92
+ self._epoch += 1
93
+ if self.pretrain_sampler is not None and hasattr(self.pretrain_sampler, 'set_epoch'):
94
+ self.pretrain_sampler.set_epoch(self._epoch)
95
+ pt_iter = iter(self.pretrain_loader)
96
+ try:
97
+ batch = next(pt_iter)
98
+ except StopIteration:
99
+ raise RuntimeError(
100
+ "Pretrain DataLoader is empty after restart. "
101
+ "Check pretrain_data path and drop_last settings."
102
+ )
103
+ else:
104
+ self._epoch += 1
105
+ if self.sft_sampler is not None and hasattr(self.sft_sampler, 'set_epoch'):
106
+ self.sft_sampler.set_epoch(self._epoch)
107
+ sft_iter = iter(self.sft_loader)
108
+ try:
109
+ batch = next(sft_iter)
110
+ except StopIteration:
111
+ raise RuntimeError(
112
+ "SFT DataLoader is empty after restart. "
113
+ "Check sft_data path and drop_last settings."
114
+ )
115
+ yield batch
116
+
117
+ # B200 Tensor Core 최대 활용: TF32 matmul + cuDNN
118
+ torch.backends.cuda.matmul.allow_tf32 = True
119
+ torch.backends.cudnn.allow_tf32 = True
120
+ torch.set_float32_matmul_precision("high") # TF32 precision for fp32 matmul
121
+
122
+ # Allow imports from the project root regardless of working directory.
123
+ _PROJECT_ROOT = Path(__file__).resolve().parent.parent
124
+ if str(_PROJECT_ROOT) not in sys.path:
125
+ sys.path.insert(0, str(_PROJECT_ROOT))
126
+
127
+ from model import LLM
128
+ from train.trainer import TrainConfig, Trainer
129
+ from train.utils import (
130
+ cleanup_ddp,
131
+ get_cosine_schedule_with_warmup,
132
+ is_main_process,
133
+ load_checkpoint,
134
+ setup_ddp,
135
+ )
136
+
137
+ # ---------------------------------------------------------------------------
138
+ # Optional TransformerEngine import (FP8 support)
139
+ # ---------------------------------------------------------------------------
140
+ try:
141
+ import transformer_engine.pytorch as te # type: ignore[import]
142
+ HAS_TE = True
143
+ except ImportError:
144
+ te = None # type: ignore[assignment]
145
+ HAS_TE = False
146
+
147
+
148
+ # ---------------------------------------------------------------------------
149
+ # Argument parsing
150
+ # ---------------------------------------------------------------------------
151
+
152
+
153
+ def parse_args() -> argparse.Namespace:
154
+ parser = argparse.ArgumentParser(
155
+ description="Supervised Fine-Tuning (SFT) of a pretrained decoder-only LLM.",
156
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
157
+ )
158
+
159
+ # --- Required paths -----------------------------------------------------
160
+ parser.add_argument(
161
+ "--base_checkpoint",
162
+ type=Path,
163
+ required=True,
164
+ help=(
165
+ "Path to the pretrained checkpoint directory. "
166
+ "Must contain model.pt and config.yaml (produced by save_checkpoint)."
167
+ ),
168
+ )
169
+ parser.add_argument(
170
+ "--sft_data",
171
+ type=Path,
172
+ required=True,
173
+ help="Path to the JSONL SFT training data file.",
174
+ )
175
+
176
+ # --- Optional paths -----------------------------------------------------
177
+ parser.add_argument(
178
+ "--val_data",
179
+ type=Path,
180
+ default=None,
181
+ help="Optional path to JSONL SFT validation data file.",
182
+ )
183
+ parser.add_argument(
184
+ "--checkpoint_dir",
185
+ type=Path,
186
+ default=Path("checkpoints/korean_1b_sft"),
187
+ help="Root directory for saving SFT checkpoints.",
188
+ )
189
+ parser.add_argument(
190
+ "--resume",
191
+ type=Path,
192
+ default=None,
193
+ help="Path to an SFT checkpoint directory to resume fine-tuning from.",
194
+ )
195
+ parser.add_argument(
196
+ "--tokenizer",
197
+ type=Path,
198
+ default=None,
199
+ help=(
200
+ "Override path to tokenizer.json. "
201
+ "Defaults to <base_checkpoint>/tokenizer.json, "
202
+ "then falls back to tokenizer/korean_sp/tokenizer.json."
203
+ ),
204
+ )
205
+ parser.add_argument(
206
+ "--log_file",
207
+ type=Path,
208
+ default=None,
209
+ help=(
210
+ "Path to a text file for structured training logs (rank-0 only). "
211
+ "If omitted, logs go only to stdout."
212
+ ),
213
+ )
214
+
215
+ # --- Training hyper-parameters ------------------------------------------
216
+ parser.add_argument(
217
+ "--max_steps",
218
+ type=int,
219
+ default=3000,
220
+ help="Total number of optimiser steps.",
221
+ )
222
+ parser.add_argument(
223
+ "--batch_size",
224
+ type=int,
225
+ default=4,
226
+ help="Per-GPU micro-batch size.",
227
+ )
228
+ parser.add_argument(
229
+ "--lr",
230
+ type=float,
231
+ default=2e-5,
232
+ help=(
233
+ "Peak learning rate. "
234
+ "SFT uses a much lower lr than pretraining (2e-5 vs 2e-4) "
235
+ "to preserve pretrained representations."
236
+ ),
237
+ )
238
+ parser.add_argument(
239
+ "--weight_decay",
240
+ type=float,
241
+ default=0.01,
242
+ help="AdamW weight decay. Lower than pretrain (0.01 vs 0.1).",
243
+ )
244
+ parser.add_argument(
245
+ "--warmup_steps",
246
+ type=int,
247
+ default=100,
248
+ help="Number of linear LR warmup steps.",
249
+ )
250
+ parser.add_argument(
251
+ "--grad_accum",
252
+ type=int,
253
+ default=2,
254
+ help="Gradient accumulation steps.",
255
+ )
256
+ parser.add_argument(
257
+ "--seed",
258
+ type=int,
259
+ default=42,
260
+ help="Base random seed (rank offset is added automatically in DDP).",
261
+ )
262
+ parser.add_argument(
263
+ "--use_fp8",
264
+ action="store_true",
265
+ default=False,
266
+ help=(
267
+ "Enable TransformerEngine FP8 training "
268
+ "(requires B200/H100, uses MXFP8BlockScaling)."
269
+ ),
270
+ )
271
+
272
+ # --- Single-GPU device override (ignored when using torchrun) -----------
273
+ parser.add_argument(
274
+ "--device",
275
+ type=str,
276
+ default=None,
277
+ help=(
278
+ "Explicit device string (e.g. 'cuda:0'). "
279
+ "Ignored when running under torchrun (DDP auto-assigns devices)."
280
+ ),
281
+ )
282
+
283
+ parser.add_argument(
284
+ "--config", type=Path, default=None,
285
+ help="YAML config file. Values under 'train:' section are used as CLI defaults.",
286
+ )
287
+ parser.add_argument("--save_interval", type=int, default=500, help="Checkpoint save interval (steps).")
288
+ parser.add_argument("--eval_interval", type=int, default=250, help="Validation eval interval (steps).")
289
+ parser.add_argument("--neftune_alpha", type=float, default=5.0, help="NEFTune noise magnitude (0 to disable).")
290
+ parser.add_argument("--max_grad_norm", type=float, default=1.0, help="Maximum gradient L2 norm for clipping.")
291
+
292
+ # --- Data mixing (forgetting prevention) --------------------------------
293
+ parser.add_argument(
294
+ "--pretrain_data",
295
+ type=Path,
296
+ default=None,
297
+ help="Path to pretrain .bin file for data mixing. Enables SFT+pretrain interleaving.",
298
+ )
299
+ parser.add_argument(
300
+ "--pretrain_mix_ratio",
301
+ type=float,
302
+ default=0.3,
303
+ help="Fraction of batches from pretrain data (0.3 = 30%% pretrain, 70%% SFT).",
304
+ )
305
+
306
+ # First pass: just get --config
307
+ args, remaining = parser.parse_known_args()
308
+
309
+ # Load YAML config and apply values as defaults
310
+ if args.config is not None:
311
+ if not args.config.exists():
312
+ raise FileNotFoundError(f"Config file not found: {args.config}")
313
+ import yaml
314
+ with open(args.config, "r") as f:
315
+ yaml_cfg = yaml.safe_load(f)
316
+ train_section = yaml_cfg.get("train", {})
317
+ yaml_to_arg = {
318
+ "max_steps": "max_steps",
319
+ "batch_size": "batch_size",
320
+ "lr": "lr",
321
+ "weight_decay": "weight_decay",
322
+ "warmup_steps": "warmup_steps",
323
+ "grad_accum_steps": "grad_accum",
324
+ "save_interval": "save_interval",
325
+ "eval_interval": "eval_interval",
326
+ "neftune_alpha": "neftune_alpha",
327
+ "pretrain_mix_ratio": "pretrain_mix_ratio",
328
+ "max_grad_norm": "max_grad_norm",
329
+ }
330
+ # pretrain_data is a Path, handle separately
331
+ if "pretrain_data" in train_section:
332
+ parser.set_defaults(pretrain_data=Path(train_section["pretrain_data"]))
333
+ new_defaults = {}
334
+ for yaml_key, arg_name in yaml_to_arg.items():
335
+ if yaml_key in train_section:
336
+ new_defaults[arg_name] = train_section[yaml_key]
337
+ if new_defaults:
338
+ parser.set_defaults(**new_defaults)
339
+
340
+ return parser.parse_args()
341
+
342
+
343
+ # ---------------------------------------------------------------------------
344
+ # Seed helper
345
+ # ---------------------------------------------------------------------------
346
+
347
+
348
+ def set_seed(seed: int) -> None:
349
+ """Set deterministic seeds for Python, NumPy, and PyTorch."""
350
+ random.seed(seed)
351
+ np.random.seed(seed)
352
+ torch.manual_seed(seed)
353
+ torch.cuda.manual_seed_all(seed)
354
+
355
+
356
+ # ---------------------------------------------------------------------------
357
+ # Optimizer parameter groups
358
+ # (Copied from pretrain.py to avoid circular import; identical logic)
359
+ # ---------------------------------------------------------------------------
360
+
361
+
362
+ def build_optimizer_param_groups(
363
+ model: torch.nn.Module,
364
+ weight_decay: float,
365
+ ) -> list[dict]:
366
+ """
367
+ Split parameters into two groups:
368
+ - decay group : weight tensors with ndim >= 2 (Linear, etc.)
369
+ - no-decay group: bias, LayerNorm/RMSNorm weights, and embedding weights
370
+
371
+ This follows standard practice (e.g. GPT-style training).
372
+ """
373
+ decay_params: list[torch.nn.Parameter] = []
374
+ no_decay_params: list[torch.nn.Parameter] = []
375
+
376
+ # Module types whose parameters should never be decayed.
377
+ no_decay_module_types = (
378
+ torch.nn.Embedding,
379
+ torch.nn.LayerNorm,
380
+ )
381
+ # Also skip any parameter whose name ends with '.bias'.
382
+ no_decay_name_suffixes = ("bias",)
383
+
384
+ # Collect module-level exclusions.
385
+ no_decay_module_params: set[int] = set()
386
+ for module in model.modules():
387
+ if isinstance(module, no_decay_module_types):
388
+ for param in module.parameters(recurse=False):
389
+ no_decay_module_params.add(id(param))
390
+
391
+ seen: set[int] = set()
392
+ for name, param in model.named_parameters():
393
+ if not param.requires_grad:
394
+ continue
395
+ if id(param) in seen:
396
+ continue
397
+ seen.add(id(param))
398
+
399
+ if (
400
+ id(param) in no_decay_module_params
401
+ or any(name.endswith(sfx) for sfx in no_decay_name_suffixes)
402
+ or param.ndim < 2
403
+ ):
404
+ no_decay_params.append(param)
405
+ else:
406
+ decay_params.append(param)
407
+
408
+ return [
409
+ {"params": decay_params, "weight_decay": weight_decay},
410
+ {"params": no_decay_params, "weight_decay": 0.0},
411
+ ]
412
+
413
+
414
+ # ---------------------------------------------------------------------------
415
+ # Tokenizer resolution helper
416
+ # ---------------------------------------------------------------------------
417
+
418
+
419
+ def _resolve_tokenizer_path(args: argparse.Namespace) -> Path:
420
+ """
421
+ Determine the tokenizer path in priority order:
422
+ 1. Explicit --tokenizer argument
423
+ 2. tokenizer.json inside the base_checkpoint directory
424
+ 3. Project default: tokenizer/korean_sp/tokenizer.json
425
+ """
426
+ if args.tokenizer is not None:
427
+ p = Path(args.tokenizer)
428
+ if not p.exists():
429
+ raise FileNotFoundError(f"Tokenizer not found at --tokenizer path: {p}")
430
+ return p
431
+
432
+ ckpt_tok = args.base_checkpoint / "tokenizer.json"
433
+ if ckpt_tok.exists():
434
+ return ckpt_tok
435
+
436
+ default_tok = _PROJECT_ROOT / "tokenizer" / "korean_sp" / "tokenizer.json"
437
+ if default_tok.exists():
438
+ return default_tok
439
+
440
+ raise FileNotFoundError(
441
+ "Could not locate tokenizer.json. Tried:\n"
442
+ f" 1. {ckpt_tok}\n"
443
+ f" 2. {default_tok}\n"
444
+ "Use --tokenizer to specify an explicit path."
445
+ )
446
+
447
+
448
+ # ---------------------------------------------------------------------------
449
+ # Dynamic padding collate function
450
+ # ---------------------------------------------------------------------------
451
+
452
+
453
+ def dynamic_collate_fn(batch: list) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
454
+ """
455
+ Collate function that pads each batch to its own maximum sequence length
456
+ instead of a fixed global max_seq_len. This reduces wasted FLOPs on
457
+ short sequences and speeds up SFT which tends to have highly variable
458
+ response lengths.
459
+
460
+ Pads to the batch-local max, aligned to 64 tokens (for Flash Attention
461
+ efficiency), with a floor of 512 tokens so micro-batches are not too short.
462
+
463
+ Args:
464
+ batch: List of ``(input_ids, labels)`` tuples from SFTDataset.
465
+
466
+ Returns:
467
+ Tuple of ``(input_ids, labels, attention_mask)`` tensors shaped
468
+ ``[B, max_len]``.
469
+ ``input_ids`` is right-padded with 0 (pad token).
470
+ ``labels`` is right-padded with -1 (cross-entropy ignore_index).
471
+ ``attention_mask`` is 1 for real tokens, 0 for padding.
472
+ """
473
+ # 64-token alignment + minimum 512 floor
474
+ raw_max = max(item[0].size(0) for item in batch)
475
+ max_len = max(512, ((raw_max + 63) // 64) * 64)
476
+
477
+ input_ids_list, labels_list, mask_list = [], [], []
478
+ for ids, labs in batch:
479
+ pad_len = max_len - ids.size(0)
480
+ input_ids_list.append(F.pad(ids, (0, pad_len), value=0))
481
+ labels_list.append(F.pad(labs, (0, pad_len), value=-1))
482
+ mask_list.append(
483
+ F.pad(torch.ones(ids.size(0), dtype=torch.long), (0, pad_len), value=0)
484
+ )
485
+
486
+ return (
487
+ torch.stack(input_ids_list),
488
+ torch.stack(labels_list),
489
+ torch.stack(mask_list),
490
+ )
491
+
492
+
493
+ # ---------------------------------------------------------------------------
494
+ # NEFTune helper
495
+ # ---------------------------------------------------------------------------
496
+
497
+
498
+ def add_neftune_hook(model: torch.nn.Module, noise_alpha: float = 10.0):
499
+ """
500
+ Register a forward hook on the model's input embedding layer that adds
501
+ uniform noise scaled by noise_alpha during training (NEFTune).
502
+
503
+ Reference: "NEFTune: Noisy Embeddings Improve Instruction Finetuning"
504
+ (Jain et al., 2023). https://arxiv.org/abs/2310.05914
505
+
506
+ Args:
507
+ model: Raw (non-DDP) model instance.
508
+ noise_alpha: Noise magnitude parameter (paper default: 10).
509
+
510
+ Returns:
511
+ The hook handle (call ``handle.remove()`` to deactivate), or None if
512
+ the embedding layer could not be located.
513
+ """
514
+ # Unwrap DDP if needed
515
+ raw = model.module if hasattr(model, "module") else model
516
+
517
+ # 1) Try the standard HuggingFace accessor first.
518
+ embedding: torch.nn.Embedding | None = None
519
+ if hasattr(raw, "get_input_embeddings"):
520
+ try:
521
+ emb = raw.get_input_embeddings()
522
+ if isinstance(emb, torch.nn.Embedding):
523
+ embedding = emb
524
+ except Exception:
525
+ pass
526
+
527
+ # 2) Fallback: walk common attribute paths found in open-source LLMs.
528
+ if embedding is None:
529
+ for attr_path in [
530
+ "embedding",
531
+ "embed_tokens",
532
+ "token_embedding",
533
+ "wte",
534
+ "word_embeddings",
535
+ "tok_embeddings",
536
+ "transformer.wte",
537
+ "model.embed_tokens",
538
+ "model.embedding",
539
+ ]:
540
+ obj = raw
541
+ for part in attr_path.split("."):
542
+ obj = getattr(obj, part, None)
543
+ if obj is None:
544
+ break
545
+ if obj is not None and isinstance(obj, torch.nn.Embedding):
546
+ embedding = obj
547
+ break
548
+
549
+ if embedding is None:
550
+ print("[WARN] NEFTune: embedding layer을 찾지 못함, NEFTune 비활성화")
551
+ return None
552
+
553
+ print(
554
+ f"[INFO] NEFTune: {type(embedding).__name__} hook 등록 "
555
+ f"(shape={tuple(embedding.weight.shape)}, alpha={noise_alpha})"
556
+ )
557
+
558
+ def _hook(
559
+ module: torch.nn.Module,
560
+ inp: tuple,
561
+ out: torch.Tensor,
562
+ ) -> torch.Tensor:
563
+ if module.training:
564
+ # out shape: [B, seq_len, d_model]
565
+ mag = noise_alpha / ((out.size(1) * out.size(2)) ** 0.5)
566
+ out = out + torch.empty_like(out).uniform_(-mag, mag)
567
+ return out
568
+
569
+ return embedding.register_forward_hook(_hook)
570
+
571
+
572
+ # ---------------------------------------------------------------------------
573
+ # Main
574
+ # ---------------------------------------------------------------------------
575
+
576
+
577
+ def main() -> None:
578
+ args = parse_args()
579
+
580
+ # ---- Distributed setup -------------------------------------------------
581
+ is_ddp = "RANK" in os.environ
582
+ rank = 0
583
+ local_rank = 0
584
+ world_size = 1
585
+
586
+ if is_ddp:
587
+ rank, local_rank, world_size, device = setup_ddp()
588
+ else:
589
+ # Single-GPU: honour --device flag, else pick cuda:0 or cpu.
590
+ if args.device is not None:
591
+ device = torch.device(args.device)
592
+ elif torch.cuda.is_available():
593
+ device = torch.device("cuda:0")
594
+ else:
595
+ device = torch.device("cpu")
596
+
597
+ # Per-rank seed so data shuffling differs across replicas.
598
+ set_seed(args.seed + rank)
599
+
600
+ # ---- NUMA affinity for optimal GPU↔CPU memory locality ---------------
601
+ # B200 topology: GPU 0-3 → NUMA node 0 (cores 0-35)
602
+ # GPU 4-7 → NUMA node 1 (cores 36-71)
603
+ try:
604
+ if local_rank < 4:
605
+ os.sched_setaffinity(0, set(range(0, 36))) # NUMA node 0
606
+ else:
607
+ os.sched_setaffinity(0, set(range(36, 72))) # NUMA node 1
608
+ if is_main_process():
609
+ print(f"NUMA affinity: rank {rank} (GPU {local_rank}) → "
610
+ f"{'NUMA0 cores 0-35' if local_rank < 4 else 'NUMA1 cores 36-71'}")
611
+ except (AttributeError, OSError) as e:
612
+ if is_main_process():
613
+ print(f"[WARN] NUMA affinity failed: {e}")
614
+
615
+ # ---- Validate base checkpoint ------------------------------------------
616
+ if not args.base_checkpoint.exists():
617
+ raise FileNotFoundError(
618
+ f"Base checkpoint directory not found: {args.base_checkpoint}"
619
+ )
620
+ for required_file in ("model.pt", "config.yaml"):
621
+ if not (args.base_checkpoint / required_file).exists():
622
+ raise FileNotFoundError(
623
+ f"Expected {required_file} inside base checkpoint: {args.base_checkpoint}"
624
+ )
625
+
626
+ # ---- Load pretrained model ---------------------------------------------
627
+ # LLM.from_pretrained() reads config.yaml + model.pt and returns the model on CPU.
628
+ # We move it to the target device immediately after loading.
629
+ #
630
+ # NOTE: fp8_model_init() is intentionally NOT used here (same as pretrain.py).
631
+ # MXFP8Tensor weights are incompatible with DDP's _broadcast_coalesced.
632
+ # Weights stay in float32; TransformerEngine quantizes on-the-fly inside fp8_autocast.
633
+ model = LLM.from_pretrained(args.base_checkpoint)
634
+
635
+ # When FP8 flag is passed at SFT time, enable it on the loaded config.
636
+ # This is useful if the pretrained model was trained without FP8 but you
637
+ # want to fine-tune with FP8 precision (the TE layers must exist in the model).
638
+ if args.use_fp8:
639
+ model.config.use_fp8 = True
640
+
641
+ # Move model to target device in bfloat16 (more memory-efficient than fp32
642
+ # for fine-tuning, and required when BF16 autocast + TE are active).
643
+ model = model.to(device=device, dtype=torch.bfloat16)
644
+
645
+ # ---- Gradient checkpointing ----------------------------------------
646
+ # Trades activation memory for recomputation during backward pass.
647
+ # Especially useful for large models / long sequences in SFT.
648
+ if hasattr(model, 'gradient_checkpointing_enable'):
649
+ model.gradient_checkpointing_enable()
650
+ if rank == 0:
651
+ print("[INFO] Gradient checkpointing enabled")
652
+
653
+ # FP8 alignment check: (batch_size × seq_len) must be divisible by 8.
654
+ if model.config.use_fp8:
655
+ seq_len = model.config.max_seq_len
656
+ if (args.batch_size * seq_len) % 8 != 0:
657
+ raise ValueError(
658
+ f"FP8: batch_size × max_seq_len = {args.batch_size} × {seq_len} "
659
+ f"= {args.batch_size * seq_len} must be divisible by 8."
660
+ )
661
+
662
+ if is_main_process():
663
+ total_params = sum(p.numel() for p in model.parameters())
664
+ print(f"Pretrained model loaded: {total_params:,} parameters")
665
+ print(f"LMConfig: {model.config}")
666
+
667
+ # ---- Wrap in DDP -------------------------------------------------------
668
+ if is_ddp:
669
+ from torch.nn.parallel import DistributedDataParallel as DDP
670
+
671
+ model = DDP(
672
+ model,
673
+ device_ids=[local_rank],
674
+ output_device=local_rank,
675
+ gradient_as_bucket_view=True,
676
+ bucket_cap_mb=800,
677
+ find_unused_parameters=False,
678
+ )
679
+
680
+ # ---- Tokenizer ---------------------------------------------------------
681
+ tokenizer_path = _resolve_tokenizer_path(args)
682
+ if is_main_process():
683
+ print(f"Loading tokenizer from: {tokenizer_path}")
684
+
685
+ # Use the fast tokenizers library (same as the rest of the project).
686
+ from tokenizers import Tokenizer # type: ignore[import]
687
+ tokenizer = Tokenizer.from_file(str(tokenizer_path))
688
+
689
+ # ---- Dataset & DataLoader ----------------------------------------------
690
+ # Import SFTDataset (created separately alongside this file).
691
+ # SFTDataset returns (input_ids, targets) where prompt token positions in
692
+ # targets are filled with -1. The Trainer._compute_loss already uses
693
+ # ignore_index=-1, so only response tokens contribute to the gradient.
694
+ from data.sft_dataset import SFTDataset # type: ignore[import]
695
+
696
+ max_seq_len_cfg = (
697
+ model.config.max_seq_len
698
+ if not isinstance(model, torch.nn.parallel.DistributedDataParallel)
699
+ else model.module.config.max_seq_len
700
+ )
701
+
702
+ # DDP optimization: rank 0 does tokenization + cache, other ranks load cache.
703
+ # This avoids 8× redundant work and 8× memory usage.
704
+ # Rank 0 gets all 64 CPU cores for parallel tokenization (reserve 8 for system)
705
+ tok_workers = 64 if is_main_process() else 0
706
+ if is_ddp:
707
+ if is_main_process():
708
+ # Rank 0: full tokenization with parallel workers + save cache
709
+ train_dataset = SFTDataset(
710
+ data_path=args.sft_data,
711
+ tokenizer=tokenizer,
712
+ max_seq_len=max_seq_len_cfg,
713
+ tokenizer_path=tokenizer_path,
714
+ num_workers=tok_workers,
715
+ )
716
+ # Barrier: wait for rank 0 to finish tokenization and save cache
717
+ torch.distributed.barrier()
718
+ if not is_main_process():
719
+ # Other ranks: load from cache (rank 0 already saved it)
720
+ train_dataset = SFTDataset(
721
+ data_path=args.sft_data,
722
+ tokenizer=tokenizer,
723
+ max_seq_len=max_seq_len_cfg,
724
+ )
725
+ else:
726
+ train_dataset = SFTDataset(
727
+ data_path=args.sft_data,
728
+ tokenizer=tokenizer,
729
+ max_seq_len=max_seq_len_cfg,
730
+ tokenizer_path=tokenizer_path,
731
+ num_workers=tok_workers,
732
+ )
733
+
734
+ if is_ddp:
735
+ train_sampler: DistributedSampler | RandomSampler = DistributedSampler(
736
+ train_dataset,
737
+ num_replicas=world_size,
738
+ rank=rank,
739
+ shuffle=True,
740
+ seed=args.seed,
741
+ )
742
+ shuffle = False
743
+ else:
744
+ train_sampler = RandomSampler(train_dataset)
745
+ shuffle = False # Sampler is provided; DataLoader must not also shuffle.
746
+
747
+ train_loader = DataLoader(
748
+ train_dataset,
749
+ batch_size=args.batch_size,
750
+ sampler=train_sampler,
751
+ # SFT datasets are typically small enough that 2–4 workers suffice.
752
+ # We use 4 to balance I/O with CPU parsing overhead from JSONL.
753
+ num_workers=4,
754
+ pin_memory=True,
755
+ drop_last=True,
756
+ prefetch_factor=2,
757
+ persistent_workers=True,
758
+ collate_fn=dynamic_collate_fn,
759
+ )
760
+
761
+ # ---- Pretrain Data Mixing (forgetting prevention) -----------------------
762
+ # When --pretrain_data is specified, create a second DataLoader for pretrain
763
+ # data and wrap both in MixingDataLoader. This interleaves SFT and pretrain
764
+ # batches (default 70/30 ratio) so the model retains pretrained knowledge.
765
+ pretrain_sampler = None
766
+ if args.pretrain_data is not None:
767
+ if not args.pretrain_data.exists():
768
+ raise FileNotFoundError(f"Pretrain data not found: {args.pretrain_data}")
769
+
770
+ from data import PackedDataset
771
+
772
+ max_seq_len = (
773
+ model.config.max_seq_len
774
+ if not isinstance(model, torch.nn.parallel.DistributedDataParallel)
775
+ else model.module.config.max_seq_len
776
+ )
777
+ pretrain_dataset = PackedDataset(args.pretrain_data, seq_len=max_seq_len)
778
+
779
+ if is_ddp:
780
+ pretrain_sampler = DistributedSampler(
781
+ pretrain_dataset,
782
+ num_replicas=world_size,
783
+ rank=rank,
784
+ shuffle=True,
785
+ seed=args.seed + 1000, # different seed from SFT
786
+ )
787
+ else:
788
+ pretrain_sampler = RandomSampler(pretrain_dataset)
789
+
790
+ pretrain_loader = DataLoader(
791
+ pretrain_dataset,
792
+ batch_size=args.batch_size,
793
+ sampler=pretrain_sampler,
794
+ num_workers=4,
795
+ pin_memory=True,
796
+ drop_last=True,
797
+ prefetch_factor=2,
798
+ persistent_workers=True,
799
+ )
800
+
801
+ # Wrap both loaders in MixingDataLoader
802
+ effective_loader = MixingDataLoader(
803
+ sft_loader=train_loader,
804
+ pretrain_loader=pretrain_loader,
805
+ pretrain_ratio=args.pretrain_mix_ratio,
806
+ sft_sampler=train_sampler if is_ddp else None,
807
+ pretrain_sampler=pretrain_sampler if is_ddp else None,
808
+ )
809
+
810
+ if is_main_process():
811
+ print(
812
+ f"[INFO] Data mixing enabled: "
813
+ f"{(1 - args.pretrain_mix_ratio) * 100:.0f}% SFT + "
814
+ f"{args.pretrain_mix_ratio * 100:.0f}% pretrain"
815
+ )
816
+ print(f"[INFO] Pretrain data: {args.pretrain_data} ({len(pretrain_dataset):,} samples)")
817
+ else:
818
+ effective_loader = train_loader
819
+
820
+ # Optional validation loader.
821
+ # NOTE: The current Trainer implementation does not yet accept a val_loader
822
+ # argument; the eval_interval config field is reserved for future use.
823
+ # We construct the loader here so that once Trainer gains eval support,
824
+ # wiring it in requires only passing val_loader=val_loader below.
825
+ val_loader: DataLoader | None = None
826
+ if args.val_data is not None:
827
+ if not args.val_data.exists():
828
+ raise FileNotFoundError(f"Validation data not found: {args.val_data}")
829
+ if is_ddp:
830
+ if is_main_process():
831
+ val_dataset = SFTDataset(
832
+ data_path=args.val_data,
833
+ tokenizer=tokenizer,
834
+ max_seq_len=train_dataset.max_seq_len,
835
+ tokenizer_path=tokenizer_path,
836
+ num_workers=tok_workers,
837
+ )
838
+ torch.distributed.barrier()
839
+ if not is_main_process():
840
+ val_dataset = SFTDataset(
841
+ data_path=args.val_data,
842
+ tokenizer=tokenizer,
843
+ max_seq_len=train_dataset.max_seq_len,
844
+ )
845
+ else:
846
+ val_dataset = SFTDataset(
847
+ data_path=args.val_data,
848
+ tokenizer=tokenizer,
849
+ max_seq_len=train_dataset.max_seq_len,
850
+ tokenizer_path=tokenizer_path,
851
+ num_workers=tok_workers,
852
+ )
853
+ val_loader = DataLoader(
854
+ val_dataset,
855
+ batch_size=args.batch_size,
856
+ shuffle=False,
857
+ num_workers=2,
858
+ pin_memory=True,
859
+ drop_last=False,
860
+ collate_fn=dynamic_collate_fn,
861
+ )
862
+ if is_main_process():
863
+ print(f"Validation dataset: {len(val_dataset):,} samples")
864
+
865
+ # ---- Optimizer ---------------------------------------------------------
866
+ # Use the same two-group split (weight_decay / no weight_decay) as pretrain.
867
+ # Unwrap DDP to get the raw model's parameters.
868
+ raw_model = getattr(model, "module", model)
869
+ param_groups = build_optimizer_param_groups(raw_model, args.weight_decay)
870
+ optimizer = torch.optim.AdamW(
871
+ param_groups,
872
+ lr=args.lr,
873
+ betas=(0.9, 0.95),
874
+ eps=1e-8,
875
+ fused=torch.cuda.is_available(), # Use fused kernel when on CUDA.
876
+ )
877
+
878
+ # ---- TrainConfig -------------------------------------------------------
879
+ # Set use_fp8 from the (possibly overridden) model config so Trainer builds
880
+ # the correct FP8 recipe and wraps forward passes in fp8_autocast.
881
+ use_fp8 = raw_model.config.use_fp8
882
+
883
+ train_config = TrainConfig(
884
+ max_steps=args.max_steps,
885
+ checkpoint_dir=str(args.checkpoint_dir),
886
+ grad_accum_steps=args.grad_accum,
887
+ use_fp8=use_fp8,
888
+ log_file=str(args.log_file) if args.log_file is not None else None,
889
+ save_interval=args.save_interval,
890
+ log_interval=10,
891
+ eval_interval=args.eval_interval,
892
+ max_grad_norm=args.max_grad_norm,
893
+ )
894
+
895
+ # ---- LR Scheduler ------------------------------------------------------
896
+ scheduler = get_cosine_schedule_with_warmup(
897
+ optimizer=optimizer,
898
+ warmup_steps=args.warmup_steps,
899
+ total_steps=train_config.max_steps,
900
+ )
901
+
902
+ # ---- Resume from SFT checkpoint ----------------------------------------
903
+ # When --resume is given we restore the SFT optimizer/scheduler state as
904
+ # well so learning rate, momentum buffers, etc. are correctly restored.
905
+ # NOTE: This resumes SFT training, NOT the pretrain checkpoint.
906
+ # The pretrain weights were already loaded above via from_pretrained().
907
+ start_step = 0
908
+ if args.resume is not None:
909
+ if not args.resume.exists():
910
+ raise FileNotFoundError(f"Resume checkpoint not found: {args.resume}")
911
+ start_step, resume_loss = load_checkpoint(
912
+ path=args.resume,
913
+ model=model,
914
+ optimizer=optimizer,
915
+ scheduler=scheduler,
916
+ )
917
+ if is_main_process():
918
+ print(f"Resumed SFT from {args.resume} at step {start_step} (loss={resume_loss:.4f})")
919
+
920
+ if args.resume is not None and isinstance(train_sampler, DistributedSampler):
921
+ steps_per_epoch = len(train_loader)
922
+ approx_epoch = start_step // steps_per_epoch if steps_per_epoch > 0 else 0
923
+ train_sampler.set_epoch(approx_epoch)
924
+ if is_main_process():
925
+ print(f"[INFO] Resume: sampler epoch set to {approx_epoch}")
926
+
927
+ # ---- Checkpoint directory ----------------------------------------------
928
+ args.checkpoint_dir.mkdir(parents=True, exist_ok=True)
929
+
930
+ # ---- Copy tokenizer to checkpoint dir for easy deployment later --------
931
+ # This mirrors the tokenizer into the SFT checkpoint root so that the
932
+ # final checkpoint directory is self-contained for convert_to_hf.py, etc.
933
+ if is_main_process():
934
+ dest_tok = args.checkpoint_dir / "tokenizer.json"
935
+ if not dest_tok.exists():
936
+ shutil.copy2(str(tokenizer_path), str(dest_tok))
937
+ print(f"Tokenizer copied to {dest_tok}")
938
+
939
+ # ---- Trainer -----------------------------------------------------------
940
+ # When data mixing is active, pass effective_loader (MixingDataLoader).
941
+ # MixingDataLoader handles its own epoch cycling, so no external sampler needed.
942
+ trainer = Trainer(
943
+ model=model,
944
+ train_loader=effective_loader,
945
+ optimizer=optimizer,
946
+ scheduler=scheduler,
947
+ config=train_config,
948
+ device=device,
949
+ rank=rank,
950
+ sampler=train_sampler if is_ddp and args.pretrain_data is None else None,
951
+ val_loader=val_loader,
952
+ )
953
+
954
+ # ---- Signal handlers for graceful shutdown ----------------------------
955
+ import signal as _signal_mod
956
+
957
+ _trainer_ref = trainer
958
+
959
+ def _graceful_shutdown_handler(signum, frame):
960
+ sig_name = _signal_mod.Signals(signum).name
961
+ if is_main_process():
962
+ import datetime as _dt
963
+ ts = _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
964
+ msg = (
965
+ f"[{ts}] [SIGNAL] Received {sig_name} (signum={signum}). "
966
+ f"Initiating graceful shutdown..."
967
+ )
968
+ print(f"\n{msg}")
969
+ if args.log_file is not None:
970
+ try:
971
+ with open(args.log_file, "a", encoding="utf-8") as f:
972
+ f.write(msg + "\n")
973
+ except Exception:
974
+ pass
975
+ _trainer_ref.request_shutdown(sig_name)
976
+
977
+ for _sig in (_signal_mod.SIGHUP, _signal_mod.SIGTERM):
978
+ _signal_mod.signal(_sig, _graceful_shutdown_handler)
979
+
980
+ # ---- SFT banner --------------------------------------------------------
981
+ if is_main_process():
982
+ import datetime
983
+
984
+ inner_config = raw_model.config
985
+ eff_batch_seqs = args.batch_size * args.grad_accum * world_size
986
+ eff_tokens_per_step = eff_batch_seqs * inner_config.max_seq_len
987
+ train_samples = len(train_dataset)
988
+ precision_label = "FP8 (MXFP8BlockScaling)" if use_fp8 else "BF16"
989
+ nccl_debug = os.environ.get("NCCL_DEBUG", "not set")
990
+ omp_threads = os.environ.get("OMP_NUM_THREADS", "not set")
991
+
992
+ mix_label = "none"
993
+ if args.pretrain_data is not None:
994
+ mix_label = (
995
+ f"{(1 - args.pretrain_mix_ratio) * 100:.0f}% SFT + "
996
+ f"{args.pretrain_mix_ratio * 100:.0f}% pretrain"
997
+ )
998
+
999
+ print(
1000
+ f"\n{'='*70}\n"
1001
+ f" LLM Supervised Fine-Tuning — "
1002
+ f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
1003
+ f"{'='*70}\n"
1004
+ f" base ckpt : {args.base_checkpoint}\n"
1005
+ f" sft data : {args.sft_data} ({train_samples:,} samples)\n"
1006
+ f" data mix : {mix_label}\n"
1007
+ f" model : {inner_config.num_params:,} params | "
1008
+ f"d_model={inner_config.d_model} n_layers={inner_config.n_layers}\n"
1009
+ f" precision : {precision_label}\n"
1010
+ f" GPUs : {world_size} | batch/GPU={args.batch_size} "
1011
+ f"grad_accum={args.grad_accum}\n"
1012
+ f" eff_batch : {eff_batch_seqs} seqs "
1013
+ f"= {eff_tokens_per_step:,} tok/step\n"
1014
+ f" max_steps : {train_config.max_steps:,}\n"
1015
+ f" lr : {args.lr:.2e} "
1016
+ f"warmup={args.warmup_steps} weight_decay={args.weight_decay}\n"
1017
+ f" ckpt_dir : {args.checkpoint_dir}\n"
1018
+ f" env : OMP_NUM_THREADS={omp_threads} NCCL_DEBUG={nccl_debug}\n"
1019
+ f"{'='*70}\n"
1020
+ )
1021
+
1022
+ # ---- NEFTune -----------------------------------------------------------
1023
+ # Add uniform noise to embeddings during training to improve instruction
1024
+ # following (Jain et al., 2023). Hook is registered on the raw (non-DDP)
1025
+ # model so it survives DDP's internal module wrapping.
1026
+ neftune_alpha = getattr(args, 'neftune_alpha', 5.0)
1027
+ neftune_handle = add_neftune_hook(raw_model, noise_alpha=neftune_alpha)
1028
+ if rank == 0:
1029
+ if neftune_handle is not None:
1030
+ print(f"[INFO] NEFTune enabled (noise_alpha={neftune_alpha})")
1031
+ else:
1032
+ print("[WARN] NEFTune disabled - embedding layer not found")
1033
+
1034
+ # ---- Train -------------------------------------------------------------
1035
+ try:
1036
+ trainer.train(start_step=start_step)
1037
+ except KeyboardInterrupt:
1038
+ if is_main_process():
1039
+ print("\n[INFO] SFT interrupted by user (KeyboardInterrupt).")
1040
+ except Exception as e:
1041
+ import traceback
1042
+ if is_main_process():
1043
+ tb = traceback.format_exc()
1044
+ print(f"\n[ERROR] SFT failed at rank {rank}:\n{tb}")
1045
+ if args.log_file is not None:
1046
+ with open(args.log_file, "a", encoding="utf-8") as f:
1047
+ import datetime
1048
+ f.write(
1049
+ f"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] "
1050
+ f"[FATAL] {tb}\n"
1051
+ )
1052
+ raise
1053
+ finally:
1054
+ # Remove NEFTune hook so the model is clean for inference/saving.
1055
+ if neftune_handle is not None:
1056
+ neftune_handle.remove()
1057
+ if is_ddp:
1058
+ cleanup_ddp()
1059
+
1060
+
1061
+ if __name__ == "__main__":
1062
+ main()
source/train/trainer.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ train/trainer.py — Core training loop.
3
+
4
+ Provides:
5
+ TrainConfig : Dataclass of all training hyper-parameters.
6
+ Trainer : Orchestrates gradient accumulation, AMP, gradient clipping,
7
+ tensorboard logging, and checkpoint saving.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import contextlib
13
+ import math
14
+ import time
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Optional
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ from torch.nn.parallel import DistributedDataParallel as DDP
22
+ from torch.optim import Optimizer
23
+ from torch.optim.lr_scheduler import LambdaLR
24
+ from torch.utils.data import DataLoader
25
+ from torch.utils.data.distributed import DistributedSampler
26
+ try:
27
+ from torch.utils.tensorboard import SummaryWriter
28
+ HAS_TENSORBOARD = True
29
+ except (ImportError, AttributeError):
30
+ SummaryWriter = None # type: ignore[misc,assignment]
31
+ HAS_TENSORBOARD = False
32
+
33
+ from train.utils import get_grad_norm, is_main_process, save_checkpoint
34
+
35
+
36
+ # ---------------------------------------------------------------------------
37
+ # Optional TransformerEngine import (FP8 support)
38
+ # ---------------------------------------------------------------------------
39
+ try:
40
+ import transformer_engine.pytorch as te # type: ignore[import]
41
+ from transformer_engine.common.recipe import DelayedScaling, Format # type: ignore[import]
42
+ HAS_TE = True
43
+ except ImportError:
44
+ te = None # type: ignore[assignment]
45
+ HAS_TE = False
46
+
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Configuration dataclass
50
+ # ---------------------------------------------------------------------------
51
+
52
+
53
+ @dataclass
54
+ class TrainConfig:
55
+ """Hyper-parameters that control the training loop."""
56
+
57
+ # Total number of optimiser update steps.
58
+ max_steps: int = 100_000
59
+
60
+ # Number of forward passes accumulated before each optimiser step.
61
+ grad_accum_steps: int = 1
62
+
63
+ # Maximum global gradient L2 norm; clips if exceeded (0 = disabled).
64
+ max_grad_norm: float = 1.0
65
+
66
+ # Log training metrics every this many *optimiser* steps.
67
+ log_interval: int = 10
68
+
69
+ # Save a checkpoint every this many optimiser steps.
70
+ save_interval: int = 1000
71
+
72
+ # Run validation (if val_loader provided) every this many optimiser steps.
73
+ eval_interval: int = 500
74
+
75
+ # Root directory where checkpoint sub-folders are written.
76
+ checkpoint_dir: str = "checkpoints"
77
+
78
+ # Use bf16 autocast during the forward pass (no GradScaler needed for bf16).
79
+ use_amp: bool = True
80
+
81
+ # Pass model through torch.compile() before training.
82
+ compile_model: bool = False
83
+
84
+ # FP8 (TransformerEngine) settings — only relevant when use_fp8=True.
85
+ use_fp8: bool = False
86
+ fp8_amax_history_len: int = 16
87
+ fp8_amax_compute_algo: str = "max" # "max" | "most_recent"
88
+ fp8_format: str = "MXFP8" # "MXFP8" (B200 block scaling) | "HYBRID" (E4M3+E5M2)
89
+
90
+ # Path to a text log file (rank-0 only). None = stdout only.
91
+ log_file: Optional[str] = None
92
+
93
+ # grad_norm을 파일에 기록하는 간격 (0=비활성)
94
+ log_grad_norm_interval: int = 100
95
+ # GPU 메모리를 파일에 기록하는 간격 (0=비활성)
96
+ log_memory_interval: int = 100
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # Trainer
101
+ # ---------------------------------------------------------------------------
102
+
103
+
104
+ class Trainer:
105
+ """
106
+ Manages the full pretraining loop for a decoder-only LLM.
107
+
108
+ Supports:
109
+ - Gradient accumulation over ``config.grad_accum_steps`` micro-batches.
110
+ - bf16 mixed-precision via ``torch.autocast`` (no GradScaler required).
111
+ - Global gradient norm clipping.
112
+ - Tensorboard logging on the main process.
113
+ - Periodic checkpoint saving via :func:`train.utils.save_checkpoint`.
114
+ - Optional ``torch.compile`` acceleration.
115
+
116
+ Args:
117
+ model: The LLM (plain ``nn.Module`` or DDP-wrapped).
118
+ train_loader: DataLoader yielding ``(input_ids, targets)`` batches.
119
+ optimizer: AdamW (or any ``Optimizer``) configured externally.
120
+ scheduler: LR scheduler produced by the caller.
121
+ config: ``TrainConfig`` instance controlling all loop behaviour.
122
+ device: Target device for data and model.
123
+ rank: Process rank (used to suppress logging on non-main ranks).
124
+ """
125
+
126
+ def __init__(
127
+ self,
128
+ model: nn.Module,
129
+ train_loader: DataLoader,
130
+ optimizer: Optimizer,
131
+ scheduler: LambdaLR,
132
+ config: TrainConfig,
133
+ device: torch.device,
134
+ rank: int = 0,
135
+ sampler: Optional[DistributedSampler] = None,
136
+ val_loader: Optional[DataLoader] = None,
137
+ ) -> None:
138
+ self.model = model
139
+ self.train_loader = train_loader
140
+ self.optimizer = optimizer
141
+ self.scheduler = scheduler
142
+ self.config = config
143
+ self.device = device
144
+ self.rank = rank
145
+ self._is_main = is_main_process()
146
+ self._sampler = sampler # for set_epoch() on each data pass
147
+ self._epoch = 0
148
+ self._val_loader = val_loader
149
+ self._best_val_loss: float = float("inf")
150
+ self._val_patience_counter: int = 0
151
+ self._val_patience_limit: int = 10 # early stopping patience (v2: 5→10, warmup 후 충분한 학습 보장)
152
+
153
+ # Graceful shutdown support — signal handler에서 flag 설정,
154
+ # 학습 루프가 각 step 완료 후 확인하여 비상 체크포인트 저장 후 종료
155
+ self._shutdown_requested = False
156
+ self._shutdown_signal = ""
157
+
158
+ # Build FP8 recipe once (reused every step) ----------------------
159
+ self._fp8_recipe = None
160
+ if config.use_fp8 and HAS_TE:
161
+ if config.fp8_format == "MXFP8":
162
+ from transformer_engine.common.recipe import MXFP8BlockScaling # type: ignore[import]
163
+ self._fp8_recipe = MXFP8BlockScaling()
164
+ else:
165
+ self._fp8_recipe = DelayedScaling(
166
+ fp8_format=getattr(Format, config.fp8_format),
167
+ amax_history_len=config.fp8_amax_history_len,
168
+ amax_compute_algo=config.fp8_amax_compute_algo,
169
+ )
170
+
171
+ # Optionally compile the model (unwrap DDP first to compile the inner module).
172
+ if config.compile_model:
173
+ inner: nn.Module = getattr(self.model, "module", self.model)
174
+ compiled = torch.compile(inner)
175
+ if hasattr(self.model, "module"):
176
+ self.model.module = compiled # type: ignore[assignment]
177
+ else:
178
+ self.model = compiled # type: ignore[assignment]
179
+
180
+ # Tensorboard writer — only on rank 0.
181
+ self._writer: Optional[SummaryWriter] = None
182
+ self._log_fh = None # optional file handle for structured text log
183
+ if self._is_main:
184
+ if HAS_TENSORBOARD:
185
+ log_dir = Path(config.checkpoint_dir) / "tensorboard"
186
+ self._writer = SummaryWriter(log_dir=str(log_dir))
187
+ if config.log_file is not None:
188
+ Path(config.log_file).parent.mkdir(parents=True, exist_ok=True)
189
+ self._log_fh = open(config.log_file, "a", encoding="utf-8", buffering=1)
190
+
191
+ # 학습 시작 시각 기록 (통계 요약 로그에 사용)
192
+ import datetime
193
+ self._train_start_time = datetime.datetime.now()
194
+
195
+ # Infinite iterator over the DataLoader.
196
+ self._loader_iter = iter(self.train_loader)
197
+
198
+ # ------------------------------------------------------------------
199
+ # Public API
200
+ # ------------------------------------------------------------------
201
+
202
+ def request_shutdown(self, signal_name: str = "UNKNOWN") -> None:
203
+ """Request graceful shutdown after the current training step.
204
+
205
+ Called from signal handlers (SIGHUP, SIGTERM). Sets a flag
206
+ that the training loop checks after each optimizer step.
207
+ The loop will save an emergency checkpoint and exit cleanly.
208
+ """
209
+ self._shutdown_requested = True
210
+ self._shutdown_signal = signal_name
211
+
212
+ def train(self, start_step: int = 0) -> None:
213
+ """
214
+ Run the main training loop from ``start_step`` to ``config.max_steps``.
215
+
216
+ Args:
217
+ start_step: First optimiser step index (non-zero when resuming).
218
+ """
219
+ cfg = self.config
220
+ model = self.model
221
+
222
+ model.train()
223
+
224
+ # Timing state for tokens/sec estimation.
225
+ t0 = time.perf_counter()
226
+ running_loss = 0.0
227
+ log_step_count = 0
228
+ accum_loss = torch.tensor(0.0, device=self.device) # initialise so end-of-training save is safe on empty loops
229
+
230
+ for step in range(start_step, cfg.max_steps):
231
+ # ---- Gradient accumulation loop --------------------------------
232
+ self.optimizer.zero_grad(set_to_none=True)
233
+ # Accumulate loss on GPU to avoid one GPU-CPU sync per micro-step.
234
+ accum_loss = torch.zeros(1, device=self.device)
235
+
236
+ for micro_step in range(cfg.grad_accum_steps):
237
+ batch = self._next_batch()
238
+ # Suppress DDP all-reduce on all but the last micro-step (Bug 3).
239
+ is_last_micro = micro_step == cfg.grad_accum_steps - 1
240
+ sync_ctx = (
241
+ contextlib.nullcontext()
242
+ if not isinstance(model, DDP) or is_last_micro
243
+ else model.no_sync()
244
+ )
245
+ try:
246
+ with sync_ctx:
247
+ micro_loss = self._step(batch) # returns detached GPU tensor
248
+ except torch.cuda.OutOfMemoryError as e:
249
+ torch.cuda.empty_cache()
250
+ mem_total = torch.cuda.get_device_properties(self.device).total_memory / 1e9
251
+ mem_alloc = torch.cuda.memory_allocated() / 1e9
252
+ raise RuntimeError(
253
+ f"CUDA OOM at step {step}, micro_step {micro_step}. "
254
+ f"GPU mem: {mem_alloc:.1f}/{mem_total:.1f} GB. "
255
+ f"Try reducing batch_size or grad_accum_steps."
256
+ ) from e
257
+ except RuntimeError as e:
258
+ self._log(f"RuntimeError at step {step}, micro_step {micro_step}: {e}", level="ERROR")
259
+ raise
260
+ accum_loss += micro_loss # GPU-side accumulation, no CPU sync
261
+
262
+ # Single GPU-CPU sync per optimizer step (was one sync per micro-step).
263
+ avg_loss = accum_loss.item() / cfg.grad_accum_steps
264
+
265
+ # Detect NaN/Inf loss — indicates numerical instability.
266
+ if not math.isfinite(avg_loss):
267
+ mem_gb = torch.cuda.memory_allocated() / 1e9
268
+ mem_total = torch.cuda.get_device_properties(self.device).total_memory / 1e9
269
+ raise RuntimeError(
270
+ f"Non-finite loss detected: {avg_loss}. "
271
+ f"GPU mem: {mem_gb:.1f}/{mem_total:.1f} GB. "
272
+ f"Check lr, grad clipping, FP8 amax history. "
273
+ f"Try: lower lr, increase fp8_amax_history_len, or switch to BF16."
274
+ )
275
+
276
+ # ---- Gradient clipping -----------------------------------------
277
+ # clip_grad_norm_ already computes the global norm internally.
278
+ # Reuse its return value to avoid a second pass of ~50 GPU-CPU syncs.
279
+ if cfg.max_grad_norm > 0.0:
280
+ grad_norm = torch.nn.utils.clip_grad_norm_(
281
+ model.parameters(), cfg.max_grad_norm
282
+ ).item()
283
+ else:
284
+ grad_norm = get_grad_norm(model)
285
+
286
+ # ---- Optimiser + scheduler step ---------------------------------
287
+ self.optimizer.step()
288
+ self.scheduler.step()
289
+
290
+ # ---- Graceful shutdown check -----------------------------------
291
+ # Signal handler가 request_shutdown()을 호출하면 이 flag가 True.
292
+ # 현재 step의 optimizer 업데이트가 완료된 시점에서 체크하므로
293
+ # 모델 가중치는 항상 일관된 상태로 저장됩니다.
294
+ if self._shutdown_requested:
295
+ self._log(
296
+ f"Graceful shutdown initiated (signal: {self._shutdown_signal}) "
297
+ f"at step {step + 1}, loss={avg_loss:.4f}",
298
+ level="WARN",
299
+ )
300
+ if self._is_main:
301
+ ckpt_path = save_checkpoint(
302
+ model=self.model,
303
+ optimizer=self.optimizer,
304
+ scheduler=self.scheduler,
305
+ step=step + 1,
306
+ loss=avg_loss,
307
+ path=cfg.checkpoint_dir,
308
+ )
309
+ self._log(f"Emergency checkpoint saved → {ckpt_path}", level="WARN")
310
+ # DDP 동기화: 모든 rank가 함께 종료하도록 barrier
311
+ try:
312
+ if torch.distributed.is_initialized():
313
+ torch.distributed.barrier()
314
+ except Exception:
315
+ pass # DDP 미사용 또는 이미 해체된 경우 무시
316
+ self._log("Shutdown complete. Exiting training loop.", level="WARN")
317
+ if self._writer is not None:
318
+ self._writer.close()
319
+ if self._log_fh is not None:
320
+ self._log_fh.flush()
321
+ return
322
+
323
+ running_loss += avg_loss
324
+ log_step_count += 1
325
+
326
+ # ---- Logging ---------------------------------------------------
327
+ if (step + 1) % cfg.log_interval == 0 and self._is_main:
328
+ t1 = time.perf_counter()
329
+ elapsed = t1 - t0
330
+
331
+ avg_loss = running_loss / log_step_count
332
+
333
+ # Estimate throughput: tokens processed during this log window.
334
+ batch_size, seq_len = self._last_batch_shape
335
+ tokens_per_sec = (
336
+ batch_size * seq_len * cfg.grad_accum_steps * cfg.log_interval
337
+ ) / max(elapsed, 1e-9)
338
+
339
+ current_lr = self.scheduler.get_last_lr()[0]
340
+ global_step = step + 1
341
+
342
+ mem_gb = torch.cuda.memory_allocated() / 1e9
343
+ self._log(
344
+ f"step {global_step:>7d} | "
345
+ f"loss {avg_loss:.4f} | "
346
+ f"lr {current_lr:.2e} | "
347
+ f"gnorm {grad_norm:.3f} | "
348
+ f"tok/s {tokens_per_sec:,.0f} | "
349
+ f"mem {mem_gb:.1f}GB | "
350
+ f"epoch {self._epoch}"
351
+ )
352
+
353
+ if self._writer is not None:
354
+ self._writer.add_scalar("train/loss", avg_loss, global_step)
355
+ self._writer.add_scalar("train/lr", current_lr, global_step)
356
+ self._writer.add_scalar("train/grad_norm", grad_norm, global_step)
357
+ self._writer.add_scalar("train/tokens_per_sec", tokens_per_sec, global_step)
358
+
359
+ # Reset accumulators.
360
+ running_loss = 0.0
361
+ log_step_count = 0
362
+ t0 = t1
363
+
364
+ # ---- Validation ------------------------------------------------
365
+ if (step + 1) % cfg.eval_interval == 0 and self._val_loader is not None:
366
+ val_loss = self._run_validation()
367
+ # Determine early stopping on rank 0, broadcast to all ranks
368
+ # so every DDP rank exits together (prevents hang).
369
+ should_stop = False
370
+ if self._is_main:
371
+ self._log(f"step {step + 1:>7d} | val_loss {val_loss:.4f}")
372
+ if self._writer is not None:
373
+ self._writer.add_scalar("val/loss", val_loss, step + 1)
374
+ # Save best checkpoint when val loss improves.
375
+ if val_loss < self._best_val_loss:
376
+ self._best_val_loss = val_loss
377
+ self._val_patience_counter = 0
378
+ best_path = save_checkpoint(
379
+ model=self.model,
380
+ optimizer=self.optimizer,
381
+ scheduler=self.scheduler,
382
+ step=step + 1,
383
+ loss=val_loss,
384
+ path=cfg.checkpoint_dir,
385
+ suffix="best",
386
+ )
387
+ self._log(
388
+ f"New best val_loss={val_loss:.4f} → {best_path}"
389
+ )
390
+ else:
391
+ self._val_patience_counter += 1
392
+ self._log(
393
+ f"val_loss {val_loss:.4f} did not improve "
394
+ f"(best={self._best_val_loss:.4f}, "
395
+ f"patience={self._val_patience_counter}/{self._val_patience_limit})"
396
+ )
397
+ if self._val_patience_counter >= self._val_patience_limit:
398
+ self._log(
399
+ f"Early stopping triggered at step {step + 1} "
400
+ f"(patience {self._val_patience_limit} exhausted)"
401
+ )
402
+ should_stop = True
403
+ # Broadcast early stopping decision to all DDP ranks.
404
+ if torch.distributed.is_initialized():
405
+ stop_tensor = torch.tensor(
406
+ [1 if should_stop else 0], dtype=torch.int32,
407
+ device=self.device,
408
+ )
409
+ torch.distributed.broadcast(stop_tensor, src=0)
410
+ should_stop = stop_tensor.item() == 1
411
+ if should_stop:
412
+ return
413
+
414
+ # ---- Checkpoint save -------------------------------------------
415
+ if (step + 1) % cfg.save_interval == 0 and self._is_main:
416
+ ckpt_path = save_checkpoint(
417
+ model=self.model,
418
+ optimizer=self.optimizer,
419
+ scheduler=self.scheduler,
420
+ step=step + 1,
421
+ loss=avg_loss,
422
+ path=cfg.checkpoint_dir,
423
+ )
424
+ self._log(f"Checkpoint saved → {ckpt_path}")
425
+
426
+ # ---- End of training cleanup ---------------------------------------
427
+ if self._is_main:
428
+ # Save final checkpoint.
429
+ final_path = save_checkpoint(
430
+ model=self.model,
431
+ optimizer=self.optimizer,
432
+ scheduler=self.scheduler,
433
+ step=cfg.max_steps,
434
+ loss=avg_loss,
435
+ path=cfg.checkpoint_dir,
436
+ )
437
+ self._log(f"Training complete. Final checkpoint → {final_path}")
438
+
439
+ import datetime
440
+ elapsed = (datetime.datetime.now() - self._train_start_time).total_seconds()
441
+ total_steps_done = cfg.max_steps - start_step
442
+ self._log(
443
+ f"Training summary: {total_steps_done} steps, "
444
+ f"{elapsed/3600:.2f}h elapsed, "
445
+ f"avg {total_steps_done/elapsed:.1f} steps/s"
446
+ )
447
+
448
+ if self._writer is not None:
449
+ self._writer.close()
450
+ if self._log_fh is not None:
451
+ self._log_fh.close()
452
+
453
+ # ------------------------------------------------------------------
454
+ # Internal helpers
455
+ # ------------------------------------------------------------------
456
+
457
+ @torch.no_grad()
458
+ def _run_validation(self) -> float:
459
+ """
460
+ Evaluate the model on the entire validation set and return the mean loss.
461
+
462
+ Temporarily switches the model to eval mode and back to train mode
463
+ afterwards so that dropout / NEFTune hooks are inactive during eval.
464
+ """
465
+ model = self.model
466
+ model.eval()
467
+ total_loss = 0.0
468
+ total_batches = 0
469
+
470
+ for batch in self._val_loader: # type: ignore[union-attr]
471
+ input_ids = batch[0].to(self.device, dtype=torch.long, non_blocking=True)
472
+ targets = batch[1].to(self.device, dtype=torch.long, non_blocking=True)
473
+ # Consume attention_mask if provided (model does not use it yet).
474
+ _attn_mask = batch[2].to(self.device, non_blocking=True) if len(batch) > 2 else None # noqa: F841
475
+
476
+ device_type = self.device.type
477
+ with contextlib.ExitStack() as stack:
478
+ if self.config.use_fp8 and self._fp8_recipe is not None:
479
+ stack.enter_context(
480
+ torch.autocast(device_type=device_type, dtype=torch.bfloat16)
481
+ )
482
+ stack.enter_context(
483
+ te.fp8_autocast(enabled=True, fp8_recipe=self._fp8_recipe)
484
+ )
485
+ elif self.config.use_amp:
486
+ stack.enter_context(
487
+ torch.autocast(device_type=device_type, dtype=torch.bfloat16)
488
+ )
489
+ logits, _ = model(input_ids)
490
+ loss = self._compute_loss(logits, targets)
491
+
492
+ total_loss += loss.item()
493
+ total_batches += 1
494
+
495
+ model.train()
496
+ if total_batches == 0:
497
+ self._log("Validation set is empty — returning inf", level="WARN")
498
+ return float("inf")
499
+ return total_loss / total_batches
500
+
501
+ def _log(self, msg: str, level: str = "INFO") -> None:
502
+ """Print to stdout and optionally write to the log file."""
503
+ import datetime
504
+ ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
505
+ line = f"[{ts}] [{level}] {msg}"
506
+ print(line)
507
+ if self._log_fh is not None:
508
+ self._log_fh.write(line + "\n")
509
+
510
+ def _step(self, batch: tuple) -> torch.Tensor:
511
+ """
512
+ Execute one forward + backward pass for a single micro-batch.
513
+
514
+ The loss is divided by ``grad_accum_steps`` so that gradients
515
+ accumulated over multiple micro-batches sum to the correct scale.
516
+
517
+ Args:
518
+ batch: ``(input_ids, targets)`` or ``(input_ids, targets, attention_mask)``
519
+ tensors on CPU; moved to device here.
520
+
521
+ Returns:
522
+ Raw (un-scaled) loss as a detached GPU tensor (no CPU sync).
523
+ The caller is responsible for calling .item() once per optimizer step.
524
+ """
525
+ input_ids = batch[0].to(self.device, dtype=torch.long, non_blocking=True)
526
+ targets = batch[1].to(self.device, dtype=torch.long, non_blocking=True)
527
+ # Consume attention_mask if the dataset provides it (future-proof).
528
+ # Current model forward(input_ids, targets=None) does not accept
529
+ # attention_mask, so we read it but do not forward it yet.
530
+ _attn_mask = batch[2].to(self.device, non_blocking=True) if len(batch) > 2 else None # noqa: F841
531
+
532
+ # Store for tokens/sec calculation.
533
+ self._last_batch_shape = (input_ids.shape[0], input_ids.shape[1])
534
+
535
+ device_type = self.device.type
536
+ # te.fp8_autocast must be combined with torch.autocast(bfloat16) so that
537
+ # all tensors entering TE modules are in BF16 (not FP32 master weights).
538
+ # te.fp8_autocast only affects TE modules (te.Linear, te.LayerNormMLP).
539
+ # Hybrid Mamba-2 layers use nn.Linear → stay in bf16 under torch.autocast.
540
+ with contextlib.ExitStack() as stack:
541
+ if self.config.use_fp8 and self._fp8_recipe is not None:
542
+ stack.enter_context(
543
+ torch.autocast(device_type=device_type, dtype=torch.bfloat16)
544
+ )
545
+ stack.enter_context(
546
+ te.fp8_autocast(enabled=True, fp8_recipe=self._fp8_recipe)
547
+ )
548
+ elif self.config.use_amp:
549
+ stack.enter_context(
550
+ torch.autocast(device_type=device_type, dtype=torch.bfloat16)
551
+ )
552
+ logits, _ = self.model(input_ids)
553
+ loss = self._compute_loss(logits, targets)
554
+
555
+ # Scale loss for gradient accumulation before backward.
556
+ scaled_loss = loss / self.config.grad_accum_steps
557
+ scaled_loss.backward()
558
+
559
+ # Return detached GPU tensor — no CPU sync here.
560
+ # Caller accumulates on GPU and calls .item() once per optimizer step.
561
+ return loss.detach()
562
+
563
+ @staticmethod
564
+ def _compute_loss(
565
+ logits: torch.Tensor, targets: torch.Tensor
566
+ ) -> torch.Tensor:
567
+ """
568
+ Compute cross-entropy loss, ignoring target positions equal to -1.
569
+
570
+ Args:
571
+ logits: ``[B, T, vocab_size]`` float tensor.
572
+ targets: ``[B, T]`` long tensor (may contain -1 as ignore index).
573
+
574
+ Returns:
575
+ Scalar loss tensor.
576
+ """
577
+ B, T, V = logits.shape
578
+ return nn.functional.cross_entropy(
579
+ logits.view(B * T, V),
580
+ targets.view(B * T),
581
+ ignore_index=-1,
582
+ )
583
+
584
+ def _next_batch(self) -> tuple:
585
+ """Return the next batch, restarting the DataLoader iterator if exhausted."""
586
+ try:
587
+ return next(self._loader_iter)
588
+ except StopIteration:
589
+ self._epoch += 1
590
+ # Advance DistributedSampler epoch so each pass has a fresh shuffle.
591
+ if self._sampler is not None:
592
+ self._sampler.set_epoch(self._epoch)
593
+ self._loader_iter = iter(self.train_loader)
594
+ return next(self._loader_iter)
source/train/utils.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ train/utils.py — Training utility functions.
3
+
4
+ Provides:
5
+ get_cosine_schedule_with_warmup : LambdaLR scheduler with linear warmup + cosine decay
6
+ save_checkpoint : Persist model/optimizer/scheduler state to disk
7
+ load_checkpoint : Restore state from a saved checkpoint directory
8
+ get_grad_norm : Compute total L2 gradient norm across all parameters
9
+ setup_ddp : Initialise NCCL distributed process group
10
+ cleanup_ddp : Tear down distributed process group
11
+ is_main_process : True when this process is rank 0 (or non-distributed)
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ import os
18
+ import shutil
19
+ from pathlib import Path
20
+ from typing import Optional, Tuple
21
+
22
+ import numpy as np
23
+ import torch
24
+ import torch.distributed as dist
25
+ import yaml
26
+ from torch.optim import Optimizer
27
+ from torch.optim.lr_scheduler import LambdaLR
28
+
29
+
30
+ # ---------------------------------------------------------------------------
31
+ # Learning-rate schedule
32
+ # ---------------------------------------------------------------------------
33
+
34
+
35
+ def get_cosine_schedule_with_warmup(
36
+ optimizer: Optimizer,
37
+ warmup_steps: int,
38
+ total_steps: int,
39
+ min_lr_ratio: float = 0.1,
40
+ ) -> LambdaLR:
41
+ """
42
+ Create a LambdaLR scheduler with:
43
+ - Linear warmup: lr scales from 0 → 1 over [0, warmup_steps)
44
+ - Cosine decay: lr scales from 1 → min_lr_ratio over [warmup_steps, total_steps]
45
+
46
+ Args:
47
+ optimizer: The wrapped optimizer.
48
+ warmup_steps: Number of linear-warmup steps.
49
+ total_steps: Total number of training steps.
50
+ min_lr_ratio: Minimum lr as a fraction of the peak lr (default 0.1).
51
+
52
+ Returns:
53
+ A LambdaLR scheduler instance.
54
+ """
55
+ if warmup_steps < 0:
56
+ raise ValueError(f"warmup_steps must be >= 0, got {warmup_steps}")
57
+ if total_steps <= 0:
58
+ raise ValueError(f"total_steps must be > 0, got {total_steps}")
59
+ if not (0.0 <= min_lr_ratio <= 1.0):
60
+ raise ValueError(f"min_lr_ratio must be in [0, 1], got {min_lr_ratio}")
61
+
62
+ def lr_lambda(current_step: int) -> float:
63
+ # Linear warmup phase.
64
+ if current_step < warmup_steps:
65
+ return float(current_step) / float(max(1, warmup_steps))
66
+
67
+ # After total_steps, hold at min_lr_ratio.
68
+ if current_step >= total_steps:
69
+ return min_lr_ratio
70
+
71
+ # Cosine decay phase.
72
+ decay_steps = total_steps - warmup_steps
73
+ progress = float(current_step - warmup_steps) / float(max(1, decay_steps))
74
+ cosine_factor = 0.5 * (1.0 + math.cos(math.pi * progress))
75
+ # Scale cosine output from [0, 1] into [min_lr_ratio, 1].
76
+ return min_lr_ratio + (1.0 - min_lr_ratio) * cosine_factor
77
+
78
+ return LambdaLR(optimizer, lr_lambda)
79
+
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # Checkpoint save / load
83
+ # ---------------------------------------------------------------------------
84
+
85
+
86
+ def save_checkpoint(
87
+ model: torch.nn.Module,
88
+ optimizer: Optimizer,
89
+ scheduler: LambdaLR,
90
+ step: int,
91
+ loss: float,
92
+ path: str | Path,
93
+ suffix: str | None = None,
94
+ ) -> Path:
95
+ """
96
+ Save a training checkpoint to ``path/checkpoint-{step:07d}/``.
97
+
98
+ Saves:
99
+ - model.pt : model state_dict
100
+ - optimizer.pt : optimizer state_dict
101
+ - scheduler.pt : scheduler state_dict
102
+ - train_state.pt : step and loss scalars
103
+ - config.yaml : model LMConfig (if the model exposes a ``.config`` attribute)
104
+
105
+ Handles both plain ``nn.Module`` and DDP-wrapped models by unwrapping
106
+ via ``.module`` when present.
107
+
108
+ Args:
109
+ model: The model (plain or DDP-wrapped).
110
+ optimizer: The optimizer.
111
+ scheduler: The LR scheduler.
112
+ step: Current training step (used in directory name).
113
+ loss: Current loss value (stored for reference).
114
+ path: Root checkpoint directory.
115
+
116
+ Returns:
117
+ Path to the created checkpoint sub-directory.
118
+ """
119
+ dir_name = f"checkpoint-{suffix}" if suffix else f"checkpoint-{step:07d}"
120
+ ckpt_dir = Path(path) / dir_name
121
+ tmp_dir = Path(path) / f".tmp_{dir_name}"
122
+
123
+ # Write to temp directory first for crash safety
124
+ if tmp_dir.exists():
125
+ shutil.rmtree(tmp_dir)
126
+ tmp_dir.mkdir(parents=True, exist_ok=True)
127
+
128
+ raw_model: torch.nn.Module = getattr(model, "module", model)
129
+
130
+ torch.save(raw_model.state_dict(), tmp_dir / "model.pt")
131
+ torch.save(optimizer.state_dict(), tmp_dir / "optimizer.pt")
132
+ torch.save(scheduler.state_dict(), tmp_dir / "scheduler.pt")
133
+
134
+ import random as _random
135
+ train_state = {
136
+ "step": step,
137
+ "loss": loss,
138
+ "rng_state": {
139
+ "python": _random.getstate(),
140
+ "numpy": np.random.get_state(),
141
+ "torch_cpu": torch.random.get_rng_state(),
142
+ "torch_cuda": torch.cuda.get_rng_state_all(),
143
+ },
144
+ }
145
+ torch.save(train_state, tmp_dir / "train_state.pt")
146
+
147
+ # Persist the model config when available.
148
+ if hasattr(raw_model, "config"):
149
+ cfg = raw_model.config
150
+ if hasattr(cfg, "to_dict"):
151
+ config_dict = cfg.to_dict()
152
+ else:
153
+ # Fallback: try __dict__ for plain dataclasses.
154
+ config_dict = {
155
+ k: v for k, v in vars(cfg).items() if not k.startswith("_")
156
+ }
157
+ with open(tmp_dir / "config.yaml", "w", encoding="utf-8") as f:
158
+ yaml.safe_dump(config_dict, f, default_flow_style=False, sort_keys=False)
159
+
160
+ # Atomic swap: rename old → trash, tmp → final, delete trash
161
+ trash_dir = Path(path) / f".trash_{dir_name}"
162
+ if trash_dir.exists():
163
+ shutil.rmtree(trash_dir)
164
+ if ckpt_dir.exists():
165
+ ckpt_dir.rename(trash_dir)
166
+ tmp_dir.rename(ckpt_dir)
167
+ if trash_dir.exists():
168
+ shutil.rmtree(trash_dir)
169
+
170
+ # Clean up old checkpoints (keep recent N + best)
171
+ cleanup_old_checkpoints(Path(path))
172
+
173
+ return ckpt_dir
174
+
175
+
176
+ def cleanup_old_checkpoints(path: Path, keep: int = 5) -> None:
177
+ """Remove old checkpoints, keeping the most recent `keep` plus checkpoint-best."""
178
+ ckpts = sorted(
179
+ [d for d in path.glob("checkpoint-[0-9]*") if d.is_dir()],
180
+ key=lambda d: d.stat().st_mtime,
181
+ )
182
+ for old in ckpts[:-keep]:
183
+ shutil.rmtree(old)
184
+
185
+
186
+ def load_checkpoint(
187
+ path: str | Path,
188
+ model: torch.nn.Module,
189
+ optimizer: Optional[Optimizer] = None,
190
+ scheduler: Optional[LambdaLR] = None,
191
+ ) -> Tuple[int, float]:
192
+ """
193
+ Load a checkpoint from a directory created by :func:`save_checkpoint`.
194
+
195
+ The model weights are always restored. Optimizer and scheduler states are
196
+ only restored when the corresponding objects are provided.
197
+
198
+ Args:
199
+ path: Path to the checkpoint directory (e.g. ``checkpoints/checkpoint-0001000``).
200
+ model: Model to load weights into (plain or DDP-wrapped).
201
+ optimizer: Optional optimizer to restore state into.
202
+ scheduler: Optional LR scheduler to restore state into.
203
+
204
+ Returns:
205
+ ``(step, loss)`` — the training step and loss recorded at save time.
206
+ """
207
+ ckpt_dir = Path(path)
208
+ if not ckpt_dir.is_dir():
209
+ raise FileNotFoundError(f"Checkpoint directory not found: {ckpt_dir}")
210
+
211
+ # Unwrap DDP model if necessary.
212
+ raw_model: torch.nn.Module = getattr(model, "module", model)
213
+
214
+ # Determine the device the model lives on.
215
+ try:
216
+ device = next(raw_model.parameters()).device
217
+ except StopIteration:
218
+ device = torch.device("cpu")
219
+
220
+ raw_model.load_state_dict(
221
+ torch.load(ckpt_dir / "model.pt", map_location=device, weights_only=True)
222
+ )
223
+
224
+ if optimizer is not None:
225
+ optimizer.load_state_dict(
226
+ torch.load(ckpt_dir / "optimizer.pt", map_location=device, weights_only=True)
227
+ )
228
+
229
+ if scheduler is not None:
230
+ scheduler.load_state_dict(
231
+ torch.load(ckpt_dir / "scheduler.pt", map_location=device, weights_only=True)
232
+ )
233
+
234
+ train_state = torch.load(
235
+ ckpt_dir / "train_state.pt", map_location="cpu", weights_only=True
236
+ )
237
+ step: int = int(train_state["step"])
238
+ loss: float = float(train_state["loss"])
239
+
240
+ # Restore RNG states if available (for exact resume reproducibility)
241
+ rng_state = train_state.get("rng_state")
242
+ if rng_state is not None:
243
+ import random as _random
244
+ try:
245
+ _random.setstate(rng_state["python"])
246
+ np.random.set_state(rng_state["numpy"])
247
+ torch.random.set_rng_state(rng_state["torch_cpu"])
248
+ torch.cuda.set_rng_state_all(rng_state["torch_cuda"])
249
+ except Exception as e:
250
+ print(f"[WARN] RNG state restore failed (non-fatal): {e}")
251
+
252
+ return step, loss
253
+
254
+
255
+ # ---------------------------------------------------------------------------
256
+ # Gradient utilities
257
+ # ---------------------------------------------------------------------------
258
+
259
+
260
+ def get_grad_norm(model: torch.nn.Module) -> float:
261
+ """
262
+ Compute the total L2 norm of all parameter gradients.
263
+
264
+ Uses a single GPU kernel + one GPU-CPU sync instead of one sync per
265
+ parameter (the naive loop approach). Only parameters with non-None
266
+ ``.grad`` attribute contribute.
267
+
268
+ Args:
269
+ model: The model (plain or DDP-wrapped).
270
+
271
+ Returns:
272
+ Scalar float — the global gradient L2 norm.
273
+ """
274
+ raw_model: torch.nn.Module = getattr(model, "module", model)
275
+ grads = [p.grad.detach().float() for p in raw_model.parameters() if p.grad is not None]
276
+ if not grads:
277
+ return 0.0
278
+ # Stack individual norms and compute the L2 norm of norms — single sync.
279
+ return torch.stack([g.norm(2) for g in grads]).norm(2).item()
280
+
281
+
282
+ # ---------------------------------------------------------------------------
283
+ # Distributed training helpers
284
+ # ---------------------------------------------------------------------------
285
+
286
+
287
+ def setup_ddp() -> Tuple[int, int, int, torch.device]:
288
+ """
289
+ Initialise the NCCL distributed process group for DDP training.
290
+
291
+ Reads ``RANK``, ``LOCAL_RANK``, and ``WORLD_SIZE`` from the environment
292
+ (set automatically by ``torchrun``).
293
+
294
+ Returns:
295
+ ``(rank, local_rank, world_size, device)``
296
+ """
297
+ rank = int(os.environ["RANK"])
298
+ local_rank = int(os.environ["LOCAL_RANK"])
299
+ world_size = int(os.environ["WORLD_SIZE"])
300
+
301
+ # Limit CPU thread count per process to avoid contention across 8 ranks.
302
+ # 72 cores / 8 ranks = 9; use 4 to leave headroom for DataLoader workers.
303
+ os.environ.setdefault("OMP_NUM_THREADS", "4")
304
+ os.environ.setdefault("MKL_NUM_THREADS", "4")
305
+
306
+ import datetime as _dt
307
+ dist.init_process_group(
308
+ backend="nccl",
309
+ timeout=_dt.timedelta(seconds=7200), # 2h for large checkpoint loads
310
+ )
311
+
312
+ torch.cuda.set_device(local_rank)
313
+ device = torch.device(f"cuda:{local_rank}")
314
+
315
+ return rank, local_rank, world_size, device
316
+
317
+
318
+ def cleanup_ddp() -> None:
319
+ """Tear down the distributed process group (call at end of training)."""
320
+ if dist.is_available() and dist.is_initialized():
321
+ dist.destroy_process_group()
322
+
323
+
324
+ def is_main_process() -> bool:
325
+ """
326
+ Return ``True`` when this process is rank 0 or when running without DDP.
327
+
328
+ Reads the ``RANK`` environment variable; if it is absent the process is
329
+ assumed to be the sole process (rank 0).
330
+ """
331
+ return int(os.environ.get("RANK", "0")) == 0