Compare commits

...
Author SHA1 Message Date
d49f3939e7 update dependency (#2317)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
2026-04-18 13:00:52 -07:00
9eeffdb6fb feat: drop filtered rollouts instead of masking (#2277)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: drop filtered rollouts from training batch instead of masking

Previously, enforced filters zeroed the completion_mask on detected
rollouts but still sent them through the entire training pipeline.
This wastes compute on samples that contribute nothing to the loss.

Now, `apply_filters` returns the subset of rollouts that should be
sent to the trainer. Enforced-detected rollouts are excluded before
pretokenization, VLM cache building, and sample construction.

The trainer handles the resulting empty batches ("phantom steps") by
skipping forward/backward and logging `data/is_empty_batch`.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: retry empty filtered batches instead of passing them to trainer

Keep the invariant that the trainer only receives non-empty batches. If
all rollouts are filtered out, regenerate the batch (up to 3 retries)
and crash the orchestrator on sustained failure. Warn at <=10% trainable.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: drop redundant num_rollouts guard

The retry loop only breaks when len(filtered_rollouts) > 0, which implies
num_rollouts > 0, so the guard is unreachable.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: expand low-trainable-ratio warning with env review hint

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: drop empty-df guard and inline filtered metrics

filtered_rollouts is guaranteed non-empty after the retry loop, so the
empty-df branch is unreachable and the intermediate locals add no value.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: hoist MAX_EMPTY_BATCH_RETRIES to module scope

Also rename the loop var and warning message to "retry N/MAX" so the
counter excludes the initial attempt and reads less ambiguously.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: adjust log style in filter retry warnings

Drop trailing periods and replace ";" with " - " as clause separator.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: clarify low-trainable-ratio warning hint

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: compute metrics over all rollouts, drop only from trainer

Metric logging reverts to main's semantics: all rollouts contribute to
prefill_len, decode_len, samples_per_rollout, and results_df. Filtered
rollouts are still pretokenized and interleaved, but their samples are
simply not added to train_examples. Also inline the generate_batch
coroutine since it is awaited immediately.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: move filter flags to rollout["filter"] + is_filtered

Per-filter detection booleans now live under rollout["filter"], and a
top-level rollout["is_filtered"] captures whether any enforcing filter
triggered. The orchestrator uses is_filtered directly as the keep gate
(no more id() mapping). apply_filters no longer returns filtered_rollouts
- the in-place flags are the single source of truth. Also unbound-var
fix for retry-loop locals, and per-env filter/<env>/<flag>_rate logging
that mirrors the metrics logging pattern.

Both new fields are serialized to train_rollouts.jsonl via save_rollouts,
which already writes all top-level rollout keys.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: cap to 3 total batch-generation attempts, not 3 retries

Rename MAX_EMPTY_BATCH_RETRIES to MAX_EMPTY_BATCH_ATTEMPTS and have the
loop run exactly that many times. Warning now reports the attempt that
just failed ("Attempt N/3 ... retrying").

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: log error line before raising on exhausted retries

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: align filter metric key names with per-env logging

Rename filter/total_detected_rate -> filter/detected_rate and
filter/total_enforced_rate -> filter/is_filtered_rate so the overall
keys mirror the per-env filter/<env>/is_filtered_rate naming.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: unify filter logging under filter/{all,<env>}/{<filter>,is_filtered}

Move is_filtered into results_df so it can be aggregated per-env like
is_truncated. filter_df now holds just per-filter detection booleans.
apply_filters no longer returns an aggregate metrics dict - the
orchestrator derives the rates uniformly across the "all" and per-env
scopes, with symmetric key naming and no _rate/_count suffixes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: rename rollout["filter"] to rollout["filters"] + log keys

Aligns with the plural configs list and the rollout-level "filters"
namespace. Log keys change from filter/{all,<env>}/... to
filters/{all,<env>}/....

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: self-evict orchestrator when batches carry no learning signal

Write control/evicted.txt before raising, so the multi-run manager
skips the run on rediscovery instead of treating it as a hard crash.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-18 09:22:28 -07:00
03689b8ac0 chore: remove prefix-cache-salt and reset-prefix-cache config flags (#2314)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore: remove prefix-cache-salt and reset-prefix-cache config flags

Hardcode the defaults: always set cache_salt on inference requests
(keyed by ckpt_step) and never reset the prefix cache after weight or
LoRA updates. The salt alone is sufficient to invalidate stale KV
states across policy updates, so the reset path is redundant.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: keep empty experimental sub-configs as extension points

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:03:37 -07:00
12 changed files with 175 additions and 155 deletions
+1
View File
@@ -110,6 +110,7 @@ The eviction takes effect through two mechanisms:
- The orchestrator checks for `evicted.txt` at the start of each iteration in its main loop
- If found, it raises a `RuntimeError` with the eviction reason, causing the orchestrator to exit
- This surfaces the eviction reason to the user
- The orchestrator also self-evicts by writing `evicted.txt` if a training batch has no learning signal (all rollouts filtered out) on `MAX_EMPTY_BATCH_ATTEMPTS` (3) consecutive attempts
## LoRA Module Registration
+2
View File
@@ -91,6 +91,8 @@ all = [
"prime-rl[flash-attn]",
"prime-rl[disagg]",
"prime-rl[quack]",
"prime-rl[flash-attn-3]",
"prime-rl[flash-attn-cute]",
]
[dependency-groups]
-9
View File
@@ -247,15 +247,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
class InferenceExperimentalConfig(BaseConfig):
"""Experimental features for inference."""
reset_prefix_cache_after_update: Annotated[
bool,
Field(
description="Whether to reset the prefix cache after weight updates (update_weights, load_lora_adapter). "
"Ensures all KV states are recomputed with the new weights at the cost of extra prefill. "
"When False, prefer using orchestrator.experimental.use_prefix_cache_salt to invalidate stale caches via salt instead.",
),
] = False
class InferenceConfig(BaseConfig):
"""Configures inference."""
+3 -12
View File
@@ -715,7 +715,7 @@ class GibberishFilterConfig(BaseModel):
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
),
] = False
token_id_threshold: Annotated[
@@ -739,7 +739,7 @@ class RepetitionFilterConfig(BaseModel):
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
),
] = False
window: Annotated[
@@ -765,7 +765,7 @@ class ZeroAdvantageFilterConfig(BaseModel):
enforce: Annotated[
bool,
Field(
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
),
] = True
@@ -812,15 +812,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
class OrchestratorExperimentalConfig(BaseConfig):
"""Experimental features for the orchestrator."""
use_prefix_cache_salt: Annotated[
bool,
Field(
description="Whether to set a cache_salt on inference requests that changes with each weight update. "
"This invalidates prefix-cached KV states from previous policies without resetting the entire cache, "
"while preserving cache hits for in-flight off-policy rollouts.",
),
] = True
class TeacherModelConfig(BaseConfig):
"""Configures the teacher model for computing teacher logprobs (e.g. for distillation)."""
+1 -12
View File
@@ -198,24 +198,16 @@ async def resume(request: Request):
async def update_weights(request: Request):
data = await request.json()
await engine_client(request).collective_rpc("update_weights_from_path", args=(data.get("weight_dir"),))
if request.app.state.reset_prefix_cache_after_update:
await engine_client(request).reset_prefix_cache()
return {"status": "ok"}
@router.post("/load_lora_adapter")
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
"""Load a LoRA adapter, optionally resetting the prefix cache.
Wrapper around vLLM's /v1/load_lora_adapter that also resets the prefix cache
to invalidate KV states computed with old weights (unless disabled via config).
"""
"""Wrapper around vLLM's /v1/load_lora_adapter."""
handler = models(raw_request)
response = await handler.load_lora_adapter(lora_request)
if isinstance(response, ErrorResponse):
return JSONResponse(content=response.model_dump(), status_code=response.error.code)
if raw_request.app.state.reset_prefix_cache_after_update:
await engine_client(raw_request).reset_prefix_cache()
return {"status": "ok"}
@@ -274,8 +266,6 @@ async def custom_init_app_state(
"""
await init_app_state(engine_client, state, args, supported_tasks)
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
if "generate" in supported_tasks and state.openai_serving_chat is not None:
original_chat = state.openai_serving_chat
serving_chat = object.__new__(OpenAIServingChatWithTokens)
@@ -342,7 +332,6 @@ def server(config: InferenceConfig, vllm_extra: dict[str, Any] | None = None):
args.tool_call_parser = resolve_tool_call_parser(args.model, args.tool_call_parser)
args.enable_auto_tool_choice = args.tool_call_parser is not None
args.reset_prefix_cache_after_update = config.experimental.reset_prefix_cache_after_update
if args.tool_call_parser is not None:
logger.info(f"Using tool_call_parser='{args.tool_call_parser}' for model '{args.model}'")
+4 -6
View File
@@ -104,9 +104,7 @@ class Env:
self._env_server_process = process
return address
def _sampling_args_with_salt(self, cache_salt: str | None) -> dict:
if cache_salt is None:
return self.sampling_args
def _sampling_args_with_salt(self, cache_salt: str) -> dict:
sampling_args = {**self.sampling_args}
extra_body = {**sampling_args.get("extra_body", {}), "cache_salt": cache_salt}
sampling_args["extra_body"] = extra_body
@@ -117,7 +115,7 @@ class Env:
client: vf.ClientConfig,
example: dict,
model_name: str,
cache_salt: str | None = None,
cache_salt: str,
) -> vf.RolloutOutput:
"""Run a single rollout for an example."""
return await self.env.run_rollout(
@@ -136,7 +134,7 @@ class Env:
example: dict,
model_name: str,
rollouts_per_example: int,
cache_salt: str | None = None,
cache_salt: str,
) -> list[vf.RolloutOutput]:
"""Run a group of rollouts for an example. Required for group-scoring envs."""
return await self.env.run_group(
@@ -181,7 +179,7 @@ class EvalEnv(Env):
get_client: Callable[[], Awaitable[vf.ClientConfig]],
ckpt_step: int,
step: int,
cache_salt: str | None = None,
cache_salt: str,
) -> list[vf.RolloutOutput]:
num_examples = len(self.examples)
rollouts_per_example = self.config.rollouts_per_example
+17 -40
View File
@@ -2,9 +2,8 @@
Filters run after rollouts complete, inspecting token IDs and logprobs to
detect gibberish or repetition. Detection metrics are always tracked.
When enforce=True, detected rollouts get their completion mask cleared so
they don't contribute to training. Reward is kept as-is for baseline
calculation.
When enforce=True, detected rollouts are skipped entirely during training and
are not sent to the trainer. Reward is kept as-is for baseline calculation.
"""
import math
@@ -149,63 +148,41 @@ def setup_filters(configs: list[FilterConfig], vocab_size: int) -> list[RolloutF
return filters
def apply_filters(
filters: list[RolloutFilter],
rollouts: list[vf.RolloutOutput],
) -> dict[str, float]:
"""Apply filters to rollouts. Detection metrics are always tracked.
def apply_filters(filters: list[RolloutFilter], rollouts: list[vf.RolloutOutput]) -> None:
"""Flag rollouts in-place with per-filter detection and drop decision.
When a filter has enforce=True, detected rollouts get their completion
mask cleared and stop_condition set. Reward is kept as-is for baseline
calculation.
First matching filter wins per rollout (no double-counting).
Returns aggregate metrics dict for logging.
Each rollout gets a `filters` dict with per-filter detection booleans and
an `is_filtered` bool that is True iff an enforcing filter detected it.
First matching filter wins per rollout (no double-counting). Reward and
trajectory tokens are left untouched so the rollout can still contribute
to baseline calculations and metric aggregation.
"""
for rollout in rollouts:
rollout["filters"] = {f.name: False for f in filters}
rollout["is_filtered"] = False
if not filters:
return {}
return
counts: dict[str, int] = {f.name: 0 for f in filters}
total_detected = 0
total_enforced = 0
for rollout in rollouts:
if rollout.get("metrics") is None:
rollout["metrics"] = {}
for filt in filters:
rollout["metrics"].setdefault(f"filter/{filt.name}", 0.0)
for filt in filters:
result = filt.check(rollout)
if result.detected:
counts[filt.name] += 1
total_detected += 1
rollout["metrics"][f"filter/{filt.name}"] = 1.0
rollout["filters"][filt.name] = True
if filt.enforce:
for step in rollout["trajectory"]:
tokens = step["tokens"]
if tokens is not None:
tokens["completion_mask"] = [0] * len(tokens["completion_mask"])
rollout["stop_condition"] = filt.name
rollout["is_filtered"] = True
total_enforced += 1
break
n = len(rollouts)
metrics: dict[str, float] = {}
for f in filters:
metrics[f"filter/{f.name}_count"] = float(counts[f.name])
metrics[f"filter/{f.name}_rate"] = counts[f.name] / n if n > 0 else 0.0
metrics["filter/total_detected_rate"] = total_detected / n if n > 0 else 0.0
metrics["filter/total_enforced_rate"] = total_enforced / n if n > 0 else 0.0
if total_detected > 0:
enforced_msg = f", enforced {total_enforced}" if total_enforced > 0 else ""
get_logger().info(
f"Detected {total_detected}/{n} rollouts "
f"Detected {total_detected}/{len(rollouts)} rollouts "
f"({', '.join(f'{name}={c}' for name, c in counts.items() if c > 0)})" + enforced_msg
)
return metrics
+78 -35
View File
@@ -76,6 +76,11 @@ from prime_rl.utils.utils import (
# and artifacts are persisted *before* this point, so a forced exit is safe.
SHUTDOWN_TIMEOUT_S = 300
# Maximum number of times to attempt generating a training batch when all
# rollouts are filtered out. After this many attempts, the orchestrator crashes
# rather than silently skipping training steps.
MAX_EMPTY_BATCH_ATTEMPTS = 3
@clean_exit
async def orchestrate(config: OrchestratorConfig):
@@ -236,7 +241,6 @@ async def orchestrate(config: OrchestratorConfig):
enable_policy_updates=enable_policy_updates,
lora_name=config.model.lora.name if config.model.lora else None,
config=config,
use_prefix_cache_salt=config.experimental.use_prefix_cache_salt,
)
scheduler.model_name = rollout_model_name
@@ -380,7 +384,6 @@ async def orchestrate(config: OrchestratorConfig):
logger.info("Cancelling in-flight training rollouts before starting evals to avoid congestion.")
await scheduler.cancel_inflight_rollouts()
eval_cache_salt = str(ckpt_step) if config.experimental.use_prefix_cache_salt else None
eval_results = await asyncio.gather(
*[
eval_env.evaluate(
@@ -388,7 +391,7 @@ async def orchestrate(config: OrchestratorConfig):
get_client=inference_pool.get_eval_client,
ckpt_step=ckpt_step,
step=progress.step,
cache_salt=eval_cache_salt,
cache_salt=str(ckpt_step),
)
for eval_env in envs_to_eval
]
@@ -408,13 +411,55 @@ async def orchestrate(config: OrchestratorConfig):
# Update prev_ckpt_step for next iteration
prev_ckpt_step = ckpt_step
# Schedule generating the training batch
train_task = asyncio.create_task(scheduler.generate_batch(step=progress.step))
# Schedule generating the training batch. Retry on empty-after-filter
# batches so the trainer never receives an empty batch.
generate_completions_time = 0.0
train_rollouts: list[vf.RolloutOutput] = []
num_rollouts = 0
num_unique_examples = 0
n_trainable = 0
for attempt in range(MAX_EMPTY_BATCH_ATTEMPTS):
train_rollouts = await scheduler.generate_batch(step=progress.step)
generate_completions_time += scheduler.last_batch_generation_time
# Await train rollouts
await train_task
generate_completions_time = scheduler.last_batch_generation_time
train_rollouts = train_task.result()
# Compute advantages (in-place)
num_rollouts = len(train_rollouts)
num_unique_examples = len({r["example_id"] for r in train_rollouts})
compute_advantages(train_rollouts, config.rollouts_per_example, config.advantage)
# Apply rollout filters — sets rollout["filters"] and rollout["is_filtered"]
apply_filters(rollout_filters, train_rollouts)
n_trainable = sum(1 for r in train_rollouts if not r["is_filtered"])
if n_trainable > 0:
break
if attempt == MAX_EMPTY_BATCH_ATTEMPTS - 1:
logger.error(
f"Attempt {attempt + 1}/{MAX_EMPTY_BATCH_ATTEMPTS} at step {progress.step} "
f"filtered out all {num_rollouts} rollouts - crashing orchestrator"
)
reason = (
f"All {num_rollouts} rollouts were filtered out on "
f"{MAX_EMPTY_BATCH_ATTEMPTS} consecutive attempts at step {progress.step}"
)
evicted_path = config.output_dir / "control" / "evicted.txt"
evicted_path.parent.mkdir(parents=True, exist_ok=True)
evicted_path.write_text(reason)
raise RuntimeError(reason)
logger.warning(
f"Attempt {attempt + 1}/{MAX_EMPTY_BATCH_ATTEMPTS} at step {progress.step} "
f"filtered out all {num_rollouts} rollouts - retrying batch generation"
)
trainable_ratio = n_trainable / num_rollouts
if trainable_ratio <= 0.1:
logger.warning(
f"Only {n_trainable}/{num_rollouts} rollouts in the batch are trainable "
f"({trainable_ratio:.1%}) - this can mean the tasks are too easy or too hard for the "
"model, consider reviewing the task difficulty of your environment(s)"
)
# Save train rollouts to disk (fire-and-forget background thread)
step_path = get_step_path(get_rollout_dir(config.output_dir), progress.step)
@@ -431,15 +476,6 @@ async def orchestrate(config: OrchestratorConfig):
f"VLM offloaded {num_offloaded} unique images to disk in {time.perf_counter() - offload_start:.2f}s"
)
# Compute advantages (in-place)
example_ids = [r["example_id"] for r in train_rollouts]
num_rollouts = len(train_rollouts)
num_unique_examples = len(set(example_ids))
compute_advantages(train_rollouts, config.rollouts_per_example, config.advantage)
# Apply rollout filters (zeros reward/mask for degenerate generations)
filter_metrics = apply_filters(rollout_filters, train_rollouts)
# Convert rollouts to training samples
parallel_preprocess_start = time.perf_counter()
@@ -476,7 +512,8 @@ async def orchestrate(config: OrchestratorConfig):
*(asyncio.to_thread(process_rollout, r, rollout_idx) for rollout_idx, r in enumerate(train_rollouts))
)
# Collect results and assign advantages
# Collect results and assign advantages. Metrics are computed over all
# rollouts; only non-filtered samples are sent to the trainer.
train_examples: list[TrainingSample] = []
rollout_prefill_lens: list[int] = []
rollout_decode_lens: list[int] = []
@@ -486,18 +523,18 @@ async def orchestrate(config: OrchestratorConfig):
for rollout, samples in zip(train_rollouts, results):
rollout_prefill_tokens = 0
rollout_decode_tokens = 0
if samples is not None:
rollout_samples_per_rollout.append(len(samples))
for sample in samples:
sample.advantage = rollout["advantage"]
sample.reward = rollout["reward"]
sample_decode_tokens = sum(sample.completion_mask)
sample_prefill_tokens = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode_tokens
rollout_decode_tokens += sample_decode_tokens
rollout_prefill_tokens += sample_prefill_tokens
if samples is None:
samples = []
rollout_samples_per_rollout.append(len(samples))
for sample in samples:
sample.advantage = rollout["advantage"]
sample.reward = rollout["reward"]
sample_decode_tokens = sum(sample.completion_mask)
sample_prefill_tokens = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode_tokens
rollout_decode_tokens += sample_decode_tokens
rollout_prefill_tokens += sample_prefill_tokens
if not rollout["is_filtered"]:
train_examples.append(sample)
else:
rollout_samples_per_rollout.append(0)
rollout_prefill_lens.append(rollout_prefill_tokens)
rollout_decode_lens.append(rollout_decode_tokens)
num_prefill_tokens += rollout_prefill_tokens
@@ -540,6 +577,7 @@ async def orchestrate(config: OrchestratorConfig):
"env_name": [rollout["env_name"] for rollout in train_rollouts],
"reward": [rollout["reward"] for rollout in train_rollouts],
"is_truncated": [rollout["is_truncated"] for rollout in train_rollouts],
"is_filtered": [rollout["is_filtered"] for rollout in train_rollouts],
"stop_condition": [rollout.get("stop_condition") for rollout in train_rollouts],
"seq_len": [get_seq_len(rollout) for rollout in train_rollouts],
"prefill_len": rollout_prefill_lens,
@@ -551,8 +589,9 @@ async def orchestrate(config: OrchestratorConfig):
}
)
# Separate DataFrame for env reward function metrics to avoid column name collisions
# Separate DataFrames for env reward function metrics and filter flags to avoid column name collisions
metrics_df = pd.DataFrame([rollout["metrics"] for rollout in train_rollouts])
filter_df = pd.DataFrame([rollout["filters"] for rollout in train_rollouts])
# Update progress metrics
num_tokens = int(results_df.seq_len.sum())
@@ -634,8 +673,9 @@ async def orchestrate(config: OrchestratorConfig):
**buffer.get_metrics(),
# Event loop lag metrics
**event_loop_lag_monitor.get_metrics(),
# Rollout filter metrics
**filter_metrics,
# Rollout filter metrics (detection rate per filter + overall drop rate)
"filters/all/is_filtered": results_df.is_filtered.astype(float).mean(),
**{f"filters/all/{name}": filter_df[name].astype(float).mean() for name in filter_df.columns},
# W&B axis
"step": progress.step,
}
@@ -674,6 +714,10 @@ async def orchestrate(config: OrchestratorConfig):
env_metrics_df = metrics_df.loc[env_df.index]
for metric in metrics_df.columns:
to_log[f"metrics/{env}/{metric}"] = env_metrics_df.groupby(env_df["example_id"])[metric].mean().mean()
to_log[f"filters/{env}/is_filtered"] = env_df.is_filtered.astype(float).mean()
env_filter_df = filter_df.loc[env_df.index]
for name in filter_df.columns:
to_log[f"filters/{env}/{name}"] = env_filter_df[name].astype(float).mean()
# Log metrics to monitor(s)
monitor.log(to_log, step=progress.step)
@@ -718,7 +762,6 @@ async def orchestrate(config: OrchestratorConfig):
if config.eval and eval_envs is not None:
logger.info("Running final evals")
final_cache_salt = str(ckpt_step) if config.experimental.use_prefix_cache_salt else None
eval_results = await asyncio.gather(
*[
eval_env.evaluate(
@@ -726,7 +769,7 @@ async def orchestrate(config: OrchestratorConfig):
get_client=inference_pool.get_eval_client,
ckpt_step=ckpt_step,
step=progress.step,
cache_salt=final_cache_salt,
cache_salt=str(ckpt_step),
)
for eval_env in eval_envs
]
+1 -3
View File
@@ -68,7 +68,6 @@ class Scheduler:
tasks_per_minute: int | None,
enable_policy_updates: bool = True,
lora_name: str | None = None,
use_prefix_cache_salt: bool = False,
):
self.logger = get_logger()
if tasks_per_minute is not None:
@@ -87,7 +86,6 @@ class Scheduler:
self.strict_async_level = strict_async_level
self.enable_policy_updates = enable_policy_updates
self.lora_name = lora_name
self.use_prefix_cache_salt = use_prefix_cache_salt
self.model_name = self.config.model.name
self.json_logging = config.log.json_logging
@@ -198,7 +196,7 @@ class Scheduler:
env_name = group.example["env_name"]
env = self.train_envs.get(env_name)
cache_salt = str(self.ckpt_step) if self.use_prefix_cache_salt else None
cache_salt = str(self.ckpt_step)
if env.requires_group_scoring:
rollout_count = group.rollouts_to_schedule
group.rollouts_to_schedule = 0
+64 -37
View File
@@ -218,7 +218,7 @@ def test_setup_filters_multiple():
# --- apply_filters tests (enforce=True) ---
def test_apply_filters_enforced_zeros_mask():
def test_apply_filters_enforced_flags_rollout():
gibberish_filter = _make_gibberish_filter(enforce=True)
rollout = _make_rollout(
@@ -227,16 +227,14 @@ def test_apply_filters_enforced_zeros_mask():
reward=1.0,
)
metrics = apply_filters([gibberish_filter], [rollout])
apply_filters([gibberish_filter], [rollout])
assert rollout["reward"] == 1.0
assert all(m == 0 for m in rollout["trajectory"][0]["tokens"]["completion_mask"])
assert rollout["stop_condition"] == "gibberish"
assert rollout["metrics"]["filter/gibberish"] == 1.0
assert metrics["filter/gibberish_count"] == 1.0
assert metrics["filter/gibberish_rate"] == 1.0
assert metrics["filter/total_detected_rate"] == 1.0
assert metrics["filter/total_enforced_rate"] == 1.0
assert rollout["trajectory"][0]["tokens"]["completion_ids"] == [120_000]
assert rollout["trajectory"][0]["tokens"]["completion_mask"] == [1]
assert rollout["stop_condition"] is None
assert rollout["filters"] == {"gibberish": True}
assert rollout["is_filtered"] is True
def test_apply_filters_preserves_clean_rollouts():
@@ -248,14 +246,14 @@ def test_apply_filters_preserves_clean_rollouts():
reward=1.0,
)
metrics = apply_filters([gibberish_filter], [rollout])
apply_filters([gibberish_filter], [rollout])
assert rollout["reward"] == 1.0
assert rollout["trajectory"][0]["tokens"]["completion_ids"] == [50, 60, 70]
assert all(m == 1 for m in rollout["trajectory"][0]["tokens"]["completion_mask"])
assert rollout["stop_condition"] is None
assert metrics["filter/gibberish_count"] == 0.0
assert metrics["filter/total_detected_rate"] == 0.0
assert metrics["filter/total_enforced_rate"] == 0.0
assert rollout["filters"] == {"gibberish": False}
assert rollout["is_filtered"] is False
def test_apply_filters_first_filter_wins():
@@ -268,13 +266,11 @@ def test_apply_filters_first_filter_wins():
reward=1.0,
)
metrics = apply_filters([gibberish_filter, repetition_filter], [rollout])
apply_filters([gibberish_filter, repetition_filter], [rollout])
assert rollout["stop_condition"] == "gibberish"
assert metrics["filter/gibberish_count"] == 1.0
assert metrics["filter/repetition_count"] == 0.0
assert metrics["filter/total_detected_rate"] == 1.0
assert metrics["filter/total_enforced_rate"] == 1.0
assert rollout["stop_condition"] is None
assert rollout["filters"] == {"gibberish": True, "repetition": False}
assert rollout["is_filtered"] is True
def test_apply_filters_empty_list():
@@ -282,8 +278,9 @@ def test_apply_filters_empty_list():
completion_ids=[1, 2, 3],
completion_logprobs=[-1.0, -1.0, -1.0],
)
metrics = apply_filters([], [rollout])
assert metrics == {}
apply_filters([], [rollout])
assert rollout["filters"] == {}
assert rollout["is_filtered"] is False
assert rollout["reward"] == 1.0
@@ -295,15 +292,49 @@ def test_apply_filters_mixed_batch():
completion_ids=[120_000], completion_logprobs=[gibberish_filter.logprob_threshold - 1.0], reward=1.0
)
metrics = apply_filters([gibberish_filter], [clean, dirty])
apply_filters([gibberish_filter], [clean, dirty])
assert clean["reward"] == 1.0
assert dirty["reward"] == 1.0
assert all(m == 0 for m in dirty["trajectory"][0]["tokens"]["completion_mask"])
assert metrics["filter/gibberish_count"] == 1.0
assert metrics["filter/gibberish_rate"] == 0.5
assert metrics["filter/total_detected_rate"] == 0.5
assert metrics["filter/total_enforced_rate"] == 0.5
assert clean["is_filtered"] is False
assert dirty["is_filtered"] is True
def test_apply_filters_enforced_preserves_rollout_tokens():
gibberish_filter = _make_gibberish_filter(enforce=True)
rollout = _make_rollout(
completion_ids=[10, 120_000, 30],
completion_logprobs=[-1.0, gibberish_filter.logprob_threshold - 1.0, -0.5],
reward=1.0,
)
apply_filters([gibberish_filter], [rollout])
assert rollout["trajectory"][0]["tokens"]["completion_ids"] == [10, 120_000, 30]
assert rollout["trajectory"][0]["tokens"]["completion_logprobs"] == [
-1.0,
gibberish_filter.logprob_threshold - 1.0,
-0.5,
]
assert rollout["trajectory"][0]["tokens"]["completion_mask"] == [1, 1, 1]
assert rollout["is_filtered"] is True
def test_apply_filters_preserves_existing_stop_condition():
gibberish_filter = _make_gibberish_filter(enforce=True)
rollout = _make_rollout(
completion_ids=[120_000],
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0],
reward=1.0,
)
rollout["stop_condition"] = "generation_truncated"
apply_filters([gibberish_filter], [rollout])
assert rollout["stop_condition"] == "generation_truncated"
assert rollout["is_filtered"] is True
# --- apply_filters tests (monitor-only, enforce=False) ---
@@ -318,16 +349,13 @@ def test_apply_filters_monitor_only_tracks_detection():
reward=1.0,
)
metrics = apply_filters([gibberish_filter], [rollout])
apply_filters([gibberish_filter], [rollout])
assert rollout["reward"] == 1.0
assert all(m == 1 for m in rollout["trajectory"][0]["tokens"]["completion_mask"])
assert rollout["stop_condition"] is None
assert rollout["metrics"]["filter/gibberish"] == 1.0
assert metrics["filter/gibberish_count"] == 1.0
assert metrics["filter/gibberish_rate"] == 1.0
assert metrics["filter/total_detected_rate"] == 1.0
assert metrics["filter/total_enforced_rate"] == 0.0
assert rollout["filters"] == {"gibberish": True}
assert rollout["is_filtered"] is False
def test_apply_filters_monitor_only_mixed_batch():
@@ -338,10 +366,9 @@ def test_apply_filters_monitor_only_mixed_batch():
completion_ids=[120_000], completion_logprobs=[gibberish_filter.logprob_threshold - 1.0], reward=1.0
)
metrics = apply_filters([gibberish_filter], [clean, dirty])
apply_filters([gibberish_filter], [clean, dirty])
assert clean["reward"] == 1.0
assert dirty["reward"] == 1.0
assert metrics["filter/gibberish_rate"] == 0.5
assert metrics["filter/total_detected_rate"] == 0.5
assert metrics["filter/total_enforced_rate"] == 0.0
assert clean["is_filtered"] is False
assert dirty["is_filtered"] is False
@@ -29,7 +29,6 @@ def make_scheduler() -> Scheduler:
scheduler.inflight_policy_update_task = None
scheduler.update_policy_task = None
scheduler.enable_policy_updates = True
scheduler.use_prefix_cache_salt = False
return scheduler
Generated
+4
View File
@@ -2683,6 +2683,8 @@ all = [
{ name = "deep-ep", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "deep-gemm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "flash-attn", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "flash-attn-3", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "flash-attn-4", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nixl", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "nixl-cu12", version = "0.10.1", source = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "quack-kernels", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -2774,6 +2776,8 @@ requires-dist = [
{ name = "prime", specifier = ">=0.5.63" },
{ name = "prime-rl", extras = ["disagg"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["flash-attn"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["flash-attn-3"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["flash-attn-cute"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
{ name = "pyarrow", specifier = ">=21.0.0" },
{ name = "pydantic", specifier = ">=1.10.13" },