Download training_artifacts/sft_train.py from MercanAI/final_sft_corrected: direct link, hf CLI and curl.
- Browser
- Download file 58.6 kB
-
https://huggingface.co/datasets/MercanAI/final_sft_corrected/resolve/main/training_artifacts/sft_train.py
- Command line
-
hf download hf://datasets/MercanAI/final_sft_corrected/training_artifacts/sft_train.py
-
curl -L -o sft_train.py https://huggingface.co/datasets/MercanAI/final_sft_corrected/resolve/main/training_artifacts/sft_train.py
58.6 kB
| """Full-parameter assistant-only SFT for NedoLM 0.8B.""" | |
| from __future__ import annotations | |
| import argparse | |
| from concurrent.futures import ThreadPoolExecutor | |
| import contextlib | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| import signal | |
| import sys | |
| import time | |
| from pathlib import Path | |
| from typing import Any, Optional | |
| import torch | |
| import torch.distributed as dist | |
| import torch.nn.functional as F | |
| import yaml | |
| from torch.nn.parallel import DistributedDataParallel as DDP | |
| from .checkpoint import latest_checkpoint, save_checkpoint, save_model_archive, write_run_metadata | |
| from .config import EOS_ID, OptimConfig, RunConfig | |
| from .distributed import Logger, cleanup, gather_object, setup_distributed | |
| from .model import build_model, packed_flash_attn_available | |
| from .optim import build_optimizer, lr_at_step, set_lr | |
| from .sft_data import build_sft_loader, corpus_stats, discover_sft_shards, validate_roles | |
| _STOP_REQUESTED = False | |
| def _request_stop(signum, frame) -> None: # noqa: ANN001 | |
| global _STOP_REQUESTED | |
| _STOP_REQUESTED = True | |
| print(f"[signal] received {signum}; will checkpoint and exit", flush=True) | |
| def parse_args() -> argparse.Namespace: | |
| p = argparse.ArgumentParser(description="NedoLM 0.8B assistant-only SFT") | |
| p.add_argument("--config", required=True, type=Path) | |
| p.add_argument("--smoke-steps", type=int, default=0) | |
| p.add_argument("--no-compile", action="store_true") | |
| return p.parse_args() | |
| def set_seed(seed: int, rank: int) -> None: | |
| import random | |
| import numpy as np | |
| torch.manual_seed(seed) | |
| if torch.cuda.is_available(): | |
| torch.cuda.manual_seed_all(seed) | |
| random.seed(seed + rank) | |
| np.random.seed((seed + rank) % (2**32 - 1)) | |
| def load_yaml(path: Path) -> dict[str, Any]: | |
| raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {} | |
| required = {"run_dir", "base_config", "base_run_dir", "data_dir", "optim", "train"} | |
| missing = sorted(required - set(raw)) | |
| if missing: | |
| raise ValueError(f"missing SFT config keys: {missing}") | |
| return raw | |
| def _load_torch(path: Path) -> dict[str, Any]: | |
| try: | |
| return torch.load(path, map_location="cpu", weights_only=False, mmap=True) | |
| except TypeError: | |
| return torch.load(path, map_location="cpu", weights_only=False) | |
| def _sum_all(value: torch.Tensor) -> torch.Tensor: | |
| if dist.is_initialized(): | |
| dist.all_reduce(value, op=dist.ReduceOp.SUM) | |
| return value | |
| def _main_rank_call(info, action: str, fn): # noqa: ANN001 | |
| """Run a rank-0-only action and propagate success/failure to every rank. | |
| This replaces the unsafe pattern ``if rank0: action(); barrier()`` where a | |
| Python exception on rank 0 can strand all other ranks inside a barrier. | |
| The return value is broadcast as a small Python object when distributed. | |
| """ | |
| result = None | |
| error = "" | |
| if info.is_main: | |
| try: | |
| result = fn() | |
| except Exception as exc: # noqa: BLE001 | |
| error = f"{action} failed on rank 0: {type(exc).__name__}: {exc}" | |
| if dist.is_initialized(): | |
| payload = [result, error] | |
| dist.broadcast_object_list(payload, src=0) | |
| result, error = payload | |
| if error: | |
| raise RuntimeError(str(error)) | |
| return result | |
| def _broadcast_module_state(module: torch.nn.Module, src: int = 0) -> None: | |
| """Synchronize model parameters/buffers before compile warmup and DDP. | |
| Fresh SFT reads the large base checkpoint on rank 0 only. Compile warmup | |
| deliberately runs before DDP so failures cannot deadlock DDP collectives; | |
| therefore the bare module must first be made identical on every rank. | |
| """ | |
| if not dist.is_initialized(): | |
| return | |
| with torch.no_grad(): | |
| for param in module.parameters(): | |
| dist.broadcast(param.data, src=src) | |
| for buf in module.buffers(): | |
| dist.broadcast(buf.data, src=src) | |
| def _collect_rank_errors(info, local_error: str) -> list[str]: | |
| if not dist.is_initialized(): | |
| return [local_error] if local_error else [] | |
| errors = gather_object(local_error, info.world_size) | |
| return [f"rank {rank}: {msg}" for rank, msg in enumerate(errors) if msg] | |
| def _all_rank_call(info, action: str, fn): # noqa: ANN001 | |
| """Run local non-collective work on every rank, then make failure global.""" | |
| result = None | |
| local_error = "" | |
| try: | |
| result = fn() | |
| except Exception as exc: # noqa: BLE001 | |
| local_error = f"{type(exc).__name__}: {exc}" | |
| errors = _collect_rank_errors(info, local_error) | |
| if errors: | |
| raise RuntimeError(f"{action} failed: " + " | ".join(errors)) | |
| return result | |
| def _sync_control_flags( | |
| control_flags: torch.Tensor, | |
| *, | |
| rank0_archive_due: bool, | |
| local_stop: bool, | |
| ) -> tuple[bool, bool]: | |
| """Synchronize archive/stop decisions so every rank takes the same branch.""" | |
| control_flags[0] = 1 if rank0_archive_due else 0 | |
| control_flags[1] = 1 if local_stop else 0 | |
| if dist.is_initialized(): | |
| dist.all_reduce(control_flags, op=dist.ReduceOp.MAX) | |
| return bool(control_flags[0].item()), bool(control_flags[1].item()) | |
| def _sha256(path: Path) -> str: | |
| h = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1 << 20), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def _validate_dataset_contract(data_dir: Path, vocab_size: int, seq_len: int) -> dict[str, Any]: | |
| verify_path = data_dir / "FINAL_BINARY_VERIFY_REPORT.json" | |
| special_path = data_dir / "SPECIAL_TOKENS.json" | |
| packing_path = data_dir / "PACKING_POLICY_ADAPTIVE_AUDIT.json" | |
| manifest_path = data_dir / "SHARD_MANIFEST.json" | |
| required = (verify_path, special_path, packing_path, manifest_path) | |
| missing_contract = [path.name for path in required if not path.exists()] | |
| if missing_contract: | |
| raise RuntimeError(f"verified SFT contract missing: {missing_contract}") | |
| verify = json.loads(verify_path.read_text(encoding="utf-8")) | |
| special = json.loads(special_path.read_text(encoding="utf-8")) | |
| packing = json.loads(packing_path.read_text(encoding="utf-8")) | |
| manifest = json.loads(manifest_path.read_text(encoding="utf-8")) | |
| if verify.get("status") != "PASS": | |
| raise RuntimeError("SFT final binary verifier is not PASS") | |
| if packing.get("status") != "PASS": | |
| raise RuntimeError("SFT adaptive packing audit is not PASS") | |
| if packing.get("schema") != "nedolm_sft_adaptive_packing_audit_v2": | |
| raise RuntimeError(f"unexpected adaptive packing schema: {packing.get('schema')}") | |
| if int(packing.get("seq_len", -1)) != seq_len: | |
| raise RuntimeError( | |
| f"adaptive packing audit seq_len={packing.get('seq_len')} but train seq_len={seq_len}" | |
| ) | |
| if int(packing.get("read_span_tokens", -1)) != seq_len + 1: | |
| raise RuntimeError("adaptive packing read span is not seq_len+1") | |
| if packing.get("packing_policy") != "adaptive_document_turn_overlap_v2": | |
| raise RuntimeError("unexpected adaptive packing policy") | |
| if packing.get("target_policy") != "exact_once_non_tool_assistant_targets": | |
| raise RuntimeError("adaptive packing is not exact-once target policy") | |
| if packing.get("continuation_policy") != ( | |
| "prefer_latest_user_or_system_boundary_else_assistant_message_boundary" | |
| ): | |
| raise RuntimeError("unexpected adaptive continuation policy") | |
| if int(packing.get("hard_continuations", -1)) != 0: | |
| raise RuntimeError("adaptive packing contains unsafe hard continuations") | |
| if manifest.get("status") != "PASS" or manifest.get("algorithm") != "sha256": | |
| raise RuntimeError("SFT shard manifest is not a PASS sha256 manifest") | |
| if manifest.get("schema") != "nedolm_sft_shard_manifest_v1": | |
| raise RuntimeError(f"unexpected shard manifest schema: {manifest.get('schema')}") | |
| entries = manifest.get("files") | |
| if not isinstance(entries, list) or not entries: | |
| raise RuntimeError("SFT shard manifest has no files") | |
| if int(manifest.get("file_count", -1)) != len(entries): | |
| raise RuntimeError("SFT shard manifest file_count mismatch") | |
| canonical_entries = json.dumps( | |
| entries, sort_keys=True, separators=(",", ":") | |
| ).encode("utf-8") | |
| if hashlib.sha256(canonical_entries).hexdigest() != str( | |
| manifest.get("aggregate_sha256", "") | |
| ): | |
| raise RuntimeError("SFT shard manifest aggregate digest is invalid") | |
| actual_binary = sorted( | |
| path.relative_to(data_dir).as_posix() | |
| for pattern in ("*.tokens.bin", "*.segments.bin", "*.index.bin") | |
| for path in (data_dir / "shards").glob(pattern) | |
| ) | |
| listed_binary = sorted(str(item.get("path", "")) for item in entries) | |
| if listed_binary != actual_binary: | |
| raise RuntimeError("SFT shard manifest file set differs from on-disk binary shard set") | |
| # Verify the actual binaries, not only the verifier JSON. This runs on rank | |
| # 0 only (via _main_rank_call) and hashes independent files in parallel so | |
| # the integrity gate remains cheap without multiplying Lustre traffic by | |
| # world_size. | |
| def _check_manifest_entry(item: dict[str, Any]) -> None: | |
| rel = str(item["path"]) | |
| path = data_dir / rel | |
| expected_size = int(item["size"]) | |
| if path.stat().st_size != expected_size: | |
| raise RuntimeError(f"SFT shard size changed after verification: {rel}") | |
| digest = _sha256(path) | |
| if digest != str(item["sha256"]): | |
| raise RuntimeError(f"SFT shard sha256 changed after verification: {rel}") | |
| with ThreadPoolExecutor(max_workers=min(8, len(entries))) as pool: | |
| list(pool.map(_check_manifest_entry, entries)) | |
| if int(verify.get("vocab_size", -1)) != vocab_size: | |
| raise RuntimeError(f"SFT vocab={verify.get('vocab_size')} but model vocab={vocab_size}") | |
| if int(verify.get("message_start_id", -1)) != 32000: | |
| raise RuntimeError("unexpected message_start_id") | |
| if int(verify.get("message_end_id", -1)) != 32001: | |
| raise RuntimeError("unexpected message_end_id") | |
| if int(verify.get("eos_id", -1)) != EOS_ID: | |
| raise RuntimeError("unexpected EOS id in verified corpus") | |
| if int(verify.get("max_token_id", vocab_size)) >= vocab_size: | |
| raise RuntimeError("verified corpus contains token id outside model vocab") | |
| required_true = ( | |
| "global_doc_keys_unique", | |
| "content_tokens_exact_vs_source", | |
| "offsets_lengths_exact", | |
| "turkish_user_header_verified", | |
| "assistant_only_trainable_contract_verified", | |
| "header_schema_verified", | |
| "structural_control_counts_verified", | |
| "token_id_range_verified", | |
| ) | |
| missing = [key for key in required_true if verify.get(key) is not True] | |
| if missing: | |
| raise RuntimeError(f"SFT verifier contract missing PASS fields: {missing}") | |
| controls = {int(x["id"]): x["token"] for x in special.get("control_tokens", [])} | |
| if controls != {32000: "<|mesaj_basla|>", 32001: "<|mesaj_bitir|>"}: | |
| raise RuntimeError(f"unexpected SFT control-token registry: {controls}") | |
| roles = special.get("roles") | |
| expected_roles = {"system": "sistem", "user": "kullanici", "assistant": "asistan"} | |
| if roles != expected_roles: | |
| raise RuntimeError(f"unexpected SFT role registry: {roles}") | |
| fingerprint = hashlib.sha256( | |
| verify_path.read_bytes() | |
| + b"\0" | |
| + special_path.read_bytes() | |
| + b"\0" | |
| + packing_path.read_bytes() | |
| + b"\0" | |
| + manifest_path.read_bytes() | |
| ).hexdigest() | |
| return { | |
| "fingerprint": fingerprint, | |
| "verify_sha256": _sha256(verify_path), | |
| "special_tokens_sha256": _sha256(special_path), | |
| "packing_policy_sha256": _sha256(packing_path), | |
| "shard_manifest_sha256": _sha256(manifest_path), | |
| "shard_manifest_files": len(entries), | |
| "training_windows": int(packing["windows"]), | |
| "assistant_target_tokens_per_epoch": int(packing["assistant_target_tokens"]), | |
| "valid_context_tokens_per_epoch": int(packing["valid_context_tokens"]), | |
| "padded_tokens_per_epoch": int(packing["padded_tokens"]), | |
| "turn_aligned_continuations": int(packing["turn_aligned_continuations"]), | |
| "assistant_aligned_continuations": int( | |
| packing["assistant_aligned_continuations"] | |
| ), | |
| "documents": int(verify["documents"]), | |
| "messages": int(verify["messages"]), | |
| "tokens": int(verify["tokens_including_eos"]), | |
| "vocab_size": int(verify["vocab_size"]), | |
| } | |
| def _packed_layout(input_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: | |
| """Return FlashAttention boundaries and RoPE positions for packed rows. | |
| EOS and every batch-row start are hard conversation boundaries. Attention | |
| isolation alone is not enough: rotary positions must also restart at zero | |
| after each boundary, otherwise later conversations inherit arbitrary packed | |
| row offsets (for example position 5000 instead of position 0). | |
| """ | |
| if input_ids.ndim != 2 or input_ids.size(1) == 0: | |
| raise ValueError("packed attention expects non-empty [B,S] input_ids") | |
| starts = torch.zeros_like(input_ids, dtype=torch.bool) | |
| starts[:, 0] = True | |
| starts[:, 1:] = input_ids[:, :-1].eq(EOS_ID) | |
| offsets = torch.nonzero(starts.reshape(-1), as_tuple=False).flatten().to(torch.int32) | |
| end = torch.full((1,), input_ids.numel(), device=input_ids.device, dtype=torch.int32) | |
| cu_seqlens = torch.cat((offsets, end), dim=0).contiguous() | |
| cols = torch.arange(input_ids.size(1), device=input_ids.device, dtype=torch.long) | |
| cols = cols.unsqueeze(0).expand(input_ids.size(0), -1) | |
| boundary_cols = torch.where(starts, cols, torch.zeros_like(cols)) | |
| last_boundary = torch.cummax(boundary_cols, dim=1).values | |
| position_ids = (cols - last_boundary).contiguous() | |
| return cu_seqlens, position_ids | |
| def _packed_cu_seqlens(input_ids: torch.Tensor) -> torch.Tensor: | |
| """Compatibility helper used by older tests/tools.""" | |
| return _packed_layout(input_ids)[0] | |
| def _shard_id(shard) -> int: | |
| name = shard.token_path.name | |
| try: | |
| return int(name.split("-")[1]) | |
| except (IndexError, ValueError) as exc: | |
| raise RuntimeError(f"cannot parse SFT shard id from {name}") from exc | |
| def _split_train_val_shards(shards, val_ids: list[int]): | |
| wanted = set(int(x) for x in val_ids) | |
| if not wanted: | |
| return shards, [] | |
| train = [sh for sh in shards if _shard_id(sh) not in wanted] | |
| val = [sh for sh in shards if _shard_id(sh) in wanted] | |
| found = {_shard_id(sh) for sh in val} | |
| missing = sorted(wanted - found) | |
| if missing: | |
| raise RuntimeError(f"validation shard ids not found: {missing}") | |
| if not train: | |
| raise RuntimeError("validation split consumed every SFT shard") | |
| return train, val | |
| def _training_contract_fingerprint( | |
| dataset_fingerprint: str, | |
| seq_len: int, | |
| val_shard_ids: list[int], | |
| recipe: dict[str, Any], | |
| ) -> str: | |
| """Fingerprint every setting that can change the optimization trajectory.""" | |
| payload = json.dumps( | |
| { | |
| "schema": "nedolm_sft_training_contract_v2", | |
| "dataset_fingerprint": dataset_fingerprint, | |
| "seq_len": int(seq_len), | |
| "read_span": int(seq_len) + 1, | |
| "val_shard_ids": sorted(int(x) for x in val_shard_ids), | |
| "packing_policy": "adaptive_document_turn_overlap_v2", | |
| "target_policy": "exact_once_non_tool_assistant_targets", | |
| "continuation_policy": ( | |
| "prefer_latest_user_or_system_boundary_else_assistant_message_boundary" | |
| ), | |
| "attention_policy": "eos_plus_row_boundaries_varlen", | |
| "position_policy": "eos_plus_row_boundaries_reset_rope_to_zero", | |
| "recipe": recipe, | |
| }, | |
| sort_keys=True, | |
| separators=(",", ":"), | |
| ).encode("utf-8") | |
| return hashlib.sha256(payload).hexdigest() | |
| def _run_validation( | |
| base_model: torch.nn.Module, | |
| val_loader, | |
| info, | |
| *, | |
| seq_len: int, | |
| batches: int, | |
| assistant_only_head: bool, | |
| loss_fp32_logits: bool, | |
| use_amp: bool, | |
| device_type: str, | |
| ) -> dict[str, float | int]: | |
| """Run held-out validation without allowing one rank to strand its peers.""" | |
| if batches <= 0: | |
| raise ValueError("validation batches must be positive") | |
| was_training = base_model.training | |
| base_model.eval() | |
| local_loss = torch.zeros((), device=info.device, dtype=torch.float32) | |
| local_targets = torch.zeros((), device=info.device, dtype=torch.int64) | |
| local_context = torch.zeros((), device=info.device, dtype=torch.int64) | |
| local_error = "" | |
| try: | |
| try: | |
| it = iter(val_loader) | |
| for _ in range(batches): | |
| batch = next(it) | |
| raw_tokens = batch["tokens"].to( | |
| info.device, dtype=torch.long, non_blocking=True | |
| ) | |
| inputs = raw_tokens[:, :-1] | |
| labels = raw_tokens[:, 1:].clone() | |
| trainable_mask = batch["trainable_mask"][:, 1:].to( | |
| info.device, non_blocking=True | |
| ) | |
| labels.masked_fill_(~trainable_mask, -100) | |
| target_count = int(trainable_mask.sum().item()) | |
| if target_count <= 0: | |
| raise RuntimeError("validation batch contains zero assistant targets") | |
| cu_seqlens, position_ids = _packed_layout(inputs) | |
| with torch.autocast(device_type, dtype=torch.bfloat16, enabled=use_amp): | |
| if assistant_only_head: | |
| loss_sum, _ = base_model( | |
| inputs, | |
| labels=labels, | |
| return_logits=False, | |
| loss_reduction="sum", | |
| loss_fp32_logits=loss_fp32_logits, | |
| cu_seqlens=cu_seqlens, | |
| max_seqlen=seq_len, | |
| position_ids=position_ids, | |
| ) | |
| else: | |
| _, logits = base_model( | |
| inputs, | |
| return_logits=True, | |
| cu_seqlens=cu_seqlens, | |
| max_seqlen=seq_len, | |
| position_ids=position_ids, | |
| ) | |
| loss_sum = F.cross_entropy( | |
| logits.reshape(-1, logits.size(-1)).float(), | |
| labels.reshape(-1), | |
| ignore_index=-100, | |
| reduction="sum", | |
| ) | |
| del logits | |
| if not torch.isfinite(loss_sum): | |
| raise RuntimeError("non-finite validation loss") | |
| local_loss += loss_sum.float() | |
| local_targets += target_count | |
| local_context += inputs.numel() | |
| del ( | |
| raw_tokens, | |
| inputs, | |
| labels, | |
| trainable_mask, | |
| cu_seqlens, | |
| position_ids, | |
| loss_sum, | |
| ) | |
| except Exception as exc: # noqa: BLE001 | |
| local_error = f"{type(exc).__name__}: {exc}" | |
| # Every rank reaches this object collective before any metric all-reduce. | |
| # A recoverable Python/data/model error on one rank therefore becomes a | |
| # uniform exception instead of leaving healthy ranks blocked in SUM. | |
| validation_errors = _collect_rank_errors(info, local_error) | |
| if validation_errors: | |
| raise RuntimeError( | |
| "distributed validation failed: " + " | ".join(validation_errors) | |
| ) | |
| _sum_all(local_loss) | |
| _sum_all(local_targets) | |
| _sum_all(local_context) | |
| targets = int(local_targets.item()) | |
| if targets <= 0: | |
| raise RuntimeError("global validation target count is zero") | |
| mean_loss = float(local_loss.item() / targets) | |
| if not math.isfinite(mean_loss): | |
| raise RuntimeError(f"non-finite validation mean loss: {mean_loss}") | |
| return { | |
| "loss": mean_loss, | |
| "ppl": math.exp(min(20.0, mean_loss)), | |
| "assistant_tokens": targets, | |
| "context_tokens": int(local_context.item()), | |
| } | |
| finally: | |
| if was_training: | |
| base_model.train() | |
| def main() -> int: | |
| args = parse_args() | |
| sft = load_yaml(args.config) | |
| base_cfg = RunConfig.load(sft["base_config"]) | |
| tcfg = dict(sft["train"]) | |
| ocfg = OptimConfig(**dict(sft["optim"])) | |
| run_dir = Path(sft["run_dir"]) | |
| data_dir = Path(sft["data_dir"]) | |
| seq_len = int(tcfg.get("seq_len", base_cfg.model.max_seq_len)) | |
| micro_batch = int(tcfg.get("micro_batch_size", 8)) | |
| grad_accum = int(tcfg.get("grad_accum_steps", 4)) | |
| num_workers = int(tcfg.get("num_workers", 4)) | |
| prefetch_factor = int(tcfg.get("prefetch_factor", 4)) | |
| persistent_workers = bool(tcfg.get("persistent_workers", True)) | |
| seed = int(tcfg.get("seed", 20260907)) | |
| compile_model = bool(tcfg.get("compile", True)) and not args.no_compile | |
| compile_mode = str(tcfg.get("compile_mode", "default")) | |
| grad_checkpoint = bool(tcfg.get("grad_checkpoint", False)) | |
| morph_dispatch = str(tcfg.get("morph_dispatch", base_cfg.model.morph_dispatch)) | |
| if morph_dispatch not in ("masked", "sparse"): | |
| raise ValueError("train.morph_dispatch must be 'masked' or 'sparse'") | |
| base_cfg.model.morph_dispatch = morph_dispatch | |
| assistant_only_head = bool(tcfg.get("assistant_only_head", True)) | |
| loss_fp32_logits = bool(tcfg.get("loss_fp32_logits", True)) | |
| ddp_static_graph = bool(tcfg.get("ddp_static_graph", True)) | |
| ddp_bucket_cap_mb = int(tcfg.get("ddp_bucket_cap_mb", 100)) | |
| control_interval = max(1, int(tcfg.get("control_interval", 20))) | |
| log_interval = int(tcfg.get("log_interval", 10)) | |
| ckpt_interval = int(tcfg.get("ckpt_interval", 250)) | |
| keep_last = int(tcfg.get("keep_last", 3)) | |
| keep_every = int(tcfg.get("keep_every", 1000)) | |
| archive_interval_hours = float(tcfg.get("archive_interval_hours", 4.0)) | |
| max_hours = float(tcfg.get("max_hours", 71.0)) | |
| save_final_checkpoint = bool(tcfg.get("save_final_checkpoint", True)) | |
| vcfg = dict(sft.get("validation", {})) | |
| val_enabled = bool(vcfg.get("enabled", True)) | |
| val_shard_ids = [int(x) for x in vcfg.get("shard_ids", [53])] if val_enabled else [] | |
| val_interval = max(1, int(vcfg.get("interval", 250))) | |
| val_batches = max(1, int(vcfg.get("batches", 8))) | |
| val_micro_batch = max(1, int(vcfg.get("micro_batch_size", micro_batch))) | |
| val_workers = max(0, int(vcfg.get("num_workers", min(2, num_workers)))) | |
| val_seed = int(vcfg.get("seed", 20260920)) | |
| val_at_start = bool(vcfg.get("at_start", True)) | |
| info = setup_distributed() | |
| signal.signal(signal.SIGUSR1, _request_stop) | |
| signal.signal(signal.SIGTERM, _request_stop) | |
| def _validate_local_runtime(): | |
| if seq_len > base_cfg.model.max_seq_len: | |
| raise ValueError( | |
| f"SFT seq_len={seq_len} exceeds model max_seq_len={base_cfg.model.max_seq_len}" | |
| ) | |
| if base_cfg.model.attn_impl != "flash": | |
| raise ValueError("packed SFT isolation requires model.attn_impl='flash'") | |
| if not packed_flash_attn_available(): | |
| raise RuntimeError( | |
| "packed SFT isolation requires flash_attn_func and flash_attn_varlen_func" | |
| ) | |
| return True | |
| _all_rank_call(info, "validate local SFT runtime", _validate_local_runtime) | |
| _main_rank_call( | |
| info, "create run directory", lambda: run_dir.mkdir(parents=True, exist_ok=True) | |
| ) | |
| log = _all_rank_call( | |
| info, "initialize SFT logger", lambda: Logger(run_dir, info) | |
| ) | |
| dataset_contract = _main_rank_call( | |
| info, | |
| "validate SFT binary/dataset contract", | |
| lambda: _validate_dataset_contract(data_dir, base_cfg.model.vocab_size, seq_len), | |
| ) | |
| set_seed(seed, info.rank) | |
| if torch.cuda.is_available(): | |
| torch.backends.cuda.matmul.allow_tf32 = True | |
| torch.backends.cudnn.allow_tf32 = True | |
| # H200 benefits from the reduced-precision BF16 accumulation paths; | |
| # model numerics remain BF16 under autocast with fp32 master weights. | |
| torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = True | |
| torch.set_float32_matmul_precision("high") | |
| # Discover/build the adaptive plan on every rank, but synchronize any | |
| # local filesystem/data failure before later collectives can deadlock. | |
| def _discover_runtime_data(): | |
| local_all_shards = discover_sft_shards(data_dir, seq_len) | |
| local_all_stats = corpus_stats(local_all_shards, seq_len) | |
| if int(local_all_stats["windows"]) != int(dataset_contract["training_windows"]): | |
| raise RuntimeError( | |
| "runtime adaptive sample count differs from audited packing contract: " | |
| f"{local_all_stats['windows']} != {dataset_contract['training_windows']}" | |
| ) | |
| if int(local_all_stats["assistant_target_tokens"]) != int( | |
| dataset_contract["assistant_target_tokens_per_epoch"] | |
| ): | |
| raise RuntimeError( | |
| "runtime adaptive assistant-target count differs from audited contract: " | |
| f"{local_all_stats['assistant_target_tokens']} != " | |
| f"{dataset_contract['assistant_target_tokens_per_epoch']}" | |
| ) | |
| if int(local_all_stats["hard_continuations"]) != 0: | |
| raise RuntimeError("runtime adaptive plan contains hard continuations") | |
| local_shards, local_val_shards = _split_train_val_shards( | |
| local_all_shards, val_shard_ids | |
| ) | |
| if val_enabled and not local_val_shards: | |
| raise RuntimeError("validation enabled but validation shard set is empty") | |
| local_stats = corpus_stats(local_shards, seq_len) | |
| local_val_stats = ( | |
| corpus_stats(local_val_shards, seq_len) if local_val_shards else None | |
| ) | |
| return local_all_shards, local_shards, local_val_shards, local_stats, local_val_stats | |
| all_shards, shards, val_shards, stats, val_stats = _all_rank_call( | |
| info, "discover/validate adaptive SFT plan", _discover_runtime_data | |
| ) | |
| def _rank0_role_audit(): | |
| role_stats = validate_roles(shards) | |
| val_role_stats = validate_roles(val_shards) if val_stats is not None else None | |
| return {"train": role_stats, "validation": val_role_stats} | |
| role_audit = _main_rank_call(info, "SFT role audit", _rank0_role_audit) | |
| if info.is_main: | |
| log.info_msg( | |
| f"SFT train: {stats['shards']} shards, {stats['raw_tokens']/1e9:.3f}B raw tokens, " | |
| f"{stats['windows']:,} adaptive samples, " | |
| f"valid_context={100*stats['valid_context_ratio']:.3f}% " | |
| f"assistant_target={100*stats['assistant_target_ratio']:.3f}% " | |
| f"turn_cont={stats['turn_aligned_continuations']:,} " | |
| f"assistant_cont={stats['assistant_aligned_continuations']:,}" | |
| ) | |
| log.info_msg(f"train role audit: {role_audit['train']}") | |
| if val_stats is not None: | |
| log.info_msg( | |
| f"SFT held-out validation: shard_ids={val_shard_ids} " | |
| f"{val_stats['raw_tokens']/1e6:.1f}M raw tokens, " | |
| f"{val_stats['windows']:,} windows" | |
| ) | |
| log.info_msg(f"validation role audit: {role_audit['validation']}") | |
| sequences_per_step = micro_batch * grad_accum * info.world_size | |
| tokens_per_step = sequences_per_step * seq_len | |
| auto_steps = math.ceil(int(stats["windows"]) / sequences_per_step) | |
| configured_steps = int(tcfg.get("max_steps", 0)) | |
| max_steps = configured_steps if configured_steps > 0 else auto_steps | |
| if args.smoke_steps: | |
| max_steps = args.smoke_steps | |
| training_recipe = { | |
| "max_steps": int(max_steps), | |
| "micro_batch_size": micro_batch, | |
| "grad_accum_steps": grad_accum, | |
| "seed": seed, | |
| "num_workers": num_workers, | |
| "morph_dispatch": morph_dispatch, | |
| "grad_checkpoint": grad_checkpoint, | |
| "assistant_only_head": assistant_only_head, | |
| "loss_fp32_logits": loss_fp32_logits, | |
| "compile_requested": bool(tcfg.get("compile", True)), | |
| "compile_mode_requested": compile_mode, | |
| "optim": { | |
| "lr": ocfg.lr, | |
| "min_lr_ratio": ocfg.min_lr_ratio, | |
| "betas": list(ocfg.betas), | |
| "eps": ocfg.eps, | |
| "weight_decay": ocfg.weight_decay, | |
| "grad_clip": ocfg.grad_clip, | |
| "schedule": ocfg.schedule, | |
| "warmup_steps": ocfg.warmup_steps, | |
| "decay_fraction": ocfg.decay_fraction, | |
| }, | |
| "model_config": base_cfg.model.__dict__, | |
| } | |
| split_fingerprint = _training_contract_fingerprint( | |
| dataset_contract["fingerprint"], seq_len, val_shard_ids, training_recipe | |
| ) | |
| log.info_msg( | |
| f"world_size={info.world_size} device={info.device} seq_len={seq_len} " | |
| f"micro_batch={micro_batch} accum={grad_accum} tokens/step={tokens_per_step:,} " | |
| f"steps={max_steps} (auto_one_epoch={auto_steps})" | |
| ) | |
| # Build architecture exactly from the pretraining config. Fail together | |
| # if a rank has a local construction/runtime problem. | |
| base_model = _all_rank_call( | |
| info, "build SFT model", lambda: build_model(base_cfg.model) | |
| ) | |
| base_model.grad_checkpoint = grad_checkpoint | |
| start_step = 0 | |
| context_tokens_seen = 0 | |
| assistant_tokens_seen = 0 | |
| resume_state: Optional[dict[int, list[int]]] = None | |
| source_checkpoint = "" | |
| sft_ckpt_value = _main_rank_call( | |
| info, | |
| "resolve latest SFT checkpoint", | |
| lambda: str(latest_checkpoint(run_dir) or ""), | |
| ) | |
| sft_ckpt = Path(str(sft_ckpt_value)) if sft_ckpt_value else None | |
| state: Optional[dict[str, Any]] = None | |
| if sft_ckpt is not None: | |
| def _load_and_validate_local_resume(): | |
| local_state = _load_torch(sft_ckpt) | |
| base_model.load_state_dict(local_state["model"]) | |
| saved_fingerprint = str(local_state.get("dataset_fingerprint", "")) | |
| if not saved_fingerprint: | |
| raise RuntimeError( | |
| "refusing legacy SFT resume without dataset_fingerprint; use a fresh run_dir" | |
| ) | |
| if saved_fingerprint != dataset_contract["fingerprint"]: | |
| raise RuntimeError( | |
| "SFT dataset contract changed since checkpoint; refusing unsafe resume" | |
| ) | |
| saved_split = str(local_state.get("training_contract_fingerprint", "")) | |
| if not saved_split: | |
| raise RuntimeError( | |
| "refusing legacy SFT resume without training_contract_fingerprint" | |
| ) | |
| if saved_split != split_fingerprint: | |
| raise RuntimeError( | |
| "SFT train/validation split or packing/recipe contract changed; " | |
| "refusing unsafe resume" | |
| ) | |
| return local_state | |
| state = _all_rank_call( | |
| info, "load/validate local SFT resume checkpoint", _load_and_validate_local_resume | |
| ) | |
| start_step = int(state["step"]) | |
| context_tokens_seen = int(state.get("context_tokens_seen", 0)) | |
| assistant_tokens_seen = int(state.get("assistant_tokens_seen", 0)) | |
| source_checkpoint = str(state.get("base_checkpoint", "")) | |
| log.info_msg(f"resuming SFT from {sft_ckpt} at step {start_step}") | |
| else: | |
| def _resolve_base_checkpoint(): | |
| explicit = str(sft.get("base_checkpoint", "")).strip() | |
| if explicit: | |
| candidate = Path(explicit) | |
| else: | |
| candidate = latest_checkpoint(Path(sft["base_run_dir"])) | |
| if candidate is None: | |
| raise FileNotFoundError( | |
| f"no pretraining checkpoint under {sft['base_run_dir']}" | |
| ) | |
| if not candidate.exists(): | |
| raise FileNotFoundError(candidate) | |
| return str(candidate) | |
| base_ckpt_value = _main_rank_call( | |
| info, "resolve base pretraining checkpoint", _resolve_base_checkpoint | |
| ) | |
| base_ckpt = Path(str(base_ckpt_value)) | |
| source_checkpoint = str(base_ckpt) | |
| # Fresh multi-GPU SFT only needs one Lustre read of the large base | |
| # checkpoint. DDP construction below broadcasts rank-0 parameters to | |
| # every other rank anyway. Resume checkpoints still load on every rank | |
| # because optimizer/data state is rank-local and must be restored. | |
| def _load_base_on_rank0(): | |
| base_state = _load_torch(base_ckpt) | |
| try: | |
| base_model.load_state_dict(base_state["model"]) | |
| finally: | |
| del base_state | |
| if info.world_size == 1: | |
| _load_base_on_rank0() | |
| else: | |
| _main_rank_call(info, "load base checkpoint", _load_base_on_rank0) | |
| log.info_msg(f"starting NEW SFT from latest pretraining weights: {base_ckpt}") | |
| if info.world_size > 1: | |
| log.info_msg("fresh distributed init: base checkpoint read on rank 0 only; bare model state broadcast before compile") | |
| log.info_msg("pretraining optimizer/scheduler/data state intentionally NOT loaded") | |
| base_model.to(info.device) | |
| device_type = info.device.type | |
| use_amp = device_type == "cuda" | |
| # Fresh SFT only read the base checkpoint on rank 0. Synchronize the bare | |
| # module before compile warmup; this also verifies resume ranks are bitwise | |
| # aligned before optimizer construction. | |
| if info.world_size > 1: | |
| _broadcast_module_state(base_model, src=0) | |
| log.info_msg("bare model state synchronized from rank 0 before compile warmup") | |
| model: torch.nn.Module = base_model | |
| if compile_model: | |
| compiled_candidate: Optional[torch.nn.Module] = None | |
| local_compile_error = "" | |
| warm_x = warm_y = warm_cu = warm_pos = None | |
| try: | |
| compiled_candidate = torch.compile(base_model, mode=compile_mode) | |
| warm_x = torch.randint( | |
| 0, base_cfg.model.vocab_size, (micro_batch, seq_len), device=info.device | |
| ) | |
| warm_y = warm_x.clone() | |
| warm_y[:, : seq_len // 3] = -100 | |
| warm_x[:, seq_len // 4] = EOS_ID | |
| warm_x[:, seq_len // 2] = EOS_ID | |
| warm_x[:, (3 * seq_len) // 4] = EOS_ID | |
| warm_cu, warm_pos = _packed_layout(warm_x) | |
| warm_start = time.time() | |
| with torch.autocast(device_type, dtype=torch.bfloat16, enabled=use_amp): | |
| if assistant_only_head: | |
| warm_loss, _ = compiled_candidate( | |
| warm_x, labels=warm_y, return_logits=False, | |
| loss_reduction="sum", loss_fp32_logits=loss_fp32_logits, | |
| cu_seqlens=warm_cu, max_seqlen=seq_len, | |
| position_ids=warm_pos, | |
| ) | |
| warm_loss = warm_loss / max(1, int((warm_y != -100).sum().item())) | |
| else: | |
| _, warm_logits = compiled_candidate( | |
| warm_x, return_logits=True, | |
| cu_seqlens=warm_cu, max_seqlen=seq_len, | |
| position_ids=warm_pos, | |
| ) | |
| warm_loss = F.cross_entropy( | |
| warm_logits.reshape(-1, warm_logits.size(-1)).float(), | |
| warm_y.reshape(-1), ignore_index=-100, reduction="sum", | |
| ) / max(1, int((warm_y != -100).sum().item())) | |
| warm_loss.backward() | |
| log.info_msg(f"local SFT compile warmup ok ({time.time()-warm_start:.1f}s)", all_ranks=True) | |
| except Exception as exc: # noqa: BLE001 | |
| local_compile_error = f"{type(exc).__name__}: {exc}" | |
| finally: | |
| base_model.zero_grad(set_to_none=True) | |
| del warm_x, warm_y, warm_cu, warm_pos | |
| compile_errors = _collect_rank_errors(info, local_compile_error) | |
| if compile_errors: | |
| compile_model = False | |
| compiled_candidate = None | |
| model = base_model | |
| if info.is_main: | |
| log.info_msg( | |
| "torch.compile disabled globally because at least one rank failed warmup: " | |
| + " | ".join(compile_errors) | |
| ) | |
| else: | |
| model = compiled_candidate | |
| log.info_msg(f"torch.compile globally accepted mode={compile_mode}") | |
| # DDP is constructed only after every rank has made the same compile/eager | |
| # decision. Compile failures therefore cannot split the world into mixed | |
| # execution modes or strand a rank inside a DDP backward collective. | |
| if info.world_size > 1: | |
| model = DDP( | |
| model, | |
| device_ids=[info.device.index] if info.device.type == "cuda" else None, | |
| broadcast_buffers=False, | |
| gradient_as_bucket_view=True, | |
| static_graph=ddp_static_graph, | |
| bucket_cap_mb=ddp_bucket_cap_mb, | |
| ) | |
| effective_compile = bool(compile_model) | |
| if state is not None: | |
| saved_effective_compile = state.get("effective_compile") | |
| if saved_effective_compile is None: | |
| raise RuntimeError( | |
| "refusing legacy SFT resume without effective_compile runtime contract" | |
| ) | |
| if bool(saved_effective_compile) != effective_compile: | |
| raise RuntimeError( | |
| "SFT execution mode changed since checkpoint: " | |
| f"saved effective_compile={bool(saved_effective_compile)} " | |
| f"current effective_compile={effective_compile}. " | |
| "Resume with the same compile/eager mode or use a fresh run_dir." | |
| ) | |
| optimizer = _all_rank_call( | |
| info, "build SFT optimizer", lambda: build_optimizer(base_model, ocfg) | |
| ) | |
| if state is not None: | |
| def _restore_local_optimizer_and_data_state(): | |
| optimizer.load_state_dict(state["optimizer"]) | |
| saved_world = int(state.get("world_size", info.world_size)) | |
| saved_workers = int(state.get("num_workers", num_workers)) | |
| if saved_world != info.world_size or saved_workers != num_workers: | |
| raise RuntimeError( | |
| "refusing SFT resume with changed world_size/num_workers: " | |
| f"saved world={saved_world}, workers={saved_workers}; " | |
| f"current world={info.world_size}, workers={num_workers}. " | |
| "Use the original topology or start a fresh run_dir." | |
| ) | |
| local_resume_state: Optional[dict[int, list[int]]] = None | |
| per_rank = state.get("data_state", []) | |
| if info.rank < len(per_rank) and per_rank[info.rank]: | |
| local_resume_state = { | |
| int(k): list(v) for k, v in per_rank[info.rank].items() | |
| } | |
| return local_resume_state | |
| restored_resume = _all_rank_call( | |
| info, | |
| "restore local optimizer/data resume state", | |
| _restore_local_optimizer_and_data_state, | |
| ) | |
| if restored_resume is not None: | |
| resume_state = restored_resume | |
| del state | |
| def _build_local_loaders(): | |
| local_train_loader, _ = build_sft_loader( | |
| data_dir=data_dir, | |
| seq_len=seq_len, | |
| micro_batch_size=micro_batch, | |
| rank=info.rank, | |
| world_size=info.world_size, | |
| num_workers=num_workers, | |
| prefetch_factor=prefetch_factor, | |
| seed=seed, | |
| resume_state=resume_state, | |
| shards=shards, | |
| persistent_workers=persistent_workers, | |
| ) | |
| local_train_iter = iter(local_train_loader) | |
| local_val_loader = None | |
| if val_shards: | |
| local_val_loader, _ = build_sft_loader( | |
| data_dir=data_dir, | |
| seq_len=seq_len, | |
| micro_batch_size=val_micro_batch, | |
| rank=info.rank, | |
| world_size=info.world_size, | |
| num_workers=val_workers, | |
| prefetch_factor=max(1, prefetch_factor), | |
| seed=val_seed, | |
| resume_state=None, | |
| shards=val_shards, | |
| persistent_workers=False, | |
| ) | |
| # Force worker construction now so startup failures are synchronized. | |
| if val_workers > 0: | |
| probe = iter(local_val_loader) | |
| del probe | |
| return local_train_loader, local_train_iter, local_val_loader | |
| train_loader, train_iter, val_loader = _all_rank_call( | |
| info, "build SFT data loaders", _build_local_loaders | |
| ) | |
| def _write_rank0_metadata(): | |
| resolved = { | |
| "sft_config": sft, | |
| "base_model_config": base_cfg.to_dict(), | |
| "resolved_base_checkpoint": source_checkpoint, | |
| "world_size": info.world_size, | |
| "tokens_per_step": tokens_per_step, | |
| "auto_one_epoch_steps": auto_steps, | |
| "corpus_stats": stats, | |
| "validation_stats": val_stats, | |
| "validation_shard_ids": val_shard_ids, | |
| "dataset_contract": dataset_contract, | |
| "training_recipe": training_recipe, | |
| "training_contract_fingerprint": split_fingerprint, | |
| "effective_compile": effective_compile, | |
| } | |
| (run_dir / "config.resolved.json").write_text( | |
| json.dumps(resolved, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" | |
| ) | |
| write_run_metadata( | |
| run_dir, | |
| { | |
| "job_id": os.environ.get("SLURM_JOB_ID", ""), | |
| "nodes": os.environ.get("SLURM_JOB_NODELIST", ""), | |
| "world_size": info.world_size, | |
| "start_step": start_step, | |
| "base_checkpoint": source_checkpoint, | |
| "raw_sft_tokens": stats["raw_tokens"], | |
| "packed_windows": stats["windows"], | |
| "dataset_fingerprint": dataset_contract["fingerprint"], | |
| "training_contract_fingerprint": split_fingerprint, | |
| "validation_shard_ids": val_shard_ids, | |
| "effective_compile": effective_compile, | |
| "torch": torch.__version__, | |
| }, | |
| ) | |
| _main_rank_call(info, "write SFT run metadata", _write_rank0_metadata) | |
| control_flags = torch.zeros(2, device=info.device, dtype=torch.int32) | |
| data_state: dict[int, list[int]] = dict(resume_state or {}) | |
| job_start = time.time() | |
| step_timer = time.time() | |
| last_archive = time.time() | |
| done = start_step | |
| loss_log_sum = torch.zeros((), device=info.device, dtype=torch.float32) | |
| last_log_step = start_step | |
| last_log_assistant_tokens = assistant_tokens_seen | |
| assistant_tokens_seen_device = ( | |
| torch.tensor(assistant_tokens_seen, device=info.device, dtype=torch.int64) | |
| if info.world_size > 1 else None | |
| ) | |
| def assistant_seen_value() -> int: | |
| if assistant_tokens_seen_device is not None: | |
| return int(assistant_tokens_seen_device.item()) | |
| return int(assistant_tokens_seen) | |
| if val_loader is not None and val_at_start: | |
| val_t0 = time.time() | |
| metrics = _run_validation( | |
| base_model, val_loader, info, | |
| seq_len=seq_len, | |
| batches=val_batches, | |
| assistant_only_head=assistant_only_head, | |
| loss_fp32_logits=loss_fp32_logits, | |
| use_amp=use_amp, | |
| device_type=device_type, | |
| ) | |
| def _log_initial_validation(): | |
| log.metric({ | |
| "step": start_step, | |
| "kind": "validation", | |
| "val_loss": round(float(metrics["loss"]), 6), | |
| "val_ppl": round(float(metrics["ppl"]), 4), | |
| "val_assistant_tokens": int(metrics["assistant_tokens"]), | |
| "val_context_tokens": int(metrics["context_tokens"]), | |
| }) | |
| log.info_msg( | |
| f"VAL step={start_step} loss={metrics['loss']:.4f} " | |
| f"ppl={metrics['ppl']:.2f} assistant={int(metrics['assistant_tokens']):,} " | |
| f"context={int(metrics['context_tokens']):,}" | |
| ) | |
| _main_rank_call(info, "log initial validation", _log_initial_validation) | |
| # Benchmark/throughput timing starts after optional compile/JIT warmup and | |
| # initial validation. | |
| step_timer = time.time() | |
| log.info_msg(f"SFT training steps {start_step} -> {max_steps}") | |
| model.train() | |
| for step in range(start_step, max_steps): | |
| lr = lr_at_step(step, ocfg, max_steps) | |
| set_lr(optimizer, lr) | |
| optimizer.zero_grad(set_to_none=True) | |
| # Pull one whole optimizer step first so loss can be normalized by the | |
| # exact number of assistant tokens across all ranks/microbatches. | |
| micro_batches = [] | |
| local_target_tokens = 0 | |
| batch_fetch_error = "" | |
| try: | |
| for _ in range(grad_accum): | |
| batch = next(train_iter) | |
| micro_batches.append(batch) | |
| local_target_tokens += int(batch["trainable_tokens"].sum().item()) | |
| row = batch["state"][-1].tolist() | |
| data_state[int(row[0])] = [int(v) for v in row] | |
| if local_target_tokens <= 0: | |
| raise RuntimeError( | |
| f"optimizer step contains zero assistant trainable tokens on rank {info.rank}" | |
| ) | |
| except Exception as exc: # noqa: BLE001 | |
| batch_fetch_error = f"{type(exc).__name__}: {exc}" | |
| if info.world_size > 1: | |
| # Fuse the per-rank batch-fetch status with the target-count SUM. | |
| # The hot path therefore keeps exactly one tiny collective here. | |
| # Expensive object gathering happens only on the exceptional path. | |
| target_status = torch.tensor( | |
| [local_target_tokens, 1 if batch_fetch_error else 0], | |
| device=info.device, | |
| dtype=torch.int64, | |
| ) | |
| _sum_all(target_status) | |
| if int(target_status[1].item()) > 0: | |
| batch_fetch_errors = _collect_rank_errors(info, batch_fetch_error) | |
| raise RuntimeError( | |
| f"SFT batch fetch failed at optimizer step {step}: " | |
| + " | ".join(batch_fetch_errors) | |
| ) | |
| global_target = target_status[0] | |
| # Count targets exactly in int64; only the normalization scalar is | |
| # converted to float on-device. | |
| grad_scale = info.world_size / global_target.to(torch.float32) | |
| else: | |
| if batch_fetch_error: | |
| raise RuntimeError( | |
| f"SFT batch fetch failed at optimizer step {step}: {batch_fetch_error}" | |
| ) | |
| global_target = None | |
| grad_scale = 1.0 / float(local_target_tokens) | |
| local_loss_sum = torch.zeros((), device=info.device, dtype=torch.float32) | |
| for micro, batch in enumerate(micro_batches): | |
| raw_tokens = batch["tokens"].to( | |
| info.device, dtype=torch.long, non_blocking=True | |
| ) | |
| inputs = raw_tokens[:, :-1] | |
| labels = raw_tokens[:, 1:].clone() | |
| cu_seqlens, position_ids = _packed_layout(inputs) | |
| trainable_mask = batch["trainable_mask"][:, 1:].to( | |
| info.device, non_blocking=True | |
| ) | |
| labels.masked_fill_(~trainable_mask, -100) | |
| is_last = micro == grad_accum - 1 | |
| sync_ctx = model.no_sync() if (info.world_size > 1 and not is_last) else contextlib.nullcontext() | |
| with sync_ctx: | |
| with torch.autocast(device_type, dtype=torch.bfloat16, enabled=use_amp): | |
| if assistant_only_head: | |
| # Exact assistant-only objective. The LM head + CE live | |
| # inside model.forward so tied-embedding gradients are | |
| # covered by DDP and torch.compile can optimize the full | |
| # training graph. | |
| loss_sum, _ = model( | |
| inputs, | |
| labels=labels, | |
| return_logits=False, | |
| loss_reduction="sum", | |
| loss_fp32_logits=loss_fp32_logits, | |
| cu_seqlens=cu_seqlens, | |
| max_seqlen=seq_len, | |
| position_ids=position_ids, | |
| ) | |
| else: | |
| _, logits = model( | |
| inputs, return_logits=True, | |
| cu_seqlens=cu_seqlens, max_seqlen=seq_len, | |
| position_ids=position_ids, | |
| ) | |
| loss_sum = F.cross_entropy( | |
| logits.reshape(-1, logits.size(-1)).float(), | |
| labels.reshape(-1), ignore_index=-100, reduction="sum" | |
| ) | |
| (loss_sum * grad_scale).backward() | |
| local_loss_sum += loss_sum.detach() | |
| if not assistant_only_head: | |
| del logits | |
| del loss_sum, raw_tokens, inputs, labels, trainable_mask, cu_seqlens, position_ids | |
| grad_norm = torch.nn.utils.clip_grad_norm_( | |
| base_model.parameters(), ocfg.grad_clip, foreach=True, | |
| error_if_nonfinite=True, | |
| ) | |
| optimizer.step() | |
| done = step + 1 | |
| context_tokens_seen += tokens_per_step | |
| if assistant_tokens_seen_device is not None: | |
| assistant_tokens_seen_device.add_(global_target.detach()) | |
| else: | |
| assistant_tokens_seen += local_target_tokens | |
| loss_log_sum += local_loss_sum | |
| # Loss is metrics-only. Reduce/synchronize only when a log is emitted. | |
| if done % log_interval == 0 or done == start_step + 1: | |
| global_loss_sum = loss_log_sum.clone() | |
| _sum_all(global_loss_sum) | |
| assistant_seen_log = assistant_seen_value() | |
| target_log_tokens = assistant_seen_log - last_log_assistant_tokens | |
| mean_loss = float(global_loss_sum.item() / max(1, target_log_tokens)) | |
| if use_amp: | |
| torch.cuda.synchronize() | |
| elapsed = time.time() - step_timer | |
| span = max(1, done - last_log_step) | |
| sec_per_step = elapsed / span | |
| tok_per_s = tokens_per_step / sec_per_step | |
| target_ratio = target_log_tokens / (tokens_per_step * span) | |
| rec = { | |
| "step": done, | |
| "loss": round(mean_loss, 6), | |
| "ppl": round(math.exp(min(20.0, mean_loss)), 4), | |
| "lr": lr, | |
| "grad_norm": round(float(grad_norm), 4), | |
| "context_tokens_seen": context_tokens_seen, | |
| "assistant_tokens_seen": assistant_seen_log, | |
| "assistant_ratio_step": round(target_ratio, 5), | |
| "sec_per_step": round(sec_per_step, 3), | |
| "tokens_per_s": round(tok_per_s, 1), | |
| "peak_mem_gib": round( | |
| torch.cuda.max_memory_allocated(info.device) / (1024**3), 3 | |
| if use_amp else 0.0 | |
| ) if use_amp else 0.0, | |
| "hours": round((time.time() - job_start) / 3600.0, 3), | |
| } | |
| def _log_training_step(): | |
| log.metric(rec) | |
| log.info_msg( | |
| f"SFT {done}/{max_steps} loss {mean_loss:.4f} ppl {rec['ppl']:.2f} " | |
| f"lr {lr:.3e} gn {rec['grad_norm']:.2f} target={target_ratio*100:.1f}% " | |
| f"{tok_per_s/1e3:.0f}k tok/s context={context_tokens_seen/1e9:.2f}B " | |
| f"assistant={assistant_seen_log/1e9:.2f}B" | |
| ) | |
| _main_rank_call(info, f"log training metrics at step {done}", _log_training_step) | |
| loss_log_sum.zero_() | |
| last_log_assistant_tokens = assistant_seen_log | |
| last_log_step = done | |
| step_timer = time.time() | |
| if val_loader is not None and (done % val_interval == 0 or done == max_steps): | |
| val_wall = time.time() | |
| metrics = _run_validation( | |
| base_model, val_loader, info, | |
| seq_len=seq_len, | |
| batches=val_batches, | |
| assistant_only_head=assistant_only_head, | |
| loss_fp32_logits=loss_fp32_logits, | |
| use_amp=use_amp, | |
| device_type=device_type, | |
| ) | |
| def _log_validation(): | |
| log.metric({ | |
| "step": done, | |
| "kind": "validation", | |
| "val_loss": round(float(metrics["loss"]), 6), | |
| "val_ppl": round(float(metrics["ppl"]), 4), | |
| "val_assistant_tokens": int(metrics["assistant_tokens"]), | |
| "val_context_tokens": int(metrics["context_tokens"]), | |
| }) | |
| log.info_msg( | |
| f"VAL step={done} loss={metrics['loss']:.4f} " | |
| f"ppl={metrics['ppl']:.2f} assistant={int(metrics['assistant_tokens']):,} " | |
| f"context={int(metrics['context_tokens']):,}" | |
| ) | |
| _main_rank_call(info, f"log validation at step {done}", _log_validation) | |
| # Keep validation wall time out of training throughput estimates. | |
| step_timer += time.time() - val_wall | |
| # All ranks enter control collectives on deterministic step boundaries. | |
| # Rank 0 alone decides wall-clock archive cadence; MAX-reduction then | |
| # broadcasts that decision while also OR-ing stop requests from any rank. | |
| # This removes the former per-rank time.time() branch that could send one | |
| # rank into a barrier while its peers skipped it. | |
| local_stop = _STOP_REQUESTED or ( | |
| bool(max_hours) and (time.time() - job_start) / 3600.0 >= max_hours | |
| ) | |
| control_due = ( | |
| done % control_interval == 0 | |
| or done % ckpt_interval == 0 | |
| or done == max_steps | |
| ) | |
| archive_due = False | |
| must_stop = False | |
| if control_due: | |
| rank0_archive_due = ( | |
| info.is_main | |
| and archive_interval_hours > 0 | |
| and (time.time() - last_archive) / 3600.0 >= archive_interval_hours | |
| ) | |
| archive_due, must_stop = _sync_control_flags( | |
| control_flags, | |
| rank0_archive_due=rank0_archive_due, | |
| local_stop=local_stop, | |
| ) | |
| if archive_due: | |
| def _write_archive(): | |
| path = save_model_archive( | |
| run_dir, | |
| done, | |
| { | |
| "step": done, | |
| "base_checkpoint": source_checkpoint, | |
| "context_tokens_seen": context_tokens_seen, | |
| "assistant_tokens_seen": assistant_seen_value(), | |
| "dataset_fingerprint": dataset_contract["fingerprint"], | |
| "training_contract_fingerprint": split_fingerprint, | |
| "validation_shard_ids": val_shard_ids, | |
| "effective_compile": effective_compile, | |
| "model": base_model.state_dict(), | |
| }, | |
| ) | |
| log.info_msg(f"SFT model archive written: {path.name}") | |
| return path | |
| _main_rank_call(info, f"write model archive at step {done}", _write_archive) | |
| # Keep every rank's local cadence anchor aligned to the same event. | |
| last_archive = time.time() | |
| step_timer = time.time() | |
| checkpoint_due = ( | |
| must_stop | |
| or done % ckpt_interval == 0 | |
| or (done == max_steps and save_final_checkpoint) | |
| ) | |
| if checkpoint_due: | |
| gathered = gather_object({str(k): v for k, v in data_state.items()}, info.world_size) | |
| def _write_checkpoint(): | |
| payload = { | |
| "step": done, | |
| "base_checkpoint": source_checkpoint, | |
| "context_tokens_seen": context_tokens_seen, | |
| "assistant_tokens_seen": assistant_seen_value(), | |
| "model": base_model.state_dict(), | |
| "optimizer": optimizer.state_dict(), | |
| "data_state": [{int(k): v for k, v in d.items()} for d in gathered], | |
| "world_size": info.world_size, | |
| "num_workers": num_workers, | |
| "dataset_fingerprint": dataset_contract["fingerprint"], | |
| "training_contract_fingerprint": split_fingerprint, | |
| "validation_shard_ids": val_shard_ids, | |
| "effective_compile": effective_compile, | |
| "dataset_contract": dataset_contract, | |
| "training_recipe": training_recipe, | |
| "sft_config": sft, | |
| } | |
| path = save_checkpoint( | |
| run_dir, done, payload, | |
| keep_last=keep_last, keep_every=keep_every, | |
| ) | |
| log.info_msg(f"SFT checkpoint written: {path.name}") | |
| return path | |
| _main_rank_call(info, f"write SFT checkpoint at step {done}", _write_checkpoint) | |
| step_timer = time.time() | |
| if must_stop: | |
| log.info_msg("stop requested; exiting after SFT checkpoint") | |
| break | |
| final_assistant_seen = assistant_seen_value() | |
| def _finalize_log_rank0(): | |
| log.info_msg( | |
| f"SFT finished at step {done}: context={context_tokens_seen/1e9:.3f}B, " | |
| f"assistant={final_assistant_seen/1e9:.3f}B, " | |
| f"hours={(time.time()-job_start)/3600:.2f}" | |
| ) | |
| log.close() | |
| _main_rank_call(info, "finalize SFT log", _finalize_log_rank0) | |
| cleanup() | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |