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(grpo): resolve a prm_reward Hub id before training instead of dying at the first reward call (#1466) (#1580)

Srinivasan Rbd767b7a24f2
diff --git a/changelog.d/0.75.1/1580.fixed.md b/changelog.d/0.75.1/1580.fixed.md
new file mode 100644
index 00000000..b9e3a895
--- /dev/null
+++ b/changelog.d/0.75.1/1580.fixed.md
@@ -0,0 +1 @@
+- **A `training.prm_reward` Hub id is downloaded before training, and a PRM without a reward head is refused before the model loads (#1466 by @Srinivasan8888 in #1580).** `prm_reward` is documented as a path or a Hub id, but the PRM's reward head was read only from a local directory, so a GRPO run given `org/name` loaded the tokenizer and the model and then died at the first reward call with "path is not a directory". The id (optionally `org/name@revision`) is now resolved through Soup's Hub download wrapper (`utils.hubs.snapshot_download`, which runs the repo-id, revision and namespace-pin checks first), restricted to weights, tokenizer files and custom-code modules, and the head is read from that snapshot when the reward is built; a repo that is not a Soup-trained PRM, a download failure, or a value that is neither an existing directory nor a repo id each stop with one message naming the value, before any training. Existing local paths keep their containment check and now also fail early when they carry no reward head.
diff --git a/docs/training.md b/docs/training.md
index abb75b28..b777d041 100644
--- a/docs/training.md
+++ b/docs/training.md
@@ -852,7 +852,10 @@ weights would round most updates away at these learning rates (#1235).
Use a trained PRM as the **per-step reward** inside GRPO — the o1-era
process-supervision signal. Set `training.prm_reward` to a PRM directory (a
-`task=prm` checkpoint) or HF id; the PRM splits each generated completion into
+`task=prm` checkpoint) or a Hub id, `org/name` or `org/name@revision`; a Hub id is
+downloaded (weights, tokenizer and custom-code files) when the reward is built,
+before training, and a repo that is not a Soup-trained PRM (no reward head) is
+refused there, naming the configured value (#1466). The PRM splits each generated completion into
reasoning steps (newline heuristic), scores every step with its reward head, and
folds the per-step scores into one scalar reward that GRPO optimises. It
**replaces** `reward_fn` and rides the existing reward-shaping +
diff --git a/src/soup_cli/utils/prm_reward.py b/src/soup_cli/utils/prm_reward.py
index 7372229d..d3462caa 100644
--- a/src/soup_cli/utils/prm_reward.py
+++ b/src/soup_cli/utils/prm_reward.py
@@ -37,6 +37,7 @@ Security:
from __future__ import annotations
import math
+import re
from typing import TYPE_CHECKING, Any, Union
if TYPE_CHECKING: # pragma: no cover — type-only, keeps the module torch-free
@@ -369,10 +370,13 @@ def build_prm_reward_fn(
) -> PRMScorer:
"""Build the :class:`PRMScorer` for GRPO from a ``TrainingConfig``.
- Validates local-path containment (realpath + commonpath under cwd) and
- surfaces a ``trust_remote_code`` probe/warning, then returns the scorer.
- A non-existent local path is treated as a Hugging Face repo id (loaded via
- ``from_pretrained``); only *existing local paths* are containment-checked.
+ An existing local path is containment-checked (realpath + commonpath under
+ cwd) and used in place. Anything else that is shaped like a Hub repo id,
+ ``org/name`` or ``org/name@revision``, is downloaded to a local snapshot
+ first (#1466), so the tokenizer, the model and the reward head all load from
+ the same directory; a value that is neither is refused by name. The reward
+ head is read here, before any model loads, and the ``trust_remote_code``
+ probe/warning runs on the resolved directory.
"""
import os
@@ -386,10 +390,10 @@ def build_prm_reward_fn(
if prm_path is None:
raise ValueError("build_prm_reward_fn called with prm_reward=None")
- # Containment: only enforce for a path that exists on disk (a bare repo id
- # with no local existence is handled by from_pretrained). Reuse the shared
- # is_under_cwd helper (realpath + commonpath, Windows-safe) so future
- # hardening applies here too (security-review LOW).
+ configured = prm_path
+ # An existing path wins over the repo-id shape (`checkpoints/prm` is a
+ # directory here before it is an org/name), and is containment-checked with
+ # the shared is_under_cwd helper (realpath + commonpath, Windows-safe).
if os.path.exists(prm_path):
if not is_under_cwd(prm_path):
raise ValueError(
@@ -397,6 +401,24 @@ def build_prm_reward_fn(
f"directory; got {prm_path!r}"
)
prm_path = os.path.realpath(prm_path)
+ elif _HUB_ID_RE.fullmatch(prm_path):
+ # #1466: a Hub id used to pass here and die at the first reward call, because
+ # the head is read from a directory. Download it now, before training starts.
+ prm_path = _download_prm_snapshot(prm_path)
+ else:
+ raise ValueError(
+ f"prm_reward {prm_path!r} is neither an existing directory nor a Hub repo id "
+ "(org/name, optionally @revision)."
+ )
+ # Refuse a checkpoint without a reward head here, before the model loads (#1466).
+ # Named by the configured value: for a Hub id the snapshot path says nothing a
+ # user would recognise.
+ try:
+ load_reward_head_weights(prm_path)
+ except ValueError as exc:
+ if prm_path != configured:
+ raise ValueError(f"prm_reward {configured!r}: {exc}") from exc
+ raise
resolved_trust = _resolve_trust(prm_path, trust_remote_code, console)
# Announce that the PRM reward is active AND replaces the configured
@@ -404,7 +426,7 @@ def build_prm_reward_fn(
# no signal those are being ignored (code-review MEDIUM/LOW). escape() the
# path so a crafted config value cannot inject Rich markup (security MEDIUM).
console.print(
- f"[dim]Using PRM reward: prm_reward={escape(repr(prm_path))}, "
+ f"[dim]Using PRM reward: prm_reward={escape(repr(configured))}, "
f"aggregate={escape(repr(tcfg.prm_aggregate))} "
"(this replaces reward_fn/verifiable_domain).[/]"
)
@@ -416,6 +438,39 @@ def build_prm_reward_fn(
)
+# `org/name`, optionally `@revision`. Each segment starts alphanumerically, so a relative
+# path such as ./my-prm or ../x is never mistaken for a repo id; ASCII only (`\w` would
+# admit non-ASCII letters, `$` a trailing newline); a git ref never contains `..`.
+_HUB_ID_RE = re.compile(
+ r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*(@(?!.*\.\.)[A-Za-z0-9_./-]+)?"
+)
+# Weights, tokenizer files, and the custom-code modules a trust_remote_code base needs
+# (inert unless the trust probe says to execute them); never *.bin / *.pt.
+_PRM_SNAPSHOT_PATTERNS = ("*.safetensors", "*.json", "*.txt", "*.model", "*.tiktoken", "*.py")
+
+
+def _download_prm_snapshot(spec: str) -> str:
+ """Local snapshot of a Hub PRM, ``org/name`` or ``org/name@revision``: weights and
+ tokenizer files only. Goes through ``utils.hubs.snapshot_download``, the wrapper
+ every download Soup starts itself uses (repo-id shape, revision and namespace-pin
+ checks, #186), with ``cache_dir=None`` for the Hub's own cache snapshot. A failure
+ is a refusal that names the configured value, not a traceback."""
+ from soup_cli.utils.hubs import snapshot_download
+
+ repo_id, _, revision = spec.partition("@")
+ try:
+ return snapshot_download(
+ repo_id,
+ cache_dir=None,
+ revision=revision or None,
+ allow_patterns=list(_PRM_SNAPSHOT_PATTERNS),
+ )
+ except Exception as exc: # noqa: BLE001 - every Hub / network error is one refusal
+ raise ValueError(
+ f"prm_reward {spec!r}: could not download the PRM from the Hub ({exc})"
+ ) from exc
+
+
def _resolve_trust(base: str, requested: bool, console: Any) -> bool:
"""Trust-remote-code probe + warn, mirroring the trainer convention."""
from soup_cli.utils.trust_remote import (
diff --git a/tests/test_issue1466_prm_reward_hub_id.py b/tests/test_issue1466_prm_reward_hub_id.py
new file mode 100644
index 00000000..01863890
--- /dev/null
+++ b/tests/test_issue1466_prm_reward_hub_id.py
@@ -0,0 +1,229 @@
+"""#1466, the ``prm_reward`` item: a Hub id is resolved before training, not refused after it.
+
+``training.prm_reward`` is documented as "Path (or HF id)". A Hub id parsed and built,
+but the PRM's reward head was read only from a local directory, so the GRPO run died at
+the first reward call, after both ``from_pretrained`` calls, with "path is not a
+directory". The id is now downloaded to a local snapshot when the reward is built, the
+head is read from it (and refused there, before training, when the repo is not a
+Soup-trained PRM), and a value that is neither an existing directory nor a repo id is
+refused by name.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+import pytest
+import torch
+from safetensors.torch import save_file
+
+from soup_cli.config.loader import load_config_from_string
+from soup_cli.utils import prm_reward
+
+_HUB_ID = "my-org/soup-prm-135m"
+
+
+def _tcfg(value: str):
+ cfg = load_config_from_string(
+ "base: HuggingFaceTB/SmolLM2-135M-Instruct\ntask: grpo\n"
+ "data:\n train: p.jsonl\n format: chatml\n"
+ f"training:\n prm_reward: {value}\n num_generations: 2\n"
+ "output: out\n"
+ )
+ return cfg.training
+
+
+def _prm_dir(path: Path, *, with_head: bool = True) -> Path:
+ path.mkdir(parents=True, exist_ok=True)
+ tensors = {"model.embed_tokens.weight": torch.zeros(4, 8)}
+ if with_head:
+ tensors["reward_head.weight"] = torch.ones(1, 8)
+ tensors["reward_head.bias"] = torch.zeros(1)
+ save_file(tensors, str(path / "model.safetensors"))
+ return path
+
+
+def no_hub_probe(monkeypatch: pytest.MonkeyPatch):
+ # The trust-remote-code probe would ask the Hub; the issue's reproduction stubs it too.
+ monkeypatch.setattr(prm_reward, "_resolve_trust", lambda base, requested, console: False)
+ # ... and so would the namespace-pin gate inside utils.hubs.snapshot_download (#186).
+ from soup_cli.utils import hubs
+
+ monkeypatch.setattr(hubs, "_hf_repo_metadata", lambda repo_id: None)
+
+
+def snapshot(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ """Stub ``huggingface_hub.snapshot_download``: record the call, hand back a prepared dir."""
+ import huggingface_hub
+
+ calls: list[dict] = []
+ target = _prm_dir(tmp_path / "snapshot")
+
+ def fake(repo_id: str, **kwargs):
+ calls.append({"repo_id": repo_id, **kwargs})
+ return str(target)
+
+ monkeypatch.setattr(huggingface_hub, "snapshot_download", fake)
+ return calls, target
+
+
+class TestHubIdResolution:
+ def test_a_hub_id_is_downloaded_and_the_head_read_from_the_snapshot(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe, snapshot
+ ) -> None:
+ calls, target = snapshot
+ monkeypatch.chdir(tmp_path)
+ scorer = prm_reward.build_prm_reward_fn(_tcfg(_HUB_ID), "cpu", False)
+ assert Path(scorer.prm_path) == target
+ assert calls[0]["repo_id"] == _HUB_ID and calls[0].get("revision") is None
+ head = prm_reward.load_reward_head_weights(scorer.prm_path)
+ assert set(head) == {"weight", "bias"}
+
+ def test_an_at_revision_spelling_becomes_the_revision_argument(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe, snapshot
+ ) -> None:
+ calls, _ = snapshot
+ monkeypatch.chdir(tmp_path)
+ prm_reward.build_prm_reward_fn(_tcfg(f"{_HUB_ID}@main"), "cpu", False)
+ assert calls[0]["repo_id"] == _HUB_ID and calls[0]["revision"] == "main"
+
+ def test_only_weights_and_tokenizer_files_are_requested(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe, snapshot
+ ) -> None:
+ calls, _ = snapshot
+ monkeypatch.chdir(tmp_path)
+ prm_reward.build_prm_reward_fn(_tcfg(_HUB_ID), "cpu", False)
+ patterns = calls[0]["allow_patterns"]
+ assert "*.safetensors" in patterns and "*.json" in patterns
+ assert "*.py" in patterns # a trust_remote_code base ships its modules as .py
+ assert not any(p.endswith(".bin") or p.endswith(".pt") for p in patterns)
+
+ def test_the_download_goes_through_the_namespace_pin_gate(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe, snapshot
+ ) -> None:
+ """The move to ``utils.hubs.snapshot_download`` (review of #1580): the wrapper
+ consults the namespace-pin metadata before downloading, so a direct
+ ``huggingface_hub`` import, or ``namespace_check=False``, fails this."""
+ from soup_cli.utils import hubs
+
+ asked: list[str] = []
+
+ def metadata(repo_id: str):
+ asked.append(repo_id)
+ return None # fail open: the pin store is not touched
+
+ monkeypatch.setattr(hubs, "_hf_repo_metadata", metadata)
+ monkeypatch.chdir(tmp_path)
+ prm_reward.build_prm_reward_fn(_tcfg(f"{_HUB_ID}@main"), "cpu", False)
+ assert asked == [_HUB_ID]
+
+ def test_a_hub_repo_without_a_reward_head_is_refused_at_build_time(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe
+ ) -> None:
+ import huggingface_hub
+
+ target = _prm_dir(tmp_path / "plain-base", with_head=False)
+ monkeypatch.setattr(huggingface_hub, "snapshot_download", lambda repo_id, **kw: str(target))
+ monkeypatch.chdir(tmp_path)
+ with pytest.raises(ValueError, match="not a Soup-trained PRM"):
+ prm_reward.build_prm_reward_fn(_tcfg(_HUB_ID), "cpu", False)
+
+ def test_a_download_failure_is_a_refusal_naming_the_repo(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe
+ ) -> None:
+ import huggingface_hub
+
+ def offline(repo_id: str, **kw):
+ raise OSError("offline")
+
+ monkeypatch.setattr(huggingface_hub, "snapshot_download", offline)
+ monkeypatch.chdir(tmp_path)
+ with pytest.raises(ValueError, match="my-org/soup-prm-135m") as info:
+ prm_reward.build_prm_reward_fn(_tcfg(_HUB_ID), "cpu", False)
+ assert "offline" in str(info.value)
+
+ def test_neither_a_directory_nor_a_repo_id_is_refused_by_name(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe
+ ) -> None:
+ import huggingface_hub
+
+ def never(repo_id: str, **kw):
+ raise AssertionError("the Hub was queried for a path-looking value")
+
+ monkeypatch.setattr(huggingface_hub, "snapshot_download", never)
+ monkeypatch.chdir(tmp_path)
+ with pytest.raises(ValueError, match="missing-prm") as info:
+ prm_reward.build_prm_reward_fn(_tcfg("./missing-prm"), "cpu", False)
+ # the by-name refusal, not a failed download attempt dressed as one
+ assert "neither an existing directory nor a Hub repo id" in str(info.value)
+
+
+class TestLocalPathsUnchanged:
+ def test_an_existing_local_prm_is_used_in_place_and_the_hub_is_not_asked(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe
+ ) -> None:
+ import huggingface_hub
+
+ def never(repo_id: str, **kw):
+ raise AssertionError("snapshot_download called for a local directory")
+
+ monkeypatch.setattr(huggingface_hub, "snapshot_download", never)
+ monkeypatch.chdir(tmp_path)
+ local = _prm_dir(tmp_path / "my-prm")
+ scorer = prm_reward.build_prm_reward_fn(_tcfg("./my-prm"), "cpu", False)
+ assert os.path.realpath(scorer.prm_path) == os.path.realpath(local)
+
+ def test_an_existing_local_path_shaped_like_a_repo_id_stays_local(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe
+ ) -> None:
+ """Review of #1580: every other local value starts with ./ or is absolute, so
+ the order of the two checks was never exercised. `checkpoints/prm` is a
+ directory here before it is an org/name."""
+ import huggingface_hub
+
+ def never(repo_id: str, **kw):
+ raise AssertionError("snapshot_download called for an existing local directory")
+
+ monkeypatch.setattr(huggingface_hub, "snapshot_download", never)
+ monkeypatch.chdir(tmp_path)
+ local = _prm_dir(tmp_path / "checkpoints" / "prm")
+ scorer = prm_reward.build_prm_reward_fn(_tcfg("checkpoints/prm"), "cpu", False)
+ assert os.path.realpath(scorer.prm_path) == os.path.realpath(local)
+
+ def test_a_hub_repo_without_a_head_is_refused_naming_the_configured_value(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe
+ ) -> None:
+ import huggingface_hub
+
+ target = _prm_dir(tmp_path / "plain-base", with_head=False)
+ monkeypatch.setattr(huggingface_hub, "snapshot_download", lambda repo_id, **kw: str(target))
+ monkeypatch.chdir(tmp_path)
+ with pytest.raises(ValueError, match="my-org/soup-prm-135m") as info:
+ prm_reward.build_prm_reward_fn(_tcfg(_HUB_ID), "cpu", False)
+ assert "not a Soup-trained PRM" in str(info.value)
+
+ @pytest.mark.parametrize("value", ["org/[email protected]", "org/n\u00e4me", "org/name\n"])
+ def test_an_id_the_hub_would_not_take_is_refused_by_name(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe, value: str
+ ) -> None:
+ import huggingface_hub
+
+ monkeypatch.setattr(
+ huggingface_hub, "snapshot_download",
+ lambda repo_id, **kw: pytest.fail("the Hub was queried for a malformed id"),
+ )
+ monkeypatch.chdir(tmp_path)
+ with pytest.raises(ValueError, match="neither an existing directory nor a Hub repo id"):
+ prm_reward.build_prm_reward_fn(_tcfg(json.dumps(value)), "cpu", False)
+
+ def test_a_local_directory_without_a_head_is_refused_before_training(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_hub_probe
+ ) -> None:
+ monkeypatch.chdir(tmp_path)
+ _prm_dir(tmp_path / "base-only", with_head=False)
+ with pytest.raises(ValueError, match="not a Soup-trained PRM"):
+ prm_reward.build_prm_reward_fn(_tcfg("./base-only"), "cpu", False)
diff --git a/tests/test_v07130.py b/tests/test_v07130.py
index 6cc44726..198a72c8 100644
--- a/tests/test_v07130.py
+++ b/tests/test_v07130.py
@@ -429,11 +429,35 @@ class TestPRMScorerInputCap:
assert out == [0.0]
+def _write_prm_dir(path):
+ """A directory that passes the build-time reward-head check (#1466)."""
+ import torch
+ from safetensors.torch import save_file
+
+ path.mkdir(parents=True, exist_ok=True)
+ save_file(
+ {"reward_head.weight": torch.ones(1, 8), "reward_head.bias": torch.zeros(1)},
+ str(path / "model.safetensors"),
+ )
+ return path
+
+
class TestBuildPrmRewardFn:
- def test_returns_named_scorer(self, monkeypatch):
+ def test_returns_named_scorer(self, tmp_path, monkeypatch):
+ import huggingface_hub
+
import soup_cli.utils.prm_reward as mod
monkeypatch.setattr(mod, "_resolve_trust", lambda *a, **k: False)
+ # #1466: a Hub id is downloaded when the reward is built; stub the download and
+ # the namespace-pin metadata query it goes through (utils.hubs, #186).
+ from soup_cli.utils import hubs
+
+ snapshot = _write_prm_dir(tmp_path / "snapshot")
+ monkeypatch.setattr(
+ huggingface_hub, "snapshot_download", lambda repo_id, **kw: str(snapshot)
+ )
+ monkeypatch.setattr(hubs, "_hf_repo_metadata", lambda repo_id: None)
class _T:
prm_reward = "some/hf-id-not-on-disk"
@@ -473,7 +497,7 @@ class TestBuildPrmRewardFn:
monkeypatch.setattr(mod, "_resolve_trust", lambda *a, **k: False)
monkeypatch.chdir(tmp_path)
- (tmp_path / "my_prm").mkdir()
+ _write_prm_dir(tmp_path / "my_prm") # #1466: the head is checked at build time
class _T:
prm_reward = "./my_prm"