Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d49f3939e7 | ||
|
|
9eeffdb6fb | ||
|
|
03689b8ac0 | ||
|
|
f29e947585 | ||
|
|
bb7449c829 | ||
|
|
82fa41f4f2 | ||
|
|
1ade129004 | ||
|
|
26ea8df85e | ||
|
|
d4bddbaed7 | ||
|
|
6bf14b80f8 | ||
|
|
586e0f8e5d | ||
|
|
18e895651e | ||
|
|
2c54d5c834 | ||
|
|
3a6b46189a | ||
|
|
ba86b9ba88 | ||
|
|
2d659eecc7 | ||
|
|
56cdd2c579 | ||
|
|
4dcf86f0ea | ||
|
|
ad3134ac03 | ||
|
|
8c5aa67aa5 | ||
|
|
fde3006470 | ||
|
|
67783e4a6c | ||
|
|
52b1ae14a6 | ||
|
|
3cd633205b | ||
|
|
bc34bae348 | ||
|
|
f2e97b2bf5 | ||
|
|
8c1e6505e8 | ||
|
|
fa63a5a65a | ||
|
|
f8a1460638 |
+2
-2
@@ -32,8 +32,8 @@ Documenting **breaking** configuration changes — renamed, removed, or moved fi
|
||||
- **`model.deepep_token_chunk_size`**: Added optional token chunk size for DeepEP MoE pipelining (default: `None`, minimum: `1`). When set, DeepEP dispatch for chunk `i+1` overlaps expert compute for chunk `i`. This field is only used when `model.ep_comm_backend='deepep'`. (2026-03-22)
|
||||
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models)**: Added validation that VLM models must use `optimization_dtype='bfloat16'` and `reduce_dtype='bfloat16'` to match vLLM inference. Previously valid configs with `float32` (the default) are now rejected for VLM model names. Set both fields to `"bfloat16"` when training VLMs. (2026-03-21)
|
||||
- **`model.ac.mode`** and **`model.ac.targets`**: Added selective activation checkpointing configuration. `model.ac.mode` accepts `full` (default) or `selective`. When `selective`, `model.ac.targets` selects subcomponents to checkpoint. Supported public targets are currently `norm`, `attention_sdpa`, `mla_up_proj`, and `routed_experts`; runtime validation remains the source of truth. `model.ac.targets` defaults to `["norm"]`, and selective mode requires at least one target. (2026-03-20)
|
||||
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping_alpha` is set. Existing configs must delete this field. (2026-03-19)
|
||||
- **`orchestrator.advantage.length_shaping_alpha`**: Added Group Relative Reward Rescaling coefficient to the default advantage config. When set, applies length-based GR3 shaping during advantage computation and requires `orchestrator.buffer.online_difficulty_filtering = true` (default: `None`) (2026-03-18)
|
||||
- **`orchestrator.advantage.length_shaping_alpha` → `orchestrator.advantage.length_shaping`**: Replaced GR³ (`length_shaping_alpha: float | None`) with correctness-gated efficiency shaping (`length_shaping: bool`, default: `false`). No hyperparameter needed, no `online_difficulty_filtering` requirement. Existing configs using `length_shaping_alpha` must switch to `length_shaping = true`. (2026-04-13)
|
||||
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping` is enabled. Existing configs must delete this field. (2026-03-19)
|
||||
- **`prime_monitor.log_extras.sample_ratio`**: Added ratio-based rollout sampling (0.0–1.0, default: None). When set, caps the number of rollouts logged per step to `len(rollouts) * sample_ratio`. `None` preserves current behavior (log all rollouts). Interacts with existing `interval` gate which still runs first. (2026-03-12)
|
||||
- **`client.connect_timeout`**: Added configurable TCP connect timeout for inference API requests (default: 30.0s). Previously hardcoded to 5.0s. Helps with vLLM or cluster flakiness (2026-03-11)
|
||||
- **`model.fused_lm_head_token_chunk_size`**: Added as the fused LM-head chunking field for the token-chunked implementation. Unlike the removed `model.fused_lm_head_chunk_size`, this chunks over flattened sequence tokens rather than vocabulary rows. `model.fused_lm_head_chunk_size` is no longer accepted; switch configs to `model.fused_lm_head_token_chunk_size` explicitly. (2026-03-09)
|
||||
|
||||
+1
-1
@@ -53,7 +53,7 @@ COPY examples /app/examples
|
||||
COPY benchmarks/scripts /app/benchmarks/scripts
|
||||
|
||||
RUN --mount=type=cache,target=/app/.cache/uv \
|
||||
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --group mamba-ssm --locked --no-dev
|
||||
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --group mamba-ssm --locked --no-dev
|
||||
|
||||
# arm64: build flash-attn from source, fix namespace conflicts, apply workarounds
|
||||
ARG TARGETARCH
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Qwen 2.5 32B Math
|
||||
# Qwen 3 30B - A3B Math
|
||||
|
||||
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on math tasks.
|
||||
This example guides you through RL training [Qwen3-30B-A3B-Thinking-2507](https://huggingface.co/Qwen/Qwen3-30B-A3B-Thinking-2507) on math tasks.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Qwen 2.5 32B SWE
|
||||
# Qwen 3 30B - A3B SWE
|
||||
|
||||
This example guides you through RL training [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) on agentic SWE tasks.
|
||||
This example guides you through RL training [Qwen3-30B-A3B-Thinking-2507](https://huggingface.co/Qwen/Qwen3-30B-A3B-Thinking-2507) on agentic SWE tasks.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
+5
-3
@@ -22,7 +22,7 @@ dependencies = [
|
||||
"vllm>=0.19.0",
|
||||
"wandb>=0.24.2",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.5.37",
|
||||
"prime>=0.5.63",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -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.18/vllm_router-0.1.16-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" }
|
||||
|
||||
@@ -4,5 +4,13 @@ set -e
|
||||
# Set higher ulimit for file descriptors to prevent API timeout issues
|
||||
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
|
||||
|
||||
# Allow runtime override of the verifiers package version.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
|
||||
if [ -n "$VERIFIERS_VERSION" ]; then
|
||||
echo "Installing verifiers version: $VERIFIERS_VERSION"
|
||||
uv pip install --reinstall-package verifiers \
|
||||
"verifiers @ git+https://github.com/PrimeIntellect-ai/verifiers.git@${VERIFIERS_VERSION}"
|
||||
fi
|
||||
|
||||
# Execute the main command
|
||||
exec "$@"
|
||||
|
||||
+48
-14
@@ -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
|
||||
|
||||
@@ -13,6 +13,7 @@ class EnvServerConfig(BaseConfig):
|
||||
|
||||
env: EnvConfig = EnvConfig()
|
||||
log: LogConfig = LogConfig()
|
||||
env_install_prerelease: bool = False
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
|
||||
@@ -85,7 +85,7 @@ class ModelConfig(BaseModelConfig):
|
||||
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
|
||||
'Set to "auto" to infer from the model name.',
|
||||
),
|
||||
] = None
|
||||
] = "auto"
|
||||
|
||||
reasoning_parser: Annotated[
|
||||
str | None,
|
||||
@@ -244,6 +244,10 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class InferenceExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for inference."""
|
||||
|
||||
|
||||
class InferenceConfig(BaseConfig):
|
||||
"""Configures inference."""
|
||||
|
||||
@@ -413,6 +417,11 @@ class InferenceConfig(BaseConfig):
|
||||
|
||||
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
|
||||
|
||||
experimental: Annotated[
|
||||
InferenceExperimentalConfig,
|
||||
Field(description="Experimental features for inference."),
|
||||
] = InferenceExperimentalConfig()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_multi_node_requires_slurm(self):
|
||||
if self.deployment.type == "multi_node" and self.slurm is None:
|
||||
|
||||
@@ -676,10 +676,16 @@ class DefaultAdvantageConfig(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
length_shaping_alpha: Annotated[
|
||||
float | None,
|
||||
Field(description="Penalty coefficient for Group Relative Reward Rescaling (GR³). Recommended value: 0.33"),
|
||||
] = None
|
||||
length_shaping: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"Enable correctness-gated length shaping. In mixed groups, shorter correct rollouts get "
|
||||
"amplified advantage (up to 2x), longer correct rollouts are unchanged, incorrect untouched. "
|
||||
"In all-correct groups, below-average-length rollouts get advantage in [0, 1], others get 0."
|
||||
)
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseModel):
|
||||
@@ -709,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[
|
||||
@@ -733,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[
|
||||
@@ -759,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
|
||||
|
||||
@@ -803,6 +809,10 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class OrchestratorExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for the orchestrator."""
|
||||
|
||||
|
||||
class TeacherModelConfig(BaseConfig):
|
||||
"""Configures the teacher model for computing teacher logprobs (e.g. for distillation)."""
|
||||
|
||||
@@ -891,6 +901,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
# The prime monitor configuration
|
||||
prime_monitor: PrimeMonitorConfig | None = None
|
||||
|
||||
# Whether to collect inference server metrics (requires wandb)
|
||||
collect_inference_metrics: bool = True
|
||||
|
||||
# The checkpoint configuration
|
||||
ckpt: CheckpointConfig | None = None
|
||||
|
||||
@@ -1023,6 +1036,18 @@ class OrchestratorConfig(BaseConfig):
|
||||
),
|
||||
] = True
|
||||
|
||||
env_install_prerelease: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Allow pre-release versions when installing environments (e.g. verifiers>=0.1.12.dev5). Passes --prerelease to prime env install."
|
||||
),
|
||||
] = False
|
||||
|
||||
experimental: Annotated[
|
||||
OrchestratorExperimentalConfig,
|
||||
Field(description="Experimental features for the orchestrator."),
|
||||
] = OrchestratorExperimentalConfig()
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _env_to_train(cls, data: Any) -> Any:
|
||||
@@ -1107,13 +1132,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_length_shaping_requires_online_difficulty_filtering(self):
|
||||
if isinstance(self.advantage, DefaultAdvantageConfig) and self.advantage.length_shaping_alpha is not None:
|
||||
if not self.buffer.online_difficulty_filtering:
|
||||
raise ValueError("Group Relative Reward (GR³) scaling requires online difficulty filtering")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench:
|
||||
|
||||
@@ -52,6 +52,10 @@ from prime_rl.utils.validation import (
|
||||
)
|
||||
|
||||
|
||||
class RLExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for RL training."""
|
||||
|
||||
|
||||
class SharedLogConfig(BaseConfig):
|
||||
"""Configures shared logging."""
|
||||
|
||||
@@ -350,6 +354,11 @@ class RLConfig(BaseConfig):
|
||||
|
||||
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
|
||||
|
||||
experimental: Annotated[
|
||||
RLExperimentalConfig,
|
||||
Field(description="Experimental features for RL training."),
|
||||
] = RLExperimentalConfig()
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -733,9 +742,8 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_session_headers(self):
|
||||
"""Auto-configure X-Session-ID header for sticky routing at the inference router."""
|
||||
if "extra_headers_from_state" not in self.orchestrator.client.model_fields_set:
|
||||
self.orchestrator.client.extra_headers_from_state = {"X-Session-ID": "example_id"}
|
||||
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
|
||||
self.orchestrator.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -159,6 +159,10 @@ SFTDeploymentConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class SFTExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for SFT training."""
|
||||
|
||||
|
||||
class SFTConfig(BaseConfig):
|
||||
"""Configures the SFT trainer"""
|
||||
|
||||
@@ -270,6 +274,11 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
|
||||
|
||||
experimental: Annotated[
|
||||
SFTExperimentalConfig,
|
||||
Field(description="Experimental features for SFT training."),
|
||||
] = SFTExperimentalConfig()
|
||||
|
||||
### Pre-validation normalization
|
||||
|
||||
@model_validator(mode="before")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -719,6 +719,10 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class TrainerExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for the trainer."""
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
"""Configures the RL trainer"""
|
||||
|
||||
@@ -837,6 +841,11 @@ class TrainerConfig(BaseConfig):
|
||||
),
|
||||
] = 1
|
||||
|
||||
experimental: Annotated[
|
||||
TrainerExperimentalConfig,
|
||||
Field(description="Experimental features for the trainer."),
|
||||
] = TrainerExperimentalConfig()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
|
||||
|
||||
@@ -13,6 +13,7 @@ import pynvml
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
@@ -547,15 +548,26 @@ 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)
|
||||
|
||||
if config.slurm is not None:
|
||||
rl_slurm(config)
|
||||
|
||||
@@ -9,6 +9,7 @@ from threading import Event, Thread
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir, validate_output_dir
|
||||
@@ -196,6 +197,9 @@ def sft(config: SFTConfig):
|
||||
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
|
||||
config.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if not config.dry_run:
|
||||
pre_download_model(config.model.name)
|
||||
|
||||
if config.slurm is not None:
|
||||
sft_slurm(config)
|
||||
else:
|
||||
|
||||
@@ -302,10 +302,14 @@ def _patch_lora_key_prefix():
|
||||
# is embedded: "...experts.N.down_proj". Taking everything
|
||||
# after ".experts" gives "experts.N.down_proj" which is
|
||||
# never in the expected set even though "down_proj" is.
|
||||
# Fix: always compare just the last component of the path.
|
||||
# Qwen3-30B-A3B goes the other way: the expected set
|
||||
# contains the fully-qualified per-expert name
|
||||
# ("experts.N.down_proj") but not the bare suffix.
|
||||
# Accept either form.
|
||||
if ".experts" in module_name:
|
||||
expert_suffix = module_name.split(".")[-1]
|
||||
if expert_suffix not in expected_lora_modules:
|
||||
experts_qualified = "experts" + module_name.split(".experts", 1)[-1]
|
||||
if expert_suffix not in expected_lora_modules and experts_qualified not in expected_lora_modules:
|
||||
unexpected_modules.append(module_name)
|
||||
|
||||
elif module_name.rsplit(".", 1)[-1] not in expected_lora_modules:
|
||||
@@ -957,18 +961,15 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
def monkey_patch_offloading_connector_cpu_block_count():
|
||||
"""Fix CPU block count miscalculation in OffloadingConnector.
|
||||
|
||||
CPUOffloadingSpec erroneously multiplies page_size_bytes by
|
||||
len(kv_cache_config.kv_cache_tensors) when computing kv_bytes_per_block.
|
||||
For UniformTypeKVCacheSpecs the page_size is already the total per-block
|
||||
size across all layers, so the extra multiplier makes num_blocks far too
|
||||
small. When the OffloadingManager later allocates block IDs past the
|
||||
undersized CPU tensor, swap_blocks (cuMemcpyDtoHAsync_v2) segfaults on the
|
||||
invalid pinned address.
|
||||
CPUOffloadingSpec derives kv_bytes_per_block from page_size_bytes multiplied
|
||||
by len(kv_cache_config.kv_cache_tensors), which double-counts: page_size is
|
||||
already aggregated across layers in the group. The undersized CPU pool then
|
||||
produces out-of-bounds block mappings and swap_blocks segfaults.
|
||||
|
||||
Fix: remove the num_tensors multiplier.
|
||||
Fix: derive kv_bytes_per_block from the actual total GPU KV tensor size
|
||||
divided by num_blocks, matching the upstream PR.
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/pull/38395
|
||||
Related: https://github.com/vllm-project/vllm/issues/39500
|
||||
Upstream: https://github.com/vllm-project/vllm/pull/39617
|
||||
"""
|
||||
from vllm.v1.kv_offload.cpu.spec import CPUOffloadingSpec
|
||||
|
||||
@@ -977,18 +978,18 @@ def monkey_patch_offloading_connector_cpu_block_count():
|
||||
def _patched_init(self, vllm_config, kv_cache_config):
|
||||
_original_init(self, vllm_config, kv_cache_config)
|
||||
|
||||
# Recalculate num_blocks WITHOUT the erroneous num_tensors multiplier.
|
||||
cpu_bytes_to_use = self.extra_config.get("cpu_bytes_to_use")
|
||||
if not cpu_bytes_to_use:
|
||||
return
|
||||
|
||||
page_sizes = {g.kv_cache_spec.page_size_bytes for g in kv_cache_config.kv_cache_groups}
|
||||
assert len(page_sizes) == 1
|
||||
page_size_bytes = page_sizes.pop()
|
||||
if kv_cache_config.num_blocks > 0:
|
||||
total_gpu_kv_bytes = sum(t.size for t in kv_cache_config.kv_cache_tensors)
|
||||
kv_bytes_per_block = (
|
||||
total_gpu_kv_bytes // kv_cache_config.num_blocks
|
||||
) * vllm_config.parallel_config.world_size
|
||||
else:
|
||||
kv_bytes_per_block = 0
|
||||
|
||||
# page_size_bytes already covers all layers in the group.
|
||||
# Only multiply by world_size (each TP rank stores its own copy).
|
||||
kv_bytes_per_block = page_size_bytes * vllm_config.parallel_config.world_size
|
||||
kv_bytes_per_offloaded_block = kv_bytes_per_block * self.block_size_factor
|
||||
self.num_blocks = (
|
||||
int(cpu_bytes_to_use) // kv_bytes_per_offloaded_block if kv_bytes_per_offloaded_block > 0 else 0
|
||||
|
||||
@@ -39,6 +39,9 @@ MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
# GLM-5
|
||||
"zai-org/GLM-5": "glm47",
|
||||
"zai-org/GLM-5-FP8": "glm47",
|
||||
# GLM-5.1
|
||||
"zai-org/GLM-5.1": "glm47",
|
||||
"zai-org/GLM-5.1-FP8": "glm47",
|
||||
# MiniMax M2
|
||||
"MiniMaxAI/MiniMax-M2": "minimax_m2",
|
||||
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
|
||||
@@ -195,23 +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"),))
|
||||
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 and reset 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.
|
||||
"""
|
||||
"""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)
|
||||
# Reset prefix cache to invalidate KV states computed with old weights
|
||||
await engine_client(raw_request).reset_prefix_cache()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from jaxtyping import Float, Int
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.orchestrator import AdvantageConfig, CustomAdvantageConfig
|
||||
from prime_rl.orchestrator.vf_utils import get_completion_len
|
||||
from prime_rl.orchestrator.vf_utils import get_model_completion_len
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -37,21 +37,54 @@ Expected signature:
|
||||
|
||||
def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_shaping_alpha: float | None = None,
|
||||
length_shaping: bool = False,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage: reward minus per-problem baseline."""
|
||||
rewards = inputs.rewards
|
||||
|
||||
if length_shaping_alpha is not None:
|
||||
if length_shaping:
|
||||
completion_lengths = inputs.completion_lengths.to(dtype=rewards.dtype)
|
||||
lengths_normalized = completion_lengths / completion_lengths.mean(dim=1, keepdim=True)
|
||||
length_shaping = (1 + length_shaping_alpha * lengths_normalized) ** -1
|
||||
rewards = rewards * length_shaping
|
||||
baseline = rewards.mean(dim=1, keepdim=True)
|
||||
return AdvantageOutputs(advantages=_efficiency_length_shaping(rewards, completion_lengths))
|
||||
|
||||
baseline = rewards.mean(dim=1, keepdim=True)
|
||||
return AdvantageOutputs(advantages=rewards - baseline)
|
||||
|
||||
|
||||
def _efficiency_length_shaping(
|
||||
rewards: Float[Tensor, "num_problems rollouts_per_example"],
|
||||
completion_lengths: Float[Tensor, "num_problems rollouts_per_example"],
|
||||
) -> Float[Tensor, "num_problems rollouts_per_example"]:
|
||||
"""Correctness-gated length shaping with bounded advantages.
|
||||
|
||||
Shapes rewards with a bounded brevity bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages per group.
|
||||
|
||||
Correct rollouts get reward amplified by up to 2x based on relative brevity.
|
||||
Incorrect rollouts are untouched. Shorter correct rollouts get higher advantage.
|
||||
"""
|
||||
max_reward = rewards.max(dim=1, keepdim=True).values
|
||||
correct_mask = rewards >= max_reward
|
||||
num_correct = correct_mask.sum(dim=1, keepdim=True)
|
||||
|
||||
# No shaping when max reward is 0 — no correct rollouts to differentiate
|
||||
has_correct = max_reward > 0
|
||||
|
||||
# Mean length of correct rollouts per problem
|
||||
correct_lengths = completion_lengths * correct_mask
|
||||
mean_correct_len = correct_lengths.sum(dim=1, keepdim=True) / num_correct.clamp(min=1)
|
||||
|
||||
# Bounded brevity bonus: [0, 1], positive for below-average length, zero for above
|
||||
bonus = (1 - completion_lengths / mean_correct_len).clamp(0, 1)
|
||||
|
||||
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
|
||||
shaped_rewards = rewards * (1 + bonus * correct_mask)
|
||||
baseline = shaped_rewards.mean(dim=1, keepdim=True)
|
||||
|
||||
shaped = shaped_rewards - baseline
|
||||
unshaped = rewards - rewards.mean(dim=1, keepdim=True)
|
||||
return torch.where(has_correct, shaped, unshaped)
|
||||
|
||||
|
||||
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
"""Setup advantage function from config."""
|
||||
if isinstance(config, CustomAdvantageConfig):
|
||||
@@ -66,7 +99,7 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
|
||||
return default_advantage_fn(
|
||||
inputs,
|
||||
length_shaping_alpha=config.length_shaping_alpha,
|
||||
length_shaping=config.length_shaping,
|
||||
)
|
||||
|
||||
return advantage_fn
|
||||
@@ -94,7 +127,7 @@ def compute_advantages(
|
||||
return
|
||||
|
||||
advantage_fn = setup_advantage_fn(advantage_config)
|
||||
completion_lengths = [get_completion_len(r) for r in rollouts]
|
||||
completion_lengths = [get_model_completion_len(r) for r in rollouts]
|
||||
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor(rewards).view(-1, samples_per_problem),
|
||||
|
||||
@@ -18,7 +18,7 @@ def run_server(config: EnvServerConfig):
|
||||
env_ids_to_install = set()
|
||||
env_ids_to_install.update(get_env_ids_to_install([config.env]))
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id)
|
||||
install_env(env_id, prerelease=config.env_install_prerelease)
|
||||
|
||||
log_dir = (get_log_dir(config.output_dir) / config.env.resolved_name).as_posix()
|
||||
|
||||
|
||||
@@ -104,18 +104,25 @@ class Env:
|
||||
self._env_server_process = process
|
||||
return address
|
||||
|
||||
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
|
||||
return sampling_args
|
||||
|
||||
async def run_rollout(
|
||||
self,
|
||||
client: vf.ClientConfig,
|
||||
example: dict,
|
||||
model_name: str,
|
||||
cache_salt: str,
|
||||
) -> vf.RolloutOutput:
|
||||
"""Run a single rollout for an example."""
|
||||
return await self.env.run_rollout(
|
||||
vf.RolloutInput(**example),
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling_args=self.sampling_args,
|
||||
sampling_args=self._sampling_args_with_salt(cache_salt),
|
||||
max_retries=self.config.max_retries,
|
||||
state_columns=REQUIRED_STATE_COLUMNS,
|
||||
env_client=self.env_client,
|
||||
@@ -127,13 +134,14 @@ class Env:
|
||||
example: dict,
|
||||
model_name: str,
|
||||
rollouts_per_example: int,
|
||||
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(
|
||||
[vf.RolloutInput(**example) for _ in range(rollouts_per_example)],
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling_args=self.sampling_args,
|
||||
sampling_args=self._sampling_args_with_salt(cache_salt),
|
||||
max_retries=self.config.max_retries,
|
||||
state_columns=REQUIRED_STATE_COLUMNS,
|
||||
env_client=self.env_client,
|
||||
@@ -171,6 +179,7 @@ class EvalEnv(Env):
|
||||
get_client: Callable[[], Awaitable[vf.ClientConfig]],
|
||||
ckpt_step: int,
|
||||
step: int,
|
||||
cache_salt: str,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
num_examples = len(self.examples)
|
||||
rollouts_per_example = self.config.rollouts_per_example
|
||||
@@ -190,6 +199,7 @@ class EvalEnv(Env):
|
||||
example=example,
|
||||
model_name=model_name,
|
||||
rollouts_per_example=rollouts_per_example,
|
||||
cache_salt=cache_salt,
|
||||
)
|
||||
pbar.update(rollouts_per_example)
|
||||
return outputs
|
||||
@@ -206,7 +216,9 @@ class EvalEnv(Env):
|
||||
"""Run a single rollout for one example."""
|
||||
try:
|
||||
client = await get_client()
|
||||
output = await self.run_rollout(client=client, example=example, model_name=model_name)
|
||||
output = await self.run_rollout(
|
||||
client=client, example=example, model_name=model_name, cache_salt=cache_salt
|
||||
)
|
||||
pbar.update(1)
|
||||
return [output]
|
||||
except Exception as e:
|
||||
@@ -338,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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
import wandb
|
||||
from httpx import AsyncClient
|
||||
from prometheus_client.parser import text_string_to_metric_families
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
POLL_INTERVAL = 5.0
|
||||
WINDOW_SIZE = 20
|
||||
|
||||
# Gauge metrics: collected as instantaneous values
|
||||
GAUGE_METRICS = {
|
||||
"vllm:num_requests_running",
|
||||
"vllm:num_requests_waiting",
|
||||
"vllm:gpu_cache_usage_perc",
|
||||
"vllm:gpu_prefix_cache_hit_rate",
|
||||
}
|
||||
|
||||
# Counter metrics: converted to per-second rates via delta/dt
|
||||
COUNTER_METRICS = {
|
||||
"vllm:prompt_tokens",
|
||||
"vllm:generation_tokens",
|
||||
"vllm:request_success",
|
||||
}
|
||||
|
||||
COUNTER_RATE_NAMES = {
|
||||
"vllm:prompt_tokens": "prefill_throughput_tps",
|
||||
"vllm:generation_tokens": "decode_throughput_tps",
|
||||
"vllm:request_success": "completed_requests_per_s",
|
||||
}
|
||||
|
||||
# Histogram metrics: converted to average latency per interval
|
||||
HISTOGRAM_METRICS = {
|
||||
"vllm:nixl_xfer_time_seconds",
|
||||
}
|
||||
|
||||
_COUNTER_TOTAL_TO_NAME = {f"{name}_total": name for name in COUNTER_METRICS}
|
||||
|
||||
# Gauges where we log both max and mean across engines (to show imbalance)
|
||||
_DUAL_AGG_GAUGES = {"vllm:gpu_cache_usage_perc", "vllm:gpu_prefix_cache_hit_rate"}
|
||||
|
||||
|
||||
def parse_prometheus_text(text: str) -> tuple[dict[str, float], dict[str, float], dict[str, tuple[float, float]]]:
|
||||
"""Parse Prometheus exposition format into (gauges, counters, histograms).
|
||||
|
||||
For gauge metrics, returns the per-server aggregate (sum for queue sizes,
|
||||
max for per-engine metrics like kv cache within a single server).
|
||||
"""
|
||||
gauges: dict[str, float] = {}
|
||||
counters: dict[str, float] = {}
|
||||
histograms: dict[str, tuple[float, float]] = {}
|
||||
|
||||
for family in text_string_to_metric_families(text):
|
||||
if family.type == "gauge" and family.name in GAUGE_METRICS:
|
||||
for sample in family.samples:
|
||||
if family.name in _DUAL_AGG_GAUGES:
|
||||
gauges[family.name] = max(gauges.get(family.name, 0.0), sample.value)
|
||||
else:
|
||||
gauges[family.name] = gauges.get(family.name, 0.0) + sample.value
|
||||
|
||||
elif family.type == "counter" and family.name in COUNTER_METRICS:
|
||||
for sample in family.samples:
|
||||
counters[family.name] = counters.get(family.name, 0.0) + sample.value
|
||||
|
||||
elif family.name in _COUNTER_TOTAL_TO_NAME:
|
||||
canonical = _COUNTER_TOTAL_TO_NAME[family.name]
|
||||
for sample in family.samples:
|
||||
counters[canonical] = counters.get(canonical, 0.0) + sample.value
|
||||
|
||||
elif family.type == "histogram" and family.name in HISTOGRAM_METRICS:
|
||||
h_sum = 0.0
|
||||
h_count = 0.0
|
||||
for sample in family.samples:
|
||||
if sample.name.endswith("_sum"):
|
||||
h_sum += sample.value
|
||||
elif sample.name.endswith("_count"):
|
||||
h_count += sample.value
|
||||
histograms[family.name] = (h_sum, h_count)
|
||||
|
||||
return gauges, counters, histograms
|
||||
|
||||
|
||||
class InferenceMetricsCollector:
|
||||
"""Polls vLLM Prometheus /metrics and logs aggregated values to W&B.
|
||||
|
||||
Runs independently of training steps on a time-based axis.
|
||||
"""
|
||||
|
||||
def __init__(self, admin_clients: list[AsyncClient]):
|
||||
self.admin_clients = admin_clients
|
||||
self.logger = get_logger()
|
||||
self._gauge_history: dict[str, deque[float]] = {}
|
||||
self._rate_history: dict[str, deque[float]] = {}
|
||||
self._prev_counters: dict[str, tuple[float, float]] = {}
|
||||
self._prev_histograms: dict[str, tuple[float, float, float]] = {}
|
||||
self._task: asyncio.Task | None = None
|
||||
|
||||
async def start(self):
|
||||
wandb.define_metric("inference/*", step_metric="_timestamp")
|
||||
|
||||
async def poll_loop():
|
||||
while True:
|
||||
try:
|
||||
await self._collect_and_log()
|
||||
except Exception as e:
|
||||
self.logger.debug(f"Inference metrics poll failed: {e!r}")
|
||||
await asyncio.sleep(POLL_INTERVAL)
|
||||
|
||||
self._task = asyncio.create_task(poll_loop())
|
||||
|
||||
async def _collect_and_log(self):
|
||||
now = time.monotonic()
|
||||
|
||||
async def fetch(client: AsyncClient) -> str | None:
|
||||
try:
|
||||
response = await client.get("/metrics", timeout=5.0)
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
except Exception as e:
|
||||
self.logger.debug(f"Failed to fetch metrics from {client.base_url}: {e!r}")
|
||||
return None
|
||||
|
||||
results = await asyncio.gather(*[fetch(client) for client in self.admin_clients])
|
||||
|
||||
# For dual-agg gauges, collect per-server values to compute both max and mean
|
||||
dual_agg_values: dict[str, list[float]] = {}
|
||||
agg_sum_gauges: dict[str, float] = {}
|
||||
agg_counters: dict[str, float] = {}
|
||||
agg_histograms: dict[str, tuple[float, float]] = {}
|
||||
n_servers = 0
|
||||
|
||||
for text in results:
|
||||
if text is None:
|
||||
continue
|
||||
n_servers += 1
|
||||
gauges, counters, histograms = parse_prometheus_text(text)
|
||||
|
||||
for name, value in gauges.items():
|
||||
if name in _DUAL_AGG_GAUGES:
|
||||
dual_agg_values.setdefault(name, []).append(value)
|
||||
else:
|
||||
agg_sum_gauges[name] = agg_sum_gauges.get(name, 0.0) + value
|
||||
|
||||
for name, value in counters.items():
|
||||
agg_counters[name] = agg_counters.get(name, 0.0) + value
|
||||
|
||||
for name, (h_sum, h_count) in histograms.items():
|
||||
prev = agg_histograms.get(name, (0.0, 0.0))
|
||||
agg_histograms[name] = (prev[0] + h_sum, prev[1] + h_count)
|
||||
|
||||
if n_servers == 0:
|
||||
return
|
||||
|
||||
# Update gauge history — sum gauges
|
||||
for name, value in agg_sum_gauges.items():
|
||||
short = name.removeprefix("vllm:")
|
||||
if short not in self._gauge_history:
|
||||
self._gauge_history[short] = deque(maxlen=WINDOW_SIZE)
|
||||
self._gauge_history[short].append(value)
|
||||
|
||||
# Update gauge history — dual-agg gauges (max + mean across engines)
|
||||
for name, values in dual_agg_values.items():
|
||||
short = name.removeprefix("vllm:")
|
||||
max_key = f"{short}_max"
|
||||
mean_key = f"{short}_mean"
|
||||
if max_key not in self._gauge_history:
|
||||
self._gauge_history[max_key] = deque(maxlen=WINDOW_SIZE)
|
||||
if mean_key not in self._gauge_history:
|
||||
self._gauge_history[mean_key] = deque(maxlen=WINDOW_SIZE)
|
||||
self._gauge_history[max_key].append(max(values))
|
||||
self._gauge_history[mean_key].append(sum(values) / len(values))
|
||||
|
||||
# Compute rates from counters
|
||||
for name, value in agg_counters.items():
|
||||
rate_name = COUNTER_RATE_NAMES[name]
|
||||
prev = self._prev_counters.get(name)
|
||||
self._prev_counters[name] = (now, value)
|
||||
if prev is None:
|
||||
continue
|
||||
prev_time, prev_value = prev
|
||||
dt = now - prev_time
|
||||
if dt <= 0:
|
||||
continue
|
||||
delta = value - prev_value
|
||||
if delta < 0:
|
||||
continue
|
||||
rate = delta / dt
|
||||
if rate_name not in self._rate_history:
|
||||
self._rate_history[rate_name] = deque(maxlen=WINDOW_SIZE)
|
||||
self._rate_history[rate_name].append(rate)
|
||||
|
||||
# Compute average histogram latency
|
||||
for name, (h_sum, h_count) in agg_histograms.items():
|
||||
short = name.removeprefix("vllm:")
|
||||
rate_name = f"{short}_avg_ms"
|
||||
prev = self._prev_histograms.get(name)
|
||||
self._prev_histograms[name] = (now, h_sum, h_count)
|
||||
if prev is None:
|
||||
continue
|
||||
prev_time, prev_sum, prev_count = prev
|
||||
d_sum = h_sum - prev_sum
|
||||
d_count = h_count - prev_count
|
||||
if d_count < 0 or d_sum < 0:
|
||||
continue
|
||||
if d_count > 0:
|
||||
avg_ms = (d_sum / d_count) * 1000.0
|
||||
if rate_name not in self._rate_history:
|
||||
self._rate_history[rate_name] = deque(maxlen=WINDOW_SIZE)
|
||||
self._rate_history[rate_name].append(avg_ms)
|
||||
|
||||
# Build smoothed metrics dict
|
||||
metrics: dict[str, float] = {}
|
||||
for short, values in self._gauge_history.items():
|
||||
if values:
|
||||
metrics[f"inference/{short}"] = sum(values) / len(values)
|
||||
for rate_name, values in self._rate_history.items():
|
||||
if values:
|
||||
metrics[f"inference/{rate_name}"] = sum(values) / len(values)
|
||||
|
||||
if metrics:
|
||||
metrics["_timestamp"] = time.time()
|
||||
wandb.log(metrics)
|
||||
|
||||
async def stop(self):
|
||||
if self._task is not None:
|
||||
self._task.cancel()
|
||||
try:
|
||||
await self._task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
self._task = None
|
||||
@@ -8,6 +8,7 @@ import tomli_w
|
||||
from prime_rl.orchestrator.advantage import compute_advantages
|
||||
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step
|
||||
from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.patches import monkey_patch_chat_completion_logprobs, monkey_patch_oai_iterable_types
|
||||
from prime_rl.orchestrator.trajectories import (
|
||||
build_vlm_image_cache,
|
||||
@@ -75,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):
|
||||
@@ -107,7 +113,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
env_ids_to_install.update(get_env_ids_to_install(config.eval.env))
|
||||
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id)
|
||||
install_env(env_id, prerelease=config.env_install_prerelease)
|
||||
|
||||
# Setup rollout inference pool (handles both static and elastic modes)
|
||||
rollout_client_config, rollout_model_name, enable_policy_updates = setup_external_rollout_model(config, logger)
|
||||
@@ -248,6 +254,12 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
logger.success("Inference pool ready")
|
||||
|
||||
# Start inference metrics collector (requires W&B)
|
||||
inference_metrics_collector = None
|
||||
if config.wandb is not None and config.collect_inference_metrics:
|
||||
inference_metrics_collector = InferenceMetricsCollector(inference_pool.admin_clients)
|
||||
await inference_metrics_collector.start()
|
||||
|
||||
# Check health of teacher inference server if configured
|
||||
if config.teacher_model and teacher_inference_pool:
|
||||
logger.info("Waiting for teacher inference pool to be ready")
|
||||
@@ -379,6 +391,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
get_client=inference_pool.get_eval_client,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
cache_salt=str(ckpt_step),
|
||||
)
|
||||
for eval_env in envs_to_eval
|
||||
]
|
||||
@@ -388,7 +401,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
eval_rollouts = [o for outputs in eval_results for o in outputs]
|
||||
if eval_rollouts:
|
||||
step_path = get_step_path(get_rollout_dir(config.output_dir), progress.step)
|
||||
await asyncio.to_thread(save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl")
|
||||
await asyncio.to_thread(
|
||||
save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl", exclude_keys={"trajectory"}
|
||||
)
|
||||
|
||||
# Resume weight updates
|
||||
scheduler.checkpoint_ready.set()
|
||||
@@ -396,17 +411,61 @@ 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)
|
||||
await asyncio.to_thread(save_rollouts, train_rollouts, step_path / "train_rollouts.jsonl")
|
||||
await asyncio.to_thread(
|
||||
save_rollouts, train_rollouts, step_path / "train_rollouts.jsonl", exclude_keys={"trajectory"}
|
||||
)
|
||||
|
||||
# VLM: offload base64 images to disk immediately to free memory
|
||||
if is_vlm:
|
||||
@@ -417,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()
|
||||
|
||||
@@ -462,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] = []
|
||||
@@ -472,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
|
||||
@@ -526,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,
|
||||
@@ -537,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())
|
||||
@@ -620,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,
|
||||
}
|
||||
@@ -660,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)
|
||||
@@ -711,6 +769,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
get_client=inference_pool.get_eval_client,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
cache_salt=str(ckpt_step),
|
||||
)
|
||||
for eval_env in eval_envs
|
||||
]
|
||||
@@ -720,7 +779,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
eval_rollouts = [o for outputs in eval_results for o in outputs]
|
||||
if eval_rollouts:
|
||||
step_path = get_step_path(get_rollout_dir(config.output_dir), progress.step)
|
||||
await asyncio.to_thread(save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl")
|
||||
await asyncio.to_thread(
|
||||
save_rollouts, eval_rollouts, step_path / "eval_rollouts.jsonl", exclude_keys={"trajectory"}
|
||||
)
|
||||
|
||||
# Log final (immutable) samples and distributions to monitor(s)
|
||||
monitor.log_final_samples()
|
||||
@@ -741,6 +802,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
async def _graceful_shutdown() -> None:
|
||||
training_batch_sender.close()
|
||||
await scheduler.stop()
|
||||
if inference_metrics_collector is not None:
|
||||
await inference_metrics_collector.stop()
|
||||
await inference_pool.stop()
|
||||
if teacher_inference_pool is not None:
|
||||
await teacher_inference_pool.stop()
|
||||
|
||||
@@ -196,6 +196,7 @@ class Scheduler:
|
||||
env_name = group.example["env_name"]
|
||||
env = self.train_envs.get(env_name)
|
||||
|
||||
cache_salt = str(self.ckpt_step)
|
||||
if env.requires_group_scoring:
|
||||
rollout_count = group.rollouts_to_schedule
|
||||
group.rollouts_to_schedule = 0
|
||||
@@ -205,6 +206,7 @@ class Scheduler:
|
||||
example=group.example,
|
||||
model_name=self.model_name,
|
||||
rollouts_per_example=rollout_count,
|
||||
cache_salt=cache_salt,
|
||||
)
|
||||
)
|
||||
else:
|
||||
@@ -215,6 +217,7 @@ class Scheduler:
|
||||
client=client_config,
|
||||
example=group.example,
|
||||
model_name=self.model_name,
|
||||
cache_salt=cache_salt,
|
||||
)
|
||||
)
|
||||
self.inflight_requests[task] = InflightRequest(
|
||||
@@ -429,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(
|
||||
@@ -444,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)
|
||||
|
||||
@@ -50,12 +50,22 @@ def get_completion_len(output: vf.RolloutOutput) -> int:
|
||||
return get_seq_len(output) - get_prompt_len(output)
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path) -> None:
|
||||
def get_model_completion_len(output: vf.RolloutOutput) -> int:
|
||||
"""
|
||||
Computes the number of model-generated completion tokens across all turns.
|
||||
Unlike get_completion_len, this excludes environment responses injected
|
||||
between turns in multi-turn rollouts.
|
||||
"""
|
||||
return sum(len(step["tokens"]["completion_ids"]) for step in output["trajectory"] if step.get("tokens"))
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
|
||||
"""Save rollouts to a JSONL file using verifiers serialization."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
for rollout in rollouts:
|
||||
json.dump(rollout, f, default=make_serializable)
|
||||
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
|
||||
json.dump(row, f, default=make_serializable)
|
||||
f.write("\n")
|
||||
|
||||
|
||||
|
||||
@@ -53,9 +53,23 @@ from prime_rl.trainer.weights import (
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import format_time
|
||||
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
|
||||
|
||||
|
||||
def pre_download_model(model_name: str) -> None:
|
||||
"""Pre-download model from HuggingFace Hub so all nodes have cached weights before training."""
|
||||
if Path(model_name).exists():
|
||||
get_logger().info(f"Model {model_name} found at local path, skipping download")
|
||||
return
|
||||
get_logger().info(f"Pre-downloading model {model_name}")
|
||||
t0 = time.perf_counter()
|
||||
path = snapshot_download(repo_id=model_name, repo_type="model")
|
||||
get_logger().debug(
|
||||
f"Finished pre-downloading model {model_name} to {path} in {format_time(time.perf_counter() - t0)}"
|
||||
)
|
||||
|
||||
|
||||
def _patch_qwen3_5_moe_conversion_mapping():
|
||||
"""Fix Qwen3.5 MoE conversion mapping incorrectly applying qwen2_moe expert weight splitting.
|
||||
|
||||
@@ -621,6 +635,11 @@ def can_reinit_empty_buffers(model: nn.Module):
|
||||
if len(buffer_names) == 1 and buffer_names[0] == "model.rotary_emb.inv_freq":
|
||||
return True
|
||||
|
||||
# GPT-OSS (has original_inv_freq alongside inv_freq from dynamic rope scaling)
|
||||
gpt_oss_buffers = {"model.rotary_emb.inv_freq", "model.rotary_emb.original_inv_freq"}
|
||||
if set(buffer_names) == gpt_oss_buffers:
|
||||
return True
|
||||
|
||||
# Gemma3 model (has embed_scale and local rotary emb)
|
||||
gemma3_buffers = {"model.embed_tokens.embed_scale", "model.rotary_emb.inv_freq", "model.rotary_emb_local.inv_freq"}
|
||||
if set(buffer_names) == gemma3_buffers:
|
||||
@@ -635,8 +654,21 @@ def fix_model_post_empty(model: nn.Module):
|
||||
# HF standard transformer model
|
||||
if "model.rotary_emb.inv_freq" in buffer_names:
|
||||
rotary_emb = model.model.rotary_emb
|
||||
inv_freq, rotary_emb.attention_scaling = rotary_emb.rope_init_fn(rotary_emb.config, rotary_emb.inv_freq.device)
|
||||
if hasattr(rotary_emb, "rope_init_fn"):
|
||||
rope_init_fn = rotary_emb.rope_init_fn
|
||||
else:
|
||||
# GPT-OSS stores rope_init_fn only as a local in __init__; re-derive it
|
||||
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
||||
|
||||
rope_init_fn = (
|
||||
ROPE_INIT_FUNCTIONS[rotary_emb.rope_type]
|
||||
if rotary_emb.rope_type != "default"
|
||||
else rotary_emb.compute_default_rope_parameters
|
||||
)
|
||||
inv_freq, rotary_emb.attention_scaling = rope_init_fn(rotary_emb.config, rotary_emb.inv_freq.device)
|
||||
rotary_emb.inv_freq.copy_(inv_freq)
|
||||
if "model.rotary_emb.original_inv_freq" in buffer_names:
|
||||
rotary_emb.original_inv_freq.copy_(inv_freq)
|
||||
# Gemma3 local rotary emb
|
||||
if "model.rotary_emb_local.inv_freq" in buffer_names:
|
||||
rotary_emb_local = model.model.rotary_emb_local
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
"""All-to-all context parallelism for Mamba-2 SSM layers.
|
||||
|
||||
Transposes between sequence-parallel and head-parallel layouts so that each
|
||||
CP rank processes the full sequence on a subset of heads, then transposes
|
||||
back. This avoids materializing the full [S, full_heads] tensor on any GPU.
|
||||
|
||||
Communication pattern per Mamba layer:
|
||||
1. in_proj (token-parallel, no comm)
|
||||
2. all-to-all: [B, S/cp, D] -> [B, S, D/cp] (seq-to-head)
|
||||
3. conv1d + SSM on full sequence, local heads
|
||||
4. all-to-all: [B, S, D/cp] -> [B, S/cp, D] (head-to-seq)
|
||||
5. out_proj (token-parallel, no comm)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
|
||||
|
||||
class _SeqToHeadParallel(torch.autograd.Function):
|
||||
"""[B, S/cp, D] -> [B, S, D/cp] via all-to-all."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
ctx.cp_group = cp_group
|
||||
ctx.cp_size = cp_size
|
||||
return _all_to_all_seq_to_head(x, cp_group, cp_size)
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
|
||||
return _all_to_all_head_to_seq(grad_output, ctx.cp_group, ctx.cp_size), None, None
|
||||
|
||||
|
||||
class _HeadToSeqParallel(torch.autograd.Function):
|
||||
"""[B, S, D/cp] -> [B, S/cp, D] via all-to-all."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
ctx.cp_group = cp_group
|
||||
ctx.cp_size = cp_size
|
||||
return _all_to_all_head_to_seq(x, cp_group, cp_size)
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
|
||||
return _all_to_all_seq_to_head(grad_output, ctx.cp_group, ctx.cp_size), None, None
|
||||
|
||||
|
||||
def _all_to_all_seq_to_head(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
"""Transpose [B, S_local, D] -> [B, S_global, D_local] via all-to-all.
|
||||
|
||||
Each rank sends its S_local tokens split into cp_size chunks along D,
|
||||
and receives one D_local chunk from each of the cp_size ranks.
|
||||
"""
|
||||
B, S_local, D = x.shape
|
||||
D_local = D // cp_size
|
||||
|
||||
# Split D into cp_size chunks, put cp dim first for all_to_all scatter
|
||||
# [B, S_local, D] -> [B, S_local, cp, D_local] -> [cp, B, S_local, D_local]
|
||||
x = x.reshape(B, S_local, cp_size, D_local).permute(2, 0, 1, 3).contiguous()
|
||||
output = torch.empty_like(x)
|
||||
dist.all_to_all_single(output, x, group=cp_group)
|
||||
# output[i] = data from rank i (its S_local tokens, our D_local slice)
|
||||
# [cp, B, S_local, D_local] -> [B, cp, S_local, D_local] -> [B, cp*S_local, D_local]
|
||||
return output.permute(1, 0, 2, 3).reshape(B, cp_size * S_local, D_local).contiguous()
|
||||
|
||||
|
||||
def _all_to_all_head_to_seq(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
"""Transpose [B, S_global, D_local] -> [B, S_local, D] via all-to-all.
|
||||
|
||||
Inverse of _all_to_all_seq_to_head.
|
||||
"""
|
||||
B, S_global, D_local = x.shape
|
||||
S_local = S_global // cp_size
|
||||
|
||||
# Split S_global into cp_size chunks (one per rank), put cp dim first for scatter
|
||||
# [B, S_global, D_local] -> [B, cp, S_local, D_local] -> [cp, B, S_local, D_local]
|
||||
x = x.reshape(B, cp_size, S_local, D_local).permute(1, 0, 2, 3).contiguous()
|
||||
output = torch.empty_like(x)
|
||||
dist.all_to_all_single(output, x, group=cp_group)
|
||||
# Each rank now has cp chunks of [B, S_local, D_local] — one D_local slice from each rank
|
||||
# [cp, B, S_local, D_local] -> [B, S_local, cp, D_local] -> [B, S_local, D]
|
||||
return output.permute(1, 2, 0, 3).reshape(B, S_local, cp_size * D_local).contiguous()
|
||||
|
||||
|
||||
def seq_to_head_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
"""[B, S/cp, D] -> [B, S, D/cp] with correct backward."""
|
||||
return _SeqToHeadParallel.apply(x, cp_group, cp_size)
|
||||
|
||||
|
||||
def head_to_seq_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size: int) -> torch.Tensor:
|
||||
"""[B, S, D/cp] -> [B, S/cp, D] with correct backward."""
|
||||
return _HeadToSeqParallel.apply(x, cp_group, cp_size)
|
||||
|
||||
|
||||
def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessGroup, cp_rank: int, cp_size: int):
|
||||
"""CP-aware Mamba-2 forward: in_proj -> all-to-all -> conv+SSM(local heads) -> all-to-all -> out_proj.
|
||||
|
||||
Replaces the mixer's cuda_kernels_forward when CP > 1. Parameters are
|
||||
sliced at runtime so FSDP / checkpoint shapes are unchanged.
|
||||
"""
|
||||
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined
|
||||
|
||||
batch_size, seq_len, _ = hidden_states.shape # seq_len = S/cp here
|
||||
|
||||
# ── 1. in_proj (token-parallel, no communication needed) ──
|
||||
projected_states = mixer.in_proj(hidden_states)
|
||||
A = -torch.exp(mixer.A_log.float())
|
||||
|
||||
gate, hidden_states_B_C, time_step = torch.split(
|
||||
projected_states,
|
||||
[mixer.intermediate_size, mixer.conv_dim, mixer.num_heads],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
# ── 2. All-to-all: seq-parallel -> head-parallel ──
|
||||
# gate: [B, S/cp, nheads * hdim] -> [B, S, (nheads/cp) * hdim]
|
||||
# hidden_states_B_C: [B, S/cp, nheads*hdim + 2*ngroups*dstate] -> [B, S, ...]
|
||||
# time_step: [B, S/cp, nheads] -> [B, S, nheads/cp]
|
||||
gate = seq_to_head_parallel(gate, cp_group, cp_size)
|
||||
time_step = seq_to_head_parallel(time_step, cp_group, cp_size)
|
||||
|
||||
# hidden_states_B_C needs special handling: x part shards by heads, B/C parts shard by groups
|
||||
# conv_dim = intermediate_size + 2 * ngroups * dstate
|
||||
groups_time_state_size = mixer.n_groups * mixer.ssm_state_size
|
||||
x_part, B_part, C_part = torch.split(
|
||||
hidden_states_B_C,
|
||||
[mixer.intermediate_size, groups_time_state_size, groups_time_state_size],
|
||||
dim=-1,
|
||||
)
|
||||
x_part = seq_to_head_parallel(x_part, cp_group, cp_size)
|
||||
B_part = seq_to_head_parallel(B_part, cp_group, cp_size)
|
||||
C_part = seq_to_head_parallel(C_part, cp_group, cp_size)
|
||||
hidden_states_B_C = torch.cat([x_part, B_part, C_part], dim=-1)
|
||||
|
||||
full_seq_len = hidden_states_B_C.shape[1] # S (full sequence)
|
||||
|
||||
# ── 3. Local head dimensions ──
|
||||
local_num_heads = mixer.num_heads // cp_size
|
||||
local_intermediate_size = local_num_heads * mixer.head_dim
|
||||
local_n_groups = mixer.n_groups // cp_size
|
||||
|
||||
# Slice parameters for local heads
|
||||
head_start = cp_rank * local_num_heads
|
||||
head_end = head_start + local_num_heads
|
||||
|
||||
local_A = A[head_start:head_end]
|
||||
local_D = mixer.D[head_start:head_end]
|
||||
local_dt_bias = mixer.dt_bias[head_start:head_end]
|
||||
|
||||
# Slice conv1d weight/bias for local channels
|
||||
# conv1d channels = intermediate_size + 2 * ngroups * dstate (same as conv_dim)
|
||||
# After all-to-all, we have local channels: local_intermediate + 2 * local_ngroups * dstate
|
||||
local_conv_dim = local_intermediate_size + 2 * local_n_groups * mixer.ssm_state_size
|
||||
conv_x_start = cp_rank * local_intermediate_size
|
||||
conv_x_end = conv_x_start + local_intermediate_size
|
||||
conv_b_start = mixer.intermediate_size + cp_rank * local_n_groups * mixer.ssm_state_size
|
||||
conv_b_end = conv_b_start + local_n_groups * mixer.ssm_state_size
|
||||
conv_c_start = mixer.intermediate_size + groups_time_state_size + cp_rank * local_n_groups * mixer.ssm_state_size
|
||||
conv_c_end = conv_c_start + local_n_groups * mixer.ssm_state_size
|
||||
|
||||
conv_indices = torch.cat(
|
||||
[
|
||||
torch.arange(conv_x_start, conv_x_end, device=mixer.conv1d.weight.device),
|
||||
torch.arange(conv_b_start, conv_b_end, device=mixer.conv1d.weight.device),
|
||||
torch.arange(conv_c_start, conv_c_end, device=mixer.conv1d.weight.device),
|
||||
]
|
||||
)
|
||||
local_conv_weight = mixer.conv1d.weight[conv_indices]
|
||||
local_conv_bias = mixer.conv1d.bias[conv_indices] if mixer.conv1d.bias is not None else None
|
||||
|
||||
# ── 4. Conv1d on full sequence, local heads ──
|
||||
hidden_states_B_C = torch.nn.functional.silu(
|
||||
torch.nn.functional.conv1d(
|
||||
hidden_states_B_C.transpose(1, 2),
|
||||
local_conv_weight,
|
||||
local_conv_bias,
|
||||
groups=local_conv_dim,
|
||||
padding=mixer.conv1d.weight.shape[2] - 1,
|
||||
).transpose(1, 2)[:, :full_seq_len]
|
||||
)
|
||||
|
||||
local_groups_time_state_size = local_n_groups * mixer.ssm_state_size
|
||||
hidden_states_local, B_local, C_local = torch.split(
|
||||
hidden_states_B_C,
|
||||
[local_intermediate_size, local_groups_time_state_size, local_groups_time_state_size],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
# ── 5. SSM scan on full sequence, local heads ──
|
||||
dt_limit_kwargs = {} if mixer.time_step_limit is None else {"dt_limit": mixer.time_step_limit}
|
||||
|
||||
scan_output, _ = mamba_chunk_scan_combined(
|
||||
hidden_states_local.view(batch_size, full_seq_len, local_num_heads, mixer.head_dim),
|
||||
time_step,
|
||||
local_A,
|
||||
B_local.view(batch_size, full_seq_len, local_n_groups, -1),
|
||||
C_local.view(batch_size, full_seq_len, local_n_groups, -1),
|
||||
chunk_size=mixer.chunk_size,
|
||||
D=local_D,
|
||||
z=None,
|
||||
seq_idx=None,
|
||||
return_final_states=True,
|
||||
dt_bias=local_dt_bias,
|
||||
dt_softplus=True,
|
||||
**dt_limit_kwargs,
|
||||
)
|
||||
scan_output = scan_output.view(batch_size, full_seq_len, local_intermediate_size)
|
||||
|
||||
# ── 6. Gated RMSNorm with local weights ──
|
||||
# Zamba2RMSNormGated normalizes within groups of size `group_size`.
|
||||
# In head-parallel mode, we have local_intermediate_size features.
|
||||
# The group_size stays the same, but group_count is reduced.
|
||||
local_norm_weight = mixer.norm.weight[cp_rank * local_intermediate_size : (cp_rank + 1) * local_intermediate_size]
|
||||
scan_output = _gated_rms_norm(
|
||||
scan_output, gate, local_norm_weight, mixer.norm.variance_epsilon, mixer.norm.group_size
|
||||
)
|
||||
|
||||
# ── 7. All-to-all: head-parallel -> seq-parallel ──
|
||||
scan_output = head_to_seq_parallel(scan_output, cp_group, cp_size)
|
||||
|
||||
# ── 8. out_proj (token-parallel, no communication needed) ──
|
||||
return mixer.out_proj(scan_output)
|
||||
|
||||
|
||||
def _gated_rms_norm(
|
||||
x: torch.Tensor, gate: torch.Tensor, weight: torch.Tensor, eps: float, group_size: int
|
||||
) -> torch.Tensor:
|
||||
"""Gated RMSNorm matching Zamba2RMSNormGated: gate -> group-wise RMSNorm -> weight."""
|
||||
input_dtype = x.dtype
|
||||
x = x.to(torch.float32)
|
||||
if gate is not None:
|
||||
x = x * torch.nn.functional.silu(gate.to(torch.float32))
|
||||
*prefix_dims, last_dim = x.shape
|
||||
group_count = last_dim // group_size
|
||||
x_grouped = x.view(*prefix_dims, group_count, group_size)
|
||||
variance = x_grouped.pow(2).mean(-1, keepdim=True)
|
||||
x_grouped = x_grouped * torch.rsqrt(variance + eps)
|
||||
x = x_grouped.view(*prefix_dims, last_dim)
|
||||
return (weight * x).to(input_dtype)
|
||||
@@ -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],
|
||||
)
|
||||
|
||||
@@ -9,6 +9,7 @@ Hybrid Mamba-Transformer-MoE architecture with three distinct layer types:
|
||||
from typing import Optional
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch import Tensor, nn
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
@@ -18,6 +19,7 @@ from transformers.utils import auto_docstring, logging
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.cp_mamba import mamba_cp_forward
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, NemotronHRouter, NonGatedGroupedExperts
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
@@ -113,7 +115,12 @@ def _ensure_zamba2_compat(config: NemotronHConfig):
|
||||
|
||||
|
||||
class NemotronHMambaLayer(GradientCheckpointingLayer):
|
||||
"""Mamba-2 SSM layer: norm -> NemotronHMamba2Mixer -> residual."""
|
||||
"""Mamba-2 SSM layer: norm -> NemotronHMamba2Mixer -> residual.
|
||||
|
||||
With context parallelism, uses all-to-all head partitioning: transposes
|
||||
from sequence-parallel to head-parallel before the SSM, so each CP rank
|
||||
processes the full sequence on a subset of heads, then transposes back.
|
||||
"""
|
||||
|
||||
def __init__(self, config: NemotronHConfig, layer_idx: int):
|
||||
super().__init__()
|
||||
@@ -123,6 +130,21 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
|
||||
self.mamba = NemotronHMamba2Mixer(config, layer_idx=layer_idx)
|
||||
self.mlp = None # No MoE in this layer type
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
assert self.mamba.num_heads % cp_world_size == 0, (
|
||||
f"num_heads ({self.mamba.num_heads}) must be divisible by cp_world_size ({cp_world_size})"
|
||||
)
|
||||
assert self.mamba.n_groups % cp_world_size == 0, (
|
||||
f"n_groups ({self.mamba.n_groups}) must be divisible by cp_world_size ({cp_world_size})"
|
||||
)
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
|
||||
@property
|
||||
def cp_enabled(self) -> bool:
|
||||
return hasattr(self, "_cp_group")
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -132,7 +154,12 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.norm(hidden_states)
|
||||
hidden_states = self.mamba(hidden_states)
|
||||
if self.cp_enabled:
|
||||
hidden_states = mamba_cp_forward(
|
||||
self.mamba, hidden_states, self._cp_group, self._cp_rank, self._cp_world_size
|
||||
)
|
||||
else:
|
||||
hidden_states = self.mamba(hidden_states)
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
|
||||
@@ -188,10 +188,11 @@ def train(config: TrainerConfig):
|
||||
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
|
||||
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
|
||||
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
|
||||
from prime_rl.utils.cp import setup_hybrid_cp, setup_sparse_mla_cp
|
||||
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
|
||||
|
||||
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
|
||||
# Optionally, resume training from a checkpoint
|
||||
progress = Progress()
|
||||
|
||||
@@ -109,7 +109,7 @@ def train(config: SFTConfig):
|
||||
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank()
|
||||
substitute_hf_flash_attn(cp_group, heads_k_stride=1)
|
||||
substitute_ring_attn(cp_group, heads_k_stride=1, attn_impl=config.model.attn)
|
||||
from prime_rl.utils.cp import setup_hybrid_cp, setup_sparse_mla_cp
|
||||
from prime_rl.utils.cp import setup_hybrid_cp, setup_nemotron_h_cp, setup_sparse_mla_cp
|
||||
|
||||
# Set up checkpoint manager
|
||||
logger.info(f"Initializing checkpoint managers ({config.ckpt})")
|
||||
@@ -131,6 +131,7 @@ def train(config: SFTConfig):
|
||||
if parallel_dims.cp_enabled:
|
||||
setup_hybrid_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
setup_nemotron_h_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
|
||||
if config.model.lora is not None:
|
||||
multi_run_manager = get_multi_run_manager()
|
||||
|
||||
@@ -185,7 +185,7 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
return AsyncClient(
|
||||
base_url=base_url,
|
||||
headers=headers,
|
||||
limits=httpx.Limits(max_connections=1, max_keepalive_connections=0),
|
||||
limits=httpx.Limits(max_connections=4, max_keepalive_connections=1),
|
||||
timeout=httpx.Timeout(None),
|
||||
)
|
||||
|
||||
|
||||
@@ -36,6 +36,27 @@ def setup_hybrid_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int,
|
||||
get_logger().info(f"Configured hybrid CP on {count} DeltaNet modules (fla native state passing)")
|
||||
|
||||
|
||||
def setup_nemotron_h_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
"""Configure NemotronH Mamba layers for context-parallel gather/scatter."""
|
||||
layers = None
|
||||
if hasattr(model, "model") and hasattr(model.model, "layers"):
|
||||
layers = model.model.layers
|
||||
|
||||
if layers is None:
|
||||
return
|
||||
|
||||
count = 0
|
||||
for layer in layers:
|
||||
if hasattr(layer, "mamba") and hasattr(layer, "set_context_parallel_attributes"):
|
||||
layer.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
count += 1
|
||||
|
||||
if count > 0:
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
get_logger().info(f"Configured NemotronH CP on {count} Mamba layers (all-to-all head partitioning)")
|
||||
|
||||
|
||||
def setup_sparse_mla_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
"""Configure GLM-5 sparse MLA modules for context-parallel gather/scatter."""
|
||||
|
||||
|
||||
@@ -183,6 +183,7 @@ class ElasticInferencePool:
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
dp_rank_count=self.client_config.dp_rank_count,
|
||||
extra_headers_from_state=self.client_config.extra_headers_from_state,
|
||||
)
|
||||
self._train_clients = setup_clients(url_config, client_type=self.train_client_type) if urls else []
|
||||
self._eval_clients = setup_clients(url_config, client_type=self.eval_client_type) if urls else []
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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),
|
||||
|
||||
+28
-21
@@ -206,27 +206,32 @@ def to_row_format(dict_of_lists: dict[str, list[Any]]) -> list[dict[str, Any]]:
|
||||
return [dict(zip(dict_of_lists.keys(), values)) for values in zip(*dict_of_lists.values())]
|
||||
|
||||
|
||||
def format_time(time_in_seconds: float) -> str:
|
||||
"""Format a time in seconds to a human-readable format."""
|
||||
from datetime import timedelta
|
||||
|
||||
td = timedelta(seconds=time_in_seconds)
|
||||
days = td.days
|
||||
hours, remainder = divmod(td.seconds, 3600)
|
||||
minutes, seconds = divmod(remainder, 60)
|
||||
|
||||
# Format based on magnitude
|
||||
if days > 0:
|
||||
total_hours = days * 24 + hours
|
||||
return f"{total_hours + minutes / 60:.2f}h"
|
||||
elif hours > 0:
|
||||
return f"{hours + minutes / 60:.2f}h"
|
||||
elif minutes > 0:
|
||||
return f"{minutes + seconds / 60:.2f}m"
|
||||
def format_time(time_s: float) -> str:
|
||||
"""
|
||||
Format a time in seconds to a human-readable format:
|
||||
- >1d -> Xd Yh
|
||||
- >1h -> Xh Ym
|
||||
- >1m -> Xm Ys
|
||||
- <1s -> Xms
|
||||
- Else: Xs
|
||||
"""
|
||||
if time_s >= 86400:
|
||||
d = time_s // 86400
|
||||
h = (time_s % 86400) // 3600
|
||||
return f"{d:.0f}d" + (f" {h:.0f}h" if h > 0 else "")
|
||||
elif time_s >= 3600:
|
||||
h = time_s // 3600
|
||||
m = (time_s % 3600) // 60
|
||||
return f"{h:.0f}h" + (f" {m:.0f}m" if m > 0 else "")
|
||||
elif time_s >= 60:
|
||||
m = time_s // 60
|
||||
s = (time_s % 60) // 1
|
||||
return f"{m:.0f}m" + (f" {s:.0f}s" if s > 0 else "")
|
||||
elif time_s < 1:
|
||||
ms = time_s * 1e3
|
||||
return f"{ms:.0f}ms"
|
||||
else:
|
||||
# Include microseconds for sub-second precision
|
||||
total_seconds = seconds + td.microseconds / 1_000_000
|
||||
return f"{total_seconds:.2f}s"
|
||||
return f"{time_s:.0f}s"
|
||||
|
||||
|
||||
def format_num(num: float | int, precision: int = 2) -> str:
|
||||
@@ -297,11 +302,13 @@ def default_dtype(dtype):
|
||||
torch.set_default_dtype(prev)
|
||||
|
||||
|
||||
def install_env(env_id: str) -> None:
|
||||
def install_env(env_id: str, prerelease: bool = False) -> None:
|
||||
"""Install an environment in subprocess."""
|
||||
logger = get_logger()
|
||||
logger.info(f"Installing environment {env_id}")
|
||||
install_cmd = ["uv", "run", "--no-sync", "prime", "env", "install", env_id]
|
||||
if prerelease:
|
||||
install_cmd.insert(-1, "--prerelease")
|
||||
result = subprocess.run(install_cmd, capture_output=True, text=True)
|
||||
for line in result.stdout.splitlines():
|
||||
if line.strip():
|
||||
|
||||
@@ -22,18 +22,157 @@ def test_default_advantage_fn_simple_mean():
|
||||
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
|
||||
|
||||
|
||||
def test_default_advantage_fn_gr3_length_shaping():
|
||||
def test_efficiency_mixed_group():
|
||||
"""Mixed group: reward shaping preserves zero-mean, shorter correct gets higher advantage."""
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor([[1.0, 0.5, 0.8]]),
|
||||
completion_lengths=torch.tensor([[10, 20, 10]]),
|
||||
rewards=torch.tensor([[1.0, 1.0, 0.0, 1.0]]),
|
||||
completion_lengths=torch.tensor([[10, 30, 20, 20]]),
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
|
||||
result = default_advantage_fn(inputs, length_shaping_alpha=0.33)
|
||||
|
||||
expected = torch.tensor([[0.20915856, -0.25799648, 0.04883792]])
|
||||
# mean_correct_len = (10+30+20)/3 = 20
|
||||
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
|
||||
# shaped_rewards = R * (1 + bonus * correct_mask) = [1.5, 1, 0, 1]
|
||||
# baseline = mean(shaped_rewards) = 0.875
|
||||
# A = shaped_rewards - baseline = [0.625, 0.125, -0.875, 0.125]
|
||||
expected = torch.tensor([[0.625, 0.125, -0.875, 0.125]])
|
||||
assert torch.allclose(result.advantages, expected, atol=1e-6)
|
||||
|
||||
# Zero-mean per group
|
||||
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(1), atol=1e-6)
|
||||
|
||||
# All correct rollouts have positive advantage
|
||||
correct_mask = inputs.rewards[0] >= 1.0
|
||||
assert (result.advantages[0][correct_mask] > 0).all()
|
||||
|
||||
|
||||
def test_efficiency_all_correct_group():
|
||||
"""All-correct group: zero-mean, shorter gets higher advantage."""
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor([[1.0, 1.0, 1.0]]),
|
||||
completion_lengths=torch.tensor([[10, 20, 40]]),
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
|
||||
# mean_len = 70/3 ≈ 23.33
|
||||
# bonus = clamp(1 - [10, 20, 40] / (70/3), 0, 1) = [4/7, 1/7, 0]
|
||||
# shaped_rewards = [1+4/7, 1+1/7, 1] = [11/7, 8/7, 1]
|
||||
# baseline = mean = (11/7 + 8/7 + 1) / 3 = (11+8+7)/(7*3) = 26/21
|
||||
# A = shaped - baseline
|
||||
shaped = torch.tensor([[11.0 / 7, 8.0 / 7, 1.0]])
|
||||
baseline = shaped.mean(dim=1, keepdim=True)
|
||||
expected = shaped - baseline
|
||||
assert torch.allclose(result.advantages, expected, atol=1e-6)
|
||||
|
||||
# Zero-mean
|
||||
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(1), atol=1e-6)
|
||||
|
||||
# Shortest has highest advantage
|
||||
assert result.advantages[0, 0] > result.advantages[0, 1] > result.advantages[0, 2]
|
||||
|
||||
|
||||
def test_efficiency_all_zero_rewards():
|
||||
"""When all rewards are 0, no length shaping — falls back to standard GRPO."""
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor([[0.0, 0.0, 0.0]]),
|
||||
completion_lengths=torch.tensor([[10, 20, 15]]),
|
||||
)
|
||||
result_with = default_advantage_fn(inputs, length_shaping=True)
|
||||
result_without = default_advantage_fn(inputs)
|
||||
|
||||
assert torch.allclose(result_with.advantages, result_without.advantages, atol=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_single_correct():
|
||||
"""Single correct rollout: bonus=0 (at its own mean), same as standard GRPO."""
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor([[1.0, 0.0, 0.0, 0.0]]),
|
||||
completion_lengths=torch.tensor([[100, 50, 200, 150]]),
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
|
||||
expected = torch.tensor([[0.75, -0.25, -0.25, -0.25]])
|
||||
assert torch.allclose(result.advantages, expected, atol=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_shorter_correct_higher_advantage():
|
||||
"""Among correct rollouts in a mixed group, shorter always gets higher advantage."""
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor([[1.0, 1.0, 1.0, 0.0, 0.0]]),
|
||||
completion_lengths=torch.tensor([[50, 100, 200, 80, 120]]),
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
|
||||
advs = result.advantages[0]
|
||||
assert advs[0] > advs[1] > advs[2]
|
||||
assert (advs[:3] > 0).all()
|
||||
assert (advs[3:] < 0).all()
|
||||
|
||||
|
||||
def test_efficiency_zero_mean_per_group():
|
||||
"""Reward shaping preserves zero-mean advantages per group."""
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor(
|
||||
[
|
||||
[1.0, 1.0, 0.0, 1.0], # mixed
|
||||
[1.0, 1.0, 1.0, 1.0], # all correct
|
||||
]
|
||||
),
|
||||
completion_lengths=torch.tensor(
|
||||
[
|
||||
[10, 30, 20, 20],
|
||||
[10, 20, 40, 80],
|
||||
]
|
||||
),
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
|
||||
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_amplification_bounded():
|
||||
"""Even with extreme length outliers, reward amplification is capped at 2x."""
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor([[1.0, 1.0, 0.0]]),
|
||||
completion_lengths=torch.tensor([[1, 10000, 5000]]),
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
|
||||
# Shortest correct gets bonus ≈ 1, so shaped_reward ≈ 2
|
||||
# Standard reward = 1, so amplification ≈ 2x
|
||||
# shaped_rewards ≈ [2, 1, 0], baseline ≈ 1, max advantage ≈ 1
|
||||
assert result.advantages[0, 0] < 1.0 + 1e-3
|
||||
|
||||
|
||||
def test_efficiency_multiple_problems():
|
||||
"""Handles multiple problems independently."""
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor(
|
||||
[
|
||||
[1.0, 1.0, 0.0], # mixed
|
||||
[1.0, 1.0, 1.0], # all correct
|
||||
]
|
||||
),
|
||||
completion_lengths=torch.tensor(
|
||||
[
|
||||
[10, 20, 15],
|
||||
[10, 20, 40],
|
||||
]
|
||||
),
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
|
||||
# Row 0: mixed group — shorter correct > longer correct
|
||||
assert result.advantages[0, 0] > result.advantages[0, 1]
|
||||
assert (result.advantages[0, :2] > 0).all()
|
||||
assert result.advantages[0, 2] < 0
|
||||
|
||||
# Row 1: all-correct group — shorter gets higher advantage
|
||||
assert result.advantages[1, 0] > result.advantages[1, 1] > result.advantages[1, 2]
|
||||
|
||||
# Both rows have zero-mean
|
||||
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
|
||||
|
||||
|
||||
def _make_rollout(reward: float, completion_len: int) -> dict:
|
||||
"""Create a minimal rollout dict for advantage testing."""
|
||||
@@ -52,9 +191,7 @@ def test_compute_advantages_with_config():
|
||||
|
||||
advantages = [r["advantage"] for r in rollouts]
|
||||
assert len(advantages) == 6
|
||||
# First 3 should sum to ~0 (mean subtracted)
|
||||
assert abs(sum(advantages[:3])) < 1e-5
|
||||
# Last 3 should sum to ~0
|
||||
assert abs(sum(advantages[3:])) < 1e-5
|
||||
|
||||
|
||||
@@ -65,7 +202,6 @@ def test_compute_advantages_without_config():
|
||||
|
||||
compute_advantages(rollouts, samples_per_problem=3, advantage_config=None)
|
||||
|
||||
# Without config, returns raw rewards
|
||||
advantages = [r["advantage"] for r in rollouts]
|
||||
assert advantages == rewards
|
||||
|
||||
@@ -84,7 +220,6 @@ def test_setup_advantage_fn_with_custom_config():
|
||||
|
||||
result = advantage_fn(inputs)
|
||||
assert isinstance(result, AdvantageOutputs)
|
||||
# Dummy just multiplies rewards by scale
|
||||
assert torch.allclose(result.advantages, torch.tensor([[2.0, 1.0, 1.6]]))
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -13,6 +13,8 @@ from prime_rl.inference.vllm.server import resolve_tool_call_parser
|
||||
# GLM-4.7
|
||||
("zai-org/GLM-4.7", "glm47"),
|
||||
("zai-org/GLM-4.7-Flash", "glm47"),
|
||||
# GLM-5.1
|
||||
("zai-org/GLM-5.1", "glm47"),
|
||||
# MiniMax
|
||||
("MiniMaxAI/MiniMax-M2", "minimax_m2"),
|
||||
("MiniMaxAI/MiniMax-M2.1", "minimax_m2"),
|
||||
|
||||
@@ -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]"
|
||||
)
|
||||
|
||||
@@ -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]]
|
||||
@@ -1014,6 +1014,12 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a0/61/5c78b91c3143ed5c14207f463aecfc8f9dbb5092fb2869baf37c273b2705/gitdb-4.0.12-py3-none-any.whl", hash = "sha256:67073e15955400952c6565cc3e707c554a4eea2e428946f7a4c162fab9bd9bcf", size = 62794, upload-time = "2025-01-02T07:20:43.624Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gitignore-parser"
|
||||
version = "0.1.13"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/e5/51/e391a1a4238f18d0abb47be479b07af265ad4519022cf51b7da47ef82487/gitignore_parser-0.1.13.tar.gz", hash = "sha256:c7e10c8190accb8ae57fb3711889e73a9c0dbc04d4222b91ace8a4bf64d2f746", size = 5603, upload-time = "2025-08-25T06:33:22.704Z" }
|
||||
|
||||
[[package]]
|
||||
name = "gitpython"
|
||||
version = "3.1.45"
|
||||
@@ -1588,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]]
|
||||
@@ -2600,11 +2606,12 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "prime"
|
||||
version = "0.5.37"
|
||||
version = "0.5.63"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "build", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "cryptography", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "gitignore-parser", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "httpx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "prime-evals", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "prime-sandboxes", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -2615,9 +2622,9 @@ dependencies = [
|
||||
{ name = "typer", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "verifiers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/80/d6/3ee8ab09233346fd3a9b99b519126d624e44a3711b3ba4968e0d338dfadc/prime-0.5.37.tar.gz", hash = "sha256:fa9ac54e36c3b77566eba708a943a897aff63c86ad842a4caa18c62baf48d0fd", size = 294164, upload-time = "2026-02-13T12:08:07.739Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0e/39/d33077f9e3e0c0558c81ab0cfda07f26de84d25ea1ec267d707c1acae24a/prime-0.5.63.tar.gz", hash = "sha256:63ebb306550239f3194b44e289916db89e5381badef15495eca8ea38b91d2347", size = 327336, upload-time = "2026-04-14T22:31:21.671Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ca/1e/500239bb5d6bfaadbbbf092f09172e22c6764e81287751bb07657daf08f4/prime-0.5.37-py3-none-any.whl", hash = "sha256:d8bfa14c9c681d60f44522de031320fbc5dd1bf0ff24482016fbc806fc29c759", size = 144603, upload-time = "2026-02-13T12:08:06.723Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/31/94/015026f60bb8dbd2367883e117a7653db1fe568dd1ec4b2db9bc4388a557/prime-0.5.63-py3-none-any.whl", hash = "sha256:a60d7a61e56a2a9b426b18af7563da48bbbf37da061161bd2db2a20eb5688614", size = 166706, upload-time = "2026-04-14T22:31:20.225Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2676,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')" },
|
||||
@@ -2764,9 +2773,11 @@ requires-dist = [
|
||||
{ name = "numpy", specifier = ">=2.2.6" },
|
||||
{ name = "nvidia-ml-py", specifier = ">=12.575.51" },
|
||||
{ name = "openai", specifier = ">=1.106.1" },
|
||||
{ name = "prime", specifier = ">=0.5.37" },
|
||||
{ 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" },
|
||||
@@ -2787,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.18/vllm_router-0.1.16-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/" },
|
||||
]
|
||||
@@ -2824,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]]
|
||||
@@ -4024,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')" },
|
||||
@@ -4145,8 +4156,8 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "vllm-router"
|
||||
version = "0.1.16"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.18/vllm_router-0.1.16-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'" },
|
||||
@@ -4156,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.18/vllm_router-0.1.16-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:8bea20e6bbb1792208204d034d68c9a88872a812af2734f27f700738c1070d89" },
|
||||
{ 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]
|
||||
|
||||
Reference in New Issue
Block a user