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(relora): implement paper-faithful merge-and-reinit restarts (#693) (#1133)
Jagadeep Mamidib57f9128995d
diff --git a/changelog.d/0.75.1/1133.changed.md b/changelog.d/0.75.1/1133.changed.mdnew file mode 100644index 00000000..4f9888bc--- /dev/null+++ b/changelog.d/0.75.1/1133.changed.md@@ -0,0 +1 @@+- ReLoRA restarts now follow the paper contract (#693 by @jagadeepmamidi in #1133): each fire merges the PEFT-scaled LoRA update into the base weight, reinitializes `lora_A`/`lora_B`, clears optimizer state when `relora_reset_optimizer` is set, and re-warms the learning rate from `1/(W+1)` without an exact-zero step. Behaviour break: `relora_steps` requires explicit `quantization: none` because the schema default is `4bit`. Embedding adapters with an empty `lora_A` are skipped; Linear LoRA is still merged. The final active adapter is merged into the accumulated in-memory base and saved as a standalone dense output; `--resume` and `--hf-resume` are refused for ReLoRA because intermediate checkpoints do not encode restart history. Distributed/sharded execution remains explicitly refused, and `relora_prune_ratio` remains ignored with a warning for backward-compatible YAML.diff --git a/docs/commands.md b/docs/commands.mdindex c728515a..d8639b1a 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -15,6 +15,7 @@ soup advise compare Show prior verdicts from advise hisoup advise explain Rubric + evidence trail of the last verdictsoup fetch <name> Fetch a ready-to-edit example config from the bundled catalogsoup train --config soup.yaml Start training+soup train --config soup.yaml --resume ./output/checkpoint-100 Resume from local checkpoint (not with training.relora_steps)soup train --config soup.yaml --tensorboard Train with TensorBoard loggingsoup train --config soup.yaml --replay old.jsonl --replay-ratio 0.1 Continual-learning rehearsal: interleave old data so the new task doesn't erase it (sft/pretrain)soup train --config soup.yaml --fsdp full_shard Train with FSDP2@@ -24,7 +25,7 @@ soup train --config soup.yaml --gpus 8 --nodes 2 --node-rank 0 --master-addr 10.soup train --config soup.yaml --gpus 4 --no-reexec Print the launch command without running itsoup train --config soup.yaml --gate evals/gate.yaml Eval-gated trainingsoup train --config soup.yaml --push-as user/repo Auto-push each checkpoint to HF as branch-soup train --config soup.yaml --push-as user/repo --hf-resume Resume from latest HF checkpoint branch+soup train --config soup.yaml --push-as user/repo --hf-resume Resume from latest HF checkpoint branch (not with training.relora_steps)soup train --config soup.yaml --find-lr LR range finder: write recommended LR JSONsoup train --config soup.yaml --cloud modal|lambda --gpu a100 Render a cloud GPU controller (plan-only; --cloud-submit submits live)soup infer --model ./output --input p.jsonl Batch inferencediff --git a/docs/peft-and-efficiency.md b/docs/peft-and-efficiency.mdindex 4325b482..d752a0da 100644--- a/docs/peft-and-efficiency.md+++ b/docs/peft-and-efficiency.md@@ -309,7 +309,7 @@ Five PEFT-surface improvements that LlamaFactory and Axolotl maintain:```yamltraining:- quantization: none # required: PiSSA initializes from float weights+ quantization: none # required: schema default is 4bit; ReLoRA/PiSSA need floatlora:init_strategy: pissa # 'random' (default), 'pissa', 'olora'rank_pattern: # per-target-module rank override@@ -317,10 +317,10 @@ training:v_proj: 16alpha_pattern: # per-target-module alpha overrideq_proj: 16- relora_steps: 500 # magnitude-prune LoRA every 500 steps+ relora_steps: 500 # merge+reinit restart every 500 stepsrelora_warmup_ratio: 0.1 # skip first 10% of training- relora_prune_ratio: 0.9 # zero out smallest 90% by magnitude- relora_reset_optimizer: true # clear optimizer state on each fire+ relora_prune_ratio: 0.9 # deprecated; kept for old YAML (ignored)+ relora_reset_optimizer: true # clear optimizer state after each restart```**PiSSA** initializes the LoRA pair from the SVD of the base weight, giving faster@@ -328,10 +328,30 @@ early convergence than random init at the cost of one extra SVD pass on the firsepoch. `init_strategy: olora` is also accepted; setting the legacy `use_olora: true`auto-aligns for back-compat.-**ReLoRA** fires every N global steps, magnitude-prunes the LoRA adapter weights-(keeping the top `1 - relora_prune_ratio` by absolute value), and optionally clears-optimizer state for the pruned parameters so momentum doesn't fight the new sparse-weights. Useful for very long training runs where the LoRA capacity saturates.+**ReLoRA is a behaviour break.** Soup's `training.quantization` **defaults to `4bit`**.+ReLoRA restarts merge the LoRA update into the base weight, so `relora_steps` now+**requires an explicit `quantization: none`** in soup.yaml. A config that previously+set only `relora_steps` is refused at parse. No shipped recipe, template, or example+sets `relora_steps`.++ReLoRA fires every N global steps, merges the LoRA update (B @ A, with PEFT+scaling) into the frozen base weight, reinitializes `lora_A` (Kaiming) and+`lora_B` (zeros), optionally clears optimizer state for those adapter parameters,+and runs a short learning-rate re-warmup. The first post-restart step uses+`1/(W+1)` of the target LR, then advances by that same increment to full LR.+Restarts accumulate faithfully only on an fp32 base; bf16/fp16 bases lose merge+delta to rounding. Embedding adapters (empty `lora_A`, typically `embed_tokens`)+are skipped; Linear LoRA is merged even though peft puts empty+`lora_embedding_A`/`lora_embedding_B` dicts on every `LoraLayer`. Useful for very+long training runs where adapter capacity saturates. `relora_prune_ratio` is+retained for backward-compatible YAML but no longer prunes adapter weights.++After training, Soup merges the active adapter into the already-accumulated+in-memory base and saves the final output as a standalone dense model. Load or+export that output directly; do not run `soup merge` on it. Intermediate+checkpoint directories remain trainer artifacts, and `--resume` / `--hf-resume`+are refused when `relora_steps` is configured because those checkpoints do not+encode the accumulated restart state.**Per-pattern rank/alpha** map module name patterns to integer ranks. Useful in MoEconfigs where expert FFNs need lower rank than attention. Caps: 256 keys × value 1024.@@ -348,8 +368,10 @@ deprecated in favour of the YAML registry.**Multi-trainer scope** — ReLoRA and the surgical patches are wired into everytransformer-backend trainer: `sft`, `dpo`, `grpo`, `kto`, `orpo`, `simpo`, `ipo`,`ppo`, `reward_model`, `pretrain`, `embedding`, `bco`, plus the unified-`task: preference` dispatcher. Schema cross-validator only rejects MLX backend-(the callback is HF Trainer-specific).+`task: preference` dispatcher. Schema cross-validator rejects MLX backend,+quantization other than `none`, `stream_layers`, `lora.use_vera`, `lora.use_dora`,+and `use_fsdp2_compile` (the callback is HF Trainer-specific and restart requires+a writable float base).## DoRA (Weight-Decomposed LoRA)diff --git a/docs/serving-and-export.md b/docs/serving-and-export.mdindex af22afc5..a69ea12d 100644--- a/docs/serving-and-export.md+++ b/docs/serving-and-export.md@@ -41,6 +41,11 @@ soup merge --adapter ./output --output ./mergedsoup merge --adapter ./output --base meta-llama/Llama-3.1-8B --dtype bfloat16```+ReLoRA training outputs are already standalone dense models: Soup merges the+final active adapter into the accumulated in-memory base before writing the+training output. Load or export that directory directly; `soup merge` is only+for adapter-only outputs and must not be used to reconstruct a ReLoRA run.+## Export to GGUFdiff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.pyindex 5279bdb6..36043c88 100644--- a/src/soup_cli/commands/train.py+++ b/src/soup_cli/commands/train.py@@ -358,7 +358,8 @@ def train("--resume","-r",help="Resume from checkpoint: path to checkpoint dir ('auto' for latest); "- "on the MLX backend, a path to a .safetensors adapter file instead",+ "on the MLX backend, a path to a .safetensors adapter file instead. "+ "Not supported when training.relora_steps is configured",),wandb: bool = typer.Option(False,@@ -438,7 +439,8 @@ def train("--hf-resume",help=("Download the latest checkpoint branch from the --push-as repo "- "and resume from it. Requires --push-as."+ "and resume from it. Requires --push-as; not supported when "+ "training.relora_steps is configured."),),find_lr: bool = typer.Option(@@ -744,6 +746,13 @@ def train(console.print(f"[red]{markup_escape(str(exc))}[/]")raise typer.Exit(code=2) from exc+ if cfg.training.relora_steps is not None and (resume is not None or hf_resume):+ console.print(+ "[red]ReLoRA runs cannot resume from checkpoints.[/] "+ "Remove training.relora_steps or start a fresh run."+ )+ raise typer.Exit(1)+# An unregistered data.chat_template name raises KeyError in the trainer,# after the model has loaded. Check it before anything is downloaded.from soup_cli.data.chat_templates import resolve_chat_template@@ -1764,6 +1773,12 @@ def train(raise# Report+ merge_hint = (+ "ReLoRA output is already dense; no soup merge is needed"+ if cfg.training.relora_steps is not None+ else f"[bold]Merge LoRA:[/] soup merge --adapter {result['output_dir']}"+ )+console.print(Panel(f"{_format_training_complete_loss(result)}\n"@@ -1772,7 +1787,7 @@ def train(f"Run ID: [bold]{run_id}[/]\n\n"f"Quick test: [bold]soup chat --model {result['output_dir']}[/]\n"f"Push to HF: [bold]soup push --model {result['output_dir']}[/]\n"- f"Merge LoRA: [bold]soup merge --adapter {result['output_dir']}[/]\n"+ f"{merge_hint}\n"f"Export GGUF: [bold]soup export --model {result['output_dir']}[/]\n"f"Run details: [bold]soup runs show {run_id}[/]",title="[bold green]Training Complete![/]",diff --git a/src/soup_cli/config/schema.py b/src/soup_cli/config/schema.pyindex 48016cb9..374f4552 100644--- a/src/soup_cli/config/schema.py+++ b/src/soup_cli/config/schema.py@@ -3217,12 +3217,15 @@ class TrainingConfig(BaseModel):default=0.5, gt=0.0, lt=1.0,description="Multiply LR by this factor on each spike recovery (0.5 = halve)",)- # ReLoRA (v0.39.0 Part B)+ # ReLoRA (v0.39.0 Part B / #693 paper-faithful restart)relora_steps: Optional[int] = Field(default=None, ge=1, le=10**7,description=(- "Fire ReLoRA magnitude-prune + optimizer reset every N global steps. "- "None disables. Requires a LoRA-style PEFT (not VeRA)."+ "Fire a paper-faithful ReLoRA restart every N global steps: merge the "+ "LoRA update into the base weight, reinitialize lora_A/lora_B, and "+ "optionally clear optimizer state. None disables. Requires float LoRA "+ "(training.quantization defaults to '4bit' and must be set to 'none'; "+ "incompatible with VeRA, DoRA, layer streaming, and FSDP2 compile)."),)relora_warmup_ratio: float = Field(@@ -3231,13 +3234,17 @@ class TrainingConfig(BaseModel):)relora_reset_optimizer: bool = Field(default=True,- description="Clear optimizer state for pruned LoRA params on each ReLoRA fire",+ description=(+ "Clear optimizer state for lora_A/lora_B parameters after each "+ "ReLoRA merge+reinit restart"+ ),)relora_prune_ratio: float = Field(default=0.9, gt=0.0, lt=1.0,description=(- "Fraction of LoRA weights to zero out by magnitude on each fire "- "(0.9 keeps the top 10%). Must be < 1.0."+ "Deprecated: kept so older YAML still loads. Restarts no longer "+ "magnitude-prune adapter weights; relora_reset_optimizer controls "+ "optimizer clearing instead."),)# Convergence detection (v0.32.0 Part F)@@ -6833,9 +6840,11 @@ class SoupConfig(BaseModel):def _validate_relora_supported_tasks(self) -> "SoupConfig":"""v0.40.6 (#67) — ReLoRA callback wired in every transformer-backendtrainer (sft / dpo / grpo / kto / orpo / simpo / ipo / ppo /- reward_model / pretrain / embedding / bco).+ reward_model / pretrain / embedding / bco / distill).- MLX backend still rejected: the callback is HF Trainer-specific.+ #693 — paper-faithful restart merges into the base weight, so reject+ combos where the base is not a writable float tensor or where the+ adapter is not standard LoRA A/B."""if self.training.relora_steps is None:return self@@ -6845,6 +6854,36 @@ class SoupConfig(BaseModel):"(callback is HF Trainer-specific). ""Use backend='transformers' or remove relora_steps.")+ tcfg = self.training+ lcfg = tcfg.lora+ if tcfg.quantization != "none":+ raise ValueError(+ f"relora_steps requires quantization='none' "+ f"(got {tcfg.quantization!r}); ReLoRA restart merges into the "+ f"base weight, which requires a writable float base."+ )+ if tcfg.stream_layers:+ raise ValueError(+ "relora_steps is incompatible with training.stream_layers=True: "+ "layer streaming loads weights ephemerally and cannot accept "+ "in-place base merges."+ )+ if lcfg.use_vera:+ raise ValueError(+ "relora_steps is incompatible with lora.use_vera=True: ReLoRA "+ "restart merges B@A into the base; VeRA uses shared vectors, "+ "not standard LoRA A/B matrices."+ )+ if lcfg.use_dora:+ raise ValueError(+ "relora_steps is incompatible with lora.use_dora=True: ReLoRA "+ "restart merges B@A; DoRA decomposes magnitude separately."+ )+ if tcfg.use_fsdp2_compile:+ raise ValueError(+ "relora_steps is incompatible with training.use_fsdp2_compile=True: "+ "compiled FSDP2 wraps parameters and prevents in-place base merges."+ )return self@model_validator(mode="after")diff --git a/src/soup_cli/trainer/bco.py b/src/soup_cli/trainer/bco.pyindex 7115e680..005ee0e7 100644--- a/src/soup_cli/trainer/bco.py+++ b/src/soup_cli/trainer/bco.py@@ -420,7 +420,14 @@ class BCOTrainerWrapper:self.trainer.train(resume_from_checkpoint=resume_from_checkpoint)duration = time.time() - start- self.trainer.save_model(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )self.tokenizer.save_pretrained(self._output_dir)logs = self.trainer.state.log_historydiff --git a/src/soup_cli/trainer/distill.py b/src/soup_cli/trainer/distill.pyindex 265efc62..8e1c5e3f 100644--- a/src/soup_cli/trainer/distill.py+++ b/src/soup_cli/trainer/distill.py@@ -1126,7 +1126,14 @@ class DistillTrainerWrapper:self.nonfinite_tracker.check_and_warn()duration = time.time() - start- self.trainer.save_model(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )self.tokenizer.save_pretrained(self._output_dir)logs = self.trainer.state.log_historydiff --git a/src/soup_cli/trainer/dpo.py b/src/soup_cli/trainer/dpo.pyindex 8742046f..a7b4ea0e 100644--- a/src/soup_cli/trainer/dpo.py+++ b/src/soup_cli/trainer/dpo.py@@ -263,7 +263,7 @@ class DPOTrainerWrapper(StreamingSetupMixin):attach_empty_param_group_guard(self.trainer)- # v0.40.6 #67 — ReLoRA callback (magnitude-prune LoRA every N steps).+ # v0.40.6 #67 — ReLoRA merge-and-reinitialize restart callback.from soup_cli.utils.peft_wiring import (attach_curriculum_callback,attach_loraplus_optimizer,@@ -456,9 +456,16 @@ class DPOTrainerWrapper(StreamingSetupMixin):self.trainer.train(resume_from_checkpoint=resume_from_checkpoint)duration = time.time() - start- # Save final model (LoRA adapter)- self.trainer.save_model(self._output_dir)- self._assert_streamed_adapter_saved(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )+ if self.config.training.relora_steps is None:+ self._assert_streamed_adapter_saved(self._output_dir)self.tokenizer.save_pretrained(self._output_dir)# Extract metricsdiff --git a/src/soup_cli/trainer/embedding.py b/src/soup_cli/trainer/embedding.pyindex 1e79964e..b37b088a 100644--- a/src/soup_cli/trainer/embedding.py+++ b/src/soup_cli/trainer/embedding.py@@ -425,7 +425,14 @@ class EmbeddingTrainerWrapper:self.trainer.train(resume_from_checkpoint=resume_from_checkpoint)duration = time.time() - start- self.trainer.save_model(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )self.tokenizer.save_pretrained(self._output_dir)logs = self.trainer.state.log_historydiff --git a/src/soup_cli/trainer/grpo.py b/src/soup_cli/trainer/grpo.pyindex 4b667966..d0f8dfe6 100644--- a/src/soup_cli/trainer/grpo.py+++ b/src/soup_cli/trainer/grpo.py@@ -604,7 +604,7 @@ class GRPOTrainerWrapper:task="grpo",)- # v0.40.6 #67 — ReLoRA callback (magnitude-prune LoRA every N steps).+ # v0.40.6 #67 — ReLoRA merge-and-reinitialize restart callback.from soup_cli.utils.peft_wiring import (attach_curriculum_callback,attach_loraplus_optimizer,@@ -786,8 +786,14 @@ class GRPOTrainerWrapper:self.trainer.train(resume_from_checkpoint=resume_from_checkpoint)duration = time.time() - start- # Save final model (LoRA adapter)- self.trainer.save_model(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )self.tokenizer.save_pretrained(self._output_dir)# Extract metricsdiff --git a/src/soup_cli/trainer/ipo.py b/src/soup_cli/trainer/ipo.pyindex 4e37fe7a..092b9f2e 100644--- a/src/soup_cli/trainer/ipo.py+++ b/src/soup_cli/trainer/ipo.py@@ -386,7 +386,14 @@ class IPOTrainerWrapper:self.trainer.train(resume_from_checkpoint=resume_from_checkpoint)duration = time.time() - start- self.trainer.save_model(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )self.tokenizer.save_pretrained(self._output_dir)logs = self.trainer.state.log_historydiff --git a/src/soup_cli/trainer/kto.py b/src/soup_cli/trainer/kto.pyindex f365e2da..b9ab6b07 100644--- a/src/soup_cli/trainer/kto.py+++ b/src/soup_cli/trainer/kto.py@@ -228,7 +228,7 @@ class KTOTrainerWrapper(StreamingSetupMixin):attach_empty_param_group_guard(self.trainer)- # v0.40.6 #67 — ReLoRA callback (magnitude-prune LoRA every N steps).+ # v0.40.6 #67 — ReLoRA merge-and-reinitialize restart callback.from soup_cli.utils.peft_wiring import (attach_curriculum_callback,attach_loraplus_optimizer,@@ -406,9 +406,17 @@ class KTOTrainerWrapper(StreamingSetupMixin):self.trainer.train(resume_from_checkpoint=resume_from_checkpoint)duration = time.time() - start- # Save final model (LoRA adapter)- self.trainer.save_model(self._output_dir)- self._assert_streamed_adapter_saved(self._output_dir)+ # Save final model; ReLoRA output is dense.+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )+ if self.config.training.relora_steps is None:+ self._assert_streamed_adapter_saved(self._output_dir)self.tokenizer.save_pretrained(self._output_dir)# Extract metricsdiff --git a/src/soup_cli/trainer/orpo.py b/src/soup_cli/trainer/orpo.pyindex 5663e1f5..faf8d1a1 100644--- a/src/soup_cli/trainer/orpo.py+++ b/src/soup_cli/trainer/orpo.py@@ -426,8 +426,16 @@ class ORPOTrainerWrapper(StreamingSetupMixin):self.trainer.train(resume_from_checkpoint=resume_from_checkpoint)duration = time.time() - start- self.trainer.save_model(self._output_dir)- self._assert_streamed_adapter_saved(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )+ if self.config.training.relora_steps is None:+ self._assert_streamed_adapter_saved(self._output_dir)self.tokenizer.save_pretrained(self._output_dir)logs = self.trainer.state.log_historydiff --git a/src/soup_cli/trainer/ppo.py b/src/soup_cli/trainer/ppo.pyindex 567fd246..d00b23b4 100644--- a/src/soup_cli/trainer/ppo.py+++ b/src/soup_cli/trainer/ppo.py@@ -462,7 +462,7 @@ class PPOTrainerWrapper:task="ppo",)- # v0.40.6 #67 — ReLoRA callback (magnitude-prune LoRA every N steps).+ # v0.40.6 #67 — ReLoRA merge-and-reinitialize restart callback.# LoRA+ (#724/#745) is wired ABOVE via constructor injection, not here:# PPO's trainer builds its scheduler eagerly, so the optimizer has to be# passed to the constructor rather than attached after it.@@ -787,8 +787,14 @@ class PPOTrainerWrapper:self.trainer.train()duration = time.time() - start- # Save final model (LoRA adapter)- self.trainer.save_model(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )self.tokenizer.save_pretrained(self._output_dir)# Extract metrics@@ -883,8 +889,14 @@ class PPOTrainerWrapper:duration = time.time() - start- # Save final model (LoRA adapter)- self.model.save_pretrained(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )self.tokenizer.save_pretrained(self._output_dir)# Extract metricsdiff --git a/src/soup_cli/trainer/pretrain.py b/src/soup_cli/trainer/pretrain.pyindex 79f76eb5..4b9599cd 100644--- a/src/soup_cli/trainer/pretrain.py+++ b/src/soup_cli/trainer/pretrain.py@@ -281,7 +281,7 @@ class PretrainTrainerWrapper:attach_empty_param_group_guard(self.trainer)- # v0.40.6 #67 — ReLoRA callback (magnitude-prune LoRA every N steps).+ # v0.40.6 #67 — ReLoRA merge-and-reinitialize restart callback.from soup_cli.utils.peft_wiring import (attach_curriculum_callback,attach_lisa_callback,@@ -523,8 +523,15 @@ class PretrainTrainerWrapper:self.trainer.train(resume_from_checkpoint=resume_from_checkpoint)duration = time.time() - start- # Save final model (LoRA adapter)- self.trainer.save_model(self._output_dir)+ # Save final model; ReLoRA output is dense.+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )self.tokenizer.save_pretrained(self._output_dir)# Extract metricsdiff --git a/src/soup_cli/trainer/reward_model.py b/src/soup_cli/trainer/reward_model.pyindex 1f23cce9..c97b0cfd 100644--- a/src/soup_cli/trainer/reward_model.py+++ b/src/soup_cli/trainer/reward_model.py@@ -354,7 +354,14 @@ class RewardModelTrainerWrapper:duration = time.time() - start# Save final model- self.trainer.save_model(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )self.tokenizer.save_pretrained(self._output_dir)# Extract metricsdiff --git a/src/soup_cli/trainer/sft.py b/src/soup_cli/trainer/sft.pyindex 1ae6c3a3..d21d3f27 100644--- a/src/soup_cli/trainer/sft.py+++ b/src/soup_cli/trainer/sft.py@@ -2311,13 +2311,20 @@ class SFTTrainerWrapper(StreamingSetupMixin):self.trainer.state.log_history, model=self.trainer.model)- # Save final model (LoRA adapter)- self.trainer.save_model(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )if self._quest_metadata is not None:from soup_cli.utils.quest import write_metadatawrite_metadata(self._output_dir, self._quest_metadata)- self._assert_streamed_adapter_saved(self._output_dir)+ if self.config.training.relora_steps is None:+ self._assert_streamed_adapter_saved(self._output_dir)# #335 — under torch.compile the Trainer saves THROUGH the wrapper, so# every key gains `_orig_mod.` and PeftModel.from_pretrained then matches# none of them: it warns and leaves lora_B at zero init, i.e. the rundiff --git a/src/soup_cli/trainer/simpo.py b/src/soup_cli/trainer/simpo.pyindex 451dccc8..afef1bfd 100644--- a/src/soup_cli/trainer/simpo.py+++ b/src/soup_cli/trainer/simpo.py@@ -411,8 +411,16 @@ class SimPOTrainerWrapper(StreamingSetupMixin):self.trainer.train(resume_from_checkpoint=resume_from_checkpoint)duration = time.time() - start- self.trainer.save_model(self._output_dir)- self._assert_streamed_adapter_saved(self._output_dir)+ if self.config.training.relora_steps is None:+ self.trainer.save_model(self._output_dir)+ else:+ from soup_cli.utils.peft_wiring import save_model_with_relora++ save_model_with_relora(+ self.trainer, self._output_dir, self.config.training.relora_steps+ )+ if self.config.training.relora_steps is None:+ self._assert_streamed_adapter_saved(self._output_dir)self.tokenizer.save_pretrained(self._output_dir)logs = self.trainer.state.log_historydiff --git a/src/soup_cli/utils/peft_wiring.py b/src/soup_cli/utils/peft_wiring.pyindex 4368e7e2..3473ea6b 100644--- a/src/soup_cli/utils/peft_wiring.py+++ b/src/soup_cli/utils/peft_wiring.py@@ -544,6 +544,32 @@ def apply_post_lora_patches(model: Any) -> None:logger.debug("strip_lora_dropout_for_3d_experts skipped: %s", exc)+def _relora_merge_target(trainer: Any) -> tuple[Any, Any, str | None, Any]:+ """Return the save owner, model holder, optional policy attr, and PEFT model."""+ owner = getattr(trainer, "__dict__", {}).get("_trainer", trainer)+ holder = getattr(owner, "model", None)+ policy = getattr(holder, "policy", None)+ if policy is not None and callable(getattr(policy, "merge_and_unload", None)):+ return owner, holder, "policy", policy+ return owner, holder, None, holder+++def _validate_relora_save_capability(trainer: Any) -> None:+ """Reject ReLoRA trainers whose final model cannot be merged into a dense model."""+ try:+ import torch.nn as nn+ except ImportError:+ return++ _owner, _holder, _policy_attr, model = _relora_merge_target(trainer)+ if isinstance(model, nn.Module) and not callable(+ getattr(model, "merge_and_unload", None)+ ):+ raise RuntimeError(+ "ReLoRA requires a PEFT model with merge_and_unload() for dense final saving."+ )++def attach_relora_callback(trainer: Any, tcfg: Any) -> bool:"""Attach :class:`ReLoRACallback` when ``training.relora_steps`` is set.@@ -558,9 +584,49 @@ def attach_relora_callback(trainer: Any, tcfg: Any) -> bool:# rather than a silent skip. Matches project policy (v0.34.0 / v0.39.0).if relora_steps is None:return False++ args = getattr(trainer, "args", None)+ try:+ world_size = int(getattr(args, "world_size", 1)) if args is not None else 1+ except (TypeError, ValueError):+ world_size = 1+ if world_size > 1:+ raise ValueError(+ "ReLoRA is not supported with world_size > 1 "+ f"(got world_size={world_size}): restarts are single-process only. "+ "Run with one process or remove training.relora_steps."+ )+ # `is True` is intentional: MagicMock trainers expose unset flags as+ # truthy mocks, but only an actual Trainer flag should refuse the run.+ if getattr(trainer, "is_deepspeed_enabled", False) is True:+ raise ValueError(+ "ReLoRA is not supported with DeepSpeed "+ "(is_deepspeed_enabled=True): restarts cannot merge sharded bases. "+ "Run without DeepSpeed or remove training.relora_steps."+ )+ if getattr(trainer, "is_fsdp_enabled", False) is True:+ raise ValueError(+ "ReLoRA is not supported with FSDP "+ "(is_fsdp_enabled=True): restarts cannot merge sharded bases. "+ "Run without FSDP or remove training.relora_steps."+ )+# Pydantic schema guarantees these fields exist on `TrainingConfig`. Read# them directly so a misnamed attr fails loudly with `AttributeError`.- from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy+ from soup_cli.utils.relora import (+ ReLoRACallback,+ ReLoRAPolicy,+ _preflight_writable_bases,+ )++ model = getattr(trainer, "model", None)+ try:+ import torch.nn as nn+ except ImportError:+ nn = None+ if nn is not None and isinstance(model, nn.Module):+ _preflight_writable_bases(model)+ _validate_relora_save_capability(trainer)policy = ReLoRAPolicy(steps=int(relora_steps),@@ -568,10 +634,42 @@ def attach_relora_callback(trainer: Any, tcfg: Any) -> bool:reset_optimizer=bool(tcfg.relora_reset_optimizer),prune_ratio=float(tcfg.relora_prune_ratio),)+ if "relora_prune_ratio" in getattr(tcfg, "model_fields_set", ()):+ logger.warning(+ "training.relora_prune_ratio is ignored: ReLoRA restarts no longer prune "+ "adapter weights"+ )trainer.add_callback(ReLoRACallback(policy=policy))return True+def save_model_with_relora(+ trainer: Any,+ output_dir: str,+ relora_steps: int | None,+) -> None:+ """Save a dense final model when ReLoRA has been configured."""+ if relora_steps is None:+ trainer.save_model(output_dir)+ return++ owner, holder, policy_attr, model = _relora_merge_target(trainer)+ merge_and_unload = getattr(model, "merge_and_unload", None)+ if merge_and_unload is None:+ raise RuntimeError(+ "ReLoRA final save requires a PEFT model with merge_and_unload()."+ )++ merged_model = merge_and_unload()+ if policy_attr is not None:+ setattr(holder, policy_attr, merged_model)+ else:+ owner.model = merged_model+ if getattr(owner, "model_wrapped", None) is not None:+ owner.model_wrapped = merged_model+ trainer.save_model(output_dir)++def build_loraplus_optimizer(model: Any, args: Any, tcfg: Any) -> Any:"""Build a PEFT LoRA+ optimizer from a model + ``TrainingArguments``, or ``None``.diff --git a/src/soup_cli/utils/relora.py b/src/soup_cli/utils/relora.pyindex 7b4be8c0..76869434 100644--- a/src/soup_cli/utils/relora.py+++ b/src/soup_cli/utils/relora.py@@ -1,9 +1,9 @@-"""ReLoRA — periodic LoRA adapter magnitude-prune + optimizer reset.+"""ReLoRA — periodic merge-into-base restarts for LoRA training.-Mirrors the technique described in the ReLoRA paper / Axolotl-``monkeypatch/relora.py``: every N steps, magnitude-prune the LoRA-adapter weights and reset the optimizer state. Useful for very long-training runs where the LoRA capacity saturates.+Implements the restart loop from the ReLoRA paper (arXiv:2307.05695):+every N steps, merge the low-rank update into the frozen base weight,+reinitialize ``lora_A`` / ``lora_B``, clear optimizer state for those+adapters, and run a short learning-rate warm-up.The callback is a no-op when ``policy`` is ``None``. Pass a:class:`ReLoRAPolicy` to enable it. Lazy imports keep the module CLI-fast.@@ -11,26 +11,16 @@ The callback is a no-op when ``policy`` is ``None``. Pass afrom __future__ import annotations+import mathfrom dataclasses import dataclass-from typing import Any, Optional+from typing import Any, Iterator, Optional, Tuple-# Cap relora_steps to a sane upper bound.MAX_RELORA_STEPS = 10**7@dataclass(frozen=True)class ReLoRAPolicy:- """Frozen policy for the ReLoRA callback.-- Attributes:- steps: fire every N global steps (must be > 0).- warmup_ratio: fraction of total steps to skip at the start ([0, 1]).- reset_optimizer: if True, clears optimizer state for the pruned- LoRA parameters after pruning so momentum doesn't fight the- new sparse weights.- prune_ratio: fraction of LoRA weights to zero out, by magnitude- (0 < x <= 1; e.g. 0.9 keeps the top 10%).- """+ """Frozen policy for the ReLoRA callback."""steps: intwarmup_ratio: float = 0.1@@ -66,13 +56,15 @@ class ReLoRAPolicy:return Falsereturn True+ def lr_warmup_steps(self) -> int:+ return min(100, max(1, self.steps // 10))+def magnitude_prune_tensor(tensor: Any, prune_ratio: float) -> Any:- """Zero out the smallest-magnitude entries of ``tensor`` in place.+ """Zero smallest-magnitude entries in place with exact keep-count (#693).- ``prune_ratio=0.9`` keeps the top 10% of weights by absolute value.- ``prune_ratio`` of exactly 0.0 or 1.0 is rejected to avoid silent- no-ops or wholesale zeroing.+ Unused by the restart callback (optimizer moments are fully cleared, not+ pruned); retained so the exact keep-count under ties stays tested."""if not (0.0 < prune_ratio < 1.0):raise ValueError(@@ -84,43 +76,219 @@ def magnitude_prune_tensor(tensor: Any, prune_ratio: float) -> Any:raise TypeError(f"magnitude_prune_tensor expects torch.Tensor, got {type(tensor)}")flat = tensor.detach().abs().reshape(-1)- # Empty / 1-element tensor: nothing meaningful to prune.if flat.numel() <= 1:return tensor- k = max(1, int(flat.numel() * prune_ratio))- if k >= flat.numel():- # keep the single largest- k = flat.numel() - 1- # The k-th smallest absolute value: anything <= it gets zeroed- threshold = torch.kthvalue(flat, k).values- mask = tensor.detach().abs() > threshold- tensor.detach().mul_(mask.to(tensor.dtype))+ num_prune = max(1, int(flat.numel() * prune_ratio))+ if num_prune >= flat.numel():+ num_prune = flat.numel() - 1+ num_keep = flat.numel() - num_prune+ _, keep_idx = torch.topk(flat, num_keep, largest=True, sorted=False)+ mask = torch.zeros_like(flat, dtype=torch.bool)+ mask[keep_idx] = True+ tensor.detach().mul_(mask.reshape(tensor.shape).to(tensor.dtype))return tensor-def _is_lora_param_name(name: str) -> bool:- """Match PEFT's lora_A / lora_B parameter naming."""- return ("lora_A" in name) or ("lora_B" in name)+def _is_sharded_or_quantized_tensor(tensor: Any) -> bool:+ import torch # lazy++ if not isinstance(tensor, torch.Tensor):+ return True+ type_name = type(tensor).__name__+ if type_name in {"DTensor", "Params4bit", "Int8Params"}:+ return True+ if getattr(tensor, "quant_state", None) is not None:+ return True+ data = getattr(tensor, "data", None)+ if data is not None and data is not tensor and not isinstance(data, torch.Tensor):+ return True+ return False-def _try_import_callback_base():- """Return HF ``TrainerCallback`` (or ``object`` when transformers is absent).+def _require_writable_base(base_weight: Any) -> Any:+ import torch # lazy- Imported inside the function so the module has no top-level transformers- dependency; the class below still inherits every no-op event stub the HF- dispatch loop requires. Mirrors ``monitoring/curriculum_callback.py`` /- ``utils/lisa.py``.- """+ if _is_sharded_or_quantized_tensor(base_weight):+ raise RuntimeError(+ "ReLoRA restart cannot merge into a quantized or sharded base weight. "+ "Use quantization='none' on a resident float LoRA run."+ )+ if not isinstance(base_weight, torch.Tensor):+ raise RuntimeError(+ f"ReLoRA restart expected a torch.Tensor base weight, got {type(base_weight)}"+ )+ if not base_weight.is_floating_point():+ raise RuntimeError(+ "ReLoRA restart requires a floating-point base weight "+ f"(got dtype={base_weight.dtype})."+ )+ return base_weight+++def _resolve_adapter_key(module: Any) -> str:+ active = getattr(module, "active_adapter", None)+ if active is None:+ return "default"+ if isinstance(active, str):+ return active+ if isinstance(active, list):+ return active[0]+ return "default"+++def _resolve_lora_weight(module: Any, attr: str, adapter: str) -> Any:+ import torch.nn as nn # lazy++ container = getattr(module, attr, None)+ if container is None:+ raise RuntimeError(f"ReLoRA module missing {attr}")+ if isinstance(container, nn.ModuleDict):+ if adapter not in container:+ raise RuntimeError(+ f"ReLoRA adapter {adapter!r} not found in {attr} "+ f"(available: {list(container.keys())})"+ )+ return container[adapter].weight+ if hasattr(container, "weight"):+ return container.weight+ raise RuntimeError(f"ReLoRA could not resolve {attr} weight on {type(module)}")+++def _resolve_base_weight(module: Any) -> Any:+ if hasattr(module, "base_layer") and hasattr(module.base_layer, "weight"):+ return module.base_layer.weight+ if hasattr(module, "base") and hasattr(module.base, "weight"):+ return module.base.weight+ if hasattr(module, "weight") and not hasattr(module, "lora_embedding_A"):+ return module.weight+ raise RuntimeError(+ f"ReLoRA could not locate a base weight on module {type(module).__name__}"+ )+++def _compute_delta(module: Any, adapter: str) -> Any:+ get_delta_weight = getattr(module, "get_delta_weight", None)+ if get_delta_weight is None:+ raise RuntimeError(+ f"ReLoRA module {type(module).__name__} does not expose PEFT "+ "`get_delta_weight`"+ )+ return get_delta_weight(adapter)+++def _iter_lora_modules(model: Any) -> Iterator[Tuple[Any, str]]:+ import torch.nn as nn # lazy++ seen: set[int] = set()+ for module in model.modules():+ if not isinstance(module, nn.Module):+ continue+ if id(module) in seen:+ continue+ if not (hasattr(module, "lora_A") and hasattr(module, "lora_B")):+ continue+ # peft embedding adapters keep an empty lora_A ModuleDict. Linear LoRA+ # is still merged: peft puts empty embedding dicts on every LoraLayer.+ lora_a = getattr(module, "lora_A", None)+ if isinstance(lora_a, nn.ModuleDict) and len(lora_a) == 0:+ continue+ seen.add(id(module))+ yield module, _resolve_adapter_key(module)+++def _reinit_lora_weights(weight_a: Any, weight_b: Any) -> None:+ import torch.nn as nn # lazy++ nn.init.kaiming_uniform_(weight_a, a=math.sqrt(5))+ nn.init.zeros_(weight_b)+++def merge_reinit_lora_module(+ module: Any,+ adapter: str,+ *,+ merge: bool = True,+) -> Tuple[Any, Any]:+ """Merge one LoRA module into its base and reinitialize A/B."""+ import torch # lazy++ weight_a = _resolve_lora_weight(module, "lora_A", adapter)+ weight_b = _resolve_lora_weight(module, "lora_B", adapter)+ base_weight = _require_writable_base(_resolve_base_weight(module))++ if merge:+ delta = _compute_delta(module, adapter)+ if delta.shape != base_weight.shape:+ raise RuntimeError(+ f"ReLoRA delta shape {tuple(delta.shape)} does not match base "+ f"{tuple(base_weight.shape)} on {type(module).__name__}"+ )+ with torch.no_grad():+ base_weight.add_(delta.to(device=base_weight.device, dtype=base_weight.dtype))+ _reinit_lora_weights(weight_a, weight_b)+ return weight_a, weight_b+++def _preflight_writable_bases(model: Any) -> None:+ """Refuse a restart if any LoRA module's base cannot be merged in-place."""+ for module, _adapter in _iter_lora_modules(model):+ _require_writable_base(_resolve_base_weight(module))+++def _assert_optimizer_resettable(optimizer: Any) -> None:+ state = getattr(optimizer, "state", None)+ if state is None:+ raise RuntimeError(+ "ReLoRA restart could not clear optimizer state: optimizer has no "+ "`.state` dict (wrapped DeepSpeed/FSDP optimizers are unsupported)."+ )+++def _clear_optimizer_state(optimizer: Any, lora_params: list[Any]) -> None:+ state = optimizer.state+ for param in lora_params:+ if param in state:+ state[param] = type(state[param])() if state[param] else {}+++def _merge_reinit_and_reset(+ model: Any,+ optimizer: Any,+ *,+ reset_optimizer: bool,+ merge: bool = True,+) -> None:+ if optimizer is not None:+ _assert_optimizer_resettable(optimizer)++ _preflight_writable_bases(model)++ lora_params = []+ for module, adapter in _iter_lora_modules(model):+ weight_a, weight_b = merge_reinit_lora_module(module, adapter, merge=merge)+ if weight_a.requires_grad:+ lora_params.append(weight_a)+ if weight_b.requires_grad:+ lora_params.append(weight_b)++ if optimizer is None or not reset_optimizer or not lora_params:+ return++ _clear_optimizer_state(optimizer, lora_params)+++def _try_import_callback_base():+ """Return ``TrainerCallback`` without importing Transformers at module load."""try:from transformers import TrainerCallback # noqa: PLC0415return TrainerCallback- except Exception: # noqa: BLE001 — transformers optional in slim test envs.+ except Exception: # noqa: BLE001return objectclass _ReLoRACallback_body: # type: ignore[misc] # noqa: N801- """HF ``TrainerCallback`` that magnitude-prunes LoRA weights every N steps.+ """HF TrainerCallback that runs ReLoRA restarts every N steps.Subclasses the lazily-resolved ``TrainerCallback`` so it inherits the no-opdefault for every Trainer event — HF's ``CallbackHandler.call_event``@@ -134,6 +302,9 @@ class _ReLoRACallback_body: # type: ignore[misc] # noqa: N801self.policy = policyself.console = consoleself.fire_count = 0+ self._warmup_steps_total: Optional[int] = None+ self._warmup_steps_done = 0+ self._warmup_target_lrs: Optional[list[float]] = Nonedef on_step_end(self,@@ -144,6 +315,9 @@ class _ReLoRACallback_body: # type: ignore[misc] # noqa: N801) -> Any:if self.policy is None:return control+ optimizer = kwargs.get("optimizer")+ self._maybe_advance_lr_warmup(optimizer)+global_step = int(getattr(state, "global_step", 0) or 0)total_steps = getattr(state, "max_steps", None)try:@@ -153,47 +327,53 @@ class _ReLoRACallback_body: # type: ignore[misc] # noqa: N801if not self.policy.should_fire(global_step, total_steps_int):return controlmodel = kwargs.get("model")- optimizer = kwargs.get("optimizer")if model is None:return control- self._prune_and_reset(model, optimizer)+ self._merge_reinit_and_reset(model, optimizer)+ self._start_lr_warmup(optimizer)self.fire_count += 1if self.console is not None:try:self.console.print(- f"[yellow]ReLoRA[/yellow] fired at step {global_step} "- f"(prune_ratio={self.policy.prune_ratio})"+ f"[yellow]ReLoRA[/yellow] restart at step {global_step}")- except Exception: # noqa: BLE001 — console.print is best-effort in callback+ except Exception: # noqa: BLE001passreturn control- def _prune_and_reset(self, model: Any, optimizer: Any) -> None:- import torch # lazy-- pruned_params = []- for name, param in model.named_parameters():- if not _is_lora_param_name(name):- continue- if param.requires_grad and param.numel() > 0:- with torch.no_grad():- magnitude_prune_tensor(param.data, self.policy.prune_ratio)- pruned_params.append(param)+ def _merge_reinit_and_reset(self, model: Any, optimizer: Any) -> None:+ if self.policy is None:+ return+ _merge_reinit_and_reset(+ model,+ optimizer,+ reset_optimizer=self.policy.reset_optimizer,+ )- if optimizer is None or not self.policy.reset_optimizer:+ def _start_lr_warmup(self, optimizer: Any) -> None:+ if optimizer is None or self.policy is None:return- # Reset optimizer state only for the pruned parameters.- try:- state = getattr(optimizer, "state", None)- if state is None:- return- for param in pruned_params:- if param in state:- state[param] = type(state[param])() if state[param] else {}- except Exception:- # Optimizer state structure varies (DeepSpeed / FSDP wrap it);- # silent best-effort is the documented Axolotl behaviour too.+ warmup_steps = self.policy.lr_warmup_steps()+ self._warmup_steps_total = warmup_steps + 1+ self._warmup_steps_done = 1+ self._warmup_target_lrs = [float(pg["lr"]) for pg in optimizer.param_groups]+ frac = 1 / self._warmup_steps_total+ for pg, target in zip(optimizer.param_groups, self._warmup_target_lrs):+ pg["lr"] = target * frac++ def _maybe_advance_lr_warmup(self, optimizer: Any) -> None:+ if (+ optimizer is None+ or self._warmup_steps_total is None+ or self._warmup_target_lrs is None+ ):+ return+ if self._warmup_steps_done >= self._warmup_steps_total:return+ self._warmup_steps_done += 1+ frac = self._warmup_steps_done / self._warmup_steps_total+ for pg, target in zip(optimizer.param_groups, self._warmup_target_lrs):+ pg["lr"] = target * frac_LAZY_CALLBACKS = {diff --git a/tests/test_hf_integration.py b/tests/test_hf_integration.pyindex 6d7c3623..18fc6cbb 100644--- a/tests/test_hf_integration.py+++ b/tests/test_hf_integration.py@@ -1172,6 +1172,68 @@ class TestHfResumeRequiresPushAs:assert "push-as" in result.output.lower()++class TestReLoRAResumeRefusal:+ def _write_config(self, path):+ path.write_text(+ "base: meta-llama/Llama-3.1-8B\n"+ "task: sft\n"+ "data:\n"+ " train: data.jsonl\n"+ "training:\n"+ " quantization: none\n"+ " relora_steps: 1\n",+ encoding="utf-8",+ )++ def test_local_resume_is_rejected_before_checkpoint_resolution(+ self, tmp_path, monkeypatch+ ):+ cfg = tmp_path / "soup.yaml"+ self._write_config(cfg)+ monkeypatch.setattr(+ "soup_cli.commands.train._resolve_resume_or_exit",+ lambda *_args, **_kwargs: pytest.fail("checkpoint resolution should not run"),+ )+ result = runner.invoke(+ app,+ [+ "train",+ "--config",+ str(cfg),+ "--resume",+ str(tmp_path / "checkpoint"),+ "--dry-run",+ ],+ )+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert "cannot resume" in result.output.lower()+ assert "relora_steps" in result.output++ def test_hf_resume_is_rejected_before_download(self, tmp_path, monkeypatch):+ cfg = tmp_path / "soup.yaml"+ self._write_config(cfg)+ monkeypatch.setattr(+ "soup_cli.monitoring.hf_push.prepare_hf_resume",+ lambda *_args, **_kwargs: pytest.fail("HF resume should not run"),+ )+ result = runner.invoke(+ app,+ [+ "train",+ "--config",+ str(cfg),+ "--push-as",+ "user/model",+ "--hf-resume",+ "--dry-run",+ ],+ )+ assert result.exit_code == 1, (result.output, repr(result.exception))+ assert "cannot resume" in result.output.lower()+ assert "relora_steps" in result.output++class TestDataPushHappyPathExtras:def test_create_repo_called_with_dataset_type(self, tmp_path, monkeypatch):monkeypatch.chdir(tmp_path)diff --git a/tests/test_relora.py b/tests/test_relora.pyindex 95f8d586..41e7ec6b 100644--- a/tests/test_relora.py+++ b/tests/test_relora.py@@ -1,7 +1,10 @@-"""Tests for v0.39.0 Part B — ReLoRA callback."""+"""Tests for v0.39.0 Part B — ReLoRA callback (#693 paper-faithful restarts)."""from __future__ import annotations+import ast+from pathlib import Path+from types import SimpleNamespacefrom unittest.mock import MagicMockimport pytest@@ -9,6 +12,9 @@ from pydantic import ValidationErrorfrom soup_cli.config.schema import TrainingConfig+TRAINER_DIR = Path(__file__).resolve().parents[1] / "src" / "soup_cli" / "trainer"++class TestReLoRASchema:def test_default_disabled(self):@@ -31,7 +37,6 @@ class TestReLoRASchema:TrainingConfig(relora_steps=-1)def test_relora_steps_upper_bound(self):- # Cap at 10**7 to prevent overflow / nonsensical valueswith pytest.raises(ValidationError):TrainingConfig(relora_steps=10**8)@@ -59,30 +64,34 @@ class TestReLoRAPolicy:from dataclasses import FrozenInstanceErrorfrom soup_cli.utils.relora import ReLoRAPolicy+p = ReLoRAPolicy(steps=500, warmup_ratio=0.1, reset_optimizer=True, prune_ratio=0.9)with pytest.raises(FrozenInstanceError):p.steps = 999 # type: ignoredef test_policy_should_fire_step_zero_no(self):from soup_cli.utils.relora import ReLoRAPolicy+p = ReLoRAPolicy(steps=500)assert p.should_fire(global_step=0) is Falsedef test_policy_should_fire_at_multiple(self):from soup_cli.utils.relora import ReLoRAPolicy+p = ReLoRAPolicy(steps=500)assert p.should_fire(global_step=500) is Trueassert p.should_fire(global_step=1000) is Truedef test_policy_should_fire_skips_warmup(self):from soup_cli.utils.relora import ReLoRAPolicy- # warmup_ratio=0.5 over total 1000 = first 500 skipped+p = ReLoRAPolicy(steps=200, warmup_ratio=0.5)assert p.should_fire(global_step=200, total_steps=1000) is Falseassert p.should_fire(global_step=600, total_steps=1000) is Truedef test_policy_rejects_invalid_steps(self):from soup_cli.utils.relora import ReLoRAPolicy+with pytest.raises(ValueError):ReLoRAPolicy(steps=0)with pytest.raises(ValueError):@@ -90,6 +99,7 @@ class TestReLoRAPolicy:def test_policy_rejects_invalid_prune_ratio(self):from soup_cli.utils.relora import ReLoRAPolicy+with pytest.raises(ValueError):ReLoRAPolicy(steps=500, prune_ratio=0.0)with pytest.raises(ValueError):@@ -107,14 +117,23 @@ class TestMagnitudePrune:from soup_cli.utils.relora import magnitude_prune_tensorx = torch.tensor([0.01, 0.02, 0.5, 1.0, 2.0])- # prune_ratio=0.6 → keep top 40% (2 of 5) → smallest 3 zeroedout = magnitude_prune_tensor(x.clone(), prune_ratio=0.6)nonzero = (out != 0).sum().item()assert nonzero == 2- # the two largest must surviveassert (out.abs() == 2.0).any()assert (out.abs() == 1.0).any()+ def test_magnitude_prune_tie_keeps_exact_count(self):+ try:+ import torch+ except ImportError:+ pytest.skip("torch not available")+ from soup_cli.utils.relora import magnitude_prune_tensor++ x = torch.ones(10)+ out = magnitude_prune_tensor(x.clone(), prune_ratio=0.9)+ assert (out != 0).sum().item() == 1+def test_magnitude_prune_single_element_no_crash(self):try:import torch@@ -122,10 +141,8 @@ class TestMagnitudePrune:pytest.skip("torch not available")from soup_cli.utils.relora import magnitude_prune_tensor- # 1-element tensor — kthvalue(_, 0) would raise; helper must short-circuit.x = torch.tensor([3.14])out = magnitude_prune_tensor(x.clone(), prune_ratio=0.5)- # untouched (use approx for float32 storage)assert out.item() == pytest.approx(3.14, abs=1e-5)def test_magnitude_prune_keep_all(self):@@ -137,7 +154,6 @@ class TestMagnitudePrune:x = torch.tensor([1.0, 2.0, 3.0])out = magnitude_prune_tensor(x.clone(), prune_ratio=0.001)- # near-zero prune ratio → at least one element keptassert (out != 0).any()def test_magnitude_prune_rejects_invalid_ratio(self):@@ -146,6 +162,7 @@ class TestMagnitudePrune:except ImportError:pytest.skip("torch not available")from soup_cli.utils.relora import magnitude_prune_tensor+x = torch.zeros(3)with pytest.raises(ValueError):magnitude_prune_tensor(x, prune_ratio=0.0)@@ -158,6 +175,7 @@ class TestMagnitudePrune:except ImportError:pytest.skip("torch not available")from soup_cli.utils.relora import magnitude_prune_tensor+with pytest.raises(TypeError):magnitude_prune_tensor([1.0, 2.0, 3.0], prune_ratio=0.5)with pytest.raises(TypeError):@@ -167,183 +185,369 @@ class TestMagnitudePrune:class TestReLoRACallback:def test_callback_disabled_no_op(self):from soup_cli.utils.relora import ReLoRACallback+cb = ReLoRACallback(policy=None)- # disabled callback never firesstate = MagicMock(global_step=500, max_steps=1000)ctrl = MagicMock()- args = MagicMock()- cb.on_step_end(args, state, ctrl)+ cb.on_step_end(MagicMock(), state, ctrl)assert cb.fire_count == 0def test_callback_fires_on_relora_step(self):from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy+cb = ReLoRACallback(policy=ReLoRAPolicy(steps=100))- # mock model with PEFT-style lora_A / lora_B parameters- cb._prune_and_reset = MagicMock() # type: ignore[method-assign]+ cb._merge_reinit_and_reset = MagicMock() # type: ignore[method-assign]state = MagicMock(global_step=100, max_steps=1000)- ctrl = MagicMock()- args = MagicMock()- cb.on_step_end(args, state, ctrl, model=MagicMock(), optimizer=MagicMock())+ cb.on_step_end(MagicMock(), state, MagicMock(), model=MagicMock(), optimizer=MagicMock())assert cb.fire_count == 1- cb._prune_and_reset.assert_called_once()+ cb._merge_reinit_and_reset.assert_called_once()def test_callback_does_not_fire_off_step(self):from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy+cb = ReLoRACallback(policy=ReLoRAPolicy(steps=100))- cb._prune_and_reset = MagicMock() # type: ignore[method-assign]+ cb._merge_reinit_and_reset = MagicMock() # type: ignore[method-assign]state = MagicMock(global_step=99, max_steps=1000)cb.on_step_end(MagicMock(), state, MagicMock())assert cb.fire_count == 0- cb._prune_and_reset.assert_not_called()+ cb._merge_reinit_and_reset.assert_not_called()def test_callback_skips_warmup(self):from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy+cb = ReLoRACallback(policy=ReLoRAPolicy(steps=100, warmup_ratio=0.5))- cb._prune_and_reset = MagicMock() # type: ignore[method-assign]- # at step 100 with total 1000 → warmup is 500 → skip+ cb._merge_reinit_and_reset = MagicMock() # type: ignore[method-assign]state = MagicMock(global_step=100, max_steps=1000)cb.on_step_end(MagicMock(), state, MagicMock(), model=MagicMock(), optimizer=MagicMock())assert cb.fire_count == 0+ def test_lr_warmup_via_param_groups(self):+ from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy-class TestReLoRATaskGate:- def _base_cfg(self, task: str = "sft", backend: str = "transformers") -> dict:- return {- "base": "meta-llama/Llama-3.1-8B",- "task": task,- "backend": backend,- "data": {"train": "./data.jsonl"},- "training": {"relora_steps": 100},- }+ class _Opt:+ def __init__(self, lr):+ self.param_groups = [{"lr": lr}]+ self.state = {}- def test_sft_accepted(self):- import yaml+ cb = ReLoRACallback(policy=ReLoRAPolicy(steps=20))+ opt = _Opt(0.01)+ cb._start_lr_warmup(opt)+ assert opt.param_groups[0]["lr"] == pytest.approx(0.01 / 3)+ assert cb._warmup_target_lrs == [0.01]+ cb._maybe_advance_lr_warmup(opt)+ assert opt.param_groups[0]["lr"] == pytest.approx(0.02 / 3)+ cb._maybe_advance_lr_warmup(opt)+ assert opt.param_groups[0]["lr"] == pytest.approx(0.01)- from soup_cli.config.loader import load_config_from_string- cfg = load_config_from_string(yaml.safe_dump(self._base_cfg("sft")))- assert cfg.training.relora_steps == 100+ def test_lr_warmup_advances_on_next_step_after_fire(self):+ from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy- @pytest.mark.parametrize(- "task",- ["dpo", "grpo", "kto", "orpo", "simpo", "ipo",- "ppo", "reward_model", "pretrain", "embedding", "bco"],- )- def test_other_tasks_accepted(self, task):- # v0.40.6 (#67) — multi-trainer expansion lifted the SFT-only gate.- import yaml+ class _Opt:+ def __init__(self, lr):+ self.param_groups = [{"lr": lr}]+ self.state = {}- from soup_cli.config.loader import load_config_from_string- cfg = load_config_from_string(yaml.safe_dump(self._base_cfg(task)))- assert cfg.training.relora_steps == 100- assert cfg.task == task+ cb = ReLoRACallback(policy=ReLoRAPolicy(steps=10, warmup_ratio=0.0))+ model = _make_fake_lora_module()+ opt = _Opt(1e-3)+ state = MagicMock(global_step=10, max_steps=1000)+ cb.on_step_end(MagicMock(), state, MagicMock(), model=model, optimizer=opt)+ assert cb.fire_count == 1+ assert opt.param_groups[0]["lr"] == pytest.approx(5e-4)+ state = MagicMock(global_step=11, max_steps=1000)+ cb.on_step_end(MagicMock(), state, MagicMock(), model=model, optimizer=opt)+ assert cb.fire_count == 1+ assert opt.param_groups[0]["lr"] == pytest.approx(1e-3)- def test_mlx_backend_rejected(self):- import yaml+ def test_relora_step_one_never_uses_zero_lr(self):+ from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy- from soup_cli.config.loader import load_config_from_string- with pytest.raises(ValueError, match="mlx"):- load_config_from_string(yaml.safe_dump(self._base_cfg("sft", "mlx")))+ class _Opt:+ def __init__(self, lr):+ self.param_groups = [{"lr": lr}]+ self.state = {}- def test_no_relora_no_gate(self):- # multi-task without relora_steps stays valid- import yaml+ cb = ReLoRACallback(policy=ReLoRAPolicy(steps=1, warmup_ratio=0.0))+ model = _make_fake_lora_module()+ opt = _Opt(1e-3)+ cb.on_step_end(+ MagicMock(),+ MagicMock(global_step=1, max_steps=100),+ MagicMock(),+ model=model,+ optimizer=opt,+ )+ assert opt.param_groups[0]["lr"] == pytest.approx(5e-4)+ cb.on_step_end(+ MagicMock(),+ MagicMock(global_step=2, max_steps=100),+ MagicMock(),+ model=model,+ optimizer=opt,+ )+ assert 0 < opt.param_groups[0]["lr"] <= 1e-3- from soup_cli.config.loader import load_config_from_string- d = self._base_cfg("dpo")- d["training"].pop("relora_steps")- cfg = load_config_from_string(yaml.safe_dump(d))- assert cfg.training.relora_steps is None-class TestPruneAndReset:- def test_prune_and_reset_targets_lora_modules(self):+def _make_fake_lora_module():+ try:+ import torch.nn as nn+ except ImportError:+ pytest.skip("torch not available")++ class _Fake(nn.Module):+ def __init__(self):+ super().__init__()+ self.lora_A = nn.Linear(4, 2, bias=False)+ self.lora_B = nn.Linear(2, 4, bias=False)+ self.base = nn.Linear(4, 4, bias=False)++ def forward(self, x):+ return self.base(x) + self.lora_B(self.lora_A(x))++ def get_delta_weight(self, adapter):+ return self.lora_B.weight @ self.lora_A.weight++ return _Fake()+++def _make_quantized_lora_module():+ try:+ import torch.nn as nn+ except ImportError:+ pytest.skip("torch not available")++ class _QuantWeight:+ quant_state = object()++ class _Fake(nn.Module):+ def __init__(self):+ super().__init__()+ self.lora_A = nn.Linear(4, 2, bias=False)+ self.lora_B = nn.Linear(2, 4, bias=False)++ class _Base:+ weight = _QuantWeight()++ self.base = _Base()++ return _Fake()+++def _make_mixed_writable_quantized_parent():+ try:+ import torch.nn as nn+ except ImportError:+ pytest.skip("torch not available")++ class _Parent(nn.Module):+ def __init__(self):+ super().__init__()+ self.first = _make_fake_lora_module()+ self.second = _make_quantized_lora_module()++ return _Parent()+++def _single_process_trainer():+ trainer = MagicMock()+ trainer.args.world_size = 1+ trainer.is_deepspeed_enabled = False+ trainer.is_fsdp_enabled = False+ return trainer+++def _called_names(path: Path) -> set[str | None]:+ tree = ast.parse(path.read_text(encoding="utf-8"))+ names: set[str | None] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Call):+ func = node.func+ names.add(func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None))+ return names+++def test_every_relora_trainer_saves_through_dense_helper():+ relora_trainers = sorted(+ path.stem+ for path in TRAINER_DIR.glob("*.py")+ if "attach_relora_callback(" in path.read_text(encoding="utf-8")+ )+ assert len(relora_trainers) >= 13, relora_trainers+ for module in relora_trainers:+ assert "save_model_with_relora" in _called_names(TRAINER_DIR / f"{module}.py")+++class TestReLoRARestart:+ def test_effective_map_preserved_after_restart(self):try:import torch- import torch.nn as nnexcept ImportError:pytest.skip("torch not available")- from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy+ from soup_cli.utils.relora import _merge_reinit_and_reset- class FakeLoraModule(nn.Module):- def __init__(self):- super().__init__()- self.lora_A = nn.Linear(4, 2, bias=False)- self.lora_B = nn.Linear(2, 4, bias=False)- self.base = nn.Linear(4, 4, bias=False)+ model = _make_fake_lora_module()+ with torch.no_grad():+ model.lora_A.weight.fill_(0.1)+ model.lora_B.weight.fill_(0.2)+ model.base.weight.fill_(1.0)+ before_base = model.base.weight.clone()+ x = torch.randn(3, 4)+ before_out = model(x).detach()++ _merge_reinit_and_reset(model, None, reset_optimizer=False)- def forward(self, x):- return self.base(x) + self.lora_B(self.lora_A(x))+ after_out = model(x).detach()+ mse = ((before_out - after_out) ** 2).mean()+ assert mse.item() < 1e-5+ assert not torch.equal(model.base.weight, before_base)- model = FakeLoraModule()- # set known weight values+ def test_merge_false_mutation_large_mse(self):+ try:+ import torch+ except ImportError:+ pytest.skip("torch not available")+ from soup_cli.utils.relora import _merge_reinit_and_reset++ model = _make_fake_lora_module()with torch.no_grad():model.lora_A.weight.fill_(1.0)- model.lora_A.weight[0, 0] = 100.0+ model.lora_B.weight.fill_(1.0)+ model.base.weight.fill_(1.0)+ x = torch.ones(3, 4)+ before_out = model(x).detach()++ _merge_reinit_and_reset(model, None, reset_optimizer=False, merge=False)++ after_out = model(x).detach()+ mse = ((before_out - after_out) ** 2).mean()+ assert mse.item() > 1e-2 # merge skipped => lost LoRA delta++ def test_successive_restarts_accumulate_in_base(self):+ try:+ import torch+ except ImportError:+ pytest.skip("torch not available")+ from soup_cli.utils.relora import _merge_reinit_and_reset++ model = _make_fake_lora_module()+ with torch.no_grad():+ model.lora_A.weight.fill_(0.1)+ model.lora_B.weight.fill_(0.2)+ model.base.weight.zero_()+ base0 = model.base.weight.clone()++ _merge_reinit_and_reset(model, None, reset_optimizer=False)+ base1 = model.base.weight.clone()+ delta1 = base1 - base0+ assert delta1.abs().sum() > 0++ with torch.no_grad():+ model.lora_A.weight.fill_(0.3)+ model.lora_B.weight.fill_(0.4)+ _merge_reinit_and_reset(model, None, reset_optimizer=False)+ base2 = model.base.weight.clone()+ delta2 = base2 - base1+ assert delta2.abs().sum() > 0+ assert (base2 - base0).abs().sum() > delta1.abs().sum()++ def test_restart_cannot_dead_branch(self):+ try:+ import torch+ except ImportError:+ pytest.skip("torch not available")+ from soup_cli.utils.relora import _merge_reinit_and_reset++ model = _make_fake_lora_module()+ with torch.no_grad():+ model.lora_A.weight.fill_(0.5)model.lora_B.weight.fill_(0.5)+ model.base.weight.fill_(1.0)++ _merge_reinit_and_reset(model, None, reset_optimizer=False)++ assert not torch.all(model.lora_A.weight == 0)+ x = torch.randn(2, 4)+ out = model(x).sum()+ out.backward()+ assert model.lora_B.weight.grad is not None+ assert model.lora_B.weight.grad.abs().sum().item() > 0+++class TestMergeReinitAndReset:+ def test_merge_reinit_targets_lora_modules(self):+ try:+ import torch+ except ImportError:+ pytest.skip("torch not available")+ from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy++ model = _make_fake_lora_module()+ with torch.no_grad():+ model.lora_A.weight.fill_(0.1)+ model.lora_B.weight.fill_(0.2)model.base.weight.fill_(7.0)before_base = model.base.weight.clone()cb = ReLoRACallback(policy=ReLoRAPolicy(steps=10, prune_ratio=0.9))- opt = MagicMock()- opt.state = {}- cb._prune_and_reset(model, opt)+ cb._merge_reinit_and_reset(model, None)- # base must be untouched- assert torch.equal(model.base.weight, before_base)- # lora_A retains highest-magnitude entry- assert (model.lora_A.weight.abs() >= 100.0).any()- # lora_A overall has many zeros now (prune_ratio=0.9)- zero_frac = (model.lora_A.weight == 0).float().mean().item()- assert zero_frac > 0.5+ assert not torch.equal(model.base.weight, before_base)+ assert not torch.all(model.lora_A.weight == 0)+ assert torch.all(model.lora_B.weight == 0)- def test_prune_and_reset_clears_real_optimizer_state(self):+ def test_merge_reinit_clears_real_optimizer_state(self):try:import torch- import torch.nn as nnexcept ImportError:pytest.skip("torch not available")from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy- class FakeLoraModule(nn.Module):- def __init__(self):- super().__init__()- self.lora_A = nn.Linear(4, 2, bias=False)-- def forward(self, x):- return self.lora_A(x)-- model = FakeLoraModule()+ model = _make_fake_lora_module()opt = torch.optim.AdamW(model.parameters(), lr=1e-3)- # Run a step so opt.state is populated for the param.loss = model(torch.randn(2, 4)).sum()loss.backward()opt.step()- param = model.lora_A.weight- assert param in opt.state- assert len(opt.state[param]) > 0 # exp_avg, exp_avg_sq, step+ params = [model.lora_A.weight, model.lora_B.weight]+ for param in params:+ assert param in opt.state+ assert len(opt.state[param]) > 0cb = ReLoRACallback(policy=ReLoRAPolicy(steps=10, prune_ratio=0.9))- cb._prune_and_reset(model, opt)- # Optimizer state for the pruned param must have been reset to empty- assert len(opt.state[param]) == 0+ cb._merge_reinit_and_reset(model, opt)+ for param in params:+ assert len(opt.state[param]) == 0- def test_prune_and_reset_respects_reset_optimizer_false(self):+ def test_optimizer_reset_rejected_before_merge(self):try:import torch- import torch.nn as nnexcept ImportError:pytest.skip("torch not available")- from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy+ from soup_cli.utils.relora import _merge_reinit_and_reset- class FakeLoraModule(nn.Module):- def __init__(self):- super().__init__()- self.lora_A = nn.Linear(4, 2, bias=False)+ model = _make_fake_lora_module()+ with torch.no_grad():+ model.lora_A.weight.fill_(0.1)+ model.lora_B.weight.fill_(0.2)+ model.base.weight.fill_(1.0)+ before_base = model.base.weight.clone()++ optimizer = MagicMock()+ del optimizer.state++ with pytest.raises(RuntimeError, match="optimizer has no"):+ _merge_reinit_and_reset(model, optimizer, reset_optimizer=True)- def forward(self, x):- return self.lora_A(x)+ assert torch.equal(model.base.weight, before_base)- model = FakeLoraModule()+ def test_merge_reinit_respects_reset_optimizer_false(self):+ try:+ import torch+ except ImportError:+ pytest.skip("torch not available")+ from soup_cli.utils.relora import ReLoRACallback, ReLoRAPolicy++ model = _make_fake_lora_module()opt = torch.optim.AdamW(model.parameters(), lr=1e-3)loss = model(torch.randn(2, 4)).sum()loss.backward()@@ -354,6 +558,594 @@ class TestPruneAndReset:cb = ReLoRACallback(policy=ReLoRAPolicy(steps=10, prune_ratio=0.9, reset_optimizer=False))- cb._prune_and_reset(model, opt)- # State preserved when reset_optimizer=False+ cb._merge_reinit_and_reset(model, opt)assert len(opt.state[param]) == before++ def test_skips_embedding_lora_modules(self):+ try:+ import torch+ import torch.nn as nn+ except ImportError:+ pytest.skip("torch not available")+ from soup_cli.utils.relora import _merge_reinit_and_reset++ class _EmbedLora(nn.Module):+ def __init__(self):+ super().__init__()+ self.lora_A = nn.ModuleDict({})+ self.lora_B = nn.ModuleDict({})+ self.lora_embedding_A = nn.Parameter(torch.ones(2, 4))+ self.lora_embedding_B = nn.Parameter(torch.ones(4, 2))++ class _Parent(nn.Module):+ def __init__(self):+ super().__init__()+ self.embed = _EmbedLora()+ self.linear = _make_fake_lora_module()++ model = _Parent()+ with torch.no_grad():+ model.linear.lora_A.weight.fill_(0.1)+ model.linear.lora_B.weight.fill_(0.2)+ model.linear.base.weight.fill_(1.0)+ embed_a_before = model.embed.lora_embedding_A.detach().clone()+ embed_b_before = model.embed.lora_embedding_B.detach().clone()+ linear_base_before = model.linear.base.weight.detach().clone()++ _merge_reinit_and_reset(model, None, reset_optimizer=False)++ assert torch.equal(model.embed.lora_embedding_A, embed_a_before)+ assert torch.equal(model.embed.lora_embedding_B, embed_b_before)+ assert not torch.equal(model.linear.base.weight, linear_base_before)++ def test_iter_yields_linear_with_empty_embedding_dicts(self):+ try:+ import torch.nn as nn+ except ImportError:+ pytest.skip("torch not available")+ from soup_cli.utils.relora import _iter_lora_modules++ class _LinearWithEmptyEmbedDicts(nn.Module):+ def __init__(self):+ super().__init__()+ self.lora_A = nn.ModuleDict({"default": nn.Linear(4, 2, bias=False)})+ self.lora_B = nn.ModuleDict({"default": nn.Linear(2, 4, bias=False)})+ self.lora_embedding_A = nn.ParameterDict()+ self.lora_embedding_B = nn.ParameterDict()+ self.base_layer = nn.Linear(4, 4, bias=False)++ module = _LinearWithEmptyEmbedDicts()+ yielded = list(_iter_lora_modules(module))+ assert len(yielded) == 1+ assert yielded[0][0] is module++ def test_restart_refuses_partial_when_later_module_quantized(self):+ try:+ import torch+ except ImportError:+ pytest.skip("torch not available")+ from soup_cli.utils.relora import _merge_reinit_and_reset++ model = _make_mixed_writable_quantized_parent()+ with torch.no_grad():+ model.first.lora_A.weight.fill_(0.1)+ model.first.lora_B.weight.fill_(0.2)+ model.first.base.weight.fill_(1.0)+ before_base = model.first.base.weight.detach().clone()+ before_b = model.first.lora_B.weight.detach().clone()++ with pytest.raises(RuntimeError, match="quantized or sharded"):+ _merge_reinit_and_reset(model, None, reset_optimizer=False)++ assert torch.equal(model.first.base.weight, before_base)+ assert torch.equal(model.first.lora_B.weight, before_b)++ def test_wrapped_optimizer_rejected_even_when_reset_false(self):+ try:+ import torch+ except ImportError:+ pytest.skip("torch not available")+ from soup_cli.utils.relora import _merge_reinit_and_reset++ model = _make_fake_lora_module()+ with torch.no_grad():+ model.lora_A.weight.fill_(0.1)+ model.lora_B.weight.fill_(0.2)+ model.base.weight.fill_(1.0)+ before_base = model.base.weight.clone()++ optimizer = MagicMock()+ del optimizer.state++ with pytest.raises(RuntimeError, match="optimizer has no"):+ _merge_reinit_and_reset(model, optimizer, reset_optimizer=False)++ assert torch.equal(model.base.weight, before_base)+++def test_attach_relora_callback_warns_prune_ratio_ignored(caplog):+ import logging++ from soup_cli.utils.peft_wiring import attach_relora_callback++ trainer = _single_process_trainer()+ tcfg = TrainingConfig(relora_steps=100, relora_prune_ratio=0.9)+ with caplog.at_level(logging.WARNING, logger="soup_cli.utils.peft_wiring"):+ attach_relora_callback(trainer, tcfg)+ assert "relora_prune_ratio" in caplog.text+ assert "ignored" in caplog.text.lower()+++def test_attach_relora_callback_default_prune_ratio_does_not_warn(caplog):+ import logging++ from soup_cli.utils.peft_wiring import attach_relora_callback++ trainer = _single_process_trainer()+ tcfg = TrainingConfig(relora_steps=100)+ assert "relora_prune_ratio" not in tcfg.model_fields_set+ with caplog.at_level(logging.WARNING, logger="soup_cli.utils.peft_wiring"):+ attach_relora_callback(trainer, tcfg)+ assert "relora_prune_ratio" not in caplog.text+++def test_attach_relora_refuses_world_size_gt_1():+ from soup_cli.utils.peft_wiring import attach_relora_callback++ trainer = _single_process_trainer()+ trainer.args.world_size = 2+ with pytest.raises(ValueError, match="world_size"):+ attach_relora_callback(trainer, TrainingConfig(relora_steps=100))+ trainer.add_callback.assert_not_called()+++def test_attach_relora_refuses_deepspeed():+ from soup_cli.utils.peft_wiring import attach_relora_callback++ trainer = _single_process_trainer()+ trainer.is_deepspeed_enabled = True+ with pytest.raises(ValueError, match="DeepSpeed"):+ attach_relora_callback(trainer, TrainingConfig(relora_steps=100))+ trainer.add_callback.assert_not_called()+++def test_attach_relora_refuses_fsdp():+ from soup_cli.utils.peft_wiring import attach_relora_callback++ trainer = _single_process_trainer()+ trainer.is_fsdp_enabled = True+ with pytest.raises(ValueError, match="FSDP"):+ attach_relora_callback(trainer, TrainingConfig(relora_steps=100))+ trainer.add_callback.assert_not_called()+++def test_attach_relora_single_process_still_attaches():+ from soup_cli.utils.peft_wiring import attach_relora_callback+ from soup_cli.utils.relora import ReLoRACallback++ trainer = _single_process_trainer()+ assert attach_relora_callback(trainer, TrainingConfig(relora_steps=100)) is True+ trainer.add_callback.assert_called_once()+ assert isinstance(trainer.add_callback.call_args[0][0], ReLoRACallback)+++def test_attach_relora_preflight_rejects_quantized_base():+ from soup_cli.utils.peft_wiring import attach_relora_callback++ trainer = _single_process_trainer()+ trainer.model = _make_mixed_writable_quantized_parent()+ with pytest.raises(RuntimeError, match="quantized or sharded"):+ attach_relora_callback(trainer, TrainingConfig(relora_steps=100))+ trainer.add_callback.assert_not_called()++def test_attach_relora_rejects_model_without_dense_merge():+ from soup_cli.utils.peft_wiring import attach_relora_callback++ trainer = _single_process_trainer()+ trainer.model = _make_fake_lora_module()+ with pytest.raises(RuntimeError, match="merge_and_unload"):+ attach_relora_callback(trainer, TrainingConfig(relora_steps=100))+ trainer.add_callback.assert_not_called()+++class TestReLoRARealPeft:+ def test_restart_merges_real_peft_linear_skips_embedding(self, tmp_path):+ try:+ import torch+ import torch.nn as nn+ from peft import LoraConfig, get_peft_model+ from transformers import LlamaConfig, LlamaForCausalLM+ except ImportError as exc:+ pytest.skip(f"torch / transformers / peft not available: {exc}")+ from soup_cli.utils.relora import (+ _iter_lora_modules,+ _merge_reinit_and_reset,+ _resolve_base_weight,+ _resolve_lora_weight,+ )++ torch.manual_seed(0)+ config = LlamaConfig(+ vocab_size=32,+ hidden_size=32,+ intermediate_size=64,+ num_hidden_layers=1,+ num_attention_heads=4,+ num_key_value_heads=4,+ max_position_embeddings=32,+ tie_word_embeddings=False,+ )+ model = LlamaForCausalLM(config).to(torch.float32).eval()+ peft_cfg = LoraConfig(+ r=4,+ lora_alpha=8,+ lora_dropout=0.0,+ bias="none",+ task_type="CAUSAL_LM",+ target_modules=["q_proj", "v_proj", "embed_tokens"],+ )+ model = get_peft_model(model, peft_cfg)+ model.eval()++ yielded = list(_iter_lora_modules(model))+ assert len(yielded) == 2++ for module, adapter in yielded:+ weight_a = _resolve_lora_weight(module, "lora_A", adapter)+ weight_b = _resolve_lora_weight(module, "lora_B", adapter)+ with torch.no_grad():+ weight_a.fill_(0.25)+ weight_b.fill_(0.5)++ embed_before = {}+ for name, module in model.named_modules():+ lora_a = getattr(module, "lora_A", None)+ if not isinstance(lora_a, nn.ModuleDict) or len(lora_a) != 0:+ continue+ if not hasattr(module, "lora_embedding_A"):+ continue+ with torch.no_grad():+ for key, param in module.lora_embedding_A.items():+ param.fill_(0.3)+ embed_before[(name, "A", key)] = param.detach().clone()+ for key, param in module.lora_embedding_B.items():+ param.fill_(0.4)+ embed_before[(name, "B", key)] = param.detach().clone()+ assert embed_before++ snapshots = []+ lora_params = []+ for module, adapter in yielded:+ weight_a = _resolve_lora_weight(module, "lora_A", adapter)+ weight_b = _resolve_lora_weight(module, "lora_B", adapter)+ base = _resolve_base_weight(module)+ delta = module.get_delta_weight(adapter)+ snapshots.append(+ (+ module,+ adapter,+ base.detach().clone(),+ delta.detach().clone(),+ weight_a.detach().clone(),+ )+ )+ lora_params.extend([weight_a, weight_b])++ input_ids = torch.randint(0, config.vocab_size, (1, 8))+ with torch.no_grad():+ before_logits = model(input_ids=input_ids).logits++ opt = torch.optim.AdamW(lora_params, lr=1e-3)+ for param in lora_params:+ opt.state[param] = {+ "exp_avg": torch.ones_like(param),+ "exp_avg_sq": torch.ones_like(param),+ }++ _merge_reinit_and_reset(model, opt, reset_optimizer=True)++ for module, adapter, old_base, delta, old_a in snapshots:+ base = _resolve_base_weight(module)+ weight_a = _resolve_lora_weight(module, "lora_A", adapter)+ weight_b = _resolve_lora_weight(module, "lora_B", adapter)+ assert torch.allclose(base, old_base + delta, atol=1e-5, rtol=1e-5)+ assert torch.all(weight_b == 0)+ assert not torch.equal(weight_a, old_a)+ for param in lora_params:+ assert len(opt.state[param]) == 0++ with torch.no_grad():+ after_logits = model(input_ids=input_ids).logits+ assert torch.allclose(before_logits, after_logits, atol=1e-5, rtol=1e-5)++ for name, module in model.named_modules():+ for key, param in getattr(module, "lora_embedding_A", {}).items():+ assert torch.equal(param, embed_before[(name, "A", key)])+ for key, param in getattr(module, "lora_embedding_B", {}).items():+ assert torch.equal(param, embed_before[(name, "B", key)])++ for module, adapter in yielded:+ weight_a = _resolve_lora_weight(module, "lora_A", adapter)+ weight_b = _resolve_lora_weight(module, "lora_B", adapter)+ with torch.no_grad():+ weight_a.fill_(0.125)+ weight_b.fill_(0.25)++ with torch.no_grad():+ live_logits = model(input_ids=input_ids).logits++ from soup_cli.utils.peft_wiring import save_model_with_relora++ class _Trainer:+ def __init__(self, model):+ self.model = model+ self.model_wrapped = model++ def save_model(self, output_dir):+ self.model.save_pretrained(output_dir)++ trainer = _Trainer(model)+ save_model_with_relora(trainer, str(tmp_path), relora_steps=1)+ assert (tmp_path / "config.json").exists()+ assert any(+ (tmp_path / filename).exists()+ for filename in ("model.safetensors", "pytorch_model.bin")+ )++ reloaded = LlamaForCausalLM.from_pretrained(tmp_path).eval()+ with torch.no_grad():+ reloaded_logits = reloaded(input_ids=input_ids).logits+ assert torch.allclose(live_logits, reloaded_logits, atol=1e-5, rtol=1e-5)++++class TestReLoRAWrapperSaves:+ def test_embedding_wrapper_saves_dense_reloadable_model(self, tmp_path):+ try:+ import torch+ from peft import LoraConfig, get_peft_model+ from transformers import LlamaConfig, LlamaModel, TrainingArguments+ except ImportError as exc:+ pytest.skip(f"torch / transformers / peft not available: {exc}")++ from soup_cli.trainer.embedding import _EmbeddingTrainer+ from soup_cli.utils.peft_wiring import (+ attach_relora_callback,+ save_model_with_relora,+ )++ config = LlamaConfig(+ vocab_size=32,+ hidden_size=32,+ intermediate_size=64,+ num_hidden_layers=1,+ num_attention_heads=4,+ num_key_value_heads=4,+ max_position_embeddings=32,+ )+ model = get_peft_model(+ LlamaModel(config),+ LoraConfig(+ r=4,+ lora_alpha=8,+ lora_dropout=0.0,+ task_type="FEATURE_EXTRACTION",+ target_modules=["q_proj"],+ ),+ ).eval()+ input_ids = torch.randint(0, config.vocab_size, (1, 8))+ with torch.no_grad():+ for name, param in model.named_parameters():+ if "lora_A" in name or "lora_B" in name:+ param.fill_(0.2)+ live_hidden = model(input_ids=input_ids).last_hidden_state++ wrapper = _EmbeddingTrainer(+ model=model,+ args=TrainingArguments(+ output_dir=str(tmp_path / "trainer"),+ report_to=[],+ ),+ train_dataset=[],+ eval_dataset=None,+ processing_class=None,+ loss_type="cosine",+ margin=0.2,+ pooling="mean",+ temperature=0.05,+ max_length=8,+ )+ assert attach_relora_callback(+ wrapper, TrainingConfig(relora_steps=1, quantization="none")+ )+ save_model_with_relora(wrapper, str(tmp_path / "output"), relora_steps=1)++ reloaded = LlamaModel.from_pretrained(tmp_path / "output").eval()+ with torch.no_grad():+ reloaded_hidden = reloaded(input_ids=input_ids).last_hidden_state+ assert torch.allclose(live_hidden, reloaded_hidden, atol=1e-5, rtol=1e-5)++ def test_ppo_policy_wrapper_saves_dense_reloadable_model(self, tmp_path):+ try:+ import torch+ from peft import LoraConfig, get_peft_model+ from transformers import (+ LlamaConfig,+ LlamaForCausalLM,+ LlamaForSequenceClassification,+ )+ from trl.experimental.ppo.ppo_trainer import PolicyAndValueWrapper+ except ImportError as exc:+ pytest.skip(f"torch / transformers / peft / trl not available: {exc}")++ from soup_cli.utils.peft_wiring import attach_relora_callback, save_model_with_relora++ config = LlamaConfig(+ vocab_size=32,+ hidden_size=32,+ intermediate_size=64,+ num_hidden_layers=1,+ num_attention_heads=4,+ num_key_value_heads=4,+ max_position_embeddings=32,+ )+ policy = get_peft_model(+ LlamaForCausalLM(config),+ LoraConfig(+ r=4,+ lora_alpha=8,+ lora_dropout=0.0,+ task_type="CAUSAL_LM",+ target_modules=["q_proj"],+ ),+ ).eval()+ input_ids = torch.randint(0, config.vocab_size, (1, 8))+ with torch.no_grad():+ for name, param in policy.named_parameters():+ if "lora_A" in name or "lora_B" in name:+ param.fill_(0.2)+ live_logits = policy(input_ids=input_ids).logits++ value_config = LlamaConfig.from_dict(config.to_dict())+ value_config.num_labels = 1+ value_config.output_hidden_states = True+ value_model = LlamaForSequenceClassification(value_config).eval()+ holder = PolicyAndValueWrapper(policy, value_model)++ class _Trainer:+ def __init__(self, model):+ self.model = model+ self.args = SimpleNamespace(world_size=1)+ self.callbacks = []++ def add_callback(self, callback):+ self.callbacks.append(callback)++ def save_model(self, output_dir):+ self.model.policy.save_pretrained(output_dir)++ trainer = _Trainer(holder)+ assert attach_relora_callback(+ trainer, TrainingConfig(relora_steps=1, quantization="none")+ )+ save_model_with_relora(trainer, str(tmp_path / "output"), relora_steps=1)++ reloaded = LlamaForCausalLM.from_pretrained(tmp_path / "output").eval()+ with torch.no_grad():+ reloaded_logits = reloaded(input_ids=input_ids).logits+ assert torch.allclose(live_logits, reloaded_logits, atol=1e-5, rtol=1e-5)++class TestReLoRATaskGate:+ def _base_cfg(self, task: str = "sft", backend: str = "transformers") -> dict:+ return {+ "base": "meta-llama/Llama-3.1-8B",+ "task": task,+ "backend": backend,+ "data": {"train": "./data.jsonl"},+ "training": {"relora_steps": 100, "quantization": "none"},+ }++ def test_sft_accepted(self):+ import yaml++ from soup_cli.config.loader import load_config_from_string++ cfg = load_config_from_string(yaml.safe_dump(self._base_cfg("sft")))+ assert cfg.training.relora_steps == 100++ @pytest.mark.parametrize(+ "task",+ [+ "dpo",+ "grpo",+ "kto",+ "orpo",+ "simpo",+ "ipo",+ "ppo",+ "reward_model",+ "pretrain",+ "embedding",+ "bco",+ ],+ )+ def test_other_tasks_accepted(self, task):+ import yaml++ from soup_cli.config.loader import load_config_from_string++ cfg = load_config_from_string(yaml.safe_dump(self._base_cfg(task)))+ assert cfg.training.relora_steps == 100+ assert cfg.task == task++ def test_mlx_backend_rejected(self):+ import yaml++ from soup_cli.config.loader import load_config_from_string++ with pytest.raises(ValueError, match="mlx"):+ load_config_from_string(yaml.safe_dump(self._base_cfg("sft", "mlx")))++ def test_quantization_rejected(self):+ import yaml++ from soup_cli.config.loader import load_config_from_string++ d = self._base_cfg()+ d["training"]["quantization"] = "4bit"+ with pytest.raises(ValueError, match="quantization"):+ load_config_from_string(yaml.safe_dump(d))++ def test_stream_layers_rejected(self):+ import yaml++ from soup_cli.config.loader import load_config_from_string++ d = self._base_cfg()+ d["training"]["stream_layers"] = True+ d["training"]["batch_size"] = 1+ with pytest.raises(+ ValueError,+ match="relora_steps is incompatible with training.stream_layers",+ ):+ load_config_from_string(yaml.safe_dump(d))++ def test_vera_rejected(self):+ import yaml++ from soup_cli.config.loader import load_config_from_string++ d = self._base_cfg()+ d["training"] = {"relora_steps": 100, "quantization": "none", "lora": {"use_vera": True}}+ with pytest.raises(ValueError, match="use_vera"):+ load_config_from_string(yaml.safe_dump(d))++ def test_dora_rejected(self):+ import yaml++ from soup_cli.config.loader import load_config_from_string++ d = self._base_cfg()+ d["training"] = {"relora_steps": 100, "quantization": "none", "lora": {"use_dora": True}}+ with pytest.raises(ValueError, match="use_dora"):+ load_config_from_string(yaml.safe_dump(d))++ def test_fsdp2_compile_rejected(self):+ import yaml++ from soup_cli.config.loader import load_config_from_string++ d = self._base_cfg()+ d["training"]["use_fsdp2_compile"] = True+ with pytest.raises(ValueError, match="use_fsdp2_compile"):+ load_config_from_string(yaml.safe_dump(d))++ def test_no_relora_no_gate(self):+ import yaml++ from soup_cli.config.loader import load_config_from_string++ d = self._base_cfg("dpo")+ d["training"].pop("relora_steps")+ cfg = load_config_from_string(yaml.safe_dump(d))+ assert cfg.training.relora_steps is Nonediff --git a/tests/test_v0406_part_a.py b/tests/test_v0406_part_a.pyindex 558fc036..77e1bec1 100644--- a/tests/test_v0406_part_a.py+++ b/tests/test_v0406_part_a.py@@ -270,6 +270,7 @@ class TestPreferenceTaskGate:"data": {"train": "./data.jsonl"},"training": {"relora_steps": 100,+ "quantization": "none","preference_loss": "dpo",},}))@@ -290,7 +291,7 @@ class TestReLoRASchemaGateWidened:"task": task,"backend": backend,"data": {"train": "./data.jsonl"},- "training": {"relora_steps": 100},+ "training": {"relora_steps": 100, "quantization": "none"},}@pytest.mark.parametrize(