Download pear15/scratch_train.py from coderofpears/pear15-stage3-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 32.4 kB
-
https://huggingface.co/datasets/coderofpears/pear15-stage3-checkpoints/resolve/main/pear15/scratch_train.py
- Command line
-
hf download hf://datasets/coderofpears/pear15-stage3-checkpoints/pear15/scratch_train.py
-
curl -L -o scratch_train.py https://huggingface.co/datasets/coderofpears/pear15-stage3-checkpoints/resolve/main/pear15/scratch_train.py
32.4 kB
| """Offline, random-initialized Llama training with single-writer durable resume. | |
| Run ``python -m pear15.scratch_train --help``. No tokenizer/weights/config are | |
| fetched: LlamaConfig and LlamaForCausalLM are constructed from local JSON. | |
| ``run_training`` accepts JSON paths or dictionaries and returns a JSON-safe | |
| session summary. ``model_factory(raw_config)`` is an optional offline test seam. | |
| The schedule horizon is training.total_steps, NOT the session limit. Checkpoints | |
| live directly in run_dir and include the next packed-data position. Step zero | |
| is saved before training. Only fully completed optimizer steps are published; | |
| KeyboardInterrupt discards ALL work since the last durable snapshot, even if | |
| it interrupted optimizer.step itself. Other exceptions propagate without a | |
| final save. SIGTERM requests a stop after the current step. A second runtime | |
| must never write this RunDir concurrently. | |
| training.precision accepts auto (default), fp32 or bf16. Auto uses BF16 autocast | |
| only on native-BF16 CUDA hardware (capability >= 8 and the non-emulation API | |
| check when available); otherwise it uses FP32. | |
| Explicit BF16 requires native CUDA support; CPU uses FP32. CUDA always retains | |
| FP32 master parameters/state and fused AdamW; CPU uses nonfused AdamW, with no | |
| automatic CUDA-error fallback. Resolved precision is part of checkpoint identity. | |
| Session wall limits are checked at step boundaries and can overshoot by a step | |
| plus evaluation/I/O. Zero session limits publish the initial snapshot (or resume | |
| the existing snapshot) without consuming a batch or performing an update. | |
| Elapsed training time counts completed steps/evaluation, not checkpoint I/O or | |
| downtime. Tokens count every B*T target in every accumulation and corpus pass. | |
| Step logs are emitted every training.log_interval_steps (default 50) and at | |
| the final schedule step; checkpoint/session events always retain full counters. | |
| Checkpoint v2 binds the exact source bytes of this trainer, scratch_data.py and | |
| cloud_checkpoint.py. Source/format changes (including a future XLA port) require | |
| matching source/version or an explicit migration into a new run_dir; environment | |
| change permission never overrides implementation identity. V1 cannot auto-resume. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from contextlib import contextmanager, nullcontext | |
| import hashlib | |
| from importlib.metadata import version | |
| import json | |
| import logging | |
| import math | |
| from pathlib import Path | |
| import platform | |
| import random | |
| import signal | |
| import threading | |
| import time | |
| from .cloud_checkpoint import load_latest, save_checkpoint | |
| from .scratch_data import PackedTokenReader, evaluation_batches | |
| _LOG = logging.getLogger(__name__) | |
| _FORMAT = "pear15.scratch-train.v2" | |
| _DEFAULTS = { | |
| "total_steps": 100_000, "warmup_steps": 1_000, | |
| "sequence_length": 1024, "batch_size": 8, "gradient_accumulation_steps": 1, | |
| "learning_rate": 0.0003, "min_lr_ratio": 0.1, "weight_decay": 0.1, | |
| "adam_beta1": 0.9, "adam_beta2": 0.95, "adam_epsilon": 1e-8, | |
| "max_grad_norm": 1.0, "seed": 1337, "gradient_checkpointing": True, | |
| "attention_backend": "sdpa", "loss_chunk_tokens": 1024, "precision": "auto", | |
| "checkpoint_interval_steps": 500, "checkpoint_interval_seconds": 900.0, | |
| "log_interval_steps": 50, | |
| "eval_interval_steps": 500, "eval_targets": 8192, | |
| } | |
| # These controls cannot change the update math/schedule. The backend is checked | |
| # separately as part of the environment and requires explicit permission to change. | |
| _OPERATIONAL = {"checkpoint_interval_steps", "checkpoint_interval_seconds", | |
| "log_interval_steps", "attention_backend"} | |
| _MODEL_FIELDS = { | |
| "model_type", "vocab_size", "hidden_size", "intermediate_size", | |
| "num_hidden_layers", "num_attention_heads", "num_key_value_heads", | |
| "max_position_embeddings", "rope_theta", "rms_norm_eps", "hidden_act", | |
| "attention_bias", "mlp_bias", "attention_dropout", "tie_word_embeddings", | |
| "bos_token_id", "eos_token_id", "pad_token_id", "use_cache", | |
| "initializer_range", "head_dim", "rope_scaling", | |
| } | |
| def _unique(pairs): | |
| result = {} | |
| for key, value in pairs: | |
| if key in result: | |
| raise ValueError(f"duplicate JSON key: {key}") | |
| result[key] = value | |
| return result | |
| def _json(value): | |
| if isinstance(value, dict): | |
| # Detach callers' mutable config and reject non-JSON/nonfinite values. | |
| return json.loads(json.dumps(value, allow_nan=False)) | |
| def reject(value): | |
| raise ValueError(f"nonfinite JSON constant: {value}") | |
| return json.loads(Path(value).read_text(encoding="utf-8"), | |
| object_pairs_hook=_unique, parse_constant=reject) | |
| def _fingerprint(value): | |
| raw = json.dumps(value, sort_keys=True, separators=(",", ":"), | |
| ensure_ascii=False, allow_nan=False) | |
| return hashlib.sha256(raw.encode("utf-8")).hexdigest() | |
| def _implementation_fingerprint(): | |
| """Path-independent identity of the exact, required local training sources. | |
| Read bytes, not decoded/normalized text or bytecode. Missing source fails | |
| closed; unrelated package/notebook/config files are deliberately excluded. | |
| """ | |
| root = Path(__file__).resolve().parent | |
| sources = {} | |
| for name in ("scratch_train.py", "scratch_data.py", "cloud_checkpoint.py"): | |
| try: | |
| sources[name] = hashlib.sha256((root / name).read_bytes()).hexdigest() | |
| except OSError as exc: | |
| raise ValueError(f"cannot fingerprint implementation source {name}; refusing training") from exc | |
| return _fingerprint({"format": _FORMAT, "sources": sources}) | |
| def _int(value, name, minimum=0): | |
| if type(value) is not int or value < minimum: | |
| raise ValueError(f"{name} must be an integer >= {minimum}") | |
| return value | |
| def _number(value, name, minimum=0, *, positive=False): | |
| if (type(value) not in (int, float) or not math.isfinite(value) | |
| or value < minimum or (positive and value == 0)): | |
| raise ValueError(f"invalid finite {name}") | |
| return value | |
| def _configs(model_config, train_config): | |
| model, raw = _json(model_config), _json(train_config) | |
| if not isinstance(model, dict) or model.get("model_type") != "llama": | |
| raise ValueError("model config must describe a local llama") | |
| if set(model) - _MODEL_FIELDS: | |
| raise ValueError(f"unsupported model config fields: {set(model) - _MODEL_FIELDS}") | |
| if model.get("vocab_size") != 49152: | |
| raise ValueError("packed scratch data requires model vocab_size 49152") | |
| for key in ("hidden_size", "intermediate_size", "num_hidden_layers", | |
| "num_attention_heads", "num_key_value_heads", "max_position_embeddings"): | |
| _int(model.get(key), key, 1) | |
| heads, kv = model["num_attention_heads"], model["num_key_value_heads"] | |
| if model["hidden_size"] % heads or heads % kv: | |
| raise ValueError("invalid Llama attention dimensions") | |
| if model.get("head_dim", model["hidden_size"] // heads) % 2: | |
| raise ValueError("Llama rotary head dimension must be even") | |
| if not isinstance(raw, dict) or set(raw) != {"training"} or not isinstance(raw["training"], dict): | |
| raise ValueError("train config requires a training object") | |
| unknown = set(raw["training"]) - set(_DEFAULTS) | |
| if unknown: | |
| raise ValueError(f"unknown training settings: {unknown}; session limits belong to the invocation") | |
| cfg = {**_DEFAULTS, **raw["training"]} | |
| for key in ("total_steps", "sequence_length", "batch_size", "gradient_accumulation_steps", | |
| "log_interval_steps"): | |
| _int(cfg[key], key, 1) | |
| for key in ("warmup_steps", "seed", "loss_chunk_tokens", "checkpoint_interval_steps", | |
| "eval_interval_steps", "eval_targets"): | |
| _int(cfg[key], key) | |
| if cfg["total_steps"] >= 10**12 or cfg["warmup_steps"] > cfg["total_steps"]: | |
| raise ValueError("invalid fixed schedule horizon/warmup") | |
| if cfg["sequence_length"] > model["max_position_embeddings"]: | |
| raise ValueError("sequence_length exceeds model position limit") | |
| for key in ("learning_rate", "adam_epsilon", "max_grad_norm"): | |
| _number(cfg[key], key, positive=True) | |
| for key in ("weight_decay", "checkpoint_interval_seconds"): | |
| _number(cfg[key], key) | |
| for key in ("adam_beta1", "adam_beta2", "min_lr_ratio"): | |
| _number(cfg[key], key) | |
| if cfg[key] >= 1 and not (key == "min_lr_ratio" and cfg[key] == 1): | |
| raise ValueError(f"{key} outside allowed [0,1] range") | |
| if type(cfg["gradient_checkpointing"]) is not bool: | |
| raise ValueError("gradient_checkpointing must be boolean") | |
| if cfg["attention_backend"] not in {"eager", "sdpa"}: | |
| raise ValueError("attention_backend must be eager or sdpa (no remote implementations)") | |
| if cfg["precision"] not in ("auto", "fp32", "bf16"): | |
| raise ValueError("precision must be auto, fp32 or bf16") | |
| if cfg["eval_interval_steps"] and not cfg["eval_targets"]: | |
| raise ValueError("eval_interval_steps requires positive eval_targets") | |
| return model, cfg | |
| def build_model(raw_config, *, attention_backend="sdpa"): | |
| """Construct REAL random HF Llama weights; no Auto*/from_pretrained/network.""" | |
| from transformers import LlamaConfig, LlamaForCausalLM | |
| config = LlamaConfig(**raw_config) | |
| config.use_cache = False | |
| config._attn_implementation = attention_backend | |
| return LlamaForCausalLM(config) | |
| def shifted_cross_entropy(logits, targets, chunk_tokens=0): | |
| """All positions are already shifted by PackedTokenReader, including row ends. | |
| Chunk checkpointing recomputes CE during backward instead of retaining a | |
| full FP32 vocab-sized log-softmax for every chunk. HF still emits full logits. | |
| """ | |
| import torch | |
| from torch.nn import functional as F | |
| from torch.utils.checkpoint import checkpoint | |
| flat, labels = logits.reshape(-1, logits.shape[-1]), targets.reshape(-1) | |
| if not chunk_tokens: | |
| return F.cross_entropy(flat.float(), labels) | |
| def summed(chunk, gold): | |
| return F.cross_entropy(chunk.float(), gold, reduction="sum") | |
| loss = logits.new_zeros((), dtype=torch.float32) | |
| for start in range(0, labels.numel(), chunk_tokens): | |
| chunk, gold = flat[start:start + chunk_tokens], labels[start:start + chunk_tokens] | |
| if torch.is_grad_enabled() and chunk.requires_grad: | |
| loss = loss + checkpoint(summed, chunk, gold, use_reentrant=False, | |
| preserve_rng_state=False) | |
| else: | |
| loss = loss + summed(chunk, gold) | |
| return loss / labels.numel() | |
| def _rng(torch, device): | |
| return {"python": random.getstate(), "cpu": torch.get_rng_state(), | |
| "cuda": torch.cuda.get_rng_state_all() if device == "cuda" else []} | |
| def _restore_rng(torch, state, device, *, restore_cuda=True): | |
| random.setstate(state["python"]) | |
| torch.set_rng_state(state["cpu"]) | |
| if device == "cuda" and restore_cuda and state["cuda"]: | |
| torch.cuda.set_rng_state_all(state["cuda"]) | |
| def _cuda_bf16_support(torch): | |
| """Report the active GPU's API/emulation result separately from native support.""" | |
| major, _ = torch.cuda.get_device_capability() | |
| api_supported = bool(torch.cuda.is_bf16_supported()) | |
| try: | |
| api_native = bool(torch.cuda.is_bf16_supported(including_emulation=False)) | |
| except TypeError: # Older PyTorch lacks the non-emulation keyword. | |
| api_native = None | |
| return {"api_supported_including_emulation": api_supported, | |
| "api_supported_excluding_emulation": api_native, | |
| "native_supported": major >= 8 and (api_supported if api_native is None else api_native)} | |
| def _resolve_precision(torch, device, precision): | |
| if precision == "fp32": | |
| return "fp32" | |
| native = device == "cuda" and _cuda_bf16_support(torch)["native_supported"] | |
| if precision == "bf16" and not native: | |
| raise RuntimeError("precision bf16 requires native CUDA BF16 support (compute capability >= 8); " | |
| "use auto or fp32") | |
| return "bf16" if native else "fp32" | |
| def _autocast(torch, device, precision): | |
| if precision == "fp32": | |
| return nullcontext() | |
| if precision != "bf16" or device != "cuda": | |
| raise ValueError("autocast requires resolved fp32 or CUDA bf16 precision") | |
| return torch.autocast(device, dtype=torch.bfloat16) | |
| def evaluate(model, data, cfg, device): | |
| """Deterministic finite validation prefix, independent cursor and RNG-neutral.""" | |
| import torch | |
| rng, was_training = _rng(torch, device), model.training | |
| total, nll = 0, 0.0 | |
| try: | |
| model.eval() | |
| with torch.no_grad(): | |
| for x, y, count in evaluation_batches( | |
| data, cfg["batch_size"], cfg["sequence_length"], | |
| eval_targets=cfg["eval_targets"]): | |
| x = torch.tensor(x, dtype=torch.long, device=device) | |
| y = torch.tensor(y, dtype=torch.long, device=device) | |
| with _autocast(torch, device, cfg["precision"]): | |
| logits = model(input_ids=x, use_cache=False).logits | |
| loss = shifted_cross_entropy(logits, y, cfg["loss_chunk_tokens"]) | |
| if not torch.isfinite(loss).item(): | |
| raise FloatingPointError("nonfinite validation loss") | |
| total += count | |
| nll += loss.item() * count | |
| if not total: | |
| raise ValueError("validation has no targets") | |
| return {"loss": nll / total, "token_count": total} | |
| finally: | |
| model.train(was_training) | |
| _restore_rng(torch, rng, device) | |
| def _lr_factor(completed, cfg): | |
| # LR for the NEXT update: first warmup update uses base_lr/warmup_steps. | |
| if completed < cfg["warmup_steps"]: | |
| return (completed + 1) / cfg["warmup_steps"] | |
| span = max(1, cfg["total_steps"] - cfg["warmup_steps"]) | |
| progress = min(1.0, (completed - cfg["warmup_steps"]) / span) | |
| return cfg["min_lr_ratio"] + (1 - cfg["min_lr_ratio"]) * (1 + math.cos(math.pi * progress)) / 2 | |
| def _environment(torch, device, cfg, factory): | |
| gpus = [] | |
| if device == "cuda": | |
| for index in range(torch.cuda.device_count()): | |
| prop = torch.cuda.get_device_properties(index) | |
| gpus.append({"name": prop.name, "capability": [prop.major, prop.minor], | |
| "total_memory": prop.total_memory}) | |
| return {"device": device, "gpus": gpus, | |
| "cuda_device": torch.cuda.current_device() if device == "cuda" else None, | |
| "torch": str(torch.__version__), "cuda_runtime": torch.version.cuda, | |
| "transformers": version("transformers") if factory is None else None, | |
| "python": platform.python_version(), "platform": platform.system(), | |
| "threads": torch.get_num_threads(), "interop_threads": torch.get_num_interop_threads(), | |
| "attention_backend": cfg["attention_backend"], "fused_adamw": device == "cuda", | |
| "precision": cfg["precision"], | |
| "cuda_bf16": _cuda_bf16_support(torch) if device == "cuda" else None, | |
| "deterministic_algorithms": torch.are_deterministic_algorithms_enabled(), | |
| "tf32": bool(torch.backends.cuda.matmul.allow_tf32)} | |
| def _termination_flag(): | |
| flag = threading.Event() | |
| previous = None | |
| installed = threading.current_thread() is threading.main_thread() | |
| if installed: | |
| previous = signal.signal(signal.SIGTERM, lambda *_: flag.set()) | |
| try: | |
| yield flag | |
| finally: | |
| if installed: | |
| signal.signal(signal.SIGTERM, previous) | |
| def run_training(data, model_config, train_config, run_dir, *, device="cuda", | |
| max_session_steps=None, max_session_seconds=None, | |
| allow_environment_change=False, model_factory=None, | |
| stop_requested=None): | |
| """Auto-resume the newest valid snapshot; reject incompatible identities. | |
| max_session_steps counts ADDITIONAL optimizer steps, never changes the LR | |
| horizon. Environment changes require opt-in and are numerical, not bitwise. | |
| Implementation source/format changes cannot use that opt-in: match the saved | |
| source/version or explicitly migrate into a new run_dir instead. | |
| A changed CUDA topology skips CUDA RNG restoration (CPU/Python still restore). | |
| On interruption the returned counters describe the durable checkpoint, not | |
| the abandoned in-memory model/cursor. Other errors are raised to the caller. | |
| """ | |
| import os | |
| import torch | |
| session_start = time.monotonic() | |
| raw_model, cfg = _configs(model_config, train_config) | |
| if device not in {"cpu", "cuda"}: | |
| raise ValueError("device must be cpu or cuda") | |
| if max_session_steps is not None: | |
| _int(max_session_steps, "max_session_steps") | |
| if max_session_seconds is not None: | |
| _number(max_session_seconds, "max_session_seconds") | |
| if device == "cuda" and not torch.cuda.is_available(): | |
| raise RuntimeError("CUDA training requires an available GPU; no CPU fallback") | |
| # Resolve before environment reporting and semantic fingerprinting: auto must | |
| # never silently change a resumed run's update precision across GPU families. | |
| cfg["precision"] = _resolve_precision(torch, device, cfg["precision"]) | |
| # This must precede CUDA allocations; deterministic CUDA GEMM needs this. | |
| os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") | |
| torch.use_deterministic_algorithms(True) | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| torch.backends.cudnn.allow_tf32 = False | |
| torch.backends.cudnn.benchmark = False | |
| env = _environment(torch, device, cfg, model_factory) | |
| factory_name = ("transformers.LlamaForCausalLM" if model_factory is None else | |
| f"{model_factory.__module__}.{model_factory.__qualname__}") | |
| semantic = {key: val for key, val in cfg.items() if key not in _OPERATIONAL} | |
| identity = {"model_fingerprint": _fingerprint(raw_model), | |
| "train_fingerprint": _fingerprint(semantic), "model_factory": factory_name, | |
| "implementation_fingerprint": _implementation_fingerprint()} | |
| root = Path(run_dir) | |
| loaded = load_latest(root) | |
| if loaded is not None: | |
| payload, _ = loaded | |
| saved_identity = payload.get("identity") | |
| if (payload.get("format") != _FORMAT or not isinstance(saved_identity, dict) | |
| or saved_identity.get("implementation_fingerprint") != identity["implementation_fingerprint"]): | |
| # Compatibility is not corruption: never search older snapshots for | |
| # matching code or let allow_environment_change bypass this gate. | |
| raise ValueError("checkpoint implementation mismatch: source bytes or format changed; " | |
| "use matching source/version or explicitly migrate into a new run_dir " | |
| "(allow_environment_change does not override implementation identity)") | |
| del payload | |
| if loaded is None and root.exists(): | |
| # Log/info directories from notebook setup do not constitute a prior run. | |
| if any(p.name not in {"logs", "info"} or not p.is_dir() or p.is_symlink() | |
| for p in root.iterdir()): | |
| raise ValueError("nonempty run_dir has no valid checkpoint; use a fresh run_dir or recover it") | |
| with PackedTokenReader(data, split="train") as reader, _termination_flag() as term: | |
| identity.update(dataset_fingerprint=reader.fingerprint, | |
| tokenizer=reader.manifest["tokenizer"]) | |
| if raw_model.get("eos_token_id") != identity["tokenizer"]["eos_token_id"]: | |
| raise ValueError("model and dataset tokenizer eos_token_id mismatch") | |
| if cfg["batch_size"] * cfg["sequence_length"] + 1 > reader.total_tokens: | |
| raise ValueError("training corpus is too short for a microbatch") | |
| changed, restore_cuda = False, True | |
| if loaded is not None: | |
| payload, resume_info = loaded | |
| if payload.get("identity") != identity: | |
| raise ValueError("checkpoint dataset/tokenizer/model/train config fingerprint mismatch") | |
| changed = payload["environment"] != env | |
| if changed and not allow_environment_change: | |
| raise ValueError("checkpoint environment changed; pass allow_environment_change explicitly (numerical, not bitwise)") | |
| restore_cuda = (payload["environment"]["gpus"] == env["gpus"] | |
| and payload["environment"]["cuda_device"] == env["cuda_device"]) | |
| else: | |
| payload, resume_info = None, None | |
| random.seed(cfg["seed"]) | |
| torch.manual_seed(cfg["seed"]) | |
| if device == "cuda": | |
| torch.cuda.manual_seed_all(cfg["seed"]) | |
| old_dtype = torch.get_default_dtype() | |
| try: | |
| torch.set_default_dtype(torch.float32) | |
| with torch.device("cpu"): | |
| model = (build_model(raw_model, attention_backend=cfg["attention_backend"]) | |
| if model_factory is None else model_factory(raw_model)) | |
| finally: | |
| torch.set_default_dtype(old_dtype) | |
| model = model.to(device=device, dtype=torch.float32) | |
| model.train() | |
| if cfg["gradient_checkpointing"]: | |
| model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) | |
| optimizer = torch.optim.AdamW( | |
| model.parameters(), lr=cfg["learning_rate"], weight_decay=cfg["weight_decay"], | |
| betas=(cfg["adam_beta1"], cfg["adam_beta2"]), eps=cfg["adam_epsilon"], | |
| fused=device == "cuda", foreach=False) | |
| scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda n: _lr_factor(n, cfg)) | |
| step = token_count = 0 | |
| elapsed = 0.0 | |
| validation = None | |
| if payload is not None: | |
| step, token_count, elapsed = payload["step"], payload["token_count"], payload["elapsed_training_seconds"] | |
| _int(step, "checkpoint step") | |
| _int(token_count, "checkpoint token_count") | |
| _number(elapsed, "checkpoint elapsed_training_seconds") | |
| expected_tokens = step * cfg["batch_size"] * cfg["sequence_length"] * cfg["gradient_accumulation_steps"] | |
| if step > cfg["total_steps"] or token_count != expected_tokens: | |
| raise ValueError("checkpoint step/token count inconsistent with fixed training budget") | |
| model.load_state_dict(payload["model"], strict=True) | |
| optimizer.load_state_dict(payload["optimizer"]) | |
| # Saved param groups override constructor options. Reapply the actual | |
| # backend, including correct scalar-step placement across CPU/CUDA. | |
| for group in optimizer.param_groups: | |
| group.update(fused=device == "cuda", foreach=False) | |
| for state in optimizer.state.values(): | |
| if "step" in state: | |
| state["step"] = state["step"].to(device if device == "cuda" else "cpu") | |
| scheduler.load_state_dict(payload["scheduler"]) | |
| if scheduler.last_epoch != step: | |
| raise ValueError("checkpoint scheduler step mismatch") | |
| reader.load_state_dict(payload["data_cursor"], fingerprint=payload["identity"]["dataset_fingerprint"], split=payload["data_split"]) | |
| cursor = reader.state_dict() | |
| if cursor["epoch"] * reader.total_tokens + cursor["offset_tokens"] != token_count: | |
| raise ValueError("checkpoint cursor/token count mismatch") | |
| validation = payload["validation"] | |
| _restore_rng(torch, payload["rng"], device, restore_cuda=restore_cuda) | |
| # Release the loaded CPU checkpoint before training/saving another copy. | |
| del loaded, payload | |
| (root / "logs").mkdir(parents=True, exist_ok=True) | |
| def emit(event, **fields): | |
| record = {"event": event, **fields} | |
| line = json.dumps(record, sort_keys=True, allow_nan=False) | |
| with (root / "logs" / "train.jsonl").open("a", encoding="utf-8") as stream: | |
| stream.write(line + "\n") | |
| _LOG.info("%s", line) | |
| emit("session_start", resume=resume_info, identity=identity, environment=env, | |
| model_config=raw_model, training_config=cfg, initialization="random; no pretrained weights") | |
| if changed: | |
| emit("environment_change", reproducibility="numerical, not bitwise", | |
| cuda_rng_restored=bool(device == "cuda" and restore_cuda), | |
| note="CUDA RNG skipped for changed topology or CPU/CUDA transition" if not restore_cuda else "compatible CUDA topology") | |
| checkpoint_step = step if resume_info else None | |
| checkpoint_info = resume_info | |
| last_save = time.monotonic() | |
| def save(): | |
| nonlocal checkpoint_step, checkpoint_info, last_save | |
| if device == "cuda": | |
| torch.cuda.synchronize() | |
| state = {"format": _FORMAT, "step": step, "token_count": token_count, | |
| "elapsed_training_seconds": elapsed, "identity": identity, | |
| "model_config": raw_model, "training_config": cfg, "environment": env, | |
| "model": model.state_dict(), "optimizer": optimizer.state_dict(), | |
| "scheduler": scheduler.state_dict(), "rng": _rng(torch, device), | |
| "data_cursor": reader.state_dict(), "data_split": "train", "validation": validation} | |
| path = save_checkpoint(root, state, keep_last=2) | |
| checkpoint_step, checkpoint_info = step, {"path": str(path), "step": step} | |
| last_save = time.monotonic() | |
| emit("checkpoint", step=step, token_count=token_count, path=str(path)) | |
| if checkpoint_step is None: | |
| save() # Mandatory initialized model/optimizer/RNG/data snapshot. | |
| starting_step = step | |
| last_logged_step = step | |
| status = "completed" | |
| try: | |
| while step < cfg["total_steps"]: | |
| if term.is_set() or (stop_requested is not None and stop_requested()): | |
| status = "stop_requested" | |
| break | |
| if max_session_steps is not None and step - starting_step >= max_session_steps: | |
| status = "session_steps" | |
| break | |
| if max_session_seconds is not None and time.monotonic() - session_start >= max_session_seconds: | |
| status = "session_seconds" | |
| break | |
| tick = time.monotonic() | |
| optimizer.zero_grad(set_to_none=True) | |
| batch_tokens, mean_loss = 0, 0.0 | |
| lr_used = optimizer.param_groups[0]["lr"] | |
| for _ in range(cfg["gradient_accumulation_steps"]): | |
| x, y, count = reader.get_batch(cfg["batch_size"], cfg["sequence_length"]) | |
| x = torch.tensor(x, dtype=torch.long, device=device) | |
| y = torch.tensor(y, dtype=torch.long, device=device) | |
| with _autocast(torch, device, cfg["precision"]): | |
| logits = model(input_ids=x, use_cache=False).logits | |
| loss = shifted_cross_entropy(logits, y, cfg["loss_chunk_tokens"]) | |
| if not torch.isfinite(loss).item(): | |
| raise FloatingPointError("nonfinite training loss; no checkpoint published") | |
| mean_loss += loss.item() / cfg["gradient_accumulation_steps"] | |
| (loss / cfg["gradient_accumulation_steps"]).backward() | |
| batch_tokens += count | |
| del logits, loss, x, y | |
| norm = torch.nn.utils.clip_grad_norm_(model.parameters(), cfg["max_grad_norm"], error_if_nonfinite=True) | |
| if not torch.isfinite(norm).item(): | |
| raise FloatingPointError("nonfinite gradient norm") | |
| optimizer.step() | |
| scheduler.step() | |
| if device == "cuda": | |
| torch.cuda.synchronize() | |
| step += 1 | |
| token_count += batch_tokens | |
| optimizer.zero_grad(set_to_none=True) | |
| if cfg["eval_interval_steps"] and (step % cfg["eval_interval_steps"] == 0 or step == cfg["total_steps"]): | |
| validation = evaluate(model, data, cfg, device) | |
| elapsed += time.monotonic() - tick | |
| if step % cfg["log_interval_steps"] == 0 or step == cfg["total_steps"]: | |
| emit("step", step=step, steps_since_last_log=step - last_logged_step, | |
| loss=mean_loss, grad_norm=norm.item(), | |
| lr=lr_used, next_lr=optimizer.param_groups[0]["lr"], | |
| token_count=token_count, num_passes=token_count / reader.total_tokens, | |
| elapsed_training_seconds=elapsed, validation=validation) | |
| last_logged_step = step | |
| due_steps = cfg["checkpoint_interval_steps"] and step % cfg["checkpoint_interval_steps"] == 0 | |
| due_seconds = cfg["checkpoint_interval_seconds"] and time.monotonic() - last_save >= cfg["checkpoint_interval_seconds"] | |
| if due_steps or due_seconds: | |
| save() | |
| # Only this successful/explicitly stopped path may save final state. | |
| if checkpoint_step != step: | |
| save() | |
| except KeyboardInterrupt: | |
| # Never serialize potentially partially mutated optimizer/cursor/RNG. | |
| recovered = load_latest(root) | |
| if recovered is None: | |
| raise RuntimeError("interrupted and no valid checkpoint remains") | |
| durable, checkpoint_info = recovered | |
| step, token_count = durable["step"], durable["token_count"] | |
| elapsed, validation = durable["elapsed_training_seconds"], durable["validation"] | |
| reader.load_state_dict(durable["data_cursor"], fingerprint=reader.fingerprint, split="train") | |
| status = "interrupted" | |
| emit("interrupted", step=step, token_count=token_count, | |
| checkpoint=checkpoint_info, note="in-memory work discarded; resume from this durable snapshot") | |
| except Exception as exc: | |
| emit("failure", error=f"{type(exc).__name__}: {exc}", | |
| last_checkpoint=checkpoint_info, note="no exception/final checkpoint saved") | |
| raise | |
| result = {"status": status, "step": step, "token_count": token_count, | |
| "session_completed_steps": step - starting_step, | |
| "elapsed_training_seconds": elapsed, "data_cursor": reader.state_dict(), | |
| "num_passes": token_count / reader.total_tokens, | |
| "validation": validation, "checkpoint": checkpoint_info, | |
| "resumed_from": resume_info, "environment_changed": changed} | |
| emit("session_end", **result) | |
| return result | |
| def main(argv=None): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--data", required=True, help="verified packed BPE dataset directory") | |
| parser.add_argument("--model-config", default="configs/scratch135.json") | |
| parser.add_argument("--train-config", default="configs/scratch-train-a100.json") | |
| parser.add_argument("--run-dir", required=True, help="persistent single-writer checkpoint root") | |
| parser.add_argument("--device", choices=("cuda", "cpu"), default="cuda") | |
| parser.add_argument("--max-session-steps", type=int, help="additional optimizer steps this invocation") | |
| parser.add_argument("--max-session-seconds", type=float) | |
| parser.add_argument("--allow-environment-change", action="store_true", default=False) | |
| args = parser.parse_args(argv) | |
| logging.basicConfig(level=logging.INFO, format="%(message)s") | |
| result = run_training(args.data, args.model_config, args.train_config, args.run_dir, | |
| device=args.device, max_session_steps=args.max_session_steps, | |
| max_session_seconds=args.max_session_seconds, | |
| allow_environment_change=args.allow_environment_change) | |
| print(json.dumps(result, sort_keys=True)) | |
| return 130 if result["status"] == "interrupted" else 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |