Download code/LOCAL_CHANGES.patch from fhyfhy/HRM-Text-checkpoints: direct link, hf CLI and curl.
- Browser
- Download file 36.1 kB
-
https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/LOCAL_CHANGES.patch
- Command line
-
hf download hf://fhyfhy/HRM-Text-checkpoints/code/LOCAL_CHANGES.patch
-
curl -L -o LOCAL_CHANGES.patch https://huggingface.co/fhyfhy/HRM-Text-checkpoints/resolve/main/code/LOCAL_CHANGES.patch
36.1 kB
| diff --git a/config/arch/net/ut.yaml b/config/arch/net/ut.yaml | |
| index 4f5c12c..4db10d7 100644 | |
| --- a/config/arch/net/ut.yaml | |
| +++ b/config/arch/net/ut.yaml | |
| head: lm_head@LMHead | |
| # UT config | |
| cycles: 4 | |
| -bp_cycles: 2 | |
| +bp_cycles: 2 # starting truncation (= fixed truncation when warmup off) | |
| + | |
| +# HRM-style warmup: ramp bp_cycles -> cycles (FULL backprop) over the first | |
| +# 20% of training steps (staircase 2->3->4). Set to 0.0 for the original | |
| +# upstream UT behavior (fixed bp_cycles forever). | |
| +bp_warmup_ratio: 0.2 | |
| diff --git a/dataset_new.py b/dataset_new.py | |
| index 7937931..51e5743 100644 | |
| --- a/dataset_new.py | |
| +++ b/dataset_new.py | |
| class V1DatasetConfig(pydantic.BaseModel): | |
| rank: int | |
| num_replicas: int | |
| + start_epoch: int = 0 # Resume: begin iteration at this epoch's index files | |
| + start_batch: int = 0 # Resume: skip this many batches of the FIRST iterated epoch | |
| + fixed_epoch: bool = False # Re-read the SAME epoch index files on every pass (eval loaders) | |
| + | |
| class V1DatasetMeta(pydantic.BaseModel): | |
| tokenizer_info: dict[str, Any] = {} | |
| class V1Dataset(IterableDataset): | |
| self._data: Optional[np.ndarray] = None | |
| self._data_indices: Optional[V1DatasetIndices] = None | |
| self._sampler: Optional[MultipackDistributedBatchSampler] = None | |
| - self._epoch = 0 | |
| + self._epoch = config.start_epoch | |
| + self._skip_batches = config.start_batch | |
| def _load_metadata(self) -> V1DatasetMeta: | |
| with open(os.path.join(self.config.dataset_path, "metadata.json"), "r") as f: | |
| class V1Dataset(IterableDataset): | |
| # Load indices | |
| self._data_indices = V1DatasetIndices(**{f.name: np.load(os.path.join(self.config.dataset_path, f"epoch_{self._epoch}", f"{f.name}.npy"), mmap_mode="r") | |
| for f in fields(V1DatasetIndices)}) | |
| - self._epoch += 1 | |
| + # A fixed-epoch dataset (held-out eval split) never advances: it can | |
| + # be iterated indefinitely and yields identical batches every pass | |
| + # (the sampler below is deterministic and RNG-free). | |
| + if not self.config.fixed_epoch: | |
| + self._epoch += 1 | |
| # Re-create sampler | |
| self._sampler = MultipackDistributedBatchSampler( | |
| class V1Dataset(IterableDataset): | |
| self._load_dataset_before_epoch_begin() | |
| + # Mid-epoch resume: replay (and discard) the first `skip` batches. The | |
| + # sampler is deterministic and RNG-free, so the remaining batches are | |
| + # bit-identical to an uninterrupted run. Replay only advances the LPT | |
| + # allocator; no token data is loaded. | |
| + skip = self._skip_batches | |
| + self._skip_batches = 0 | |
| + | |
| assert self._sampler is not None | |
| - for indices in self._sampler.iter(): | |
| + for i, indices in enumerate(self._sampler.iter()): | |
| + if i < skip: | |
| + continue | |
| yield self._load_batch(indices) | |
| diff --git a/evaluation/benchmarks.py b/evaluation/benchmarks.py | |
| index 5772412..3a4e971 100644 | |
| --- a/evaluation/benchmarks.py | |
| +++ b/evaluation/benchmarks.py | |
| class AIMEMajorityVoting(BaseBenchmark): | |
| metrics = {f"maj_pass@{k}": v / max(1, total) for k, v in maj_pass_k.items()} | |
| metrics |= {f"pass@{k}": v / max(1, total) for k, v in pass_k.items()} | |
| return result | metrics | |
| + | |
| + | |
| +# --- BIG-Bench-Hard --- | |
| + | |
| +class BBH(BaseBenchmark): | |
| + """BIG-Bench-Hard (github.com/suzgunmirac/BIG-Bench-Hard), 27 tasks. | |
| + | |
| + Default is ZERO-shot CoT, matching how GSM8k/MATH are scored here: the | |
| + model gets the bare (self-contained) question and the "synth,cot" | |
| + condition token does the work. The official 3-shot `Q:/A:` prompts are | |
| + available via num_shots>0, but this model family is trained on single-turn | |
| + [BOQ]...[EOQ]...[EOA] data and mostly emits EOA instead of continuing a | |
| + few-shot transcript, which measures format compliance rather than | |
| + reasoning (>90% of generations lack the "So the answer is" marker). | |
| + | |
| + Scored per task, then macro-averaged over the 27 tasks (the BBH protocol). | |
| + Answers are accepted as a boxed expression, an "answer is X" phrase, or the | |
| + last line; for multiple-choice tasks either the option letter or the option | |
| + text counts. | |
| + """ | |
| + DEFAULT_PATH = "/lustre/fsw/portfolios/nemotron/users/hengyuf/bbh" | |
| + _OPTION_RE = re.compile(r"^\((\w+)\)\s*(.+)$") | |
| + | |
| + def __init__(self, path: Optional[str] = None, num_shots: int = 0, tasks: Optional[list[str]] = None): | |
| + super().__init__() | |
| + import json as _json | |
| + import os as _os | |
| + | |
| + root = path or self.DEFAULT_PATH | |
| + assert 0 <= num_shots <= 3, "the official prompts provide at most 3 exemplars" | |
| + for fname in sorted(_os.listdir(_os.path.join(root, "bbh"))): | |
| + if not fname.endswith(".json"): | |
| + continue | |
| + task = fname[:-len(".json")] | |
| + if tasks is not None and task not in tasks: | |
| + continue | |
| + | |
| + preamble = "" | |
| + if num_shots > 0: | |
| + with open(_os.path.join(root, "cot-prompts", f"{task}.txt")) as f: | |
| + # Drop the canary header above the "-----" separator. | |
| + preamble = f.read().split("-----", 1)[-1].strip() | |
| + head, *shots = preamble.split("\n\nQ: ") | |
| + preamble = head + "".join(f"\n\nQ: {s}" for s in shots[:num_shots]) + "\n\n" | |
| + | |
| + with open(_os.path.join(root, "bbh", fname)) as f: | |
| + examples = _json.load(f)["examples"] | |
| + for ex in examples: | |
| + self.prompts.append(f"{preamble}Q: {ex['input']}\nA: Let's think step by step." if num_shots | |
| + else ex["input"]) | |
| + self.ground_truths.append({"task": task, "accept": self._accepted(ex)}) | |
| + | |
| + @classmethod | |
| + def _accepted(cls, ex: dict) -> set: | |
| + """Normalized strings that count as correct: the target, and for | |
| + multiple-choice questions the text of the gold option too.""" | |
| + accept = {cls._normalize(ex["target"])} | |
| + if "Options:" in ex["input"]: | |
| + for line in ex["input"].split("Options:", 1)[1].splitlines(): | |
| + m = cls._OPTION_RE.match(line.strip()) | |
| + if m and cls._normalize(f"({m.group(1)})") in accept: | |
| + accept.add(cls._normalize(m.group(2))) | |
| + return accept | |
| + | |
| + @property | |
| + def generation_overrides(self) -> dict: | |
| + return {"max_tokens": 512, "max_context": 4096} | |
| + | |
| + @classmethod | |
| + def _extract_answer(cls, text: str) -> tuple[str, bool]: | |
| + """Returns (answer, found_explicit_marker).""" | |
| + for stop in ("\nQ:", "\n\nQ:"): | |
| + idx = text.find(stop) | |
| + if idx > 0: | |
| + text = text[:idx] | |
| + boxed = last_boxed_only_string(text) | |
| + if boxed: | |
| + return boxed.strip(), True | |
| + m = re.search(r"answer is\s*[:\-]?\s*(.+)", text, flags=re.IGNORECASE | re.DOTALL) | |
| + if m: | |
| + return m.group(1).splitlines()[0].strip(), True | |
| + lines = [ln.strip() for ln in text.strip().splitlines() if ln.strip()] | |
| + return (lines[-1] if lines else ""), False | |
| + | |
| + @staticmethod | |
| + def _normalize(s: str) -> str: | |
| + """Strip the LaTeX/markdown dressing these models put around answers. | |
| + | |
| + They were pretrained on math data and box almost everything, so a | |
| + correct "No" routinely arrives as `\\boxed{\\text{No}}` or | |
| + `**Answer:** (D) foo`; without this, ~20% of correct answers are | |
| + scored wrong. | |
| + """ | |
| + s = s.strip() | |
| + s = re.sub(r"\*+", "", s) # **bold** | |
| + for _ in range(3): # nested \text{\bf{x}} | |
| + s = re.sub(r"\\(?:text|textbf|textrm|textit|mathrm|mathbf|mathit|operatorname)\s*\{([^{}]*)\}", | |
| + r"\1", s) | |
| + s = s.replace("\\(", "").replace("\\)", "").replace("\\,", " ").replace("$", "") | |
| + s = re.sub(r"^\s*(?:the\s+)?answer\s*(?:is|:)\s*", "", s, flags=re.IGNORECASE) | |
| + s = s.strip().strip("*").strip() | |
| + s = re.sub(r"[.\s]+$", "", s).lower() | |
| + m = re.fullmatch(r"\((\w+)\)", s) | |
| + return m.group(1) if m else s | |
| + | |
| + @classmethod | |
| + def _candidates(cls, answer: str) -> set: | |
| + """An answer may arrive as "(B)", "B", "B) text" or "(B) text"; accept | |
| + the letter and the trailing text as separate candidates.""" | |
| + base = cls._normalize(answer) | |
| + out = {base} | |
| + m = re.match(r"^\(?(\w)\)[.:]?\s*(.*)$", base) | |
| + if m: | |
| + out.add(m.group(1)) | |
| + if m.group(2): | |
| + out.add(cls._normalize(m.group(2))) | |
| + return out | |
| + | |
| + def compute_metrics(self, generations: list[str]) -> dict: | |
| + stats: dict[str, dict[str, Any]] = defaultdict(lambda: {"n": 0, "correct": 0.0, "invalid": 0}) | |
| + for text, gt in zip(generations, self.ground_truths): | |
| + answer, found = self._extract_answer(text) | |
| + st = stats[gt["task"]] | |
| + st["n"] += 1 | |
| + if not found: | |
| + st["invalid"] += 1 | |
| + if self._candidates(answer) & gt["accept"]: | |
| + st["correct"] += 1 | |
| + return compute_benchmark_micro_macro_avg(stats) | |
| diff --git a/evaluation/config/hrm_benchmarking.yaml b/evaluation/config/hrm_benchmarking.yaml | |
| index 66d766a..2f62ba4 100644 | |
| --- a/evaluation/config/hrm_benchmarking.yaml | |
| +++ b/evaluation/config/hrm_benchmarking.yaml | |
| benchmarks: | |
| - name: GSM8k | |
| - name: MATH | |
| + # Few-shot CoT (official BBH prompts; 27 tasks, macro-averaged) | |
| + - name: BBH | |
| + generation_config: | |
| + batch_size: 16 | |
| + | |
| # Few-shot freeform | |
| - name: DROP | |
| generation_config: | |
| diff --git a/evaluation/engines.py b/evaluation/engines.py | |
| index bbdb1a2..1a96522 100644 | |
| --- a/evaluation/engines.py | |
| +++ b/evaluation/engines.py | |
| from typing import Optional | |
| from tqdm import tqdm | |
| -from vllm import LLM, SamplingParams | |
| from simple_inference_engine import inference_load_checkpoint, inference_generate | |
| class BaseEngine: | |
| class VLLMEngine(BaseEngine): | |
| def __init__(self, ckpt_path: str, **kwargs): | |
| + # Lazy import: vllm is only needed for external-baseline evaluation, | |
| + # and the docker image's vllm build is broken (linked against CUDA 13's | |
| + # libcudart while the image ships CUDA 12.8). Keep SimpleEngine usable. | |
| + from vllm import LLM | |
| self.llm = LLM(model=ckpt_path, **kwargs) | |
| def generate(self, prompts: list[str], temperature: float = 0.0, max_tokens: Optional[int] = None, stop: Optional[str | list[str]] = None) -> list[str]: | |
| + from vllm import SamplingParams | |
| outputs = self.llm.generate(prompts, SamplingParams( | |
| temperature=temperature, | |
| max_tokens=max_tokens, | |
| diff --git a/models/baselines/hrm_nocarry_bp_warmup.py b/models/baselines/hrm_nocarry_bp_warmup.py | |
| index b6c098f..2272f58 100644 | |
| --- a/models/baselines/hrm_nocarry_bp_warmup.py | |
| +++ b/models/baselines/hrm_nocarry_bp_warmup.py | |
| -from typing import Tuple, Dict, Any, Optional | |
| +from typing import Tuple, Dict, Any, List, Optional | |
| import torch | |
| from torch import nn | |
| class HierarchicalReasoningModelConfig(TransformerConfig): | |
| bp_warmup_ratio: float = 0.0 | |
| bp_min_steps: int = 2 | |
| bp_max_steps: int = 5 | |
| + # Explicit warmup schedule of bp_steps values (overrides the min->max | |
| + # ramp when set): the LAST value activates exactly at the end of the | |
| + # warmup window and holds for the rest of training; the earlier values | |
| + # evenly split the window. E.g. [2, 3, 4, 5, 8] keeps the original 2->5 | |
| + # phases (each a bit shorter) and appends a terminal FULL-backprop phase | |
| + # (full = H_cycles + H_cycles*L_cycles = 8 for the 2x3 configuration). | |
| + bp_schedule: Optional[List[int]] = None | |
| # Change some Transformer config of H-level | |
| # TODO: Try asymmetric H and L module, such as different size, hidden dims, architecture, attention type, etc. | |
| class HierarchicalReasoningModel(nn.Module): | |
| self.bp_warmup_ratio = config.bp_warmup_ratio | |
| self.bp_min_steps = config.bp_min_steps | |
| self.bp_max_steps = config.bp_max_steps | |
| + self.bp_schedule = config.bp_schedule | |
| self.hidden_size = config.hidden_size | |
| self.head_hint = self.H_level.core.head_hint # Hint for LMHead init (inherit from H) | |
| class HierarchicalReasoningModel(nn.Module): | |
| warmup_steps = train_state.total_steps * self.bp_warmup_ratio | |
| progress = min(1.0, train_state.step / warmup_steps) if warmup_steps > 0 else 1.0 | |
| + if self.bp_schedule is not None: | |
| + # Phase i covers progress [i, i+1) / (N-1); reduces exactly to the | |
| + # legacy ramp when the schedule is consecutive ints (e.g. [2,3,4,5]). | |
| + idx = min(len(self.bp_schedule) - 1, int(progress * (len(self.bp_schedule) - 1))) | |
| + return dict(bp_steps=self.bp_schedule[idx]) | |
| return dict(bp_steps=self.bp_min_steps + int(progress * (self.bp_max_steps - self.bp_min_steps))) | |
| def initial_carry(self, batch_size: int, dtype: torch.dtype) -> None: | |
| diff --git a/models/baselines/ut_nocarry.py b/models/baselines/ut_nocarry.py | |
| index 25fd24f..1bc6858 100644 | |
| --- a/models/baselines/ut_nocarry.py | |
| +++ b/models/baselines/ut_nocarry.py | |
| class UniversalTransformerConfig(TransformerConfig): | |
| cycles: int | |
| bp_cycles: int | |
| + # HRM-style BP warmup (default 0.0 = off, exact original behavior): | |
| + # when > 0, backprop truncation ramps from bp_cycles up to FULL backprop | |
| + # (all `cycles`) over the first bp_warmup_ratio fraction of total steps. | |
| + bp_warmup_ratio: float = 0.0 | |
| + | |
| class UniversalTransformer(nn.Module): | |
| def __init__(self, config_dict: dict) -> None: | |
| class UniversalTransformer(nn.Module): | |
| # Config | |
| self.cycles = config.cycles | |
| self.bp_cycles = config.bp_cycles | |
| + self.bp_warmup_ratio = config.bp_warmup_ratio | |
| self.head_hint = self.L_level.core.head_hint # Hint for LMHead init (inherit from H) | |
| class UniversalTransformer(nn.Module): | |
| # Create cache function | |
| self.create_cache = lambda **kwargs: [self.L_level.create_cache(**kwargs) for _i in range(self.cycles)] | |
| - def forward(self, carry: None, x: Tensor, cache: Optional[list[list[Cache]]] = None, **seq_info) -> tuple[None, Tensor]: | |
| + def forward(self, carry: None, x: Tensor, cache: Optional[list[list[Cache]]] = None, bp_cycles: Optional[int] = None, **seq_info) -> tuple[None, Tensor]: | |
| + if bp_cycles is None: | |
| + bp_cycles = self.bp_cycles | |
| z = self.zL_init | |
| for i in range(self.cycles): | |
| - with (nullcontext if i >= self.cycles - self.bp_cycles else torch.no_grad)(): | |
| + with (nullcontext if i >= self.cycles - bp_cycles else torch.no_grad)(): | |
| z = self.L_level(z, x, cache=cache[i] if cache is not None else None, **seq_info) | |
| return None, z | |
| def compute_train_extra_args(self, train_state): | |
| - return {} | |
| + if self.bp_warmup_ratio <= 0.0: | |
| + return {} # original fixed-truncation behavior | |
| + warmup_steps = train_state.total_steps * self.bp_warmup_ratio | |
| + progress = min(1.0, train_state.step / warmup_steps) if warmup_steps > 0 else 1.0 | |
| + return dict(bp_cycles=self.bp_cycles + int(progress * (self.cycles - self.bp_cycles))) | |
| def initial_carry(self, batch_size: int, dtype: torch.dtype) -> None: | |
| return None | |
| diff --git a/models/lm_head.py b/models/lm_head.py | |
| index c980d35..ccd6e28 100644 | |
| --- a/models/lm_head.py | |
| +++ b/models/lm_head.py | |
| class LMHead(nn.Module): | |
| self.embed_tokens = ScaledEmbeddingInit(config.vocab_size, head_hint["in"]["dim"], init_std=head_hint["in"]["init_std"]) # pyright: ignore[reportArgumentType] | |
| self.lm_head = LinearInit(head_hint["out"]["dim"], config.vocab_size, bias=False, init_std=head_hint["out"]["init_std"]) # pyright: ignore[reportArgumentType] | |
| + # Models with a vocab-decode channel (e.g. loop_cot) receive the | |
| + # readout/write-back matrices as forward kwargs (traceable under | |
| + # fullgraph compile, and always the live FSDP-unsharded parameters). | |
| + self._pass_decode_weights = getattr(self.model, "wants_decode_embeddings", False) | |
| + | |
| def forward(self, carry: Carry, batch: dict[str, Tensor], **kwargs) -> Tuple[Carry, Tensor] | Tuple[Carry, Tensor, dict[str, Tuple[Tensor, Tensor]]]: | |
| # Token embedding | |
| input_embedding = self.embed_tokens(batch["inputs"]) | |
| # Model forward | |
| + if self._pass_decode_weights: | |
| + kwargs = kwargs | {"decode_embed_weight": self.embed_tokens.embedding_weight, | |
| + "decode_embed_scale": self.embed_tokens.scale, | |
| + "decode_lm_head_weight": self.lm_head.weight} | |
| new_carry, logits = self.model(carry, | |
| input_embedding, | |
| **{k: v for k, v in batch.items() if k not in ("inputs", "labels")}, | |
| diff --git a/pretrain.py b/pretrain.py | |
| index 7496fe2..9e4e104 100644 | |
| --- a/pretrain.py | |
| +++ b/pretrain.py | |
| from typing import Optional | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from glob import glob | |
| +from types import SimpleNamespace | |
| +import json | |
| import math | |
| import os | |
| +import time | |
| import yaml | |
| import shutil | |
| class PretrainConfig(pydantic.BaseModel): | |
| resume_from: Optional[str] = None | |
| resume_epoch: Optional[int] = None | |
| weights_only_resume_from_ema: bool = False # Swap EMA into model + reset optim | |
| + # True mid-run continuation: restore step counter (LR schedule continues), | |
| + # skip completed data, restore per-rank carry. Epoch granularity by | |
| + # default; pass resume_step to continue from a mid-epoch step checkpoint. | |
| + # Requires the SAME world size as the original run. | |
| + resume_continue: bool = False | |
| + resume_step: Optional[int] = None # resume from fsdp2_step_<S> (requires resume_continue) | |
| + | |
| + # Save a rolling mid-epoch checkpoint (fsdp2_step_<S>) every N steps; only | |
| + # the newest is kept, and all are pruned once an epoch checkpoint lands. | |
| + # Enables making progress through wall-time limits shorter than an epoch. | |
| + checkpoint_step_interval: Optional[int] = None | |
| + | |
| + # In-training held-out eval: every eval_interval steps, run the full eval | |
| + # split (eval_data_path) on the LIVE raw weights and log eval/* metrics to | |
| + # the training wandb run. The split is iterated with fixed_epoch=True so | |
| + # every pass sees bit-identical batches (comparable across steps). | |
| + eval_data_path: Optional[str] = None | |
| + eval_interval: Optional[int] = None | |
| # Extras | |
| seed: int = 0 | |
| class TrainState: | |
| total_steps: int | |
| -def create_dataloader(config: PretrainConfig, local_batch_size: int, drop_last_batch: bool, rank: int, world_size: int): | |
| +def create_dataloader(config: PretrainConfig, local_batch_size: int, drop_last_batch: bool, rank: int, world_size: int, start_epoch: int = 0, start_batch: int = 0, fixed_epoch: bool = False): | |
| dataset = V1Dataset(V1DatasetConfig( | |
| seed=config.seed, | |
| def create_dataloader(config: PretrainConfig, local_batch_size: int, drop_last_b | |
| batch_max_length=local_batch_size, | |
| rank=rank, | |
| num_replicas=world_size, | |
| + | |
| + start_epoch=start_epoch, | |
| + start_batch=start_batch, | |
| + fixed_epoch=fixed_epoch, | |
| )) | |
| dataloader = DataLoader( | |
| dataset, | |
| def create_model_and_carry(config: PretrainConfig, train_metadata: V1DatasetMeta | |
| return model, carry, optim | |
| +def resolve_resume_epoch(config: PretrainConfig) -> int: | |
| + """Epoch number of the checkpoint to resume from (explicit or latest).""" | |
| + assert config.resume_from is not None | |
| + if config.resume_epoch is not None: | |
| + return config.resume_epoch | |
| + ckpt_files = glob(os.path.join(config.resume_from, "fsdp2_epoch_*")) | |
| + if not ckpt_files: | |
| + raise FileNotFoundError(f"No checkpoint found in {config.resume_from}") | |
| + return max(int(Path(f).stem.split("_")[-1]) for f in ckpt_files) | |
| + | |
| + | |
| +def load_step_state(config: PretrainConfig) -> dict: | |
| + """Position record written alongside a fsdp2_step_<S> checkpoint.""" | |
| + assert config.resume_from is not None and config.resume_step is not None | |
| + with open(os.path.join(config.resume_from, f"train_state_step_{config.resume_step}.json"), "rt") as f: | |
| + return json.load(f) | |
| + | |
| + | |
| +def resolve_resume_position(config: PretrainConfig) -> tuple[int, int]: | |
| + """(completed_epochs, batches_done_in_current_epoch) to resume at.""" | |
| + if not config.resume_continue: | |
| + return 0, 0 | |
| + assert config.resume_from is not None, "resume_continue requires resume_from" | |
| + if config.resume_step is not None: | |
| + ss = load_step_state(config) | |
| + return ss["epoch"] - 1, ss["batch_in_epoch"] | |
| + return resolve_resume_epoch(config), 0 | |
| + | |
| + | |
| def init_train(config: PretrainConfig, rank: int, world_size: int): | |
| assert config.global_batch_size % world_size == 0, f"Global batch size {config.global_batch_size} must be divisible by world size {world_size}." | |
| local_batch_size = config.global_batch_size // world_size | |
| + # Continuation: begin data iteration at the first uncompleted position | |
| + start_epoch, start_batch = resolve_resume_position(config) | |
| + | |
| # Dataset | |
| - train_loader, train_metadata = create_dataloader(config, local_batch_size, drop_last_batch=True, rank=rank, world_size=world_size) | |
| + train_loader, train_metadata = create_dataloader(config, local_batch_size, drop_last_batch=True, rank=rank, world_size=world_size, start_epoch=start_epoch, start_batch=start_batch) | |
| # Model | |
| model, carry, optim = create_model_and_carry(config, train_metadata, local_batch_size) | |
| def train_batch(train_state: TrainState, batch: dict[str, Tensor], **kwargs): | |
| return metrics | |
| +@torch.no_grad() | |
| +def evaluate_inline(train_state: TrainState, eval_loader: DataLoader, eval_carry, world_size: int) -> dict: | |
| + """Held-out eval on the CURRENT raw weights, mid-training. | |
| + | |
| + Mirrors slurm/eval_loss.py::evaluate — eager forwards (uncompiled), fresh | |
| + carry, token-weighted global mean via summed numerators/denominators — | |
| + but needs NO reshard(): unlike eval_loss.py (which swaps weights under | |
| + FSDP2's unsharded-param cache), here the cache IS the live weights. The | |
| + multipack sampler yields the same batch count on every rank, so the | |
| + all_reduce inside LMHead.forward stays collective-safe. | |
| + """ | |
| + model = train_state.model | |
| + model.eval() | |
| + # Terminal-schedule extra args (e.g. final bp_steps); grads are off anyway. | |
| + extra_args = model.compute_train_extra_args(SimpleNamespace(step=1 << 30, total_steps=1 << 30)) # pyright: ignore[reportCallIssue] | |
| + | |
| + t0 = time.time() | |
| + agg: dict = {} | |
| + carry = eval_carry | |
| + for batch, batch_info in eval_loader: | |
| + batch = batch | {k: wrap_tensor(torch.tensor(v, device="cpu")) for k, v in batch_info.items()} | |
| + carry, _loss, metrics = model(batch=batch, carry=carry, **extra_args) | |
| + for k, (num, den) in metrics.items(): | |
| + if k not in agg: | |
| + agg[k] = [num.double().clone(), den.double().clone()] | |
| + else: | |
| + agg[k][0] += num.double() | |
| + agg[k][1] += den.double() | |
| + keys = sorted(agg.keys()) | |
| + flat = torch.stack([agg[k][0] for k in keys] + [agg[k][1] for k in keys]) | |
| + dist.all_reduce(flat) | |
| + nums, dens = flat.chunk(2) | |
| + results = {f"eval/{k}": (nums[i] / dens[i]).item() for i, k in enumerate(keys)} | |
| + results["eval/seconds"] = time.time() - t0 | |
| + | |
| + model.train() | |
| + return results | |
| + | |
| + | |
| @torch.inference_mode() | |
| def reduce_metrics(local_metrics: dict[str, Tensor], prefix: str): | |
| metric_keys = list(sorted(local_metrics.keys())) # Sort keys to guarantee all processes use the same order. | |
| def reduce_metrics(local_metrics: dict[str, Tensor], prefix: str): | |
| return {prefix + name: metrics[idx] for idx, name in enumerate(metric_keys)} | |
| -def load_checkpoint(config: PretrainConfig, train_state: TrainState): | |
| +def load_checkpoint(config: PretrainConfig, train_state: TrainState, train_metadata: V1DatasetMeta, rank: int): | |
| """Resume from a saved checkpoint. | |
| Loads both model weights and optimizer state (which carries EMA in | |
| AdamATan2). When weights_only_resume_from_ema=True, swaps the EMA buffer | |
| into the model and resets the optimizer state — typical for fine-tuning | |
| off a pretrain run with EMA-smoothed weights. | |
| + | |
| + When resume_continue=True, additionally restores the step counter (so the | |
| + LR schedule continues instead of restarting) and the per-rank carry. | |
| """ | |
| if config.resume_from is None: | |
| return | |
| - epoch = config.resume_epoch | |
| - if epoch is None: | |
| - ckpt_files = glob(os.path.join(config.resume_from, "fsdp2_epoch_*")) | |
| - if not ckpt_files: | |
| - raise FileNotFoundError(f"No checkpoint found in {config.resume_from}") | |
| - epoch = max(int(Path(f).stem.split("_")[-1]) for f in ckpt_files) | |
| - | |
| - checkpoint_id = os.path.join(config.resume_from, f"fsdp2_epoch_{epoch}") | |
| + if config.resume_step is not None: | |
| + assert config.resume_continue, "resume_step requires resume_continue" | |
| + checkpoint_id = os.path.join(config.resume_from, f"fsdp2_step_{config.resume_step}") | |
| + else: | |
| + epoch = resolve_resume_epoch(config) | |
| + checkpoint_id = os.path.join(config.resume_from, f"fsdp2_epoch_{epoch}") | |
| print(f"[Resume] Loading model + optimizer from {checkpoint_id}") | |
| optim_state = get_optimizer_state_dict(train_state.model, train_state.optim) | |
| dcp.load( | |
| def load_checkpoint(config: PretrainConfig, train_state: TrainState): | |
| train_state.optim.swap_ema() | |
| train_state.optim._init_state() | |
| + if config.resume_continue: | |
| + assert not config.weights_only_resume_from_ema, "resume_continue keeps the optimizer; incompatible with weights_only_resume_from_ema" | |
| + if config.resume_step is not None: | |
| + train_state.step = load_step_state(config)["step"] | |
| + carry_file = os.path.join(config.resume_from, f"carry_step_{config.resume_step}.{rank}.pt") | |
| + print(f"[Resume] Continuing mid-epoch at step {train_state.step}") | |
| + else: | |
| + # Step counter: exact value if the checkpoint recorded it (new runs | |
| + # do), otherwise estimate from the per-epoch step count. | |
| + state_file = os.path.join(config.resume_from, f"train_state_epoch_{epoch}.json") | |
| + if os.path.exists(state_file): | |
| + with open(state_file, "rt") as f: | |
| + train_state.step = json.load(f)["step"] | |
| + print(f"[Resume] Continuing at step {train_state.step} (recorded)") | |
| + else: | |
| + train_state.step = int(epoch * (train_metadata.total_length // config.global_batch_size)) | |
| + print(f"[Resume] Continuing at step {train_state.step} (estimated)") | |
| + carry_file = os.path.join(config.resume_from, f"carry_epoch_{epoch}.{rank}.pt") | |
| + # Per-rank carry (requires same world size as the original run) | |
| + if os.path.exists(carry_file): | |
| + train_state.carry = torch.load(carry_file, map_location="cuda", weights_only=False) | |
| + print(f"[Resume] Restored carry from {carry_file}") | |
| + else: | |
| + print(f"[Resume] WARNING: no carry file {carry_file}; using fresh initial carry") | |
| + | |
| print(f"[Resume] Done.") | |
| +def prune_step_checkpoints(config: PretrainConfig, keep_step: Optional[int]): | |
| + """Remove step-checkpoint artifacts older than keep_step (all if None).""" | |
| + for f in glob(os.path.join(config.checkpoint_path, "fsdp2_step_*")) + \ | |
| + glob(os.path.join(config.checkpoint_path, "carry_step_*.pt")) + \ | |
| + glob(os.path.join(config.checkpoint_path, "train_state_step_*.json")): | |
| + s = int(Path(f).stem.split("_")[-1].split(".")[0]) | |
| + if keep_step is None or s < keep_step: | |
| + shutil.rmtree(f) if os.path.isdir(f) else os.remove(f) | |
| + | |
| + | |
| +def save_step_checkpoint(config: PretrainConfig, train_state: TrainState, epoch: int, batch_in_epoch: int, rank: int, world_size: int): | |
| + s = train_state.step | |
| + dcp.save({"model": train_state.model.state_dict(), "optim": get_optimizer_state_dict(train_state.model, train_state.optim)}, # pyright: ignore[reportPrivateImportUsage] | |
| + checkpoint_id=os.path.join(config.checkpoint_path, f"fsdp2_step_{s}")) | |
| + torch.save(train_state.carry, os.path.join(config.checkpoint_path, f"carry_step_{s}.{rank}.pt")) | |
| + if rank == 0: | |
| + with open(os.path.join(config.checkpoint_path, f"train_state_step_{s}.json"), "wt") as f: | |
| + json.dump({"step": s, "epoch": epoch, "batch_in_epoch": batch_in_epoch, "world_size": world_size}, f) | |
| + dist.barrier() # everyone finished writing before pruning older ones | |
| + if rank == 0: | |
| + prune_step_checkpoints(config, keep_step=s) | |
| + | |
| + | |
| def save_code_and_config(config: PretrainConfig, train_metadata: V1DatasetMeta): | |
| if config.checkpoint_path is None or wandb.run is None: | |
| return | |
| def save_code_and_config(config: PretrainConfig, train_metadata: V1DatasetMeta): | |
| with open(os.path.join(config.checkpoint_path, "train_metadata.yaml"), "wt") as f: | |
| yaml.dump(train_metadata.model_dump(), f) | |
| - # Log code | |
| - wandb.run.log_code(config.checkpoint_path) | |
| + # Log code (best-effort: artifact staging writes to wandb's data dir, | |
| + # which can be a full/tiny node-local disk — never kill training over it) | |
| + try: | |
| + wandb.run.log_code(config.checkpoint_path) | |
| + except OSError as exc: | |
| + print(f"[W&B] log_code failed ({exc}); continuing without code artifact") | |
| def load_synced_config(hydra_config: DictConfig, rank: int) -> PretrainConfig: | |
| def launch(hydra_config: DictConfig): | |
| # --- Training | |
| train_state, train_loader, train_metadata = init_train(config, rank=RANK, world_size=WORLD_SIZE) | |
| - load_checkpoint(config, train_state) | |
| + load_checkpoint(config, train_state, train_metadata, RANK) | |
| + | |
| + start_epoch, start_batch = resolve_resume_position(config) | |
| + | |
| + # --- In-training held-out eval (optional) | |
| + eval_loader = None | |
| + eval_carry = None | |
| + if config.eval_interval is not None and config.eval_data_path is not None: | |
| + local_batch_size = config.global_batch_size // WORLD_SIZE | |
| + eval_cfg = config.model_copy(update={"data": config.data.model_copy(update={"path": config.eval_data_path})}) | |
| + eval_loader, eval_metadata = create_dataloader(eval_cfg, local_batch_size, drop_last_batch=False, | |
| + rank=RANK, world_size=WORLD_SIZE, fixed_epoch=True) | |
| + with torch.device("cuda"): | |
| + eval_carry = train_state.model.model.initial_carry(local_batch_size, dtype=getattr(torch, config.fwd_bwd_dtype)) # pyright: ignore[reportCallIssue] | |
| + if RANK == 0: | |
| + print(f"[Eval] every {config.eval_interval} steps on {eval_metadata.total_length:,} tokens from {config.eval_data_path}") | |
| # Progress bar and logger | |
| progress_bar = None | |
| def launch(hydra_config: DictConfig): | |
| save_code_and_config(config, train_metadata) | |
| # Training Loop | |
| - for epoch in range(1, config.epochs + 1): | |
| + # epoch_base = global step count at the start of the current epoch, so | |
| + # (step - epoch_base) is the batch offset inside it (used by mid-epoch | |
| + # checkpoints). When resuming mid-epoch, the already-done batches count. | |
| + pending_start_batch = start_batch | |
| + for epoch in range(start_epoch + 1, config.epochs + 1): | |
| print (f"[Rank {RANK}, World Size {WORLD_SIZE}]: Epoch {epoch}") | |
| + epoch_base = train_state.step - pending_start_batch | |
| + pending_start_batch = 0 | |
| # ############ Train Iter | |
| train_state.model.train() | |
| for batch, batch_info in train_loader: | |
| - train_state.step += 1 | |
| + train_state.step += 1 | |
| lr = update_lr(config, train_state) | |
| # Extra train arguments (such as BP warmup etc.) | |
| train_extra_args = train_state.model.compute_train_extra_args(train_state) # pyright: ignore[reportCallIssue] | |
| - | |
| + | |
| metrics = train_batch(train_state, batch | {k: wrap_tensor(torch.tensor(v, device="cpu")) for k, v in batch_info.items()}, **train_extra_args) | |
| if train_state.step % config.log_interval == 0: | |
| def launch(hydra_config: DictConfig): | |
| del metrics | |
| + # Periodic held-out eval on the live weights -> same wandb run | |
| + if eval_loader is not None and train_state.step % config.eval_interval == 0: | |
| + eval_metrics = evaluate_inline(train_state, eval_loader, eval_carry, WORLD_SIZE) | |
| + if RANK == 0: | |
| + print(f"[Eval @ step {train_state.step}] " + " ".join(f"{k.split('/')[-1]}={v:.4f}" for k, v in eval_metrics.items()), flush=True) | |
| + wandb.log(eval_metrics, step=train_state.step) | |
| + | |
| + # Rolling mid-epoch checkpoint | |
| + if (config.checkpoint_step_interval is not None and config.checkpoint_path is not None | |
| + and train_state.step % config.checkpoint_step_interval == 0): | |
| + save_step_checkpoint(config, train_state, epoch, train_state.step - epoch_base, RANK, WORLD_SIZE) | |
| + | |
| ############ EVAL STACK: TBD TODO | |
| ############ Checkpointing | |
| def launch(hydra_config: DictConfig): | |
| checkpoint_id=os.path.join(config.checkpoint_path, f"fsdp2_epoch_{epoch}")) | |
| # Save carry on all ranks | |
| torch.save(train_state.carry, os.path.join(config.checkpoint_path, f"carry_epoch_{epoch}.{RANK}.pt")) | |
| + # Record step counter for exact continuation (resume_continue) | |
| + if RANK == 0: | |
| + with open(os.path.join(config.checkpoint_path, f"train_state_epoch_{epoch}.json"), "wt") as f: | |
| + json.dump({"step": train_state.step, "world_size": WORLD_SIZE}, f) | |
| + # Mid-epoch checkpoints are superseded by this epoch checkpoint | |
| + prune_step_checkpoints(config, keep_step=None) | |
| # finalize | |
| if dist.is_initialized(): | |
| diff --git a/simple_inference_engine.py b/simple_inference_engine.py | |
| index 8bd2031..6c78450 100644 | |
| --- a/simple_inference_engine.py | |
| +++ b/simple_inference_engine.py | |
| def inference_load_checkpoint(ckpt_path: str, ckpt_epoch: Optional[int], ckpt_us | |
| model = model.to(getattr(torch, model_cfg.fwd_bwd_dtype)).eval() | |
| # Load tokenizer | |
| - tokenizer = AutoTokenizer.from_pretrained(train_metadata.tokenizer_info["tokenizer_path"], use_fast=True) | |
| + # tokenizer_info records the path passed to the tokenization tool, which | |
| + # may be the tokenizer.json FILE itself; AutoTokenizer only accepts a | |
| + # directory (or hub repo id), so point it at the containing directory. | |
| + tokenizer_path = train_metadata.tokenizer_info["tokenizer_path"] | |
| + if os.path.isfile(tokenizer_path): | |
| + tokenizer_path = os.path.dirname(tokenizer_path) | |
| + tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, use_fast=True) | |
| return InferenceCheckpoint( | |
| model=model, | |
| carry=carry, | |