A straightforward method for training your LLM, from downloading data to generating text.
fix(checkpoints): load models trained with torch.compile (fixes #36)
FareedKhan-devfec184841447
diff --git a/scripts/eval_post_training.py b/scripts/eval_post_training.pyindex c906562..6a76662 100644--- a/scripts/eval_post_training.py+++ b/scripts/eval_post_training.py@@ -21,25 +21,11 @@ import osimport torch-from src.models.transformer import Transformerfrom src.post_training.evaluation import gsm8k_accuracy, load_gsm8k_eval+from src.post_training.inference import load_model_from_ckpt--def model_from_ckpt(ckpt_path: str, device: str, overrides: dict | None = None) -> Transformer:- ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)- cfg = ck.get("cfg", {}) or {}- cfg = {**cfg, **(overrides or {})}- model = Transformer(- n_head=cfg.get("n_head", 16), n_embed=cfg.get("n_embed", 1024),- context_length=cfg.get("context_length", 1024), vocab_size=cfg.get("vocab_size", 50304),- N_BLOCKS=cfg.get("n_blocks", 24),- )- state = ck["model_state_dict"] if "model_state_dict" in ck else ck- state = {k.removeprefix("module.").removeprefix("transformer."): v for k, v in state.items()}- backbone_keys = set(model.state_dict().keys())- filtered = {k: v for k, v in state.items() if k in backbone_keys}- model.load_state_dict(filtered, strict=False)- return model.to(device).eval()+# Kept so older notebooks that imported this name keep working.+model_from_ckpt = load_model_from_ckptdef print_table(path: str):@@ -67,7 +53,7 @@ def main():print_table(args.table)return- model = model_from_ckpt(args.ckpt, args.device)+ model = load_model_from_ckpt(args.ckpt, args.device)qa = load_gsm8k_eval(args.split, limit=args.limit)res = gsm8k_accuracy(model, qa, device=args.device, max_new_tokens=args.max_new_tokens,greedy=True, return_samples=args.samples)diff --git a/scripts/pretrain_base.py b/scripts/pretrain_base.pyindex d132694..51e3eb4 100644--- a/scripts/pretrain_base.py+++ b/scripts/pretrain_base.py@@ -17,14 +17,16 @@ Override any config field from the CLI, e.g. ``--batch_size 16 --train_steps 500from __future__ import annotations+import contextlibimport osimport time+from dataclasses import asdict-import numpy as npimport torchfrom config.post_training_config import PretrainConfigfrom data_loader.data_loader import get_batch_iterator+from src.checkpoint import load_checkpoint, model_state_from_checkpointfrom src.post_training.cli import parse_config_with_jsonfrom src.post_training.distributed import ddp_setup, ddp_wrap, cleanup, reduce_scalarfrom src.post_training.logging_utils import MetricsLogger@@ -64,22 +66,24 @@ def main():model = build_model_from_config(cfg).to(ctx.device)start_step = 0+ ck = Noneif resume and os.path.exists(resume):- ck = torch.load(resume, map_location="cpu", weights_only=False)- unwrap(model).load_state_dict(ck["model_state_dict"])- start_step = ck.get("step", 0)+ ck = load_checkpoint(resume, map_location="cpu")+ # Strip DDP / torch.compile prefixes so checkpoints from older runs load too (issue #36).+ model.load_state_dict(model_state_from_checkpoint(ck))+ # The saved step already finished its optimizer update, so continue with the next one.+ start_step = int(ck.get("step", -1)) + 1if ctx.is_main:- print(f"Resumed from {resume} at step {start_step}")+ print(f"Resumed from {resume}, continuing at step {start_step}")if cfg.compile:model = torch.compile(model)model = ddp_wrap(model, ctx)optimizer = configure_optimizer(unwrap(model), cfg.lr, cfg.weight_decay)- if resume and os.path.exists(resume):- ck = torch.load(resume, map_location="cpu", weights_only=False)- if ck.get("optimizer_state_dict"):- optimizer.load_state_dict(ck["optimizer_state_dict"])+ if ck is not None and ck.get("optimizer_state_dict"):+ optimizer.load_state_dict(ck["optimizer_state_dict"])+ del cklogger = Noneif ctx.is_main:@@ -88,7 +92,7 @@ def main():print(f"Effective batch = {cfg.batch_size}*{cfg.grad_accum}*{ctx.world_size} "f"= {cfg.batch_size*cfg.grad_accum*ctx.world_size} seqs/step")logger = MetricsLogger("pretrain", cfg.log_dir, use_wandb=cfg.use_wandb,- wandb_project=cfg.wandb_project, config=vars(cfg).copy() if hasattr(cfg, "__dict__") else None)+ wandb_project=cfg.wandb_project, config=asdict(cfg))batch_iter = get_batch_iterator(cfg.train_path, cfg.batch_size, cfg.context_length, device=ctx.device)tokens_per_step = cfg.batch_size * cfg.context_length * cfg.grad_accum * ctx.world_size@@ -107,7 +111,7 @@ def main():xb, yb = next(batch_iter)# Only sync grads on the last micro-step (DDP optimization).sync = (micro == cfg.grad_accum - 1) or not ctx.enabled- cm = model.no_sync() if (ctx.enabled and not sync) else _nullcm()+ cm = model.no_sync() if (ctx.enabled and not sync) else contextlib.nullcontext()with cm, amp_autocast(cfg.amp_dtype, ctx.device):_, loss = model(xb, yb)loss = loss / cfg.grad_accum@@ -147,12 +151,5 @@ def main():cleanup(ctx)-import contextlib---def _nullcm():- return contextlib.nullcontext()--if __name__ == "__main__":main()diff --git a/scripts/train_transformer.py b/scripts/train_transformer.pyindex 6b92a34..6006076 100644--- a/scripts/train_transformer.py+++ b/scripts/train_transformer.py@@ -19,6 +19,7 @@ if str(ROOT_DIR) not in sys.path:sys.path.insert(0, str(ROOT_DIR))from config.config import default_config as config+from src.checkpoint import model_state_from_checkpointfrom src.models.transformer import Transformer@@ -241,7 +242,8 @@ def restore_training_checkpoint(is treated as the number of completed optimizer steps."""checkpoint = load_checkpoint_file(path, device)- model.load_state_dict(checkpoint['model_state_dict'])+ # Strip DDP / torch.compile key prefixes so checkpoints saved from a wrapped model load too.+ model.load_state_dict(model_state_from_checkpoint(checkpoint))optimizer_state = checkpoint.get('optimizer_state_dict')if optimizer_state:diff --git a/src/checkpoint.py b/src/checkpoint.pynew file mode 100644index 0000000..f2e804a--- /dev/null+++ b/src/checkpoint.py@@ -0,0 +1,135 @@+"""+Checkpoint helpers shared by every training and inference script.++A model is often wrapped before training: ``DistributedDataParallel`` stores it under+``.module`` and ``torch.compile`` stores it under ``._orig_mod``. Calling ``state_dict()`` on a+wrapper bakes those names into every key (``module._orig_mod.attn_blocks.0...``), and a bare+model then fails to load the file. The two helpers below solve this from both sides:++- :func:`unwrap_model` returns the plain module, so checkpoints are saved with clean keys.+- :func:`strip_wrapper_prefixes` cleans keys of checkpoints that were saved from a wrapper,+ so older files still load.+"""++from __future__ import annotations++import os+import tempfile+from collections.abc import Mapping+from typing import Any, TypeVar++import torch+import torch.nn as nn++V = TypeVar("V")++# Prefixes added by DistributedDataParallel / DataParallel and by torch.compile.+WRAPPER_PREFIXES: tuple[str, ...] = ("module.", "_orig_mod.")+++def unwrap_model(model: nn.Module) -> nn.Module:+ """Return the plain module behind any mix of DDP / DataParallel / torch.compile wrappers."""+ while True:+ inner = getattr(model, "_orig_mod", None) # torch.compile's OptimizedModule+ if isinstance(inner, nn.Module):+ model = inner+ continue+ if isinstance(model, (nn.parallel.DistributedDataParallel, nn.DataParallel)):+ model = model.module+ continue+ return model+++def strip_wrapper_prefixes(+ state_dict: Mapping[str, V], extra_prefixes: tuple[str, ...] = ()+) -> dict[str, V]:+ """+ Remove leading wrapper prefixes from every key, in any order and any nesting depth.++ ``module._orig_mod.lm_head.weight`` and ``_orig_mod.module.lm_head.weight`` both become+ ``lm_head.weight``. Pass ``extra_prefixes`` to strip more, for example ``("transformer.",)``+ to read the backbone out of a reward-model checkpoint.+ """+ prefixes = WRAPPER_PREFIXES + tuple(extra_prefixes)+ cleaned: dict[str, V] = {}+ for key, value in state_dict.items():+ changed = True+ while changed:+ changed = False+ for prefix in prefixes:+ if key.startswith(prefix):+ key = key[len(prefix):]+ changed = True+ cleaned[key] = value+ return cleaned+++def load_checkpoint(path: str | os.PathLike[str], map_location: Any = "cpu") -> dict[str, Any]:+ """Load a checkpoint dict on any PyTorch version (our files hold metadata, not just tensors)."""+ try:+ return torch.load(path, map_location=map_location, weights_only=False)+ except TypeError: # PyTorch < 1.13 has no weights_only argument+ return torch.load(path, map_location=map_location)+++def model_state_from_checkpoint(+ checkpoint: Mapping[str, Any], extra_prefixes: tuple[str, ...] = ()+) -> dict[str, Any]:+ """Return the model weights of a checkpoint with wrapper prefixes removed.++ Accepts both our checkpoint dicts (weights under ``model_state_dict``) and raw state dicts.+ """+ state = checkpoint["model_state_dict"] if "model_state_dict" in checkpoint else checkpoint+ return strip_wrapper_prefixes(state, extra_prefixes)+++def model_config_from_checkpoint(checkpoint: Mapping[str, Any]) -> dict[str, Any]:+ """Return the model settings stored in a checkpoint.++ Post-training stages save them under ``cfg`` and the legacy trainer under ``config``.+ Very old checkpoints have neither, which gives an empty dict.+ """+ cfg = checkpoint.get("cfg") or checkpoint.get("config") or {}+ return dict(cfg)+++def load_model_weights(+ model: nn.Module, state: Mapping[str, torch.Tensor], *, source: str = "checkpoint"+) -> None:+ """+ Copy matching weights from ``state`` into ``model``.++ Extra keys are ignored (a reward or value head saved next to the backbone, for example).+ A missing *parameter* is an error: silently keeping random weights is how a broken+ checkpoint turns into a training run that quietly starts from scratch. Missing buffers+ (the causal mask, position indices) are fine, because the model rebuilds them on init.+ """+ own_keys = set(model.state_dict().keys())+ filtered = {k: v for k, v in state.items() if k in own_keys}+ missing, _ = model.load_state_dict(filtered, strict=False)+ param_names = {name for name, _ in model.named_parameters(remove_duplicate=False)}+ missing_params = [k for k in missing if k in param_names]+ if missing_params:+ raise RuntimeError(+ f"{source} is missing {len(missing_params)} model parameters "+ f"(for example {missing_params[:3]}). Check that the checkpoint was saved from a "+ "model with the same architecture and size."+ )+++def atomic_save(payload: Any, path: str | os.PathLike[str]) -> None:+ """``torch.save`` to a temporary file first, then rename, so a crash never leaves half a file."""+ path = os.fspath(path)+ target_dir = os.path.dirname(path) or "."+ os.makedirs(target_dir, exist_ok=True)+ with tempfile.NamedTemporaryFile(+ dir=target_dir, prefix=f".{os.path.basename(path)}.", suffix=".tmp", delete=False+ ) as tmp_file:+ tmp_path = tmp_file.name+ try:+ torch.save(payload, tmp_path)+ os.replace(tmp_path, path)+ except BaseException:+ if os.path.exists(tmp_path):+ os.remove(tmp_path)+ raisediff --git a/src/post_training/inference.py b/src/post_training/inference.pyindex dd33876..a30bf7c 100644--- a/src/post_training/inference.py+++ b/src/post_training/inference.py@@ -11,25 +11,35 @@ from __future__ import annotationsimport torch+from src.checkpoint import (+ load_checkpoint,+ load_model_weights,+ model_config_from_checkpoint,+ model_state_from_checkpoint,+)from src.models.transformer import Transformer-from src.post_training.chat_template import EOT_ID, decode, encode_prompt, get_tokenizer+from src.post_training.chat_template import encode_prompt, get_tokenizerfrom src.post_training.evaluation import batched_generatedef load_model_from_ckpt(ckpt_path: str, device: str, overrides: dict | None = None) -> Transformer:- """Build a :class:`Transformer` from a checkpoint's stored cfg and load its backbone- weights (tolerates ``module.``/``transformer.`` prefixes and reward-head extras)."""- ck = torch.load(ckpt_path, map_location="cpu", weights_only=False)- cfg = {**(ck.get("cfg") or {}), **(overrides or {})}+ """+ Build a model from the settings stored in a checkpoint and load its weights.++ Works for every checkpoint in the repo: the legacy trainer (settings under ``config``),+ every post-training stage (settings under ``cfg``), and reward-model checkpoints, whose+ backbone keys start with ``transformer.``. DDP and torch.compile prefixes are stripped+ too, so a model trained with ``--compile true`` loads correctly (issue #36).+ """+ ck = load_checkpoint(ckpt_path, map_location="cpu")+ cfg = {**model_config_from_checkpoint(ck), **(overrides or {})}model = Transformer(n_head=cfg.get("n_head", 16), n_embed=cfg.get("n_embed", 1024),context_length=cfg.get("context_length", 1024), vocab_size=cfg.get("vocab_size", 50304),N_BLOCKS=cfg.get("n_blocks", 24),)- state = ck["model_state_dict"] if "model_state_dict" in ck else ck- state = {k.removeprefix("module.").removeprefix("transformer."): v for k, v in state.items()}- keys = set(model.state_dict().keys())- model.load_state_dict({k: v for k, v in state.items() if k in keys}, strict=False)+ state = model_state_from_checkpoint(ck, extra_prefixes=("transformer.",))+ load_model_weights(model, state, source=ckpt_path)return model.to(device).eval()diff --git a/src/post_training/reward_model.py b/src/post_training/reward_model.pyindex af7e171..a509aed 100644--- a/src/post_training/reward_model.py+++ b/src/post_training/reward_model.py@@ -12,10 +12,9 @@ from __future__ import annotationsimport torchimport torch.nn as nn-import torch as _torch-+from src.checkpoint import load_checkpoint, model_state_from_checkpointfrom src.models.transformer import Transformer-from src.post_training.utils import build_model_from_config, gather_last, unwrap+from src.post_training.utils import build_model_from_config, gather_lastdef load_reward_model(cfg, ckpt_path: str, device: str) -> "RewardModel":@@ -23,10 +22,7 @@ def load_reward_model(cfg, ckpt_path: str, device: str) -> "RewardModel":checkpoint saved by ``scripts/train_reward.py``."""backbone = build_model_from_config(cfg)rm = RewardModel(backbone)- ck = _torch.load(ckpt_path, map_location="cpu", weights_only=False)- state = ck["model_state_dict"] if "model_state_dict" in ck else ck- if any(k.startswith("module.") for k in state):- state = {k.removeprefix("module."): v for k, v in state.items()}+ state = model_state_from_checkpoint(load_checkpoint(ckpt_path, map_location="cpu"))rm.load_state_dict(state, strict=True)rm.to(device).eval()for p in rm.parameters():diff --git a/src/post_training/utils.py b/src/post_training/utils.pyindex 9c24dfe..ead4a01 100644--- a/src/post_training/utils.py+++ b/src/post_training/utils.py@@ -8,7 +8,6 @@ from __future__ import annotationsimport contextlibimport copy-import osimport randomfrom dataclasses import asdict, is_dataclassfrom typing import Any@@ -17,6 +16,14 @@ import numpy as npimport torchimport torch.nn as nn+from src.checkpoint import (+ atomic_save,+ load_checkpoint,+ load_model_weights,+ model_state_from_checkpoint,+ strip_wrapper_prefixes,+ unwrap_model,+)from src.models.transformer import Transformer@@ -64,36 +71,30 @@ def build_model_from_config(cfg: Any) -> Transformer:)-def _strip_ddp_prefix(state_dict: dict) -> dict:- """Remove a leading ``module.`` from keys saved by DistributedDataParallel."""- if any(k.startswith("module.") for k in state_dict):- return {k.removeprefix("module."): v for k, v in state_dict.items()}- return state_dict+# Kept for code that imported the old private name; it now also strips torch.compile's+# ``_orig_mod.`` prefix (issue #36).+_strip_ddp_prefix = strip_wrapper_prefixesdef load_backbone_from_ckpt(cfg: Any, ckpt_path: str, device: str) -> Transformer:"""Build a Transformer from ``cfg`` and load backbone weights from a checkpoint savedby the pretraining script or any post-training stage (``model_state_dict`` key).- DDP ``module.`` prefixes are stripped. Auxiliary head weights (value/reward), if- present, are ignored here -- wrappers add their own fresh heads.++ DDP (``module.``) and torch.compile (``_orig_mod.``) prefixes are stripped. Auxiliary+ head weights (value/reward), if present, are ignored here because wrappers add their own+ fresh heads. A checkpoint that does not cover every backbone parameter raises an error+ instead of silently leaving random weights in place."""model = build_model_from_config(cfg)- ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)- state = ckpt["model_state_dict"] if "model_state_dict" in ckpt else ckpt- state = _strip_ddp_prefix(state)- # Keep only keys that belong to the bare Transformer backbone.- backbone_keys = set(model.state_dict().keys())- filtered = {k: v for k, v in state.items() if k in backbone_keys}- missing, unexpected = model.load_state_dict(filtered, strict=False)- if missing:- print(f"[load_backbone] {len(missing)} missing keys (e.g. {missing[:3]})")+ state = model_state_from_checkpoint(load_checkpoint(ckpt_path, map_location="cpu"))+ load_model_weights(model, state, source=ckpt_path)return model.to(device)def unwrap(model: nn.Module) -> nn.Module:- """Return the underlying module behind a DDP wrapper (or the model itself)."""- return model.module if hasattr(model, "module") else model+ """Return the plain model behind DDP and torch.compile wrappers (or the model itself)."""+ return unwrap_model(model)def make_frozen_copy(model: nn.Module, device: str | None = None) -> nn.Module:@@ -159,10 +160,9 @@ def save_stage_ckpt("""Save a checkpoint in the repo's existing shape (``model_state_dict`` /``optimizer_state_dict``) plus post-training metadata (``stage``, ``cfg``, ``step``,- ``metrics``). DDP wrappers are unwrapped first so checkpoints load cleanly on a- single GPU.+ ``metrics``). DDP and torch.compile wrappers are unwrapped first so the keys are clean+ and the file loads into a bare model on any device. The write is atomic."""- os.makedirs(os.path.dirname(path) or ".", exist_ok=True)payload = {"model_state_dict": unwrap(model).state_dict(),"optimizer_state_dict": optimizer.state_dict() if optimizer is not None else None,@@ -175,4 +175,4 @@ def save_stage_ckpt(}if extra:payload.update(extra)- torch.save(payload, path)+ atomic_save(payload, path)diff --git a/tests/test_checkpoint_io.py b/tests/test_checkpoint_io.pynew file mode 100644index 0000000..be0f78e--- /dev/null+++ b/tests/test_checkpoint_io.py@@ -0,0 +1,136 @@+"""+Checkpoint save/load regression tests.++Covers issue #36: a model trained with ``torch.compile`` (and/or DDP) used to save keys like+``_orig_mod.lm_head.weight``. Every later stage then failed to match the keys and quietly+started from random weights. These tests pin the fix from both sides: checkpoints are now saved+with clean keys, and older prefixed checkpoints still load.+"""++from __future__ import annotations++import os++import pytest+import torch+import torch.nn as nn++from config.post_training_config import SFTConfig, smoke+from src.checkpoint import (+ load_checkpoint,+ load_model_weights,+ strip_wrapper_prefixes,+ unwrap_model,+)+from src.models.transformer import Transformer+from src.post_training.inference import load_model_from_ckpt+from src.post_training.reward_model import RewardModel, load_reward_model+from src.post_training.utils import build_model_from_config, load_backbone_from_ckpt, save_stage_ckpt+++def _weights_equal(a: nn.Module, b: nn.Module) -> bool:+ sa, sb = a.state_dict(), b.state_dict()+ return sa.keys() == sb.keys() and all(torch.equal(sa[k], sb[k]) for k in sa)+++def cfg() -> SFTConfig:+ return smoke(SFTConfig)+++def test_strip_wrapper_prefixes_handles_any_nesting() -> None:+ state = {+ "module._orig_mod.lm_head.weight": 1,+ "_orig_mod.module.token_embed.weight": 2,+ "module.module.layer_norm.bias": 3,+ "clean.key": 4,+ }+ assert strip_wrapper_prefixes(state) == {+ "lm_head.weight": 1,+ "token_embed.weight": 2,+ "layer_norm.bias": 3,+ "clean.key": 4,+ }+ reward = {"module.transformer.lm_head.weight": 5, "module.reward_head.weight": 6}+ assert strip_wrapper_prefixes(reward, ("transformer.",)) == {+ "lm_head.weight": 5,+ "reward_head.weight": 6,+ }+++def test_unwrap_model_removes_compile_and_data_parallel(cfg: SFTConfig) -> None:+ model = build_model_from_config(cfg)+ wrapped = torch.compile(nn.DataParallel(model)) # compile wraps lazily, no forward needed+ assert unwrap_model(wrapped) is model+ assert unwrap_model(model) is model+++def test_compiled_model_checkpoint_round_trip(cfg: SFTConfig, tmp_path: str) -> None:+ """The exact failure from issue #36: save a compiled model, load it into a bare one."""+ model = build_model_from_config(cfg)+ path = os.path.join(tmp_path, "compiled.pt")+ save_stage_ckpt(path, torch.compile(model), None, stage="pretrain", cfg=cfg, step=0)++ saved_keys = load_checkpoint(path)["model_state_dict"].keys()+ assert not any(k.startswith(("_orig_mod.", "module.")) for k in saved_keys)++ assert _weights_equal(load_backbone_from_ckpt(cfg, path, "cpu"), model)+ assert _weights_equal(load_model_from_ckpt(path, "cpu"), model)+++def test_old_prefixed_checkpoints_still_load(cfg: SFTConfig, tmp_path: str) -> None:+ """Files written before the fix carry ``module._orig_mod.`` keys; they must load as-is."""+ model = build_model_from_config(cfg)+ prefixed = {f"module._orig_mod.{k}": v for k, v in model.state_dict().items()}+ path = os.path.join(tmp_path, "old.pt")+ torch.save({"model_state_dict": prefixed, "cfg": cfg.__dict__}, path)++ assert _weights_equal(load_backbone_from_ckpt(cfg, path, "cpu"), model)+ assert _weights_equal(load_model_from_ckpt(path, "cpu"), model)+++def test_reward_checkpoint_loads_for_chat_and_as_reward_model(cfg: SFTConfig, tmp_path: str) -> None:+ rm = RewardModel(build_model_from_config(cfg))+ with torch.no_grad():+ rm.reward_head.weight.normal_()+ path = os.path.join(tmp_path, "reward.pt")+ save_stage_ckpt(path, torch.compile(rm), None, stage="reward", cfg=cfg, step=0)++ # chat / eval read the backbone out of the reward checkpoint ("transformer." keys)+ assert _weights_equal(load_model_from_ckpt(path, "cpu"), rm.transformer)+ # PPO with reward_source="rm" restores backbone + head+ restored = load_reward_model(cfg, path, "cpu")+ assert torch.equal(restored.reward_head.weight, rm.reward_head.weight)+++def test_legacy_checkpoint_dims_are_read_from_config(tmp_path: str) -> None:+ """Checkpoints from scripts/train_transformer.py store their sizes under ``config``."""+ model = Transformer(n_head=2, n_embed=16, context_length=8, vocab_size=64, N_BLOCKS=1)+ config = {"n_head": 2, "n_embed": 16, "context_length": 8, "vocab_size": 64, "n_blocks": 1}+ path = os.path.join(tmp_path, "legacy.pt")+ torch.save({"model_state_dict": model.state_dict(), "config": config}, path)+ assert _weights_equal(load_model_from_ckpt(path, "cpu"), model)+++def test_missing_parameters_fail_loudly(cfg: SFTConfig) -> None:+ model = build_model_from_config(cfg)+ partial = {k: v for k, v in model.state_dict().items() if not k.startswith("lm_head")}+ with pytest.raises(RuntimeError, match="missing"):+ load_model_weights(build_model_from_config(cfg), partial, source="partial.pt")+++def test_legacy_trainer_resumes_from_prefixed_checkpoint(tmp_path: str) -> None:+ from scripts.train_transformer import restore_training_checkpoint++ model = Transformer(n_head=2, n_embed=8, context_length=8, vocab_size=32, N_BLOCKS=1)+ optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)+ prefixed = {f"_orig_mod.{k}": v for k, v in model.state_dict().items()}+ path = os.path.join(tmp_path, "checkpoint_step_00000004.pt")+ torch.save({"model_state_dict": prefixed, "last_completed_step": 4, "losses": [1.0]}, path)++ fresh = Transformer(n_head=2, n_embed=8, context_length=8, vocab_size=32, N_BLOCKS=1)+ fresh_opt = torch.optim.AdamW(fresh.parameters(), lr=1e-3)+ cfg = {"t_lr": 1e-3, "t_lr_decayed": 1e-4, "t_lr_decay_step": 10}+ next_step, losses = restore_training_checkpoint(path, fresh, fresh_opt, cfg, "cpu")+ assert next_step == 5 and losses == [1.0]+ assert _weights_equal(fresh, model)