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
f29e947585 Fix Prime monitor public API flow (#2205)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Use bearer auth for Prime monitor uploads

* Fix Prime monitor presign and finalize flow

* Sanitize non-finite Prime monitor payloads

* Simplify Prime monitor payload normalization

* Simplify Prime monitor public API contract

* Simplify public presign response parsing

* Simplify non-finite payload sanitization

* Inline public presign response parsing

* Inline non-finite payload sanitization logic

* Refine Prime monitor JSON sanitization

* Address review: inline auth headers and simplify sanitize

- Remove _api_headers() helper; store self._headers once in __init__
- Always sanitize payloads; drop silent try/except and log only when values are dropped
- Remove prime_cli sys.modules mocking from tests (real dep is installed)

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

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:01:27 -07:00
JupiterandGitHub bb7449c829 Add FA4 (flash_attn.cute) support to ring attention, enabling context (#2307)
Release / Push CUDA image to Docker (push) Canceled after 0s
parallel training with FA4 kernels. Mirrors the FA3 ring attention
pattern (all-gather K/V, compute per GQA stride, reduce-scatter grads)
using FA4 low-level _flash_attn_fwd/_flash_attn_bwd.

Changes:
- ring_attn.py: FA4 forward/backward wrappers, _RingFA4Varlen autograd
  Function, ring_fa4_varlen_func public API
- attn.py: route FA4 to ring_fa4_varlen_func in substitute_ring_attn
- trainer.py: allow CP with fa4 (requires model.impl='custom')
2026-04-17 20:00:52 -07:00
82fa41f4f2 fix: serialize env server spawn to avoid port race (#2310)
Release / Push CUDA image to Docker (push) Canceled after 0s
get_free_port() only holds the port until it returns, so parallel
env spawns under asyncio.gather could hand the same port to two
children — the loser died with EADDRINUSE. Serializing start()
and awaiting wait_for_server_startup() between envs ensures each
port is bound before the next one is picked.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 15:55:37 -07:00
1ade129004 fix: check rollout error before empty trajectory in scheduler (#2308)
Release / Push CUDA image to Docker (push) Canceled after 0s
When `verifiers` CliAgentEnv catches an agent crash pre-LLM-call, it
sets `state["error"]` but the trajectory stays `[]` because the agent
never produced any messages. The previous branch order fired the
"Empty trajectory" warning first and dropped the detailed AgentError
diagnostic. Swap the branches so error-bearing rollouts surface
"Rollout error ...: {error_chain_repr}" instead.

Related: PrimeIntellect-ai/verifiers#1127, #1130

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 22:23:13 +02:00
26ea8df85e chore: bump vllm-router to v0.1.22 (#2292)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 10:52:49 -07:00
Mika SenghaasandGitHub d4bddbaed7 fix: clean stale rollouts and broadcasts on fresh runs (#2304)
Release / Push CUDA image to Docker (push) Canceled after 0s
Previously `clean_future_steps` only ran when resuming from a checkpoint,
so a fresh run started in an output_dir containing stale rollouts or
broadcasts from a previous run would consume them: the trainer would
train on stale data and the orchestrator would compute a negative async
level because it sees a trainer that is seemingly ahead of it.

Run the same cleanup from step 0 when training from scratch so these
artifacts are removed before training begins.
2026-04-17 09:26:34 -07:00
samsjaandGitHub 6bf14b80f8 vf bump (#2302)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-17 08:11:50 -07:00
halleriteandGitHub 586e0f8e5d fix: work around transformers lazy_load_kernel offline regression (#2276)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-17 15:16:27 +02:00
20 changed files with 720 additions and 263 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
+4 -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]
@@ -123,13 +125,13 @@ override-dependencies = [
[tool.uv.sources]
torch = { index = "pytorch-cu128" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "0760204" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "77a9f28" }
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 = "c1c3424" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "abd9943b" }
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.20/vllm_router-0.1.20-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
reverse-text = { index = "primeintellect" }
alphabet-sort = { index = "primeintellect" }
wiki-search = { index = "primeintellect" }
+48 -14
View File
@@ -1,21 +1,55 @@
"""Compatibility shim: ring_flash_attn + transformers >= 5.4.
"""Compatibility shims for upstream regressions.
ring_flash_attn 0.1.8 imports `is_flash_attn_greater_or_equal_2_10` from
`transformers.modeling_flash_attention_utils`. This symbol was removed from
that module in transformers 5.4 (still available as a deprecated function
in `transformers.utils.import_utils`, scheduled for removal in 5.8).
ring_flash_attn's except-branch is a no-op (imports the same symbol again),
so the import crashes on transformers >= 5.4. We patch the symbol back in as
`True` — the check is dead code since no one uses flash_attn < 2.1.0 anymore.
Upstream fix: https://github.com/zhuzilin/ring-flash-attention/pull/85
Remove this shim once ring_flash_attn ships a fixed version.
Imported early (before any model code) by trainer and orchestrator entrypoints.
Each shim documents the upstream issue and removal condition.
"""
# ---------------------------------------------------------------------------
# ring_flash_attn + transformers >= 5.4
#
# ring_flash_attn 0.1.8 imports `is_flash_attn_greater_or_equal_2_10` from
# `transformers.modeling_flash_attention_utils`, removed in transformers 5.4.
#
# Upstream fix: https://github.com/zhuzilin/ring-flash-attention/pull/85
# Remove once ring_flash_attn ships a fixed version.
# ---------------------------------------------------------------------------
import transformers.modeling_flash_attention_utils as _mfau
if not hasattr(_mfau, "is_flash_attn_greater_or_equal_2_10"):
# ring_flash_attn uses this as a bare value (if x:), but other code may
# call it as a function (if x():). Use a callable that is also truthy.
_mfau.is_flash_attn_greater_or_equal_2_10 = lambda: True
# ---------------------------------------------------------------------------
# transformers >= 5.5 hub_kernels offline regression
#
# lazy_load_kernel() resolves kernel versions via HfApi().list_repo_refs(),
# which raises OfflineModeIsEnabled when HF_HUB_OFFLINE=1 — even if the
# kernel is already cached locally. Only FileNotFoundError and AssertionError
# are caught; OfflineModeIsEnabled (a ConnectionError subclass) is not.
#
# This breaks Mamba-based models (NemotronH, Zamba2, Jamba, etc.) on SLURM
# worker nodes where HF_HUB_OFFLINE=1 is set.
#
# Fix: patch the except clause to also catch ConnectionError.
# Remove once huggingface/transformers fixes lazy_load_kernel offline handling.
# ---------------------------------------------------------------------------
try:
import transformers.integrations.hub_kernels as _hub_kernels
except ImportError:
_hub_kernels = None # transformers < 5.5, no patch needed
if _hub_kernels is not None:
from huggingface_hub.errors import OfflineModeIsEnabled
_original_lazy_load_kernel = _hub_kernels.lazy_load_kernel
def _patched_lazy_load_kernel(kernel_name, mapping=_hub_kernels._KERNEL_MODULE_MAPPING):
try:
return _original_lazy_load_kernel(kernel_name, mapping)
except OfflineModeIsEnabled:
# Return None so NemotronH skips hub kernels; prime-rl's
# _patch_mamba2_use_triton_ssd() uses mamba_ssm directly.
mapping[kernel_name] = None
return None
_hub_kernels.lazy_load_kernel = _patched_lazy_load_kernel
-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)."""
+6 -6
View File
@@ -184,7 +184,7 @@ class ModelConfig(BaseModelConfig):
attn: Annotated[
AttnImplementation,
Field(
description="The attention implementation to use. When CP is enabled, ring attention uses the matching kernel family (FA2 for flash_attention_2, FA3 for flash_attention_3).",
description="The attention implementation to use. When CP is enabled, ring attention uses the matching kernel family (FA2 for flash_attention_2, FA3 for flash_attention_3, FA4 for fa4).",
),
] = "flash_attention_2"
@@ -368,12 +368,12 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
def cp_only_with_flash_attn(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3"]:
raise ValueError("CP is only supported with flash attention 2 or flash attention 3")
if self.cp > 1 and self.attn == "flash_attention_3" and self.impl != "custom":
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "fa4"]:
raise ValueError("CP is only supported with flash attention 2, flash attention 3, or fa4")
if self.cp > 1 and self.attn in ("flash_attention_3", "fa4") and self.impl != "custom":
raise ValueError(
"CP with flash_attention_3 requires model.impl='custom' "
"(the FA3 ring-attention kernel is only implemented for the custom model path)"
f"CP with {self.attn} requires model.impl='custom' "
"(the ring-attention kernel is only implemented for the custom model path)"
)
return self
+12 -4
View File
@@ -548,15 +548,23 @@ def rl(config: RLConfig):
if ckpt_output_dir is not None:
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
# Clean stale artifacts from steps after the resume point
# Clean stale rollouts and broadcasts. When resuming, anything past the resume
# step is stale. When training from scratch, every existing step directory is
# stale — without this, a fresh run in a dirty output_dir would pick up rollouts
# from a previous run and the orchestrator would see a negative async level.
resume_step: int | None = None
if resuming:
resume_step = config.ckpt.resume_step
if resume_step == -1:
ckpt_base = ckpt_output_dir if ckpt_output_dir is not None else config.output_dir
resume_step = resolve_latest_ckpt_step(get_ckpt_dir(ckpt_base))
if resume_step is not None:
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
clean_future_steps(config.output_dir, resume_step)
if resume_step is not None:
get_logger().info(f"Resuming from step {resume_step}, cleaning future rollouts and broadcasts")
clean_future_steps(config.output_dir, resume_step)
else:
get_logger().info("Training from scratch, cleaning any stale rollouts and broadcasts")
clean_future_steps(config.output_dir, -1)
if not config.dry_run:
pre_download_model(config.trainer.model.name)
+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}'")
+11 -10
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
@@ -352,10 +350,13 @@ class Envs(Generic[EnvT]):
log_level: str | None = None,
json_logging: bool = False,
) -> None:
"""Spawn env servers (where needed) and connect all env clients in parallel."""
await asyncio.gather(
*(env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging) for env in self)
)
"""Spawn env servers (where needed) and connect env clients one at a time.
Serialized to avoid a TOCTOU port race: get_free_port() only holds the port
until it returns, so parallel spawns can hand the same port to two children.
"""
for env in self:
await env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
atexit.register(self.shutdown)
def shutdown(self) -> None:
+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
]
+9 -11
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
@@ -434,14 +432,7 @@ class Scheduler:
valid_rollouts = []
has_failures = False
for rollout in rollouts:
if len(rollout["trajectory"]) == 0:
self.empty_rollouts_by_env[env_name] += 1
has_failures = True
self.logger.warning(
f"Empty trajectory in group {group_id} ({env_name}), re-scheduling "
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
)
elif rollout["error"] is not None:
if rollout["error"] is not None:
self.errored_rollouts_by_env[env_name] += 1
has_failures = True
self.logger.warning(
@@ -449,6 +440,13 @@ class Scheduler:
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete): "
f"{rollout['error']['error_chain_repr']}"
)
elif len(rollout["trajectory"]) == 0:
self.empty_rollouts_by_env[env_name] += 1
has_failures = True
self.logger.warning(
f"Empty trajectory in group {group_id} ({env_name}), re-scheduling "
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
)
else:
rollout["env_name"] = env_name
valid_rollouts.append(rollout)
+15 -7
View File
@@ -93,14 +93,18 @@ class FlashAttention(nn.Module):
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
args = [q, k, v, cu_seqlens, cu_seqlens]
if self._flash_attn_version != 4:
args.extend([max_seqlen, max_seqlen])
kwargs: dict = {"causal": True}
sliding_window = getattr(self, "sliding_window", None)
if sliding_window is not None:
kwargs["window_size"] = (sliding_window - 1, 0)
out = self._flash_attn_call(*args, **kwargs)
if self._flash_attn_version == 4:
# FA4's flash_attn_varlen_func has qv as the 4th positional arg,
# so cu_seqlens must be passed as keyword args to avoid misalignment.
kwargs["cu_seqlens_q"] = cu_seqlens
kwargs["cu_seqlens_k"] = cu_seqlens
out = self._flash_attn_call(q, k, v, **kwargs)
else:
out = self._flash_attn_call(q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, **kwargs)
if isinstance(out, tuple):
out = out[0]
return out
@@ -291,10 +295,14 @@ def substitute_ring_attn(
"""Patch _compute_attention on FlashAttention variants to use ring attention."""
from ring_flash_attn import llama3_flash_attn_varlen_func
from .ring_attn import ring_fa3_varlen_func
from .ring_attn import ring_fa3_varlen_func, ring_fa4_varlen_func
use_fa3 = attn_impl == "flash_attention_3"
ring_func = ring_fa3_varlen_func if use_fa3 else llama3_flash_attn_varlen_func
if attn_impl == "fa4":
ring_func = ring_fa4_varlen_func
elif attn_impl == "flash_attention_3":
ring_func = ring_fa3_varlen_func
else:
ring_func = llama3_flash_attn_varlen_func
def _ring_compute_attention(self, q, k, v, cu_seqlens, max_seqlen):
from ring_flash_attn.adapters.hf_adapter import DATA_PARAMS
@@ -297,3 +297,298 @@ def ring_fa3_varlen_func(
window_size[0],
window_size[1],
)
# ---------------------------------------------------------------------------
# FA4 (flash_attn.cute) ring attention
# ---------------------------------------------------------------------------
def _fa4_varlen_forward(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
softmax_scale: float,
causal: bool,
window_size: tuple[int, int] = (-1, -1),
) -> tuple[torch.Tensor, torch.Tensor]:
from flash_attn.cute.interface import _flash_attn_fwd
wl = window_size[0] if window_size[0] != -1 else None
wr = window_size[1] if window_size[1] != -1 else None
out, lse = _flash_attn_fwd(
q,
k,
v,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
softmax_scale=softmax_scale,
causal=causal,
window_size_left=wl,
window_size_right=wr,
return_lse=True,
)
return out, lse
def _fa4_varlen_backward(
dout: torch.Tensor,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
out: torch.Tensor,
softmax_lse: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
dq: torch.Tensor,
dk: torch.Tensor,
dv: torch.Tensor,
softmax_scale: float,
causal: bool,
window_size: tuple[int, int] = (-1, -1),
) -> None:
from flash_attn.cute.interface import _flash_attn_bwd
wl = window_size[0] if window_size[0] != -1 else None
wr = window_size[1] if window_size[1] != -1 else None
_flash_attn_bwd(
q,
k,
v,
out,
dout,
softmax_lse,
softmax_scale=softmax_scale,
causal=causal,
window_size_left=wl,
window_size_right=wr,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
dq=dq,
dk=dk,
dv=dv,
)
class _RingFA4Varlen(torch.autograd.Function):
"""Ring attention using FA4 (flash_attn.cute) kernels with all-gather communication.
Mirrors _RingFA3Varlen but calls the FA4 low-level forward/backward.
"""
@staticmethod
def forward(
ctx,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
local_k_slice_start: int,
local_k_slice_stop: int,
heads_k_stride: int,
causal: bool,
group_name: str,
window_size_left: int = -1,
window_size_right: int = -1,
) -> torch.Tensor:
group = dist.group.WORLD
for pg in dist.distributed_c10d._world.pg_map:
if pg.group_name == group_name:
group = pg
break
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
window_size = (window_size_left, window_size_right)
softmax_scale = q.shape[-1] ** (-0.5)
out_list = []
lse_list = []
nheads = q.shape[1]
total_k, nheads_k, head_dim = k.shape
world_size = dist.get_world_size(group)
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_buffer_copy = torch.empty_like(kv_buffer)
comm = AllGatherComm(group)
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
for i in range(0, nheads_k, heads_k_stride):
comm.wait()
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
if i < nheads_k - heads_k_stride:
left = i + heads_k_stride
right = left + heads_k_stride
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
q_i = q[:, i * nheads // nheads_k : (i + heads_k_stride) * nheads // nheads_k]
k_i = kv_buffer[0][local_k_slice]
v_i = kv_buffer[1][local_k_slice]
out_i, lse_i = _fa4_varlen_forward(
q=q_i,
k=k_i,
v=v_i,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
softmax_scale=softmax_scale,
causal=causal,
window_size=window_size,
)
out_list.append(out_i)
lse_list.append(lse_i)
out = torch.cat(out_list, dim=1)
lse = torch.cat(lse_list, dim=-2)
ctx.save_for_backward(q, k, v, out, lse, cu_seqlens_q, cu_seqlens_k)
ctx.softmax_scale = softmax_scale
ctx.max_seqlen_q = max_seqlen_q
ctx.max_seqlen_k = max_seqlen_k
ctx.local_k_slice = local_k_slice
ctx.heads_k_stride = heads_k_stride
ctx.causal = causal
ctx.group_name = group_name
ctx.window_size = window_size
return out
@staticmethod
def backward(ctx, dout: torch.Tensor):
q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors
heads_k_stride = ctx.heads_k_stride
local_k_slice = ctx.local_k_slice
causal = ctx.causal
group = dist.group.WORLD
for pg in dist.distributed_c10d._world.pg_map:
if pg.group_name == ctx.group_name:
group = pg
break
nheads = q.shape[1]
total_k, nheads_k, head_dim = k.shape
world_size = dist.get_world_size(group)
kv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_buffer_copy = torch.empty_like(kv_buffer)
dkv_buffer = torch.empty((2, total_k * world_size, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
kv_contiguous_buffer = None
if heads_k_stride != nheads_k:
kv_contiguous_buffer = torch.empty((2, total_k, heads_k_stride, head_dim), dtype=k.dtype, device=k.device)
dq = torch.empty_like(q)
dk = torch.empty_like(k)
dv = torch.empty_like(v)
comm = AllGatherComm(group)
comm.all_gather(kv_buffer_copy[0], k[:, :heads_k_stride].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, :heads_k_stride].contiguous())
for i in range(0, nheads_k, heads_k_stride):
dkv_buffer.zero_()
q_slice = slice(i * nheads // nheads_k, (i + heads_k_stride) * nheads // nheads_k)
q_i = q[:, q_slice]
dout_i = dout[:, q_slice]
out_i = out[:, q_slice]
dq_i = dq[:, q_slice]
lse_i = softmax_lse[q_slice].contiguous()
comm.wait()
kv_buffer, kv_buffer_copy = kv_buffer_copy, kv_buffer
if i < nheads_k - heads_k_stride:
left = i + heads_k_stride
right = left + heads_k_stride
comm.all_gather(kv_buffer_copy[0], k[:, left:right].contiguous())
comm.all_gather(kv_buffer_copy[1], v[:, left:right].contiguous())
k_i = kv_buffer[0][local_k_slice]
v_i = kv_buffer[1][local_k_slice]
dk_i = dkv_buffer[0][local_k_slice]
dv_i = dkv_buffer[1][local_k_slice]
_fa4_varlen_backward(
dout=dout_i,
q=q_i,
k=k_i,
v=v_i,
out=out_i,
softmax_lse=lse_i,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=ctx.max_seqlen_q,
max_seqlen_k=ctx.max_seqlen_k,
dq=dq_i,
dk=dk_i,
dv=dv_i,
softmax_scale=ctx.softmax_scale,
causal=causal,
window_size=ctx.window_size,
)
if heads_k_stride != nheads_k:
dk_i = kv_contiguous_buffer[0]
dv_i = kv_contiguous_buffer[1]
else:
dk_i = dk
dv_i = dv
dist.reduce_scatter_tensor(dk_i, dkv_buffer[0], group=group)
dist.reduce_scatter_tensor(dv_i, dkv_buffer[1], group=group)
if heads_k_stride != nheads_k:
dk[:, i : i + heads_k_stride] = dk_i
dv[:, i : i + heads_k_stride] = dv_i
# Grads for: q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
# local_k_slice_start, local_k_slice_stop, heads_k_stride, causal, group_name,
# window_size_left, window_size_right
return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None
def ring_fa4_varlen_func(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
local_k_slice: slice,
causal: bool,
heads_k_stride: int,
group: dist.ProcessGroup,
window_size: tuple[int, int] = (-1, -1),
) -> torch.Tensor:
return _RingFA4Varlen.apply(
q,
k,
v,
cu_seqlens_q,
cu_seqlens_k,
max_seqlen_q,
max_seqlen_k,
local_k_slice.start,
local_k_slice.stop,
heads_k_stride,
causal,
group.group_name,
window_size[0],
window_size[1],
)
+108 -46
View File
@@ -1,13 +1,13 @@
import asyncio
import io
import json
import math
import os
import time
from datetime import datetime, timezone
from pathlib import Path
from threading import Thread
from typing import Any
from urllib.parse import urlparse
import httpx
import pyarrow as pa
@@ -56,9 +56,57 @@ _SAMPLE_SCHEMA = pa.schema(
)
_DROPPED_JSON_VALUE = object()
def _drop_non_finite_json_values(value: Any, dropped_paths: list[str], path: str = "") -> Any:
if isinstance(value, float) and not math.isfinite(value):
dropped_paths.append(path)
return _DROPPED_JSON_VALUE
if isinstance(value, dict):
return {
key: sanitized_item
for key, item in value.items()
if (
sanitized_item := _drop_non_finite_json_values(
item,
dropped_paths,
f"{path}.{key}" if path else str(key),
)
)
is not _DROPPED_JSON_VALUE
}
if isinstance(value, list):
return [
sanitized_item
for idx, item in enumerate(value)
if (sanitized_item := _drop_non_finite_json_values(item, dropped_paths, f"{path}[{idx}]"))
is not _DROPPED_JSON_VALUE
]
return value
class PrimeMonitor(Monitor):
"""Logs to Prime Intellect API."""
def _sanitize_json_payload(self, endpoint: str, payload: dict[str, Any]) -> dict[str, Any]:
"""Drop non-finite floats before sending JSON payloads to the public API."""
dropped_paths: list[str] = []
sanitized_payload = _drop_non_finite_json_values(payload, dropped_paths)
if not dropped_paths:
return payload
preview = ", ".join(dropped_paths[:5])
suffix = " ..." if len(dropped_paths) > 5 else ""
self.logger.warning(
f"Dropping {len(dropped_paths)} non-finite value(s) from Prime monitor {endpoint} payload: "
f"{preview}{suffix}"
)
return sanitized_payload
def __init__(
self,
config: PrimeMonitorConfig | None,
@@ -101,6 +149,11 @@ class PrimeMonitor(Monitor):
self.api_key = api_key
self.base_url = config.base_url.rstrip("/")
self._headers = {
"Authorization": f"Bearer {api_key}",
"x-api-key": api_key,
"Content-Type": "application/json",
}
run_id = os.getenv("RUN_ID")
if not run_id:
@@ -123,7 +176,7 @@ class PrimeMonitor(Monitor):
os.register_at_fork(after_in_child=self._reinit_after_fork)
# Optionally, initialize sample logging attributes
if config is not None and config.log_extras:
if config.log_extras:
if config.log_extras.samples:
self.last_log_samples_step = -1
self._pending_sample_steps: set[int] = set()
@@ -133,14 +186,6 @@ class PrimeMonitor(Monitor):
def _register_run(self, config: PrimeMonitorConfig, run_config: BaseConfig | None) -> str | None:
"""Register an external run with the platform. Returns run_id on success, None on failure."""
registration_api_key = self.api_key
if not registration_api_key:
self.logger.warning(
f"Prime Intellect API key not found. Set {config.api_key_var} environment variable or run `prime login`. "
"PrimeMonitor will not be able to register or upload data."
)
return None
prime_config = None
team_id = config.team_id
frontend_url = config.frontend_url
@@ -168,13 +213,10 @@ class PrimeMonitor(Monitor):
if wandb and getattr(wandb, "project", None):
payload["wandb_project"] = wandb.project
parsed = urlparse(config.base_url)
api_base = f"{parsed.scheme}://{parsed.netloc}/api/v1/rft"
try:
response = httpx.post(
f"{api_base}/external-runs",
headers={"Authorization": f"Bearer {registration_api_key}"},
f"{self.base_url}/external-runs",
headers=self._headers,
json=payload,
timeout=30,
)
@@ -200,21 +242,17 @@ class PrimeMonitor(Monitor):
def _finalize_run(self, success: bool) -> None:
"""Mark the run as completed or failed on the platform."""
if not getattr(self, "_registered", False):
if not self._registered:
return
registration_api_key = self.api_key
payload: dict = {"status": "completed" if success else "failed"}
status_label = "completed" if success else "failed"
self.logger.info(f"Finalizing platform run {self.run_id} as {status_label}")
parsed = urlparse(self.base_url)
finalize_url = f"{parsed.scheme}://{parsed.netloc}/api/v1/rft/external-runs/{self.run_id}/status"
try:
response = httpx.put(
finalize_url,
headers={"Authorization": f"Bearer {registration_api_key}"},
f"{self.base_url}/external-runs/{self.run_id}/status",
headers=self._headers,
json=payload,
timeout=30,
)
@@ -369,10 +407,6 @@ class PrimeMonitor(Monitor):
self.logger.warning(f"Failed to get presigned URL for samples at step {step}")
return
if "presigned_url" not in presign_data or "s3_key" not in presign_data:
self.logger.warning(f"Invalid presign response at step {step}")
return
presigned_url = presign_data["presigned_url"]
s3_key = presign_data["s3_key"]
@@ -398,15 +432,18 @@ class PrimeMonitor(Monitor):
async def _request_presigned_url(self, step: int) -> dict[str, Any] | None:
"""Request a presigned URL from the backend."""
headers = {"x-api-key": self.api_key, "Content-Type": "application/json"}
try:
response = await self._client.post(
f"{self.base_url}/samples/presign",
headers=headers,
headers=self._headers,
json={"run_id": self.run_id, "step": step},
)
response.raise_for_status()
return response.json()
response_data = response.json()["data"]
return {
"presigned_url": response_data["presignedUrl"],
"s3_key": response_data["s3Key"],
}
except Exception as e:
self.logger.warning(f"Failed to request presigned URL: {type(e).__name__}: {e}")
return None
@@ -430,12 +467,11 @@ class PrimeMonitor(Monitor):
async def _confirm_samples_upload(self, step: int, s3_key: str, max_retries: int = 3) -> bool:
"""Confirm samples upload with the backend. Returns True on success."""
headers = {"x-api-key": self.api_key, "Content-Type": "application/json"}
for attempt in range(max_retries):
try:
response = await self._client.post(
f"{self.base_url}/samples/confirm",
headers=headers,
headers=self._headers,
json={"run_id": self.run_id, "step": step, "s3_key": s3_key},
)
response.raise_for_status()
@@ -493,22 +529,51 @@ class PrimeMonitor(Monitor):
f"Logged distributions at step {step} to Prime Intellect API in {time.perf_counter() - start_time:.2f}s"
)
def _submit_final_summary(self, summary: dict[str, Any]) -> bool:
"""Submit the final summary/finalize request synchronously."""
payload = self._sanitize_json_payload(
"finalize",
{"run_id": self.run_id, "summary": summary},
)
try:
response = httpx.post(
f"{self.base_url}/finalize",
headers=self._headers,
json=payload,
timeout=30,
)
except httpx.HTTPError as e:
self.logger.warning(f"Failed to submit final summary for platform run {self.run_id}: {e}")
return False
if response.status_code != 200:
self.logger.warning(
f"Failed to submit final summary for platform run {self.run_id} "
f"(HTTP {response.status_code}): {response.text}"
)
return False
return True
def save_final_summary(self, filename: str = "final_summary.json") -> None:
"""Save final summary to Prime Intellect API."""
if not self.is_master or not self.enabled:
return
self.logger.info("Saving final summary to Prime Intellect API")
self._make_request(
"finalize",
{
"run_id": self.run_id,
"summary": self.history[-1] if self.history else {},
},
)
if os.getpid() == self._owner_pid:
self._finalize_run(success=True)
summary = self.history[-1] if self.history else {}
finalized_via_summary = self._submit_final_summary(summary)
if os.getpid() != self._owner_pid:
return
if finalized_via_summary:
self._finalized = True
return
self._finalize_run(success=True)
self._finalized = True
def close(self) -> None:
"""Close the HTTP client and stop the background event loop."""
@@ -580,18 +645,15 @@ class PrimeMonitor(Monitor):
async def _make_request_async(self, endpoint: str, data: dict[str, Any], max_retries: int = 3) -> None:
"""Make an async POST request to the Prime Intellect API with retries."""
headers = {
"x-api-key": self.api_key,
"Content-Type": "application/json",
}
full_endpoint = f"{self.base_url}/{endpoint}"
sanitized_data = self._sanitize_json_payload(endpoint, data)
for attempt in range(max_retries):
try:
response = await self._client.post(
full_endpoint,
headers=headers,
json=data,
headers=self._headers,
json=sanitized_data,
)
response.raise_for_status()
return # Success
+4 -1
View File
@@ -150,7 +150,10 @@ def validate_output_dir(output_dir: Path, *, resuming: bool, clean: bool, ckpt_o
def clean_future_steps(output_dir: Path, resume_step: int) -> None:
"""Remove stale rollouts and broadcasts from a resumed run."""
"""Remove stale rollouts and broadcasts past ``resume_step``.
Pass ``resume_step=-1`` to wipe every step directory (fresh runs).
"""
run_default = output_dir / "run_default"
dirs = [
get_rollout_dir(output_dir),
+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
+26 -2
View File
@@ -1,11 +1,18 @@
import io
import json
from unittest.mock import Mock
import pyarrow.parquet as pq
from prime_rl.utils.monitor.prime import PrimeMonitor
def _new_monitor() -> PrimeMonitor:
monitor = PrimeMonitor.__new__(PrimeMonitor)
monitor._closed = True
return monitor
def _build_rollout(*, example_id: int, reward: float, task: str) -> dict:
return {
"example_id": example_id,
@@ -35,7 +42,7 @@ def _build_rollout(*, example_id: int, reward: float, task: str) -> dict:
def test_rollouts_to_parquet_bytes_preserves_all_rollouts_and_ids():
monitor = PrimeMonitor.__new__(PrimeMonitor)
monitor = _new_monitor()
monitor.run_id = "run-123"
parquet_bytes = monitor._rollouts_to_parquet_bytes(
@@ -61,7 +68,7 @@ def test_rollouts_to_parquet_bytes_preserves_all_rollouts_and_ids():
def test_rollouts_to_parquet_bytes_skips_rollouts_without_trajectory():
monitor = PrimeMonitor.__new__(PrimeMonitor)
monitor = _new_monitor()
monitor.run_id = "run-456"
parquet_bytes = monitor._rollouts_to_parquet_bytes(
@@ -85,3 +92,20 @@ def test_rollouts_to_parquet_bytes_skips_rollouts_without_trajectory():
assert len(rows) == 1
assert rows[0]["problem_id"] == 1
assert rows[0]["sample_id"] == 0
def test_sanitize_json_payload_drops_non_finite_values_and_logs_paths():
monitor = _new_monitor()
monitor.logger = Mock()
payload = {
"metrics": {"finite": 1.0, "nan": float("nan")},
"distributions": [0.5, float("inf")],
}
sanitized = monitor._sanitize_json_payload("metrics", payload)
assert sanitized == {"metrics": {"finite": 1.0}, "distributions": [0.5]}
monitor.logger.warning.assert_called_once_with(
"Dropping 2 non-finite value(s) from Prime monitor metrics payload: metrics.nan, distributions[1]"
)
Generated
+18 -14
View File
@@ -440,7 +440,7 @@ dependencies = [
{ name = "verifiers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
wheels = [
{ url = "https://hub.primeintellect.ai/primeintellect/code-env/@905f3374/code_env-0.1.1-py3-none-any.whl", hash = "sha256:52e88748eeee933add11e3f485e2d9e4d4515cdc609acbd5789862adbd541ac8" },
{ url = "https://hub.primeintellect.ai/primeintellect/code-env/@2e4fb479/code_env-0.1.1-py3-none-any.whl", hash = "sha256:42a5c0b9bf6d858ff1f71a779d38e5268fb03f63ed347a736eb6938859303177" },
]
[[package]]
@@ -452,7 +452,7 @@ dependencies = [
{ name = "verifiers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
wheels = [
{ url = "https://hub.primeintellect.ai/primeintellect/color-codeword/@80a7a5ac/color_codeword-0.1.0-py3-none-any.whl", hash = "sha256:c8be97a91ca823074bfdd2756803d74833fe43b0d09c755b96fb432f9c0d3047" },
{ url = "https://hub.primeintellect.ai/primeintellect/color-codeword/@828f24c5/color_codeword-0.1.0-py3-none-any.whl", hash = "sha256:5bf72f74d6ee001b6be96768dd269e8762617dd3644238bda7623f58a6bc069a" },
]
[[package]]
@@ -879,7 +879,7 @@ wheels = [
[[package]]
name = "flash-attn-4"
version = "4.0.0b6.dev7+gabd9943.d20260414"
version = "4.0.0b6.dev7+gabd9943"
source = { git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=abd9943b#abd9943b66704f650ea1485a17126cd3817d1b1d" }
dependencies = [
{ name = "apache-tvm-ffi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -1594,7 +1594,7 @@ dependencies = [
{ name = "verifiers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
wheels = [
{ url = "https://hub.primeintellect.ai/primeintellect/logic-env/@faee829c/logic_env-0.1.0-py3-none-any.whl", hash = "sha256:789523bfbd87af97d67422b1ba6f89c181d8d33e4b6aedce629c312b0ab4ed1f" },
{ url = "https://hub.primeintellect.ai/primeintellect/logic-env/@7bded58d/logic_env-0.1.0-py3-none-any.whl", hash = "sha256:3ecc5f31feb13fb5bd8d9a091d1d7cf0e6a8687c758f9b2a04e5f1b3b0c235a8" },
]
[[package]]
@@ -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" },
@@ -2794,9 +2798,9 @@ requires-dist = [
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=c1c3424" },
{ name = "uvloop", specifier = ">=0.21.0" },
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=0760204" },
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=77a9f28" },
{ name = "vllm", specifier = ">=0.19.0" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.20/vllm_router-0.1.20-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "wandb", specifier = ">=0.24.2" },
{ name = "wiki-search", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
]
@@ -2831,16 +2835,16 @@ wheels = [
[[package]]
name = "prime-tunnel"
version = "0.1.5"
version = "0.1.6"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "pydantic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "tenacity", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
]
sdist = { url = "https://files.pythonhosted.org/packages/2f/d2/17236f43b855a4261252d317ef230beb0571268427418c8d471d3eba195c/prime_tunnel-0.1.5.tar.gz", hash = "sha256:eec296f92abbd761edcb779db7052bf9ce9c3469641f8f17645b7ed5c478257e", size = 12609, upload-time = "2026-03-21T00:52:56.147Z" }
sdist = { url = "https://files.pythonhosted.org/packages/d1/e8/fec186cfbcc670deed94a7b5ace67688feed38b114b1c602d35a8f8d7564/prime_tunnel-0.1.6.tar.gz", hash = "sha256:5e371bc3557d8a5257a43ef1aeea1f8918da966a8565dacd33a647b6c82a0eaa", size = 13019, upload-time = "2026-04-13T15:13:17.24Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/66/d2/26c801e0ee8ed867875a704c1fa238581f505bbd96f618c894c8dca991fc/prime_tunnel-0.1.5-py3-none-any.whl", hash = "sha256:fc24bf60d8023f53850be9602dc7d0e1be3e091a019a06c65d32a6b3d61754af", size = 14758, upload-time = "2026-03-21T00:52:55.278Z" },
{ url = "https://files.pythonhosted.org/packages/52/35/adfac88e5880418f095758729b73e395c81be869d0be786fcd4b31938b2f/prime_tunnel-0.1.6-py3-none-any.whl", hash = "sha256:bc096bca509621379f671e2401253ab2ebe6c8c143d797b6ef85d8290c462e0d", size = 14914, upload-time = "2026-04-13T15:13:16.08Z" },
]
[[package]]
@@ -4031,8 +4035,8 @@ wheels = [
[[package]]
name = "verifiers"
version = "0.1.12.dev2"
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=0760204#07602042d6909b1d3c405d6d99aee0088c7990d2" }
version = "0.1.12.dev6"
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=77a9f28#77a9f282bdea2c09b34e726a1e6c7b5e55bab8be" }
dependencies = [
{ name = "aiolimiter", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
{ name = "anthropic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
@@ -4152,8 +4156,8 @@ wheels = [
[[package]]
name = "vllm-router"
version = "0.1.20"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.20/vllm_router-0.1.20-cp38-abi3-manylinux_2_28_x86_64.whl" }
version = "0.1.22"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
dependencies = [
{ name = "aiohttp", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "fastapi", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
@@ -4163,7 +4167,7 @@ dependencies = [
{ name = "uvicorn", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
]
wheels = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.20/vllm_router-0.1.20-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:88814218907942405bf43f1086abfaff352361d5fe7955aa8234a0ebf0651243" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:6361a0387241e56932f3ba2e51af27f58d11a462e3187e58286b2f96056e4d15" },
]
[package.metadata]