Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
fix(train): wire resume_from_checkpoint for prm and moe_lora_routing (#1220) (#1303)
Nurkhan Esenbek4f51716f8d8d
diff --git a/changelog.d/0.75.1/1303.fixed.md b/changelog.d/0.75.1/1303.fixed.mdnew file mode 100644index 00000000..4818b7d5--- /dev/null+++ b/changelog.d/0.75.1/1303.fixed.md@@ -0,0 +1 @@+- **`soup train --resume` properly resumes `task: prm` and `task: moe_lora_routing` rather than retraining from step 0 and overwriting checkpoints (#1220).** Both `PRMTrainerWrapper` and `MoleRoutingTrainerWrapper` now accept and forward `resume_from_checkpoint` to `self.trainer.train()`. In MoLE training, the trained router gate weights (`mole_gate.pt`) are now saved into each periodic `checkpoint-N` directory via `_save_checkpoint`, and restored on resume via `_load_from_checkpoint` alongside adapter re-freezing prior to continuing optimization, ensuring step counts, optimizer momentum, and gate weights continue consistently. Tasks that do not support resume (such as `task: unlearn`) cleanly exit non-zero on `--resume` / `--hf-resume` with a descriptive message naming the task (#1220 by @kok-o in #1303).diff --git a/docs/backends-and-ops.md b/docs/backends-and-ops.mdindex 54160558..e9db59f5 100644--- a/docs/backends-and-ops.md+++ b/docs/backends-and-ops.md@@ -365,6 +365,8 @@ writes that shape. This is a weights-only warm start — mlx-lm's LoRA trainerexposes no optimizer state or step count, so the resumed run starts countingfrom step 0 regardless of how far the checkpoint got.+`task: unlearn` refuses `--resume` / `--hf-resume`, because it writes no checkpoints.+## Run Management & Cleanupdiff --git a/docs/training.md b/docs/training.mdindex 930a3727..d056ee1b 100644--- a/docs/training.md+++ b/docs/training.md@@ -1917,7 +1917,7 @@ training:epochs: 1```-The gate is the only trainable parameter; it is saved as `mole_gate.pt` alongside the run.+The gate is the only trainable parameter; it is saved as `mole_gate.pt` alongside the run, saved into every `checkpoint-N`, and restored by `--resume`.It trains as an fp32 master weight on every device, so its gradient and AdamW moments arefp32 too, even where the frozen base loads in bf16 (on CUDA), and `mole_gate.pt` is saved infp32: a `Linear(hidden, N)` of `4 x hidden x N` bytes, about 7 KB for the example above anddiff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.pyindex a06c07fb..0087d3e0 100644--- a/src/soup_cli/commands/train.py+++ b/src/soup_cli/commands/train.py@@ -65,6 +65,9 @@ def _nondefault_unwired_training_settings(training_config) -> list[str]:return enabled_flags + changed_tunables+UNSUPPORTED_RESUME_TASKS: frozenset[str] = frozenset({"unlearn"})++def _format_training_complete_loss(result: dict) -> str:"""Render only a loss comparison that the trainer actually measured."""summary_kind = result.get("loss_summary_kind")@@ -939,6 +942,9 @@ def train(if hf_resume and not push_as:console.print("[red]--hf-resume requires --push-as <repo>[/]")raise typer.Exit(1)+ if hf_resume and cfg.task in UNSUPPORTED_RESUME_TASKS:+ console.print(f"[red]--hf-resume is not supported for task {cfg.task!r}[/]")+ raise typer.Exit(1)# --- Eval-gate shortcut: --gate <path> sets training.eval_gate ---if gate:@@ -2313,6 +2319,9 @@ def _resolve_resume_or_exit(resume: str, cfg: "SoupConfig") -> str | None:"""if not resume:return None+ if cfg.task in UNSUPPORTED_RESUME_TASKS:+ console.print(f"[red]--resume is not supported for task {cfg.task!r}[/]")+ raise typer.Exit(1)resume_from = _resolve_checkpoint(resume, cfg.output, cfg.experiment_name, backend=cfg.backend)if resume_from:console.print(f"[green]Resuming from:[/] {resume_from}")diff --git a/src/soup_cli/trainer/mole_routing.py b/src/soup_cli/trainer/mole_routing.pyindex 19fa64fd..42493375 100644--- a/src/soup_cli/trainer/mole_routing.py+++ b/src/soup_cli/trainer/mole_routing.py@@ -34,6 +34,17 @@ logger = logging.getLogger(__name__)console = Console()+def _save_mole_gate(gate: Any, path: Path | str) -> None:+ """Save the MoLE gate module with all floating point tensors in fp32."""+ import torch++ gate_state = {+ name: tensor.to(torch.float32) if tensor.is_floating_point() else tensor+ for name, tensor in gate.state_dict().items()+ }+ torch.save(gate_state, str(path))++@lru_cache(maxsize=4)def make_mole_trainer_class(base_cls: type) -> type:"""Factory: build a ``_MoleTrainer`` subclass of HF ``Trainer``.@@ -58,6 +69,28 @@ def make_mole_trainer_class(base_cls: type) -> type:class _MoleTrainer(base_cls): # type: ignore[misc, valid-type]"""HF Trainer subclass for MoLE per-token routing."""+ def _save_checkpoint(self, model, trial):+ super()._save_checkpoint(model, trial)+ step = int(getattr(self.state, "global_step", 0) or 0)+ if step > 0 and getattr(self.args, "should_save", True):+ ckpt_dir = Path(self.args.output_dir) / f"checkpoint-{step}"+ gate = getattr(model, "mole_gate", None)+ if ckpt_dir.is_dir() and gate is not None:+ _save_mole_gate(gate, ckpt_dir / "mole_gate.pt")++ def _load_from_checkpoint(self, resume_from_checkpoint: str, model=None):+ super()._load_from_checkpoint(resume_from_checkpoint, model=model)+ target = model if model is not None else self.model+ if target is not None:+ for param in target.parameters():+ param.requires_grad_(False)+ if hasattr(target, "mole_gate"):+ target.mole_gate.requires_grad_(True)+ gate_path = Path(resume_from_checkpoint) / "mole_gate.pt"+ if gate_path.is_file():+ gate_state = torch.load(gate_path, map_location="cpu", weights_only=True)+ target.mole_gate.load_state_dict(gate_state)+def compute_loss(self, model, inputs, return_outputs=False, **kwargs):input_ids = inputs["input_ids"]attention_mask = inputs.get("attention_mask")@@ -336,8 +369,17 @@ class MoleRoutingTrainerWrapper:f"trainable_params={n_trainable}")- def train(self, **_kwargs) -> dict:+ def train(+ self,+ display=None,+ tracker=None,+ run_id=None,+ resume_from_checkpoint: Optional[str] = None,+ **_kwargs,+ ) -> dict:"""Train the gating kernel with the MoLE Trainer subclass."""+ # #802 contract: display, tracker, and run_id are accepted for caller+ # uniformity but not wired here.if self.model is None:raise RuntimeError("MoleRoutingTrainerWrapper.train() called before setup()"@@ -410,25 +452,21 @@ class MoleRoutingTrainerWrapper:from soup_cli.utils.deepspeed import attach_empty_param_group_guardattach_empty_param_group_guard(self.trainer)+console.print("[green]Starting MoLE gate training...[/]")align_trainable_dtype_for_fp16(self.trainer.model,fp16=getattr(self.trainer.args, "fp16", False),bf16=getattr(self.trainer.args, "bf16", False),)- result = self.trainer.train()+ result = self.trainer.train(resume_from_checkpoint=resume_from_checkpoint)# Persist the trained gate (the base + adapters are unchanged on disk).- import torch-gate_path = output_dir / "mole_gate.pt"# #1266: always fp32, whatever the module holds by now (a DeepSpeed bf16/fp16# engine casts it to 16-bit in place); a Linear(hidden, N) costs nothing.# The serve loader builds an fp32 gate, so a bf16 file from before loads too.- gate_state = {- name: tensor.to(torch.float32) if tensor.is_floating_point() else tensor- for name, tensor in self.model.mole_gate.state_dict().items()- }- torch.save(gate_state, str(gate_path))+ _save_mole_gate(self.model.mole_gate, gate_path)+# v0.71.17 #259 — write a self-describing manifest next to the gate so# `soup serve --mole <dir>` can reconstruct the decode-time blend# (base + N frozen task LoRAs + gate geometry).diff --git a/src/soup_cli/trainer/prm.py b/src/soup_cli/trainer/prm.pyindex 01a8d2ce..0f36701c 100644--- a/src/soup_cli/trainer/prm.py+++ b/src/soup_cli/trainer/prm.py@@ -286,8 +286,17 @@ class PRMTrainerWrapper:f"head=Linear({hidden_size}, 1)")- def train(self, **_kwargs) -> dict:+ def train(+ self,+ display=None,+ tracker=None,+ run_id=None,+ resume_from_checkpoint: Optional[str] = None,+ **_kwargs,+ ) -> dict:"""Run training with the PRM Trainer subclass."""+ # #802 contract: display, tracker, and run_id are accepted for caller+ # uniformity but not wired here.if self.model is None:raise RuntimeError("PRMTrainerWrapper.train() called before setup()")from datasets import Dataset@@ -364,6 +373,7 @@ class PRMTrainerWrapper:from soup_cli.utils.deepspeed import attach_empty_param_group_guardattach_empty_param_group_guard(self.trainer)+console.print("[green]Starting PRM training...[/]")start = time.time()align_trainable_dtype_for_fp16(@@ -371,7 +381,7 @@ class PRMTrainerWrapper:fp16=getattr(self.trainer.args, "fp16", False),bf16=getattr(self.trainer.args, "bf16", False),)- result = self.trainer.train()+ result = self.trainer.train(resume_from_checkpoint=resume_from_checkpoint)self.trainer.save_model(str(output_dir))# v0.71.30 — save the tokenizer alongside the model so the PRM# checkpoint is loadable standalone (soup shrink / PRMScorer /diff --git a/tests/test_issue1220_resume_prm_moe.py b/tests/test_issue1220_resume_prm_moe.pynew file mode 100644index 00000000..4ab5ba8f--- /dev/null+++ b/tests/test_issue1220_resume_prm_moe.py@@ -0,0 +1,442 @@+"""Tests for issue #1220: `soup train --resume` on `task: prm` and `task: moe_lora_routing`.++Verifies:+1. PRM wrapper accepts and forwards resume_from_checkpoint to HF Trainer.+2. MoLE wrapper accepts and forwards resume_from_checkpoint, saves mole_gate.pt into+ each checkpoint, and restores the gate on resume.+3. Resuming from checkpoint-4 executes 0 steps and preserves global_step.+4. Resuming from checkpoint-2 executes remaining 2 steps and does not rewrite checkpoint-2.+5. Existing checkpoint modification times are preserved.+6. Static AST scan over src/soup_cli/trainer/*.py confirms all wrappers forwarding+ resume_from_checkpoint or registered in UNSUPPORTED_RESUME_TASKS.+7. CLI refusal for unsupported tasks (e.g. unlearn) with ANSI strip verification.+"""++from __future__ import annotations++import ast+import json+import re+from pathlib import Path++from typer.testing import CliRunner++from soup_cli.cli import app+from soup_cli.commands.train import UNSUPPORTED_RESUME_TASKS+from tests._windows_ci import skip_on_windows_ci++TINY_MODEL = "hf-internal-testing/tiny-random-LlamaForCausalLM"+++def _strip_ansi(text: str) -> str:+ """Strip ANSI escape sequences from terminal output."""+ return re.sub(r"\x1b\[[0-9;]*[a-zA-Z]", "", text)+++def _collapse_whitespace(text: str) -> str:+ """Normalize internal and leading/trailing whitespace."""+ return " ".join(text.split())+++TRAINER_DIR = Path(__file__).resolve().parent.parent / "src" / "soup_cli" / "trainer"+++def _is_self_call(func: ast.expr) -> bool:+ """self.x(...), self.a.b(...) or super().x(...), never str(...) or Path(...)."""+ while isinstance(func, ast.Attribute):+ func = func.value+ if isinstance(func, ast.Name):+ return func.id == "self"+ return (+ isinstance(func, ast.Call)+ and isinstance(func.func, ast.Name)+ and func.func.id == "super"+ )+++def _forwards_resume(func: ast.FunctionDef) -> bool:+ """Some call in the BODY passes the checkpoint on; the signature proves nothing."""+ kwarg = func.args.kwarg.arg if func.args.kwarg else None+ for stmt in func.body:+ for node in ast.walk(stmt):+ if not isinstance(node, ast.Call):+ continue+ for kw in node.keywords:+ if kw.arg == "resume_from_checkpoint":+ return True+ if kw.arg is None and isinstance(kw.value, ast.Name) and kw.value.id == kwarg:+ return True+ if _is_self_call(node.func) and any(+ isinstance(a, ast.Name) and a.id == "resume_from_checkpoint" for a in node.args+ ):+ return True # ppo.py's self._train_builtin(...), mlx_sft's weight loader+ return False+++class TestTrainerScanInvariants:+ """Static AST verification that every trainer wrapper handles resume_from_checkpoint."""++ def test_all_trainer_wrappers_forward_resume_or_refuse(self):+ """A scan over src/soup_cli/trainer/*.py fails when a wrapper's train()+ accepts resume_from_checkpoint (or **kwargs) without forwarding it,+ unless the task is in UNSUPPORTED_RESUME_TASKS.+ """+ trainer_files = sorted(TRAINER_DIR.glob("*.py"))+ assert trainer_files, "No trainer files found in src/soup_cli/trainer"++ task_mapping = {+ "asr.py": "asr",+ "bco.py": "bco",+ "classifier.py": "classifier",+ "distill.py": "distill",+ "dpo.py": "dpo",+ "embedding.py": "embedding",+ "grpo.py": "grpo",+ "ipo.py": "ipo",+ "kto.py": "kto",+ "mlx_dpo.py": "dpo",+ "mlx_grpo.py": "grpo",+ "mlx_sft.py": "sft",+ "mole_routing.py": "moe_lora_routing",+ "online_dpo.py": "online_dpo",+ "orpo.py": "orpo",+ "ppo.py": "ppo",+ "preference.py": "preference",+ "pretrain.py": "pretrain",+ "prm.py": "prm",+ "reward_model.py": "reward_model",+ "sft.py": "sft",+ "simpo.py": "simpo",+ "tts.py": "tts",+ "unlearn.py": "unlearn",+ }++ failures = []+ for file_path in trainer_files:+ file_name = file_path.name+ if file_name in (+ "__init__.py",+ "loss_summary.py",+ "stream_setup.py",+ "bitnet.py",+ "mlx_masking.py",+ "mlx_optim.py",+ "mlx_routing.py",+ "rewards.py",+ "_trl_compat.py",+ "rewind_mlx.py",+ ):+ continue++ with open(file_path, encoding="utf-8") as f:+ tree = ast.parse(f.read(), filename=str(file_path))++ for node in ast.walk(tree):+ if not isinstance(node, ast.ClassDef):+ continue+ # Only check TrainerWrapper classes or primary trainers+ if not ("TrainerWrapper" in node.name or node.name.endswith("Trainer")):+ continue++ for item in node.body:+ if isinstance(item, ast.FunctionDef) and item.name == "train":+ arg_names = [a.arg for a in item.args.args]+ kwarg = item.args.kwarg.arg if item.args.kwarg else None++ accepts_resume = "resume_from_checkpoint" in arg_names or kwarg is not None+ if not accepts_resume:+ continue++ task_name = task_mapping.get(file_name)+ is_refused = task_name in UNSUPPORTED_RESUME_TASKS+ if is_refused:+ continue++ if not _forwards_resume(item):+ failures.append(+ f"{file_name}::{node.name}.train() accepts resume_from_checkpoint "+ f"but does not forward it and task {task_name!r} is not in "+ f"UNSUPPORTED_RESUME_TASKS"+ )++ assert not failures, "\n".join(failures)+++class TestResumeRefusalForUnsupportedTasks:+ """CLI test for tasks that cleanly refuse --resume / --hf-resume."""++ def test_unlearn_resume_refusal(self, tmp_path):+ runner = CliRunner()+ config_path = tmp_path / "unlearn.yaml"+ train_data = tmp_path / "forget.jsonl"+ train_data.write_text(json.dumps({"prompt": "forget me", "response": "done"}) + "\n")++ config_path.write_text(+ f"base: {TINY_MODEL}\n"+ "task: unlearn\n"+ f"data: {{train: {train_data.as_posix()}, forget_set: {train_data.as_posix()},"+ " format: chatml, val_split: 0.0}\n"+ "training: {unlearn_method: npo}\n"+ "output: ./out_unlearn\n"+ )++ res = runner.invoke(+ app, ["train", "--config", str(config_path), "--resume", "auto", "--yes"]+ )+ assert res.exit_code != 0+ clean_output = _collapse_whitespace(_strip_ansi(res.output))+ assert "--resume is not supported for task 'unlearn'" in clean_output++ def test_unlearn_hf_resume_refusal(self, tmp_path):+ runner = CliRunner()+ config_path = tmp_path / "unlearn.yaml"+ train_data = tmp_path / "forget.jsonl"+ train_data.write_text(json.dumps({"prompt": "forget me", "response": "done"}) + "\n")++ config_path.write_text(+ f"base: {TINY_MODEL}\n"+ "task: unlearn\n"+ f"data: {{train: {train_data.as_posix()}, forget_set: {train_data.as_posix()},"+ " format: chatml, val_split: 0.0}\n"+ "training: {unlearn_method: npo}\n"+ "output: ./out_unlearn\n"+ )++ res = runner.invoke(app, [+ "train", "--config", str(config_path), "--hf-resume", "--push-as", "test/repo", "--yes"+ ])+ assert res.exit_code != 0+ clean_output = _collapse_whitespace(_strip_ansi(res.output))+ assert "--hf-resume is not supported for task 'unlearn'" in clean_output+++@skip_on_windows_ci+class TestPRMResume:+ """Functional verification of PRM resume with tiny model."""++ def test_prm_resume_execution_and_checkpoints(self, tmp_path, monkeypatch):+ import transformers++ steps = []+ _orig_training_step = transformers.Trainer.training_step++ def counting_step(self, *args, **kwargs):+ if steps:+ steps[-1] += 1+ return _orig_training_step(self, *args, **kwargs)++ monkeypatch.setattr(transformers.Trainer, "training_step", counting_step)+ monkeypatch.setenv("WANDB_DISABLED", "true")++ prm_data = tmp_path / "prm.jsonl"+ rows = [+ {+ "prompt": f"Solve {i}+1.",+ "completions": [f"{i}+1 is {i + 1}.", "Done."],+ "labels": [True, True],+ }+ for i in range(8)+ ]+ prm_data.write_text("\n".join(json.dumps(r) for r in rows) + "\n")++ out_dir = tmp_path / "out_prm"+ cfg_path = tmp_path / "prm.yaml"+ cfg_path.write_text(+ f"base: {TINY_MODEL}\n"+ "task: prm\n"+ f"data: {{train: {prm_data.as_posix()}, format: prm, val_split: 0.0, max_length: 64}}\n"+ "training: {\n"+ " epochs: 1, batch_size: 2, gradient_accumulation_steps: 1, save_steps: 2,\n"+ " quantization: none, lora: {r: 0}\n"+ "}\n"+ f"output: {out_dir.as_posix()}\n"+ )++ runner = CliRunner()++ # Run 1: initial run to checkpoint-4+ steps.append(0)+ res1 = runner.invoke(app, ["train", "--config", str(cfg_path), "--yes"])+ assert res1.exit_code == 0, res1.output+ assert steps[-1] == 4, f"Expected 4 training steps on initial run, got {steps[-1]}"++ ckpt2 = out_dir / "checkpoint-2"+ ckpt4 = out_dir / "checkpoint-4"+ assert ckpt2.is_dir()+ assert ckpt4.is_dir()+ mtime2_before = (ckpt2 / "trainer_state.json").stat().st_mtime+ mtime4_before = (ckpt4 / "trainer_state.json").stat().st_mtime++ # Run 2: resume auto (from checkpoint-4) -> should execute 0 steps+ steps.append(0)+ res2 = runner.invoke(app, ["train", "--config", str(cfg_path), "--resume", "auto", "--yes"])+ assert res2.exit_code == 0, res2.output+ assert "Resuming from" in res2.output+ assert steps[-1] == 0, f"Expected 0 steps on resume auto, got {steps[-1]}"++ # Checkpoints must not be rewritten+ assert (ckpt2 / "trainer_state.json").stat().st_mtime == mtime2_before+ assert (ckpt4 / "trainer_state.json").stat().st_mtime == mtime4_before++ # Run 3: resume explicit path to checkpoint-4 -> 0 steps+ steps.append(0)+ res3 = runner.invoke(+ app, ["train", "--config", str(cfg_path), "--resume", str(ckpt4), "--yes"]+ )+ assert res3.exit_code == 0, res3.output+ assert steps[-1] == 0++ # Run 4: resume from middle checkpoint-2 -> executes remaining 2 steps+ steps.append(0)+ res4 = runner.invoke(+ app, ["train", "--config", str(cfg_path), "--resume", str(ckpt2), "--yes"]+ )+ assert res4.exit_code == 0, res4.output+ assert steps[-1] == 2, f"Expected 2 steps when resuming from checkpoint-2, got {steps[-1]}"+ # checkpoint-2 itself was not rewritten+ assert (ckpt2 / "trainer_state.json").stat().st_mtime == mtime2_before+++@skip_on_windows_ci+class TestMoleRoutingResume:+ """Functional verification of MoLE resume with tiny model and task adapters."""++ def test_mole_resume_execution_checkpoints_and_gate(self, tmp_path, monkeypatch):+ import torch+ import transformers+ from peft import LoraConfig, get_peft_model+ from transformers import AutoModelForCausalLM++ steps = []+ _orig_training_step = transformers.Trainer.training_step++ def counting_step(self, *args, **kwargs):+ if steps:+ steps[-1] += 1+ return _orig_training_step(self, *args, **kwargs)++ monkeypatch.setattr(transformers.Trainer, "training_step", counting_step)+ monkeypatch.setenv("WANDB_DISABLED", "true")++ import soup_cli.trainer.mole_routing as mole_routing++ gate_files = []+ real_save_gate = mole_routing._save_mole_gate++ def recording_save_gate(gate, path):+ gate_files.append(Path(path))+ real_save_gate(gate, path)++ monkeypatch.setattr(mole_routing, "_save_mole_gate", recording_save_gate)++ # Create two tiny task LoRA adapters+ base_model = AutoModelForCausalLM.from_pretrained(TINY_MODEL)+ lora_cfg = LoraConfig(r=4, lora_alpha=8, target_modules=["q_proj", "v_proj"])+ peft_m = get_peft_model(base_model, lora_cfg)+ adapter_a = tmp_path / "adapter_a"+ adapter_b = tmp_path / "adapter_b"+ peft_m.save_pretrained(str(adapter_a))+ peft_m.save_pretrained(str(adapter_b))++ # Dataset for routing+ chat_data = tmp_path / "chat.jsonl"+ rows = [+ {+ "messages": [+ {"role": "user", "content": f"q{i}"},+ {"role": "assistant", "content": f"a{i}"},+ ]+ }+ for i in range(8)+ ]+ chat_data.write_text("\n".join(json.dumps(r) for r in rows) + "\n")++ out_dir = tmp_path / "out_mole"+ cfg_path = tmp_path / "mole.yaml"+ c_posix = chat_data.as_posix()+ cfg_data = (+ f"base: {TINY_MODEL}\n"+ "task: moe_lora_routing\n"+ f"data: {{train: {c_posix}, format: chatml, val_split: 0.0, max_length: 64}}\n"+ "training: {\n"+ " epochs: 1, batch_size: 2, gradient_accumulation_steps: 1, save_steps: 2,\n"+ f" mole_task_adapters: [{adapter_a.as_posix()}, {adapter_b.as_posix()}],\n"+ " mole_top_k: 2, mole_temperature: 1.0, lr: 0.01, quantization: none\n"+ "}\n"+ f"output: {out_dir.as_posix()}\n"+ )+ cfg_path.write_text(cfg_data)++ runner = CliRunner()++ # Run 1: initial run to checkpoint-4+ steps.append(0)+ res1 = runner.invoke(app, ["train", "--config", str(cfg_path), "--yes"])+ assert res1.exit_code == 0, res1.output+ assert steps[-1] == 4, f"Expected 4 training steps on initial run, got {steps[-1]}"++ ckpt2 = out_dir / "checkpoint-2"+ ckpt4 = out_dir / "checkpoint-4"+ assert ckpt2.is_dir()+ assert ckpt4.is_dir()++ # Verify mole_gate.pt is saved in checkpoints+ gate2_path = ckpt2 / "mole_gate.pt"+ gate4_path = ckpt4 / "mole_gate.pt"+ assert gate2_path.is_file(), f"mole_gate.pt missing from {ckpt2}"+ assert gate4_path.is_file(), f"mole_gate.pt missing from {ckpt4}"++ # Every copy goes through the one fp32 save, the checkpoint copies included.+ written = {(p.parent.name, p.name) for p in gate_files}+ assert {+ ("checkpoint-2", "mole_gate.pt"),+ ("checkpoint-4", "mole_gate.pt"),+ (out_dir.name, "mole_gate.pt"),+ } <= written, written++ gate4_saved = torch.load(gate4_path, map_location="cpu", weights_only=True)+ mtime2_before = (ckpt2 / "trainer_state.json").stat().st_mtime+ mtime4_before = (ckpt4 / "trainer_state.json").stat().st_mtime++ # Run 2: resume auto (checkpoint-4) -> executes 0 steps+ steps.append(0)+ res2 = runner.invoke(app, ["train", "--config", str(cfg_path), "--resume", "auto", "--yes"])+ assert res2.exit_code == 0, res2.output+ assert "Resuming from" in res2.output+ assert steps[-1] == 0, f"Expected 0 steps on resume auto, got {steps[-1]}"++ # Checkpoints not rewritten+ assert (ckpt2 / "trainer_state.json").stat().st_mtime == mtime2_before+ assert (ckpt4 / "trainer_state.json").stat().st_mtime == mtime4_before++ # Gate weights after resume match saved checkpoint-4 weights+ final_gate = torch.load(out_dir / "mole_gate.pt", map_location="cpu", weights_only=True)+ for k in gate4_saved:+ assert torch.equal(gate4_saved[k], final_gate[k])++ # Run 3: resume from middle checkpoint-2 -> executes 2 steps+ steps.append(0)+ res3 = runner.invoke(+ app, ["train", "--config", str(cfg_path), "--resume", str(ckpt2), "--yes"]+ )+ assert res3.exit_code == 0, res3.output+ assert steps[-1] == 2, f"Expected 2 steps when resuming from checkpoint-2, got {steps[-1]}"+ # checkpoint-2 not modified+ assert (ckpt2 / "trainer_state.json").stat().st_mtime == mtime2_before++ # Bit-exact check: gate reproduced across checkpoint-2 resume+ resumed = torch.load(out_dir / "mole_gate.pt", map_location="cpu", weights_only=True)+ for k in gate4_saved:+ torch.testing.assert_close(resumed[k], gate4_saved[k], rtol=0, atol=1e-6)++def test_save_mole_gate_writes_fp32_from_a_16_bit_gate(tmp_path):+ """A DeepSpeed bf16/fp16 engine casts the gate to 16-bit in place; the file is fp32."""+ import torch++ from soup_cli.trainer.mole_routing import _save_mole_gate++ gate = torch.nn.Linear(8, 2, bias=False).to(torch.bfloat16)+ _save_mole_gate(gate, tmp_path / "mole_gate.pt")+ saved = torch.load(tmp_path / "mole_gate.pt", map_location="cpu", weights_only=True)+ assert saved["weight"].dtype == torch.float32, saved["weight"].dtype+ assert torch.equal(saved["weight"], gate.weight.detach().float())