Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(train): make auto-eval follow the run's --trust-remote-code flag (#1644) (#1662)

Areen Agrawale30ac2adbab8
diff --git a/changelog.d/0.75.1/1662.fixed.md b/changelog.d/0.75.1/1662.fixed.md
new file mode 100644
index 00000000..a7045532
--- /dev/null
+++ b/changelog.d/0.75.1/1662.fixed.md
@@ -0,0 +1,8 @@
+- **Auto-evaluation after `soup train` follows the run's `--trust-remote-code` flag
+ (#1644 by @Areen-09 in #1662).** `soup train --trust-remote-code` with
+ `eval.auto_eval: true` now passes the flag to the benchmark and custom
+ evaluation of the model the run just saved, instead of always `False`, which
+ made a base that needs custom code train and then fail its own evaluation.
+ Without the flag both stay off, as before. The opt-in is CLI only: a
+ `soup.yaml` with `trust_remote_code` (top level or under `eval:`) is refused
+ as an unknown key.
diff --git a/docs/evaluation.md b/docs/evaluation.md
index c24d6f5e..7598ee47 100644
--- a/docs/evaluation.md
+++ b/docs/evaluation.md
@@ -905,7 +905,7 @@ When `eval.auto_eval: true`, Soup runs the configured evaluation once after `sou
- `benchmarks` runs the configured `lm-eval-harness` benchmarks. Install the `soup-cli[eval]` extra above before enabling them.
- `custom_tasks` runs the configured custom evaluation tasks against the trained model.
- `judge` is not part of auto-evaluation; configure and run judge evaluation separately.
-- Auto-evaluation keeps `trust_remote_code` disabled even when `soup train --trust-remote-code` was passed, so for a base that ships custom code the evaluation is skipped with a message (`Auto-eval custom failed: ... Please pass the argument trust_remote_code=True`); run `soup eval custom ... --trust-remote-code` yourself for that case.
+- Auto-evaluation follows the run's `--trust-remote-code` flag: `soup train --trust-remote-code` passes it to the evaluation of the trained model (benchmarks and custom tasks); without the flag it stays off. There is no `soup.yaml` key for it.
- If auto-evaluation fails, Soup reports the failure but does not fail an otherwise successful training run.
- Auto-evaluation can take a significant amount of time. For example, MMLU evaluates multiple subtasks.
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index ba638b0b..73341940 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -963,7 +963,7 @@ all-masked sequence or saving a non-finite adapter.
Every command that loads a model now requires `--trust-remote-code` to execute custom Python from a model repo (`auto_map` in `config.json`). First-party orgs (Meta, Mistral, Qwen, Google, etc.) suppress the warning panel; everything else prints a `REMOTE CODE WARNING` panel before loading. Unknown-org local checkpoints with `auto_map` raise a friendly `ValueError` at construction time instead of silently exec'ing inside `from_pretrained`.
Coverage:
-- `soup train` (every task - SFT, DPO, GRPO, KTO, ORPO, SimPO, IPO, PPO, Reward Model, Pretrain, Embedding, BCO, and the unified Preference dispatcher; automatic evaluation after training keeps the flag disabled, see `docs/evaluation.md`)
+- `soup train` (every task - SFT, DPO, GRPO, KTO, ORPO, SimPO, IPO, PPO, Reward Model, Pretrain, Embedding, BCO, and the unified Preference dispatcher; automatic evaluation after training follows the run's flag, see `docs/evaluation.md`)
- `soup chat`, `soup serve`, `soup data download`, `soup eval auto`
- `soup diff`, `soup export`, `soup merge`, `soup infer`, `soup data generate`
- `soup eval benchmark`, `soup eval custom`, `soup train --find-lr`, `soup draft distill`, `soup shrink`
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index 10ac9874..b3efa3ac 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -112,8 +112,19 @@ def _format_duration_display(result: dict) -> str:
return f"{hours}h {minutes}m" if hours > 0 else f"{minutes}m"
-def _run_auto_eval_after_training(eval_config, output_dir: str, run_id: str) -> None:
- """Run configured evaluation once after the trained model is saved."""
+def _run_auto_eval_after_training(
+ eval_config,
+ output_dir: str,
+ run_id: str,
+ *,
+ trust_remote_code: bool = False,
+) -> None:
+ """Run configured evaluation once after the trained model is saved.
+
+ ``trust_remote_code`` is the run's own ``--trust-remote-code`` flag (CLI only;
+ there is no soup.yaml field). It reaches only the loads of the trained output
+ and its base: ``benchmark`` and ``custom``.
+ """
if not eval_config or not getattr(eval_config, "auto_eval", False):
return
if not output_dir or not _should_run_diagnose_gate_on_rank():
@@ -135,7 +146,7 @@ def _run_auto_eval_after_training(eval_config, output_dir: str, run_id: str) ->
batch_size=8,
run_id=run_id,
device=None,
- trust_remote_code=False,
+ trust_remote_code=trust_remote_code,
)
except typer.Exit:
logger.debug("Auto-eval benchmark skipped", exc_info=True)
@@ -158,7 +169,7 @@ def _run_auto_eval_after_training(eval_config, output_dir: str, run_id: str) ->
run_id=run_id,
attach_to_registry=None,
output=None,
- trust_remote_code=False,
+ trust_remote_code=trust_remote_code,
)
except typer.Exit:
logger.debug("Auto-eval custom skipped", exc_info=True)
@@ -1905,6 +1916,7 @@ def train(
cfg.eval,
result["output_dir"],
run_id,
+ trust_remote_code=trust_remote_code,
)
except Exception as exc:
tracker.fail_run(run_id, error=_describe_exception_for_tracker(exc))
diff --git a/tests/test_issue1449_trust_remote_code_dropped.py b/tests/test_issue1449_trust_remote_code_dropped.py
index c8b7d17d..a7c3bcae 100644
--- a/tests/test_issue1449_trust_remote_code_dropped.py
+++ b/tests/test_issue1449_trust_remote_code_dropped.py
@@ -492,7 +492,13 @@ class TestDefaultsStayDeny:
assert result.exit_code == 0, result.output
assert seen_generator_calls[0][1].get("trust_remote_code") is expected, seen_generator_calls
- def test_training_auto_eval_callback_never_opts_in(self, monkeypatch):
+ @pytest.mark.parametrize(
+ ("passed_flag", "expected"),
+ [(False, False), (True, True)],
+ )
+ def test_training_auto_eval_follows_run_flag(
+ self, monkeypatch, passed_flag, expected
+ ):
import soup_cli.commands.eval as ce
import soup_cli.commands.train as train_cmd
@@ -505,9 +511,11 @@ class TestDefaultsStayDeny:
"EvalCfg", (),
{"auto_eval": True, "benchmarks": ["mmlu"], "custom_tasks": "tasks.jsonl"},
)()
- train_cmd._run_auto_eval_after_training(eval_config, "out", "run-1")
- assert calls["benchmark"]["trust_remote_code"] is False, calls
- assert calls["custom"]["trust_remote_code"] is False, calls
+ train_cmd._run_auto_eval_after_training(
+ eval_config, "out", "run-1", trust_remote_code=passed_flag
+ )
+ assert calls["benchmark"]["trust_remote_code"] is expected, calls
+ assert calls["custom"]["trust_remote_code"] is expected, calls
@pytest.mark.parametrize(("flag", "panel"), [([], False), (["--trust-remote-code"], True)])
def test_data_download_warning_panel_only_with_flag(self, tmp_path, monkeypatch, flag, panel):
diff --git a/tests/test_issue1644_auto_eval_trust_remote_code.py b/tests/test_issue1644_auto_eval_trust_remote_code.py
new file mode 100644
index 00000000..8c33aa55
--- /dev/null
+++ b/tests/test_issue1644_auto_eval_trust_remote_code.py
@@ -0,0 +1,266 @@
+"""#1644 — Auto-eval after soup train follows the run's --trust-remote-code flag.
+
+The automatic evaluation that `soup train` starts follows that run's
+--trust-remote-code flag. Without the flag it stays off, as before.
+There is no config field for it: the opt-in is given on the command line
+only and never comes from a soup.yaml.
+"""
+
+from __future__ import annotations
+
+import ast
+import inspect
+import json
+import textwrap
+from unittest.mock import MagicMock
+
+import pytest
+from typer.testing import CliRunner
+
+from soup_cli.cli import app
+from soup_cli.config.loader import load_config_from_string
+from soup_cli.config.schema import EvalConfig, SoupConfig
+
+
+class TestAutoEvalTrustRemoteCodeDirect:
+ """Direct unit tests for _run_auto_eval_after_training."""
+
+ @pytest.mark.parametrize("flag", [True, False])
+ def test_benchmark_only_receives_run_flag(self, monkeypatch, flag):
+ import soup_cli.commands.eval as ce
+ import soup_cli.commands.train as train_cmd
+
+ benchmark_calls = []
+ monkeypatch.setattr(
+ ce, "benchmark", lambda **kw: benchmark_calls.append(kw)
+ )
+ monkeypatch.setattr(
+ train_cmd, "_should_run_diagnose_gate_on_rank", lambda: True
+ )
+
+ eval_config = EvalConfig(auto_eval=True, benchmarks=["mmlu"])
+ train_cmd._run_auto_eval_after_training(
+ eval_config, "out_dir", "run-1", trust_remote_code=flag
+ )
+
+ assert len(benchmark_calls) == 1
+ assert benchmark_calls[0]["trust_remote_code"] is flag
+
+ @pytest.mark.parametrize("flag", [True, False])
+ def test_custom_only_receives_run_flag(self, monkeypatch, flag):
+ import soup_cli.commands.eval as ce
+ import soup_cli.commands.train as train_cmd
+
+ custom_calls = []
+ monkeypatch.setattr(
+ ce, "custom", lambda **kw: custom_calls.append(kw)
+ )
+ monkeypatch.setattr(
+ train_cmd, "_should_run_diagnose_gate_on_rank", lambda: True
+ )
+
+ eval_config = EvalConfig(auto_eval=True, custom_tasks="tasks.jsonl")
+ train_cmd._run_auto_eval_after_training(
+ eval_config, "out_dir", "run-1", trust_remote_code=flag
+ )
+
+ assert len(custom_calls) == 1
+ assert custom_calls[0]["trust_remote_code"] is flag
+
+ def test_flag_reaches_only_the_two_evaluation_loads(self, monkeypatch):
+ """The flag must reach only the benchmark and custom loads of the trained
+
+ output and its base, and no secondary callers (e.g. judge).
+ """
+ import soup_cli.commands.eval as ce
+ import soup_cli.commands.train as train_cmd
+
+ all_calls = []
+ monkeypatch.setattr(
+ ce, "benchmark", lambda **kw: all_calls.append(("benchmark", kw))
+ )
+ monkeypatch.setattr(
+ ce, "custom", lambda **kw: all_calls.append(("custom", kw))
+ )
+ monkeypatch.setattr(
+ train_cmd, "_should_run_diagnose_gate_on_rank", lambda: True
+ )
+
+ eval_config = EvalConfig(
+ auto_eval=True,
+ benchmarks=["mmlu"],
+ custom_tasks="tasks.jsonl",
+ judge={"model": "gpt-4o-mini", "provider": "openai"},
+ )
+ train_cmd._run_auto_eval_after_training(
+ eval_config, "out_dir", "run-1", trust_remote_code=True
+ )
+
+ assert len(all_calls) == 2
+ names_and_flags = [(name, kw["trust_remote_code"]) for name, kw in all_calls]
+ assert names_and_flags == [("benchmark", True), ("custom", True)]
+
+
+class TestNoConfigFieldForTrustRemoteCode:
+ """A soup.yaml cannot switch trust_remote_code on (top-level or under eval:)."""
+
+ def test_schema_has_no_trust_remote_code_field(self):
+ assert "trust_remote_code" not in SoupConfig.model_fields
+ assert "trust_remote_code" not in EvalConfig.model_fields
+
+ @pytest.mark.parametrize(
+ ("yaml_content", "expected_key"),
+ [
+ (
+ "base: org/model\ntask: sft\ndata: {train: data.jsonl}\ntrust_remote_code: true\n",
+ "trust_remote_code",
+ ),
+ (
+ (
+ "base: org/model\n"
+ "task: sft\n"
+ "data: {train: data.jsonl}\n"
+ "eval:\n"
+ " auto_eval: true\n"
+ " trust_remote_code: true\n"
+ ),
+ "eval.trust_remote_code",
+ ),
+ ],
+ )
+ def test_soup_yaml_refuses_trust_remote_code_key(self, yaml_content, expected_key):
+ with pytest.raises(ValueError) as exc_info:
+ load_config_from_string(yaml_content)
+ assert f"unknown config key '{expected_key}'" in str(exc_info.value)
+
+
+class TestSoupTrainCliAutoEvalTrust:
+ """CLI-level tests verifying soup train passes --trust-remote-code to auto-eval."""
+
+ @pytest.mark.parametrize(
+ ("extra_args", "expected_trust"),
+ [
+ ([], False),
+ (["--trust-remote-code"], True),
+ ],
+ )
+ def test_soup_train_cli_passes_flag_to_auto_eval(
+ self, tmp_path, monkeypatch, extra_args, expected_trust
+ ):
+ import soup_cli.commands.eval as ce
+ import soup_cli.commands.train as train_cmd
+ import soup_cli.trainer.dispatch as dispatch_mod
+
+ # Prepare dummy files
+ data_file = tmp_path / "train.jsonl"
+ data_file.write_text(
+ json.dumps({"instruction": "hello", "output": "world"}) + "\n",
+ encoding="utf-8",
+ )
+ tasks_file = tmp_path / "tasks.jsonl"
+ tasks_file.write_text(
+ json.dumps({"prompt": "2+2?", "expected": "4", "scoring": "exact"}) + "\n",
+ encoding="utf-8",
+ )
+ config_file = tmp_path / "soup.yaml"
+ config_file.write_text(
+ "base: test-org/test-model\n"
+ "task: sft\n"
+ f"data: {{train: {data_file.name}, val_split: 0.0}}\n"
+ "output: out\n"
+ f"eval: {{auto_eval: true, benchmarks: [mmlu], custom_tasks: {tasks_file.name}}}\n",
+ encoding="utf-8",
+ )
+
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("SOUP_DB_PATH", str(tmp_path / "test.db"))
+
+ # Stub trainer dispatch to avoid loading heavy model/cuda
+ mock_trainer = MagicMock()
+ mock_trainer.train.return_value = {
+ "initial_loss": 2.0,
+ "final_loss": 1.0,
+ "total_steps": 1,
+ "duration_secs": 0.5,
+ "duration": "0.5s",
+ "output_dir": str(tmp_path / "out"),
+ }
+ monkeypatch.setattr(
+ dispatch_mod, "build_trainer", lambda cfg, **kw: mock_trainer
+ )
+ monkeypatch.setattr(
+ train_cmd, "_should_run_diagnose_gate_on_rank", lambda: True
+ )
+
+ # Record auto_eval calls
+ eval_calls = []
+ monkeypatch.setattr(
+ ce, "benchmark", lambda **kw: eval_calls.append(("benchmark", kw))
+ )
+ monkeypatch.setattr(
+ ce, "custom", lambda **kw: eval_calls.append(("custom", kw))
+ )
+
+ runner = CliRunner()
+ result = runner.invoke(
+ app,
+ ["train", "--config", str(config_file), "--yes", *extra_args],
+ )
+ assert result.exit_code == 0, result.output
+
+ assert len(eval_calls) == 2, eval_calls
+ assert eval_calls[0][0] == "benchmark"
+ assert eval_calls[0][1]["trust_remote_code"] is expected_trust
+ assert eval_calls[1][0] == "custom"
+ assert eval_calls[1][1]["trust_remote_code"] is expected_trust
+
+
+def test_omitted_kwarg_stays_off(monkeypatch):
+ import soup_cli.commands.eval as ce
+ import soup_cli.commands.train as train_cmd
+
+ calls = []
+ monkeypatch.setattr(ce, "benchmark", lambda **kw: calls.append(("benchmark", kw)))
+ monkeypatch.setattr(ce, "custom", lambda **kw: calls.append(("custom", kw)))
+ monkeypatch.setattr(train_cmd, "_should_run_diagnose_gate_on_rank", lambda: True)
+
+ eval_config = EvalConfig(auto_eval=True, benchmarks=["mmlu"], custom_tasks="tasks.jsonl")
+ train_cmd._run_auto_eval_after_training(eval_config, "out_dir", "run-1")
+
+ assert [(name, kw["trust_remote_code"]) for name, kw in calls] == [
+ ("benchmark", False),
+ ("custom", False),
+ ]
+
+
+def test_flag_has_exactly_two_consumers():
+ import soup_cli.commands.train as train_cmd
+
+ source = textwrap.dedent(inspect.getsource(train_cmd._run_auto_eval_after_training))
+ tree = ast.parse(source)
+
+ consumers = sorted(
+ ast.unparse(node.func)
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ for kw in node.keywords
+ if kw.arg == "trust_remote_code"
+ )
+ reads = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Name)
+ and node.id == "trust_remote_code"
+ and isinstance(node.ctx, ast.Load)
+ ]
+
+ assert consumers == ["benchmark", "custom"], consumers
+ assert len(reads) == 2, len(reads)
+ values = [
+ ast.unparse(kw.value)
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ for kw in node.keywords
+ if kw.arg == "trust_remote_code"
+ ]
+ assert values == ["trust_remote_code", "trust_remote_code"], values