Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc55a1c85a | ||
|
|
6f9c1362a1 | ||
|
|
46d210bf6e | ||
|
|
1e365924ac | ||
|
|
decced2093 |
@@ -58,5 +58,6 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`optim.mu`**: Added Muon momentum (`mu`) config field (default: 0.95). Previously hardcoded to Muon class default. Also fixed `optim.betas1`/`optim.betas2` not being passed through to the Muon optimizer (2026-02-09)
|
||||
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12)
|
||||
- **`client.api_key_var`**: Changed default from "OPENAI_API_KEY" to "VLLM_API_KEY" (2026-02-12)
|
||||
- **`orchestrator.filters`**: Added orchestrator-side rollout filters for detecting degenerate generations. Supports `[[filters]] type = "gibberish"` (rare tokens at high entropy) and `[[filters]] type = "repetition"` (high-confidence token streaks). Detected rollouts get reward zeroed and completion mask cleared (2026-02-13)
|
||||
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Based on configs/multimodal/rl_color_codeword.toml but tuned for CI
|
||||
inference_gpu_ids = [0,1,2,3]
|
||||
trainer_gpu_ids = [4,5,6,7]
|
||||
|
||||
max_steps = 25
|
||||
seq_len = 4096
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 64
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
|
||||
[orchestrator.val]
|
||||
interval = 5
|
||||
num_examples = 100
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
+4
-1
@@ -45,6 +45,9 @@ inference = "prime_rl.inference.server:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
sft = "prime_rl.trainer.sft.train:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
|
||||
[project.optional-dependencies]
|
||||
flash-attn = [
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl",
|
||||
@@ -80,7 +83,7 @@ override-dependencies = [
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cu128" }
|
||||
math-env = { index = "primeintellect" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "ad77074" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "013d4da" }
|
||||
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
def transformers_v5_compat():
|
||||
"""vLLM general plugin: patch transformers v5 config attrs that vLLM 0.16 still expects.
|
||||
|
||||
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
|
||||
in every vLLM process, including spawned workers.
|
||||
"""
|
||||
from transformers import Qwen3VLMoeTextConfig
|
||||
|
||||
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
|
||||
Qwen3VLMoeTextConfig.tie_word_embeddings = False
|
||||
|
||||
|
||||
# Monkeypatch PrometheusStatLogger to avoid NotImplementedError for LoRA in DP mode
|
||||
def monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode():
|
||||
from vllm.v1.metrics import loggers as vllm_metrics_loggers
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import AliasChoices, BaseModel, Discriminator, Field, Tag, model_validator
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Discriminator, Field, Tag, model_validator
|
||||
|
||||
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfigType
|
||||
from prime_rl.utils.config import (
|
||||
@@ -579,6 +579,62 @@ AdvantageConfigType: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class GibberishFilterConfig(BaseModel):
|
||||
"""Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387)."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["gibberish"] = "gibberish"
|
||||
enforce: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
|
||||
),
|
||||
] = False
|
||||
token_id_threshold: Annotated[
|
||||
int,
|
||||
Field(description="Token IDs above this are candidates for gibberish. BPE tokens are sorted by merge order."),
|
||||
] = 100_000
|
||||
logprob_offset: Annotated[
|
||||
float,
|
||||
Field(description="Offset from uniform distribution logprob. Threshold = -log(vocab_size) - logprob_offset."),
|
||||
] = 2.0
|
||||
|
||||
|
||||
class RepetitionFilterConfig(BaseModel):
|
||||
"""Flags rollouts where the model gets stuck in a repetition loop, emitting high-confidence tokens
|
||||
for an extended stretch. A rollout is flagged when `window` consecutive tokens are each sampled
|
||||
with probability above `prob_threshold`. (Section 3.2, https://arxiv.org/abs/2506.13585)"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["repetition"] = "repetition"
|
||||
enforce: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
|
||||
),
|
||||
] = False
|
||||
window: Annotated[
|
||||
int,
|
||||
Field(ge=1, description="Number of consecutive high-probability steps before flagging."),
|
||||
] = 3_000
|
||||
prob_threshold: Annotated[
|
||||
float,
|
||||
Field(
|
||||
gt=0,
|
||||
le=1,
|
||||
description="Tokens sampled with probability above this are considered repetitive. Consecutive such tokens count toward the window.",
|
||||
),
|
||||
] = 0.99
|
||||
|
||||
|
||||
FilterConfigType: TypeAlias = Annotated[
|
||||
GibberishFilterConfig | RepetitionFilterConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseModel):
|
||||
"""Configures the filesystem weight broadcast."""
|
||||
|
||||
@@ -649,6 +705,9 @@ class OrchestratorConfig(BaseSettings):
|
||||
# The advantage configuration
|
||||
advantage: AdvantageConfigType | None = AdvantageConfig()
|
||||
|
||||
# Rollout filters (monitor by default, enforce optionally)
|
||||
filters: list[FilterConfigType] = [GibberishFilterConfig(), RepetitionFilterConfig()]
|
||||
|
||||
# The logging configuration
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
@@ -772,6 +831,13 @@ class OrchestratorConfig(BaseSettings):
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_filter_types(self):
|
||||
types = [f.type for f in self.filters]
|
||||
if len(types) != len(set(types)):
|
||||
raise ValueError(f"Duplicate filter types: {types}. Each filter type may only appear once.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_max_concurrent(self):
|
||||
if self.max_concurrent is not None and self.max_concurrent < self.rollouts_per_example:
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import asyncio
|
||||
|
||||
from verifiers.workers import ZMQEnvServer
|
||||
|
||||
from prime_rl.orchestrator.env_server.config import EnvServerConfig
|
||||
@@ -19,15 +21,18 @@ def run_server(config: EnvServerConfig):
|
||||
|
||||
env_name = config.env.name or config.env.id
|
||||
log_file = (get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix()
|
||||
ZMQEnvServer.run_server(
|
||||
|
||||
server = ZMQEnvServer(
|
||||
env_id=strip_env_version(config.env.id),
|
||||
env_args=config.env.args,
|
||||
extra_env_kwargs=config.env.extra_env_kwargs,
|
||||
log_level=config.log.level,
|
||||
log_file_level=config.log.vf_level,
|
||||
log_file=log_file,
|
||||
json_logging=config.log.json_logging,
|
||||
**{"address": config.env.address} if config.env.address is not None else {},
|
||||
)
|
||||
asyncio.run(server.run())
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Orchestrator-side rollout filters for detecting degenerate generations.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
import verifiers as vf
|
||||
from loguru import logger
|
||||
|
||||
from prime_rl.orchestrator.config import FilterConfigType
|
||||
|
||||
|
||||
@dataclass
|
||||
class FilterResult:
|
||||
detected: bool
|
||||
detection_index: int | None = None
|
||||
|
||||
|
||||
class RolloutFilter(Protocol):
|
||||
name: str
|
||||
enforce: bool
|
||||
|
||||
def check(self, rollout: vf.RolloutOutput) -> FilterResult: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
class GibberishFilter:
|
||||
"""Flags rollouts containing rare tokens generated at high entropy.
|
||||
|
||||
A token is flagged when both:
|
||||
- id(token) > token_id_threshold (rare BPE token)
|
||||
- logprob(token) < -log(vocab_size) - logprob_offset (high entropy)
|
||||
|
||||
References:
|
||||
Section 5.2, https://arxiv.org/abs/2510.02387
|
||||
"""
|
||||
|
||||
name: str
|
||||
token_id_threshold: int
|
||||
logprob_threshold: float
|
||||
enforce: bool = False
|
||||
|
||||
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
|
||||
global_idx = 0
|
||||
for step in rollout["trajectory"]:
|
||||
tokens = step["tokens"]
|
||||
if tokens is None:
|
||||
continue
|
||||
for token_id, logprob in zip(tokens["completion_ids"], tokens["completion_logprobs"]):
|
||||
if token_id > self.token_id_threshold and logprob < self.logprob_threshold:
|
||||
return FilterResult(detected=True, detection_index=global_idx)
|
||||
global_idx += 1
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RepetitionFilter:
|
||||
"""Flags rollouts with pathological repetition loops.
|
||||
|
||||
Counts consecutive tokens where logprob > log(prob_threshold), indicating
|
||||
the model is generating with very high confidence. When the streak reaches
|
||||
the window size, the rollout is flagged.
|
||||
|
||||
References:
|
||||
Section 3.2, https://arxiv.org/abs/2506.13585
|
||||
"""
|
||||
|
||||
name: str
|
||||
window: int
|
||||
logprob_threshold: float
|
||||
enforce: bool = False
|
||||
|
||||
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
|
||||
consecutive = 0
|
||||
global_idx = 0
|
||||
for step in rollout["trajectory"]:
|
||||
tokens = step["tokens"]
|
||||
if tokens is None:
|
||||
continue
|
||||
for logprob in tokens["completion_logprobs"]:
|
||||
if logprob > self.logprob_threshold:
|
||||
consecutive += 1
|
||||
else:
|
||||
consecutive = 0
|
||||
if consecutive >= self.window:
|
||||
return FilterResult(detected=True, detection_index=global_idx)
|
||||
global_idx += 1
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
def setup_filter(config: FilterConfigType, vocab_size: int) -> RolloutFilter:
|
||||
"""Create a RolloutFilter from a filter config."""
|
||||
if config.type == "gibberish":
|
||||
return GibberishFilter(
|
||||
name="gibberish",
|
||||
token_id_threshold=config.token_id_threshold,
|
||||
logprob_threshold=-math.log(vocab_size) - config.logprob_offset,
|
||||
enforce=config.enforce,
|
||||
)
|
||||
elif config.type == "repetition":
|
||||
return RepetitionFilter(
|
||||
name="repetition",
|
||||
window=config.window,
|
||||
logprob_threshold=math.log(config.prob_threshold),
|
||||
enforce=config.enforce,
|
||||
)
|
||||
raise ValueError(f"Unknown filter type: {config.type}")
|
||||
|
||||
|
||||
def setup_filters(configs: list[FilterConfigType], vocab_size: int) -> list[RolloutFilter]:
|
||||
"""Create RolloutFilters from a list of filter configs."""
|
||||
return [setup_filter(config, vocab_size) for config in configs]
|
||||
|
||||
|
||||
def apply_filters(
|
||||
filters: list[RolloutFilter],
|
||||
rollouts: list[vf.RolloutOutput],
|
||||
) -> dict[str, float]:
|
||||
"""Apply filters to rollouts. Detection metrics are always tracked.
|
||||
|
||||
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.
|
||||
"""
|
||||
if not filters:
|
||||
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
|
||||
|
||||
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
|
||||
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 ""
|
||||
logger.info(
|
||||
f"Detected {total_detected}/{n} rollouts "
|
||||
f"({', '.join(f'{name}={c}' for name, c in counts.items() if c > 0)})" + enforced_msg
|
||||
)
|
||||
|
||||
return metrics
|
||||
@@ -30,6 +30,7 @@ from prime_rl.orchestrator.buffer import Buffer
|
||||
from prime_rl.orchestrator.ckpt import Progress, setup_ckpt_manager
|
||||
from prime_rl.orchestrator.config import BufferConfig, OrchestratorConfig
|
||||
from prime_rl.orchestrator.eval_utils import evaluate_env
|
||||
from prime_rl.orchestrator.filters import apply_filters, setup_filters
|
||||
from prime_rl.orchestrator.scheduler import Scheduler
|
||||
from prime_rl.orchestrator.utils import (
|
||||
compute_teacher_logprobs,
|
||||
@@ -42,6 +43,7 @@ from prime_rl.orchestrator.vf_utils import (
|
||||
generate,
|
||||
get_completion_len,
|
||||
get_seq_len,
|
||||
intercept_vf_logging,
|
||||
setup_env_client,
|
||||
spawn_env_server,
|
||||
wait_for_env_servers,
|
||||
@@ -58,7 +60,6 @@ from prime_rl.utils.pydantic_config import parse_argv
|
||||
from prime_rl.utils.temp_scheduling import compute_temperature
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
count_chinese_chars,
|
||||
get_env_ids_to_install,
|
||||
install_env,
|
||||
resolve_latest_ckpt_step,
|
||||
@@ -76,7 +77,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_file=config.output_dir / "logs" / "orchestrator.log" if config.log.file else None,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
vf.setup_logging(level="CRITICAL")
|
||||
intercept_vf_logging(logger="verifiers.workers", level=config.log.vf_level) # show logs from env clients
|
||||
logger.info("Starting orchestrator")
|
||||
|
||||
event_loop_lag_monitor = EventLoopLagMonitor()
|
||||
@@ -130,6 +131,11 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
config.model.name, trust_remote_code=config.model.trust_remote_code, use_fast=True
|
||||
)
|
||||
|
||||
# Build rollout filters
|
||||
rollout_filters = setup_filters(config.filters, vocab_size=tokenizer.vocab_size)
|
||||
if rollout_filters:
|
||||
logger.info(f"Initialized {len(rollout_filters)} rollout filter(s): {[f.name for f in rollout_filters]}")
|
||||
|
||||
# Setup monitor
|
||||
logger.info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
|
||||
monitor = setup_monitor(
|
||||
@@ -151,14 +157,15 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
f"Loading {len(config.env)} training environment(s) ({', '.join(env.name or env.id for env in config.env)})"
|
||||
)
|
||||
env_ids = [strip_env_version(env.id) for env in config.env]
|
||||
train_env_names = [env.name or env_id for env_id, env in zip(env_ids, config.env)]
|
||||
train_env_group = vf.EnvGroup(
|
||||
envs=[vf.load_environment(env_id, **env.args) for env_id, env in zip(env_ids, config.env)],
|
||||
env_names=[env.name or env_id for env_id, env in zip(env_ids, config.env)],
|
||||
env_names=train_env_names,
|
||||
map_kwargs=dict(writer_batch_size=1), # set defensively to not error on map operations on large datasets
|
||||
)
|
||||
|
||||
train_env_addresses = []
|
||||
for env_id, env, env_name in zip(env_ids, config.env, train_env_group.env_names):
|
||||
for env_id, env, env_name in zip(env_ids, config.env, train_env_names):
|
||||
if env.address is None:
|
||||
address = spawn_env_server(
|
||||
env_id=env_id,
|
||||
@@ -167,12 +174,15 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_level="CRITICAL",
|
||||
log_file=(get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix(),
|
||||
log_file_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
else:
|
||||
address = env.address
|
||||
logger.info(f"Connecting train environment {env_name} to server at {address}")
|
||||
train_env_addresses.append(address)
|
||||
train_env_clients = [setup_env_client(address) for address in train_env_addresses]
|
||||
train_env_clients = [
|
||||
setup_env_client(address=address, name=name) for name, address in zip(train_env_names, train_env_addresses)
|
||||
]
|
||||
|
||||
logger.info("Waiting for train environment servers to be ready")
|
||||
await wait_for_env_servers(train_env_clients)
|
||||
@@ -199,13 +209,16 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_level="CRITICAL",
|
||||
log_file=(get_log_dir(config.output_dir) / "eval" / f"{eval_env_name}.log").as_posix(),
|
||||
log_file_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
else:
|
||||
address = env.address
|
||||
logger.info(f"Connecting eval environment {eval_env_name} to server at {address}")
|
||||
eval_env_addresses.append(address)
|
||||
|
||||
eval_env_clients = [setup_env_client(address) for address in eval_env_addresses]
|
||||
eval_env_clients = [
|
||||
setup_env_client(address=address, name=name) for name, address in zip(eval_env_names, eval_env_addresses)
|
||||
]
|
||||
|
||||
logger.info("Waiting for eval environment servers to be ready")
|
||||
await wait_for_env_servers(eval_env_clients)
|
||||
@@ -440,6 +453,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
generate_completions_time = scheduler.last_batch_generation_time
|
||||
train_rollouts = train_task.result()
|
||||
|
||||
# Apply rollout filters (zeros reward/mask for degenerate generations)
|
||||
filter_metrics = apply_filters(rollout_filters, train_rollouts)
|
||||
|
||||
# Compute advantages
|
||||
example_ids = [r["example_id"] for r in train_rollouts]
|
||||
rewards = [r["reward"] for r in train_rollouts]
|
||||
@@ -569,21 +585,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Gather individual reward function metrics
|
||||
metrics_df = pd.DataFrame([rollout["metrics"] for rollout in train_rollouts])
|
||||
|
||||
# Count Chinese characters in completions
|
||||
chinese_stats = []
|
||||
for rollout in train_rollouts:
|
||||
trajectory = rollout["trajectory"]
|
||||
if not trajectory:
|
||||
continue
|
||||
last_step = trajectory[-1]
|
||||
tokens = last_step["tokens"]
|
||||
completion_text = tokenizer.decode(tokens["completion_ids"])
|
||||
chinese_count, total_count = count_chinese_chars(completion_text)
|
||||
chinese_stats.append(
|
||||
{"chinese_chars": chinese_count, "total_chars": total_count, "has_chinese": chinese_count > 0}
|
||||
)
|
||||
chinese_df = pd.DataFrame(chinese_stats)
|
||||
|
||||
val_results_df = (
|
||||
pd.DataFrame(
|
||||
{
|
||||
@@ -668,14 +669,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
},
|
||||
# Env metrics
|
||||
**{f"metrics/{metric}": metrics_df[metric].mean() for metric in metrics_df.columns},
|
||||
# Chinese character metrics (cast to native Python types for JSON serialization)
|
||||
"chinese/char_count": int(chinese_df.chinese_chars.sum()),
|
||||
"chinese/char_ratio": (
|
||||
float(chinese_df.chinese_chars.sum() / chinese_df.total_chars.sum())
|
||||
if chinese_df.total_chars.sum() > 0
|
||||
else 0.0
|
||||
),
|
||||
"chinese/rollout_ratio": float(chinese_df.has_chinese.mean()),
|
||||
# Time metrics
|
||||
"time/step": step_time,
|
||||
"time/generate_completions": generate_completions_time,
|
||||
@@ -688,6 +681,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
**buffer.get_metrics(),
|
||||
# Event loop lag metrics
|
||||
**event_loop_lag_monitor.get_metrics(),
|
||||
# Rollout filter metrics
|
||||
**filter_metrics,
|
||||
# W&B axis
|
||||
"step": progress.step,
|
||||
}
|
||||
|
||||
@@ -7,10 +7,10 @@ from typing import Any
|
||||
|
||||
import verifiers as vf
|
||||
from verifiers.envs.environment import EnvClient
|
||||
from verifiers.utils.worker_utils import get_free_port
|
||||
from verifiers.utils.worker_utils import get_free_port_pair
|
||||
from verifiers.workers import ZMQEnvClient, ZMQEnvServer
|
||||
|
||||
from prime_rl.utils.logger import InterceptHandler, ProgressTracker, get_logger
|
||||
from prime_rl.utils.logger import InterceptHandler, ProgressTracker
|
||||
|
||||
DEFAULT_RETRIES = 0
|
||||
REQUIRED_STATE_COLUMNS = ["trajectory", "sampling_args"]
|
||||
@@ -22,9 +22,11 @@ def spawn_env_server(
|
||||
env_args: dict[str, Any],
|
||||
extra_env_kwargs: dict[str, Any],
|
||||
address: str | None = None,
|
||||
# logging configs
|
||||
log_level: str | None = None,
|
||||
log_file: str | None = None,
|
||||
log_file_level: str | None = None,
|
||||
json_logging: bool = False,
|
||||
daemon: bool = True,
|
||||
) -> str:
|
||||
"""
|
||||
@@ -32,7 +34,7 @@ def spawn_env_server(
|
||||
|
||||
Mirrors vf.Environment.start_server().
|
||||
"""
|
||||
address = address or f"tcp://127.0.0.1:{get_free_port()}"
|
||||
address = address or f"tcp://127.0.0.1:{get_free_port_pair()}"
|
||||
# Use spawn to avoid inheriting file descriptors (e.g. sockets) from
|
||||
# the parent process, which has caused hangs when multiple env server
|
||||
# subprocesses share the same fds.
|
||||
@@ -46,43 +48,33 @@ def spawn_env_server(
|
||||
log_file,
|
||||
log_file_level,
|
||||
),
|
||||
kwargs=dict(address=address),
|
||||
kwargs=dict(address=address, json_logging=json_logging),
|
||||
daemon=daemon,
|
||||
).start()
|
||||
|
||||
return address
|
||||
|
||||
|
||||
def setup_env_client(address: str) -> EnvClient:
|
||||
def setup_env_client(
|
||||
address: str,
|
||||
name: str | None = None,
|
||||
# health check configs
|
||||
health_check_interval: float = 1.0, # 1s
|
||||
startup_timeout: float = 600.0, # 10m
|
||||
recovery_timeout: float = 600.0, # 10m
|
||||
) -> EnvClient:
|
||||
"""Sets up a ZMQEnvClient for a given address."""
|
||||
return ZMQEnvClient(address=address)
|
||||
return ZMQEnvClient(
|
||||
address=address,
|
||||
name=name,
|
||||
health_check_interval=health_check_interval,
|
||||
startup_timeout=startup_timeout,
|
||||
recovery_timeout=recovery_timeout,
|
||||
)
|
||||
|
||||
|
||||
async def wait_for_env_servers(
|
||||
env_clients: list[EnvClient], interval: int = 1, log_interval: int = 10, timeout: int = 1800
|
||||
) -> None:
|
||||
logger = get_logger()
|
||||
|
||||
async def wait_for_env_server(env_client: EnvClient) -> None:
|
||||
wait_time = 0
|
||||
logger.debug(f"Starting pinging environment server at {env_client.address}")
|
||||
while wait_time < timeout:
|
||||
try:
|
||||
await env_client.health(timeout=1) # quick timeout
|
||||
logger.debug(f"Environment server at {env_client.address} is ready after {wait_time} seconds")
|
||||
return
|
||||
except Exception as e:
|
||||
if wait_time % log_interval == 0 and wait_time > 0:
|
||||
logger.warning(
|
||||
f"Environment server at {env_client.address} was not reached after {wait_time} seconds (Error: {e})"
|
||||
)
|
||||
await asyncio.sleep(interval)
|
||||
wait_time += interval
|
||||
msg = f"Environment server at {env_client.address} is not ready after {wait_time} (>{timeout}) seconds. Aborting..."
|
||||
logger.error(msg)
|
||||
raise TimeoutError(msg)
|
||||
|
||||
await asyncio.gather(*[wait_for_env_server(env_client) for env_client in env_clients])
|
||||
async def wait_for_env_servers(env_clients: list[EnvClient]) -> None:
|
||||
await asyncio.gather(*[env_client.wait_for_server_startup() for env_client in env_clients])
|
||||
|
||||
|
||||
async def run_group(
|
||||
@@ -249,9 +241,9 @@ def get_completion_len(output: vf.RolloutOutput) -> int:
|
||||
return get_seq_len(output) - get_prompt_len(output)
|
||||
|
||||
|
||||
def intercept_vf_logging(level: str = "DEBUG", prefix: str = "verifiers"):
|
||||
"""Intercepts verifiers logging and routes through prime-rl logger with [verifiers] prefix."""
|
||||
vf_logger = logging.getLogger("verifiers")
|
||||
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
|
||||
"""Intercepts verifiers logging and routes through prime-rl logger with optional prefix."""
|
||||
vf_logger = logging.getLogger(logger)
|
||||
vf_logger.handlers.clear()
|
||||
vf_logger.addHandler(InterceptHandler(prefix=prefix))
|
||||
vf_logger.setLevel(level.upper())
|
||||
|
||||
@@ -17,7 +17,7 @@ from torch.distributed.device_mesh import DeviceMesh
|
||||
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
from torch.distributed.tensor.parallel import parallelize_module
|
||||
from torchtitan.distributed.expert_parallel import ExpertParallel
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, PretrainedConfig
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, PretrainedConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from transformers.utils.import_utils import is_flash_attn_3_available
|
||||
|
||||
@@ -147,9 +147,20 @@ def get_model(
|
||||
model_config.use_cache = False
|
||||
model_config.use_grouped_mm = config.moe_use_grouped_mm
|
||||
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it)
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
|
||||
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
|
||||
if not hasattr(model_config, "pad_token_id") or model_config.pad_token_id is None:
|
||||
model_config.pad_token_id = model_config.eos_token_id
|
||||
gen_config = GenerationConfig.from_model_config(model_config)
|
||||
# Use `is not None` instead of truthiness: token ID 0 is valid.
|
||||
pad_token_id = next(
|
||||
(
|
||||
v
|
||||
for v in [gen_config.pad_token_id, gen_config.eos_token_id, getattr(model_config, "eos_token_id", None)]
|
||||
if v is not None
|
||||
),
|
||||
None,
|
||||
)
|
||||
model_config.pad_token_id = pad_token_id
|
||||
|
||||
# NOTE: For VLM models, we do NOT propagate dtype to sub_configs.
|
||||
# The model should load in its default dtype (bf16) to match vLLM inference.
|
||||
@@ -180,11 +191,10 @@ def get_model(
|
||||
)
|
||||
|
||||
with device:
|
||||
# For VLM models, use AutoModelForVision2Seq or import specific model class
|
||||
if is_vlm:
|
||||
from transformers import AutoModelForVision2Seq
|
||||
from transformers import AutoModelForImageTextToText
|
||||
|
||||
model_cls = AutoModelForVision2Seq
|
||||
model_cls = AutoModelForImageTextToText
|
||||
else:
|
||||
match impl_to_use:
|
||||
case "hf":
|
||||
|
||||
@@ -118,7 +118,7 @@ class LogConfig(BaseConfig):
|
||||
vf_level: Annotated[
|
||||
str,
|
||||
Field(description="Logging level for the verifiers package. Will determine the logging verbosity and format."),
|
||||
] = "warn"
|
||||
] = "info"
|
||||
|
||||
file: Annotated[
|
||||
bool,
|
||||
|
||||
@@ -82,7 +82,7 @@ class JsonFileSink:
|
||||
class InterceptHandler(logging.Handler):
|
||||
"""Intercept standard logging library and routes to our prime-rl logger with specified prefix."""
|
||||
|
||||
def __init__(self, prefix: str):
|
||||
def __init__(self, prefix: str | None):
|
||||
super().__init__()
|
||||
self.prefix = prefix
|
||||
|
||||
@@ -98,7 +98,10 @@ class InterceptHandler(logging.Handler):
|
||||
frame = frame.f_back
|
||||
depth += 1
|
||||
|
||||
logger.opt(depth=depth, exception=record.exc_info).log(level, f"[{self.prefix}] {record.getMessage()}")
|
||||
message = record.getMessage()
|
||||
if self.prefix is not None:
|
||||
message = f"[{self.prefix}] {message}"
|
||||
logger.opt(depth=depth, exception=record.exc_info).log(level, message)
|
||||
|
||||
|
||||
def setup_logger(
|
||||
|
||||
@@ -319,28 +319,3 @@ def get_env_ids_to_install(env_configs: list[EnvConfig] | list[EvalEnvConfig]) -
|
||||
if "/" in env_config.id:
|
||||
env_ids_to_install.add(env_config.id)
|
||||
return env_ids_to_install
|
||||
|
||||
|
||||
def is_chinese_char(char: str) -> bool:
|
||||
"""Check if a character is Chinese (CJK Unified Ideographs and extensions)."""
|
||||
code_point = ord(char)
|
||||
return (
|
||||
0x4E00 <= code_point <= 0x9FFF # CJK Unified Ideographs
|
||||
or 0x3400 <= code_point <= 0x4DBF # CJK Extension A
|
||||
or 0x20000 <= code_point <= 0x2A6DF # CJK Extension B
|
||||
or 0x2A700 <= code_point <= 0x2B73F # CJK Extension C
|
||||
or 0x2B740 <= code_point <= 0x2B81F # CJK Extension D
|
||||
or 0x2B820 <= code_point <= 0x2CEAF # CJK Extension E
|
||||
or 0xF900 <= code_point <= 0xFAFF # CJK Compatibility Ideographs
|
||||
or 0x2F800 <= code_point <= 0x2FA1F # CJK Compatibility Ideographs Supplement
|
||||
)
|
||||
|
||||
|
||||
def count_chinese_chars(text: str) -> tuple[int, int]:
|
||||
"""Count Chinese characters in text.
|
||||
|
||||
Returns:
|
||||
Tuple of (chinese_char_count, total_char_count)
|
||||
"""
|
||||
chinese_count = sum(1 for char in text if is_chinese_char(char))
|
||||
return chinese_count, len(text)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_avg_reward_in_range, check_no_error, check_number_goes_up_or_down, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
REWARD_MIN_THRESHOLD = 0.85
|
||||
REWARD_AVG_LAST_N_STEPS = 7
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"multimodal-color-codeword-{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/nightly/multimodal_color_codeword.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
check_reward_goes_up = partial(check_number_goes_up_or_down, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
|
||||
def test_reward_reaches_threshold(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the average reward over the last steps exceeds the threshold"""
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_avg_reward_in_range(
|
||||
orchestrator_stdout, last_n_steps=REWARD_AVG_LAST_N_STEPS, min_threshold=REWARD_MIN_THRESHOLD
|
||||
)
|
||||
@@ -0,0 +1,347 @@
|
||||
import math
|
||||
|
||||
from prime_rl.orchestrator.config import GibberishFilterConfig, RepetitionFilterConfig
|
||||
from prime_rl.orchestrator.filters import (
|
||||
GibberishFilter,
|
||||
RepetitionFilter,
|
||||
apply_filters,
|
||||
setup_filter,
|
||||
setup_filters,
|
||||
)
|
||||
|
||||
|
||||
def _make_rollout(completion_ids, completion_logprobs, reward=1.0, multi_step=False):
|
||||
"""Create a minimal rollout dict matching the verifiers RolloutOutput structure."""
|
||||
if multi_step:
|
||||
mid = len(completion_ids) // 2
|
||||
trajectory = [
|
||||
{
|
||||
"tokens": {
|
||||
"completion_ids": completion_ids[:mid],
|
||||
"completion_logprobs": completion_logprobs[:mid],
|
||||
"completion_mask": [1] * mid,
|
||||
}
|
||||
},
|
||||
{
|
||||
"tokens": {
|
||||
"completion_ids": completion_ids[mid:],
|
||||
"completion_logprobs": completion_logprobs[mid:],
|
||||
"completion_mask": [1] * (len(completion_ids) - mid),
|
||||
}
|
||||
},
|
||||
]
|
||||
else:
|
||||
trajectory = [
|
||||
{
|
||||
"tokens": {
|
||||
"completion_ids": completion_ids,
|
||||
"completion_logprobs": completion_logprobs,
|
||||
"completion_mask": [1] * len(completion_ids),
|
||||
}
|
||||
}
|
||||
]
|
||||
return {
|
||||
"trajectory": trajectory,
|
||||
"reward": reward,
|
||||
"stop_condition": None,
|
||||
"metrics": {},
|
||||
}
|
||||
|
||||
|
||||
def _make_gibberish_filter(vocab_size=128_000, token_id_threshold=100_000, logprob_offset=2.0, enforce=False):
|
||||
logprob_threshold = -math.log(vocab_size) - logprob_offset
|
||||
return GibberishFilter(
|
||||
name="gibberish", token_id_threshold=token_id_threshold, logprob_threshold=logprob_threshold, enforce=enforce
|
||||
)
|
||||
|
||||
|
||||
def _make_repetition_filter(window=5, prob_threshold=0.99, enforce=False):
|
||||
return RepetitionFilter(
|
||||
name="repetition", window=window, logprob_threshold=math.log(prob_threshold), enforce=enforce
|
||||
)
|
||||
|
||||
|
||||
# --- GibberishFilter tests ---
|
||||
|
||||
|
||||
def test_gibberish_detects_rare_low_prob_token():
|
||||
gibberish_filter = _make_gibberish_filter()
|
||||
|
||||
result = gibberish_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=[50, 120_000, 80],
|
||||
completion_logprobs=[-1.0, gibberish_filter.logprob_threshold - 1.0, -0.5],
|
||||
)
|
||||
)
|
||||
assert result.detected is True
|
||||
assert result.detection_index == 1
|
||||
|
||||
|
||||
def test_gibberish_ignores_normal_tokens():
|
||||
gibberish_filter = _make_gibberish_filter()
|
||||
|
||||
result = gibberish_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=[10, 200, 5000],
|
||||
completion_logprobs=[-1.0, -2.0, -3.0],
|
||||
)
|
||||
)
|
||||
assert result.detected is False
|
||||
assert result.detection_index is None
|
||||
|
||||
|
||||
def test_gibberish_ignores_high_prob_rare_token():
|
||||
gibberish_filter = _make_gibberish_filter()
|
||||
|
||||
result = gibberish_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=[120_000],
|
||||
completion_logprobs=[-0.5],
|
||||
)
|
||||
)
|
||||
assert result.detected is False
|
||||
|
||||
|
||||
def test_gibberish_works_across_trajectory_steps():
|
||||
gibberish_filter = _make_gibberish_filter()
|
||||
|
||||
result = gibberish_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=[50, 60, 120_000, 80],
|
||||
completion_logprobs=[-1.0, -0.5, gibberish_filter.logprob_threshold - 1.0, -0.5],
|
||||
multi_step=True,
|
||||
)
|
||||
)
|
||||
assert result.detected is True
|
||||
assert result.detection_index == 2
|
||||
|
||||
|
||||
# --- RepetitionFilter tests ---
|
||||
|
||||
|
||||
def test_repetition_triggers_after_window():
|
||||
repetition_filter = _make_repetition_filter(window=5)
|
||||
|
||||
result = repetition_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=list(range(5)),
|
||||
completion_logprobs=[-0.001] * 5,
|
||||
)
|
||||
)
|
||||
assert result.detected is True
|
||||
assert result.detection_index == 4
|
||||
|
||||
|
||||
def test_repetition_no_trigger_below_window():
|
||||
repetition_filter = _make_repetition_filter(window=5)
|
||||
|
||||
result = repetition_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=list(range(4)),
|
||||
completion_logprobs=[-0.001] * 4,
|
||||
)
|
||||
)
|
||||
assert result.detected is False
|
||||
|
||||
|
||||
def test_repetition_resets_on_low_prob():
|
||||
repetition_filter = _make_repetition_filter(window=5)
|
||||
|
||||
logprobs = [-0.001] * 3 + [-2.0] + [-0.001] * 3
|
||||
result = repetition_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=list(range(7)),
|
||||
completion_logprobs=logprobs,
|
||||
)
|
||||
)
|
||||
assert result.detected is False
|
||||
|
||||
|
||||
def test_repetition_varied_probs_no_trigger():
|
||||
repetition_filter = _make_repetition_filter(window=3)
|
||||
|
||||
result = repetition_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=list(range(6)),
|
||||
completion_logprobs=[-0.001, -3.0, -0.001, -3.0, -0.001, -3.0],
|
||||
)
|
||||
)
|
||||
assert result.detected is False
|
||||
|
||||
|
||||
# --- setup_filter / setup_filters tests ---
|
||||
|
||||
|
||||
def test_setup_filter_gibberish():
|
||||
config = GibberishFilterConfig(token_id_threshold=100_000, logprob_offset=2.0)
|
||||
gibberish_filter = setup_filter(config, vocab_size=128_000)
|
||||
assert isinstance(gibberish_filter, GibberishFilter)
|
||||
assert gibberish_filter.name == "gibberish"
|
||||
assert gibberish_filter.token_id_threshold == 100_000
|
||||
assert abs(gibberish_filter.logprob_threshold - (-math.log(128_000) - 2.0)) < 1e-10
|
||||
assert gibberish_filter.enforce is False
|
||||
|
||||
|
||||
def test_setup_filter_gibberish_enforce():
|
||||
config = GibberishFilterConfig(enforce=True)
|
||||
gibberish_filter = setup_filter(config, vocab_size=128_000)
|
||||
assert gibberish_filter.enforce is True
|
||||
|
||||
|
||||
def test_setup_filter_repetition():
|
||||
config = RepetitionFilterConfig(window=3_000, prob_threshold=0.99)
|
||||
repetition_filter = setup_filter(config, vocab_size=128_000)
|
||||
assert isinstance(repetition_filter, RepetitionFilter)
|
||||
assert repetition_filter.name == "repetition"
|
||||
assert repetition_filter.window == 3_000
|
||||
assert abs(repetition_filter.logprob_threshold - math.log(0.99)) < 1e-10
|
||||
assert repetition_filter.enforce is False
|
||||
|
||||
|
||||
def test_setup_filter_repetition_enforce():
|
||||
config = RepetitionFilterConfig(enforce=True)
|
||||
repetition_filter = setup_filter(config, vocab_size=128_000)
|
||||
assert repetition_filter.enforce is True
|
||||
|
||||
|
||||
def test_setup_filters_multiple():
|
||||
configs = [
|
||||
GibberishFilterConfig(),
|
||||
RepetitionFilterConfig(),
|
||||
]
|
||||
filters = setup_filters(configs, vocab_size=128_000)
|
||||
assert len(filters) == 2
|
||||
assert filters[0].name == "gibberish"
|
||||
assert filters[1].name == "repetition"
|
||||
|
||||
|
||||
# --- apply_filters tests (enforce=True) ---
|
||||
|
||||
|
||||
def test_apply_filters_enforced_zeros_mask():
|
||||
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,
|
||||
)
|
||||
|
||||
metrics = 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
|
||||
|
||||
|
||||
def test_apply_filters_preserves_clean_rollouts():
|
||||
gibberish_filter = _make_gibberish_filter(enforce=True)
|
||||
|
||||
rollout = _make_rollout(
|
||||
completion_ids=[50, 60, 70],
|
||||
completion_logprobs=[-1.0, -2.0, -1.5],
|
||||
reward=1.0,
|
||||
)
|
||||
|
||||
metrics = 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 metrics["filter/gibberish_count"] == 0.0
|
||||
assert metrics["filter/total_detected_rate"] == 0.0
|
||||
assert metrics["filter/total_enforced_rate"] == 0.0
|
||||
|
||||
|
||||
def test_apply_filters_first_filter_wins():
|
||||
gibberish_filter = _make_gibberish_filter(enforce=True)
|
||||
repetition_filter = _make_repetition_filter(window=2, enforce=True)
|
||||
|
||||
rollout = _make_rollout(
|
||||
completion_ids=[120_000, 1, 2],
|
||||
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0, -0.001, -0.001],
|
||||
reward=1.0,
|
||||
)
|
||||
|
||||
metrics = 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
|
||||
|
||||
|
||||
def test_apply_filters_empty_list():
|
||||
rollout = _make_rollout(
|
||||
completion_ids=[1, 2, 3],
|
||||
completion_logprobs=[-1.0, -1.0, -1.0],
|
||||
)
|
||||
metrics = apply_filters([], [rollout])
|
||||
assert metrics == {}
|
||||
assert rollout["reward"] == 1.0
|
||||
|
||||
|
||||
def test_apply_filters_mixed_batch():
|
||||
gibberish_filter = _make_gibberish_filter(enforce=True)
|
||||
|
||||
clean = _make_rollout(completion_ids=[50], completion_logprobs=[-1.0], reward=1.0)
|
||||
dirty = _make_rollout(
|
||||
completion_ids=[120_000], completion_logprobs=[gibberish_filter.logprob_threshold - 1.0], reward=1.0
|
||||
)
|
||||
|
||||
metrics = 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
|
||||
|
||||
|
||||
# --- apply_filters tests (monitor-only, enforce=False) ---
|
||||
|
||||
|
||||
def test_apply_filters_monitor_only_tracks_detection():
|
||||
gibberish_filter = _make_gibberish_filter(enforce=False)
|
||||
|
||||
rollout = _make_rollout(
|
||||
completion_ids=[120_000],
|
||||
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0],
|
||||
reward=1.0,
|
||||
)
|
||||
|
||||
metrics = 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
|
||||
|
||||
|
||||
def test_apply_filters_monitor_only_mixed_batch():
|
||||
gibberish_filter = _make_gibberish_filter(enforce=False)
|
||||
|
||||
clean = _make_rollout(completion_ids=[50], completion_logprobs=[-1.0], reward=1.0)
|
||||
dirty = _make_rollout(
|
||||
completion_ids=[120_000], completion_logprobs=[gibberish_filter.logprob_threshold - 1.0], reward=1.0
|
||||
)
|
||||
|
||||
metrics = 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
|
||||
@@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
import torch
|
||||
from transformers import AutoConfig, AutoModelForCausalLM
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, GenerationConfig
|
||||
|
||||
from prime_rl.trainer.perf import PerfCounter
|
||||
|
||||
@@ -14,7 +14,16 @@ def test_perf_counter(model_name: str, active_params: int, flops_per_token: int)
|
||||
with torch.device("meta"):
|
||||
config = AutoConfig.from_pretrained(model_name)
|
||||
if getattr(config, "pad_token_id", None) is None:
|
||||
config.pad_token_id = config.eos_token_id
|
||||
gen_config = GenerationConfig.from_model_config(config)
|
||||
# Use `is not None` instead of truthiness: token ID 0 is valid.
|
||||
config.pad_token_id = next(
|
||||
(
|
||||
v
|
||||
for v in [gen_config.pad_token_id, gen_config.eos_token_id, getattr(config, "eos_token_id", None)]
|
||||
if v is not None
|
||||
),
|
||||
None,
|
||||
)
|
||||
model = AutoModelForCausalLM.from_config(config)
|
||||
perf_counter = PerfCounter(model, seq_len=1024, window_size=10)
|
||||
|
||||
|
||||
@@ -116,6 +116,39 @@ def check_reward_in_range(
|
||||
)
|
||||
|
||||
|
||||
def check_avg_reward_in_range(
|
||||
lines: list[str],
|
||||
last_n_steps: int,
|
||||
min_threshold: float | None = None,
|
||||
max_threshold: float | None = None,
|
||||
):
|
||||
"""Helper to assert that the average reward over the last N steps is within a threshold"""
|
||||
pattern = r"Reward:\s*(\d+\.\d{4})"
|
||||
step_lines = [line for line in lines if "SUCCESS" in line and "Step" in line and re.search(pattern, line)]
|
||||
assert len(step_lines) >= last_n_steps, (
|
||||
f"Not enough step lines found. Expected at least {last_n_steps}, got {len(step_lines)}"
|
||||
)
|
||||
|
||||
recent_lines = step_lines[-last_n_steps:]
|
||||
rewards = []
|
||||
for line in recent_lines:
|
||||
match = re.search(pattern, line)
|
||||
assert match is not None, f"Could not find Reward in line: {line}"
|
||||
rewards.append(float(match.group(1)))
|
||||
|
||||
avg_reward = sum(rewards) / len(rewards)
|
||||
if min_threshold is not None:
|
||||
assert avg_reward >= min_threshold, (
|
||||
f"Average reward over last {last_n_steps} steps did not reach minimum threshold. "
|
||||
f"Found avg_reward={avg_reward:.4f} < {min_threshold} (rewards={rewards})"
|
||||
)
|
||||
if max_threshold is not None:
|
||||
assert avg_reward <= max_threshold, (
|
||||
f"Average reward over last {last_n_steps} steps exceeded maximum threshold. "
|
||||
f"Found avg_reward={avg_reward:.4f} > {max_threshold} (rewards={rewards})"
|
||||
)
|
||||
|
||||
|
||||
def check_mismatch_kl_in_range(
|
||||
lines: list[str],
|
||||
step: int = -1,
|
||||
|
||||
@@ -2373,7 +2373,7 @@ requires-dist = [
|
||||
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
|
||||
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=609e3d5" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=ad77074" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=013d4da" },
|
||||
{ name = "vllm", url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" },
|
||||
{ name = "wandb", specifier = ">=0.24.2" },
|
||||
]
|
||||
@@ -3702,7 +3702,7 @@ wheels = [
|
||||
[[package]]
|
||||
name = "verifiers"
|
||||
version = "0.1.11.dev0"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=ad77074#ad77074e6e8585242425aabd598fc102584a0777" }
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=013d4da#013d4da8a906bef2e1cbb6b4bc4347214c1fd534" }
|
||||
dependencies = [
|
||||
{ name = "anthropic" },
|
||||
{ name = "datasets" },
|
||||
|
||||
Reference in New Issue
Block a user