Compare commits

...
Author SHA1 Message Date
e6d2b3f252 fix: meta load order (#3333)
* test(trainer): add xfail demonstrating buffer-reinit-after-load bug

load_dcp_from_hf runs init_buffers_post_meta() after dcp_load() writes
checkpoint values into persistent buffers, so any model whose reinit
touches a persistent buffer (e.g. Laguna's MoE expert_bias) has the
loaded value silently clobbered back to its reinit default.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(trainer): reinit buffers before loading checkpoint, not after

load_dcp_from_hf ran init_buffers_post_meta()/fix_model_post_empty()
after dcp_load() had already copied checkpoint values into persistent
buffers, silently clobbering any buffer both a reinit hook touches and
a checkpoint legitimately ships (e.g. Laguna's MoE expert_bias). Move
the call to run once, immediately after to_empty(), matching the
existing correct ordering in setup_model's checkpoint-deferred branch.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(trainer): rename test_model_load_order.py to models/test_state_loading.py

Group it with the other cross-cutting model-mechanism tests
(test_checkpointing.py, test_fused_moe.py) rather than the top-level
train/ dir, and name it for what it covers (weight-checkpoint state
loading) since models/test_checkpointing.py already covers activation
checkpointing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 16:41:15 -04:00
Konstantin DunasandGitHub 13553dd88a refactor(orchestrator): rename sampler to generation source (#3330) 2026-08-21 20:36:15 +02:00
Konstantin DunasandGitHub d37b57ba6e docs(training): correct saved episode references (#3329) 2026-08-21 20:36:08 +02:00
Konstantin DunasandGitHub 802a364e6a fix(orchestrator): label eval avg@k by episode group size (#3328) 2026-08-21 20:36:03 +02:00
Konstantin DunasandGitHub 9b9de2f1bc fix(orchestrator): apply taskset system_prompt override on the RL path (#3327) 2026-08-21 19:42:57 +02:00
12 changed files with 122 additions and 71 deletions
+1 -1
View File
@@ -153,7 +153,7 @@ type = "echo"
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_rl.orchestrator.sampler`) from the `sampling` component — the pool rollouts are generated from, and the home of future sampling strategies like replay buffers or branching — and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
+2 -2
View File
@@ -58,7 +58,7 @@ After a restart, verify all processes are back up and progress resumed before th
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the run dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
- `{run_dir}/configs/` — resolved configs, written as JSON so explicit None settings round-trip (`rl.json` has the full picture).
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
### Logs
@@ -152,7 +152,7 @@ JSONL files of native `vf.Episode` records (training tensors excluded), one line
curriculum-rejected work, and work that never enters a batch — so it is crash-durable.
`effective` contains the admitted clean trainable traces grouped into their original episodes
(eval: the non-errored trainable epoch cohort). Each record carries its provenance at the
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group_id`,
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group` (`id`),
and `run`. Training-run records discriminate train/eval work and include dispatch
step plus an optional live-policy version span. Traces retain their own task,
verifiers, agent, and runtime fields.
+2 -2
View File
@@ -3,7 +3,7 @@
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
is — a bundle of sampling and the per-token training signal. This package
turns the signal half into runtime objects (the sampling half is the env's
:class:`~prime_rl.orchestrator.sampler.Sampler`):
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``) — each named class owns
@@ -55,7 +55,7 @@ def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm
cls = ALGORITHM_CLASSES[config.type]
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
# The Algorithm is the runtime of the algorithm config's training signal
# (its sibling Sampler interprets the sampling half). Every algorithm is
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
# handed the live policy pool — opsd self-distills against it, others may
# judge against it or ignore it. Other models (a frozen teacher, a hint
# renderer) are built from the algorithm's own config in setup().
+12 -12
View File
@@ -163,7 +163,7 @@ class Dispatcher:
self.progress = progress
self.train_envs = train_envs
self.eval_envs = eval_envs
# Train rollouts go to the env sampler's pool; eval always
# Train rollouts go to the env's generation source; eval always
# evaluates the policy.
self.policy_pool = policy_pool
self.train_source = train_source
@@ -218,14 +218,14 @@ class Dispatcher:
self.stopped = asyncio.Event()
self.task: asyncio.Task | None = None
def _train_pool_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
def _train_generation_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
the env sampler's pool. (Eval always uses the policy.)"""
eval always uses the policy."""
assert self.train_envs is not None # train groups only exist when train is configured
sampler = self.train_envs.get(env_name).sampler
if sampler.samples_from_live_policy:
return sampler.pool, self.policy.model_name, True
return sampler.pool, sampler.pool.model_name, False
source = self.train_envs.get(env_name).generation_source
if source.uses_live_policy:
return source.pool, self.policy.model_name, True
return source.pool, source.pool.model_name, False
@property
def inflight_train_count(self) -> int:
@@ -374,10 +374,10 @@ class Dispatcher:
for meta in self.inflight.values():
if meta.kind != "train":
continue
# Frozen-sourced rollouts never go stale — their sampler doesn't
# Frozen-sourced rollouts never go stale — their generation source doesn't
# change with policy updates.
assert self.train_envs is not None
if not self.train_envs.get(meta.env_name).sampler.samples_from_live_policy:
if not self.train_envs.get(meta.env_name).generation_source.uses_live_policy:
continue
meta.off_policy_steps += 1
if meta.off_policy_steps > self.max_off_policy_steps:
@@ -490,7 +490,7 @@ class Dispatcher:
ready, no permits). Returns True after issuing one task — the caller
loops to keep scheduling.
"""
# Train rollouts use the env sampler's pool via the
# Train rollouts use the env's generation source via the
# renderer/token train client. Eval always evaluates the policy and
# goes through the eval client (chat-completions) so eval scores stay
# comparable.
@@ -498,7 +498,7 @@ class Dispatcher:
pool, model_name = self.policy_pool, self.policy.model_name
live_sourced = True
else:
pool, model_name, live_sourced = self._train_pool_for(group.env_name)
pool, model_name, live_sourced = self._train_generation_for(group.env_name)
if group.pinned_client is None:
group.pinned_client = pool.eval_client if group.kind == "eval" else pool.train_client
@@ -644,7 +644,7 @@ class Dispatcher:
live_policy = meta.kind == "eval"
if meta.kind == "train":
assert self.train_envs is not None
live_policy = self.train_envs.get(meta.env_name).sampler.samples_from_live_policy
live_policy = self.train_envs.get(meta.env_name).generation_source.uses_live_policy
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
work: vf.WorkInfo = (
vf.EvalWorkInfo(step=meta.step, policy=policy)
+16 -10
View File
@@ -29,7 +29,7 @@ from verifiers.v1.serve import EnvClient
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.sampler import Sampler
from prime_rl.orchestrator.generation_source import GenerationSource
from prime_rl.utils.logger import get_logger
# Max wait for the env server to answer health. Generous because the launcher spawns
@@ -74,11 +74,11 @@ class Env:
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
taskset = vf.load_taskset(self.config.env.taskset)
if type(taskset).INFINITE:
self.tasks = iter(taskset.load())
self.tasks = iter(taskset)
self.num_tasks = None
else:
# Materialize off the event loop — load() may pull a dataset.
materialized = await asyncio.to_thread(lambda: list(taskset.load()))
# Materialize off the event loop — iterating may pull a dataset.
materialized = await asyncio.to_thread(lambda: list(taskset))
self.tasks = iter(materialized)
self.num_tasks = len(materialized)
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
@@ -118,11 +118,17 @@ class Env:
class TrainEnv(Env):
config: TrainSourceConfig
def __init__(self, config: TrainSourceConfig, address: str, sampler: Sampler, algorithm: Algorithm):
def __init__(
self,
config: TrainSourceConfig,
address: str,
generation_source: GenerationSource,
algorithm: Algorithm,
):
super().__init__(config, address)
self.sampler = sampler
self.generation_source = generation_source
self.algorithm = algorithm
self.sampling_args = sampler.sampling_args(config.sampling.to_sampling_args())
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
class EvalEnv(Env):
@@ -175,8 +181,8 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments, each paired with its rollout
:class:`Sampler` and runtime :class:`Algorithm`, built from the env's
"""Collection of training environments, each paired with its
:class:`GenerationSource` and runtime :class:`Algorithm`, built from the env's
resolved algorithm config."""
def __init__(
@@ -193,7 +199,7 @@ class TrainEnvs(Envs[TrainEnv]):
env = TrainEnv(
config,
addresses[("train", config.resolved_name)],
Sampler(config.algo.sampling, policy_pool, renderer_config),
GenerationSource(config.algo.sampling, policy_pool, renderer_config),
build_algorithm(config.algo, policy_pool),
)
self._envs[env.name] = env
+5 -1
View File
@@ -86,4 +86,8 @@ class EvalSink:
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
env_name, step = key
episodes = self.pending_batches.pop(key, [])
return EvalBatch(env_name=env_name, step=step, episodes=EvalEpisodes(episodes))
return EvalBatch(
env_name=env_name,
step=step,
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
)
@@ -1,12 +1,4 @@
"""How an env's train rollouts are produced — the sample strategy.
The algorithm (``algo/``) consumes finalized rollouts and compiles them into
per-token loss-component weights; the sampler owns where those rollouts come
from. Today that is one question — which model generates them — and its
consequences (sampling logprobs, prefix-cache salting, and off-policy
staleness are all liveness questions about the source). Future sampling
strategies (replay buffers, branching) extend here, not the algorithm.
"""
"""Resolve the model source used to generate an env's train episodes."""
from __future__ import annotations
@@ -21,8 +13,8 @@ if TYPE_CHECKING:
from prime_rl.utils.client import InferencePool
class Sampler:
"""One env's rollout source.
class GenerationSource:
"""One env's generation model and inference pool.
``pool`` is the pool train rollouts are generated from: the policy pool,
swapped for a connected frozen pool in :meth:`setup` when the source is an
@@ -40,20 +32,20 @@ class Sampler:
self.connected_pools: list[InferencePool] = [] # client pools connected in setup(); closed at shutdown
async def setup(self) -> None:
"""Connect a client pool to a frozen sampling source and wait for
"""Connect a client pool to a frozen generation source and wait for
readiness. Must run before dispatching."""
if isinstance(self.config.source, FrozenModelConfig):
self.pool = await connect_frozen_pool(self.config.source, renderer_config=self.renderer_config)
self.connected_pools.append(self.pool)
@property
def samples_from_live_policy(self) -> bool:
def uses_live_policy(self) -> bool:
return self.config.source == "policy"
def sampling_args(self, args: dict) -> dict:
"""Source-specific sampling-arg overrides. Sampling logprobs are only
needed for importance ratios on policy-sampled tokens — frozen
endpoints may reject the knob."""
if not self.samples_from_live_policy:
if not self.uses_live_policy:
args.pop("logprobs", None)
return args
+4 -15
View File
@@ -474,30 +474,19 @@ class TrainEpisodes(EpisodeCollection):
class EvalEpisodes(EpisodeCollection):
def __init__(
self,
episodes: list[vf.Episode] | None = None,
episodes: list[vf.Episode],
group_size: int,
predicate: Callable[[TraceRecord], bool] | None = None,
group_size: int | None = None,
) -> None:
super().__init__(episodes, predicate=predicate)
self._group_size = group_size
@property
def group_size(self) -> int:
if self._group_size is not None:
return self._group_size
counts: dict = {}
for record in self.records:
if record.trace.agent.trainable:
group_id = episode_group_id(record.episode)
counts[group_id] = counts.get(group_id, 0) + 1
return max(counts.values(), default=0)
self.group_size = group_size
@property
def effective(self) -> EvalEpisodes:
return EvalEpisodes(
self.episodes,
self.group_size,
predicate=lambda record: not record.trace.has_error and record.trace.agent.trainable,
group_size=self.group_size,
)
@property
+3 -3
View File
@@ -270,10 +270,10 @@ class Orchestrator:
get_logger().info("Waiting for policy inference pool to be ready")
await self.policy_inference.wait_for_ready(config.model.name)
get_logger().success("Policy inference pool ready")
# Build + ready pools for each env's frozen sampling source and the
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
await asyncio.gather(
*(env.sampler.setup() for env in self.train_envs),
*(env.generation_source.setup() for env in self.train_envs),
*(env.algorithm.setup() for env in self.train_envs),
)
@@ -965,7 +965,7 @@ class Orchestrator:
await self.policy_inference.stop()
if self.train_envs is not None:
for env in self.train_envs:
for pool in (*env.sampler.connected_pools, *env.algorithm.connected_pools):
for pool in (*env.generation_source.connected_pools, *env.algorithm.connected_pools):
await pool.stop()
task = asyncio.create_task(teardown())
+5 -7
View File
@@ -965,16 +965,15 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
model.to_empty(device=device)
torch.distributed.barrier()
def _init_buffers_post_meta():
if isinstance(model, PreTrainedModelPrimeRL):
model.init_buffers_post_meta()
else:
fix_model_post_empty(model)
# Must run before any weight loading: reinit can zero persistent buffers that ship in checkpoints
if isinstance(model, PreTrainedModelPrimeRL):
model.init_buffers_post_meta()
else:
fix_model_post_empty(model)
logger = get_logger()
if config.debug.random_init:
logger.warning("Randomly initializing model. Skipping loading weights from HF.")
_init_buffers_post_meta()
_move_buffers_to_cuda(model, config)
return
@@ -1042,7 +1041,6 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
# Restore weight tying broken by to_empty() for HF models
if not isinstance(model, PreTrainedModelPrimeRL) and model.config.tie_word_embeddings:
model.tie_weights()
_init_buffers_post_meta()
_move_buffers_to_cuda(model, config)
+16 -4
View File
@@ -270,22 +270,34 @@ def test_train_only_metrics_absent_from_eval():
assert out["train/agg/all/agent/is_trainable/mean"] == 0.5
assert out["train/agg/all/agent/is_admitted/mean"] == 0.5
assert "train/agg/all/is_trainable/mean" not in out # pipeline verdicts are per-trace
eval_out = EvalEpisodes(rollouts).metrics.to_wandb(prefix="eval/x", subset="all")
eval_out = EvalEpisodes(rollouts, group_size=2).metrics.to_wandb(prefix="eval/x", subset="all")
assert not any("is_trainable" in key or "is_admitted" in key for key in eval_out)
def test_eval_avg_at_k_and_pass_k():
binary = EvalEpisodes([mk(reward=1.0, group_id="g0"), mk(reward=0.0, group_id="g0")])
binary = EvalEpisodes([mk(reward=1.0, group_id="g0"), mk(reward=0.0, group_id="g0")], group_size=2)
eff = binary.effective.metrics.to_wandb(prefix="eval/x", subset="effective")
assert eff["eval/x/effective/agent/avg@2"] == 0.5 # mean reward under avg@<k> (k from the groups)
assert eff["eval/x/effective/agent/avg@2"] == 0.5 # k is the configured episode group size
assert "eval/x/effective/avg@2" not in eff # scores are per-agent, never pooled
assert eff["eval/x/effective/agent/pass@1"] == 0.5 and eff["eval/x/effective/agent/pass^2"] == 0.0
all_out = binary.metrics.to_wandb(prefix="eval/x", subset="all")
assert all_out["eval/x/all/agent/avg@2"] == 0.5
assert not any("pass@" in k or "pass^" in k for k in all_out) # pass@k effective-only
non_binary = EvalEpisodes([mk(reward=0.5, group_id="g0"), mk(reward=1.0, group_id="g0")])
non_binary = EvalEpisodes([mk(reward=0.5, group_id="g0"), mk(reward=1.0, group_id="g0")], group_size=2)
assert not any("pass@" in k for k in non_binary.effective.metrics.to_wandb(prefix="eval/x", subset="effective"))
multi_agent = EvalEpisodes(
[
combine(mk(agent_name="proposer"), mk(agent_name="solver"), mk(agent_name="solver")),
combine(mk(agent_name="proposer"), mk(agent_name="solver"), mk(agent_name="solver")),
],
group_size=2,
)
multi_agent_out = multi_agent.metrics.to_wandb(prefix="eval/x", subset="all")
assert "eval/x/all/proposer/avg@2" in multi_agent_out
assert "eval/x/all/solver/avg@2" in multi_agent_out
assert not any("avg@4" in key for key in multi_agent_out)
def test_compute_pass_metrics_matches_closed_form():
out = compute_pass_metrics([1.0, 1.0, 0.0, 0.0]) # n=4, c=2
@@ -0,0 +1,50 @@
from unittest.mock import MagicMock
import pytest
import torch
from prime_rl.configs.trainer import ModelConfig
from prime_rl.trainer.model import load_dcp_from_hf
from prime_rl.trainer.models.laguna.configuration_laguna import LagunaConfig
from prime_rl.trainer.models.laguna.modeling_laguna import LagunaForCausalLM
pytestmark = [pytest.mark.gpu]
@pytest.fixture
def model() -> LagunaForCausalLM:
config = LagunaConfig(
vocab_size=64,
hidden_size=32,
intermediate_size=64,
num_hidden_layers=2,
num_attention_heads=4,
num_key_value_heads=2,
head_dim=8,
moe_intermediate_size=16,
shared_expert_intermediate_size=16,
num_experts_per_tok=2,
num_experts=4,
sliding_window=None,
layer_types=["full_attention", "full_attention"],
)
with torch.device("meta"):
return LagunaForCausalLM(config)
def test_load_dcp_from_hf_keeps_checkpoint_expert_bias(model, tmp_path, monkeypatch):
"""Checkpoint values for the persistent `expert_bias` buffer must survive loading."""
expected = torch.tensor([0.1, 0.2, 0.3, 0.4])
def fake_dcp_load(state_dict, storage_reader=None):
buffer = state_dict["model.layers.1.mlp.expert_bias"]
buffer.copy_(expected.to(device=buffer.device, dtype=buffer.dtype))
monkeypatch.setattr("prime_rl.trainer.model.dcp_load", fake_dcp_load)
monkeypatch.setattr("prime_rl.trainer.model.load_state_dict_keys", lambda path: model.state_dict().keys())
monkeypatch.setattr("torch.distributed.barrier", lambda *args, **kwargs: None)
load_dcp_from_hf(model, ModelConfig(name=str(tmp_path)), parallel_dims=MagicMock())
expert_bias = model.model.layers[1].mlp.expert_bias
torch.testing.assert_close(expert_bias.cpu(), expected.to(expert_bias.dtype))