Compare commits
46
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 | ||
|
|
c857876b9d | ||
|
|
6fa4296e79 | ||
|
|
40bcabb5c1 | ||
|
|
b6a920f10f | ||
|
|
37cfd0ce6a | ||
|
|
833920a228 | ||
|
|
2d577a42eb | ||
|
|
7bba60f3d7 | ||
|
|
b194a6ed26 | ||
|
|
fd1a68d559 | ||
|
|
11880cea13 | ||
|
|
9615fe7769 | ||
|
|
07eb6464e0 | ||
|
|
d04d7f52a9 | ||
|
|
f412e6d17e | ||
|
|
9b01fa9df3 | ||
|
|
f07543e13c |
+3
-2
@@ -2,6 +2,7 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`model.attn = "eager"` (NEW option)**: Added `eager` as a valid value for the `model.attn` field. Required for GPT-OSS models on non-Hopper GPUs, since the only flash attention kernel GPT-OSS supports (`kernels-community/vllm-flash-attn3`) is Hopper-only. A clear error message is raised at model load time if GPT-OSS is used without `eager` on unsupported hardware. Also added `kernels` as a core dependency. (2026-04-05)
|
||||
- **`[[orchestrator.env]]` → `[[orchestrator.train.env]]`**: Training environments and sampling are now configured under `[orchestrator.train]`. The old `[[orchestrator.env]]` and `[orchestrator.sampling]` paths are auto-translated with a deprecation warning and will be removed in a future release. (2026-04-09)
|
||||
- **Per-env sampling overrides (NEW)**: Both `TrainEnvConfig` and `EvalEnvConfig` now accept a `[sampling]` section for per-env overrides. Unset fields inherit from the group-level sampling config (`[orchestrator.train.sampling]` or `[orchestrator.eval.sampling]`). (2026-04-09)
|
||||
- **Per-env eval sampling overrides**: `EvalEnvConfig` now accepts a `[sampling]` section. Unset fields inherit from `[orchestrator.eval.sampling]`. All `EvalSamplingConfig` fields remain nullable (None = defer to inference server default). (2026-04-09)
|
||||
@@ -31,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
|
||||
|
||||
@@ -21,6 +21,16 @@ id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2 }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
num_examples = 50
|
||||
rollouts_per_example = 4
|
||||
args = { min_turns = 2, max_turns = 2 }
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference]
|
||||
@@ -8,11 +8,14 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
# -- train envs --
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-1"
|
||||
|
||||
[orchestrator.train.env.sampling]
|
||||
max_completion_tokens = 127
|
||||
@@ -21,6 +24,8 @@ max_completion_tokens = 127
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-2"
|
||||
|
||||
# -- eval envs --
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
|
||||
@@ -38,6 +43,7 @@ id = "reverse-text"
|
||||
name = "eval-custom"
|
||||
num_examples = 16
|
||||
rollouts_per_example = 2
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.env.sampling]
|
||||
max_completion_tokens = 256
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+8
-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",
|
||||
@@ -81,6 +81,9 @@ disagg = [
|
||||
"nixl-cu12 ; platform_machine == 'x86_64'",
|
||||
"vllm-router ; platform_machine == 'x86_64'",
|
||||
]
|
||||
gpt-oss = [
|
||||
"kernels",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.3.3",
|
||||
]
|
||||
@@ -88,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]
|
||||
@@ -120,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 "$@"
|
||||
|
||||
@@ -195,6 +195,31 @@ Key vLLM metrics to watch:
|
||||
- `vllm:num_requests_waiting` — requests queued waiting for KV cache space
|
||||
- `vllm:gpu_cache_usage_perc` — KV cache pressure (approaching 1.0 = requests will queue)
|
||||
|
||||
### Rollouts
|
||||
|
||||
Plain-text rollouts (`verifiers` format) are saved every step alongside the binary training batch inside the run directory. For single-run (local) runs this is typically `{output_dir}/run_default`.
|
||||
|
||||
```
|
||||
{output_dir}/{run_dir}/rollouts/
|
||||
└── step_{N}/
|
||||
├── train_rollouts.jsonl # all train rollouts
|
||||
├── eval_rollouts.jsonl # all eval rollouts (only present when eval ran)
|
||||
└── train_rollouts.bin # binary-encoded training batch (consumed by the trainer)
|
||||
```
|
||||
|
||||
Each line in the `.jsonl` files is a JSON-serialized `vf.RolloutOutput` dict with fields like `example_id`, `task`, `prompt`, `completion`, `reward`, `trajectory`, `metrics`, etc. To inspect rollouts for a given step:
|
||||
|
||||
```bash
|
||||
# Count rollouts at a step
|
||||
wc -l {output_dir}/{run_dir}/rollouts/step_42/train_rollouts.jsonl
|
||||
|
||||
# Preview first rollout (pretty-printed)
|
||||
head -1 {output_dir}/{run_dir}/rollouts/step_42/train_rollouts.jsonl | python -m json.tool
|
||||
|
||||
# Extract rewards
|
||||
jq '.reward' {output_dir}/{run_dir}/rollouts/step_42/train_rollouts.jsonl
|
||||
```
|
||||
|
||||
### Errors and warnings
|
||||
|
||||
As part of every check-in, grep all logs for `WARNING` and `ERROR` level messages. Pay special attention to env server and env worker logs — these are the most common source of issues since they run user-provided code.
|
||||
|
||||
+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,
|
||||
|
||||
@@ -71,13 +71,21 @@ class ModelConfig(BaseModelConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
chat_template: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Chat template to use. Can be a Jinja2 template string or a path to a template file. "
|
||||
"Passed to vLLM as `--chat-template`. If None, uses the model's default.",
|
||||
),
|
||||
] = None
|
||||
|
||||
tool_call_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
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,
|
||||
@@ -111,9 +119,8 @@ All2AllBackend = Literal[
|
||||
"allgather_reducescatter",
|
||||
"deepep_high_throughput",
|
||||
"deepep_low_latency",
|
||||
"flashinfer_all2allv",
|
||||
"naive",
|
||||
"pplx",
|
||||
"flashinfer_nvlink_one_sided",
|
||||
"flashinfer_nvlink_two_sided",
|
||||
]
|
||||
|
||||
|
||||
@@ -140,20 +147,23 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
|
||||
router_port: Annotated[int, Field(description="Port for the vllm-router.")] = 8000
|
||||
backend_port: Annotated[int, Field(description="Port for vLLM backend instances.")] = 8100
|
||||
router_policy: Annotated[
|
||||
str, Field(description="Routing policy for the vllm-router (e.g. 'consistent_hash', 'round_robin').")
|
||||
] = "consistent_hash"
|
||||
|
||||
|
||||
class KVCacheOffloadConfig(BaseModel):
|
||||
"""CPU KV cache offloading for disaggregated prefill nodes.
|
||||
"""CPU KV cache offloading for disaggregated serving.
|
||||
|
||||
When configured, prefill nodes use MultiConnector (NixlConnector + OffloadingConnector).
|
||||
Decode nodes always use NixlConnector only.
|
||||
When configured, both prefill and decode nodes use
|
||||
MultiConnector (NixlConnector + OffloadingConnector).
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
block_size: Annotated[int, Field(ge=1, description="Block size for the CPU offloading connector.")] = 64
|
||||
|
||||
cpu_bytes: Annotated[int, Field(ge=0, description="CPU bytes available for KV cache offloading.")] = 1_000_000_000
|
||||
cpu_bytes: Annotated[int, Field(ge=0, description="CPU bytes available for KV cache offloading per worker.")] = (
|
||||
1_000_000_000
|
||||
)
|
||||
|
||||
|
||||
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
@@ -191,6 +201,9 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
router_port: Annotated[int, Field(description="Port for the vllm-router on each replica.")] = 8000
|
||||
prefill_port: Annotated[int, Field(description="Port for prefill vLLM instances.")] = 8100
|
||||
decode_port: Annotated[int, Field(description="Port for decode vLLM instances.")] = 8200
|
||||
router_policy: Annotated[
|
||||
str, Field(description="Routing policy for the vllm-router (e.g. 'consistent_hash', 'round_robin').")
|
||||
] = "consistent_hash"
|
||||
|
||||
prefill_env_overrides: Annotated[
|
||||
dict[str, str],
|
||||
@@ -231,6 +244,10 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class InferenceExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for inference."""
|
||||
|
||||
|
||||
class InferenceConfig(BaseConfig):
|
||||
"""Configures inference."""
|
||||
|
||||
@@ -400,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:
|
||||
@@ -483,6 +505,7 @@ class InferenceConfig(BaseConfig):
|
||||
"model.max_model_len": "max_model_len",
|
||||
"model.enforce_eager": "enforce_eager",
|
||||
"model.trust_remote_code": "trust_remote_code",
|
||||
"model.chat_template": "chat_template",
|
||||
"model.tool_call_parser": "tool_call_parser",
|
||||
"model.reasoning_parser": "reasoning_parser",
|
||||
"model.rope_scaling": "rope_scaling",
|
||||
@@ -513,6 +536,10 @@ class InferenceConfig(BaseConfig):
|
||||
# Set `logprobs_mode` to `processed_logprobs` by default
|
||||
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
|
||||
|
||||
# Remove chat_template if not set (vLLM doesn't accept None)
|
||||
if namespace.chat_template is None:
|
||||
delattr(namespace, "chat_template")
|
||||
|
||||
# Remove reasoning_parser if not set (vLLM doesn't accept None)
|
||||
if namespace.reasoning_parser is None:
|
||||
delattr(namespace, "reasoning_parser")
|
||||
|
||||
@@ -14,6 +14,7 @@ from prime_rl.configs.shared import (
|
||||
TransportConfig,
|
||||
WandbWithExtrasConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import TokenizerConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -382,6 +383,14 @@ class EvalEnvConfig(EnvConfig):
|
||||
),
|
||||
] = 1
|
||||
|
||||
interval: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Per-env eval interval. If unset, inherits from the group-level eval interval.",
|
||||
),
|
||||
] = 100
|
||||
|
||||
|
||||
class TrainConfig(BaseConfig):
|
||||
"""Configures training environments and their shared sampling settings."""
|
||||
@@ -390,17 +399,32 @@ class TrainConfig(BaseConfig):
|
||||
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
|
||||
num_workers: Annotated[
|
||||
int | Literal["auto"],
|
||||
Field(
|
||||
description="Default number of worker processes for env servers. Can be overridden per env.",
|
||||
),
|
||||
] = "auto"
|
||||
|
||||
max_retries: Annotated[
|
||||
int,
|
||||
Field(ge=0, description="Default number of retries for failed rollouts. Can be overridden per env."),
|
||||
] = 0
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_sampling(self):
|
||||
"""Resolve each env's sampling by merging group defaults with per-env overrides."""
|
||||
group = self.sampling.model_dump()
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_workers, and max_retries."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
env.sampling = TrainSamplingConfig(**group)
|
||||
env.sampling = TrainSamplingConfig(**group_sampling)
|
||||
else:
|
||||
merged = group.copy()
|
||||
merged.update(env.sampling.model_dump(exclude_unset=True))
|
||||
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
|
||||
env.sampling = TrainSamplingConfig(**merged)
|
||||
if "num_workers" not in env.model_fields_set:
|
||||
env.num_workers = self.num_workers
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -445,6 +469,18 @@ class EvalConfig(BaseConfig):
|
||||
Field(ge=1, description="Default number of rollouts per example. Can be overridden per env."),
|
||||
] = 1
|
||||
|
||||
num_workers: Annotated[
|
||||
int | Literal["auto"],
|
||||
Field(
|
||||
description="Default number of worker processes for env servers. Can be overridden per env.",
|
||||
),
|
||||
] = "auto"
|
||||
|
||||
max_retries: Annotated[
|
||||
int,
|
||||
Field(ge=0, description="Default number of retries for failed rollouts. Can be overridden per env."),
|
||||
] = 0
|
||||
|
||||
interval: Annotated[
|
||||
int,
|
||||
Field(
|
||||
@@ -454,27 +490,26 @@ class EvalConfig(BaseConfig):
|
||||
] = 100
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_sampling(self):
|
||||
"""Resolve each env's sampling by merging group defaults with per-env overrides."""
|
||||
group = self.sampling.model_dump()
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_workers, max_retries, num_examples, rollouts_per_example, and interval. Then resolve auto num_workers."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
env.sampling = EvalSamplingConfig(**group)
|
||||
env.sampling = EvalSamplingConfig(**group_sampling)
|
||||
else:
|
||||
merged = group.copy()
|
||||
merged.update(env.sampling.model_dump(exclude_unset=True))
|
||||
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
|
||||
env.sampling = EvalSamplingConfig(**merged)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Fill per-env num_examples and rollouts_per_example from group defaults, then resolve num_workers."""
|
||||
for env in self.env:
|
||||
if "num_examples" not in env.model_fields_set:
|
||||
env.num_examples = self.num_examples
|
||||
if "rollouts_per_example" not in env.model_fields_set:
|
||||
env.rollouts_per_example = self.rollouts_per_example
|
||||
# Resolve num_workers now that num_examples and rollouts_per_example are set
|
||||
if "interval" not in env.model_fields_set:
|
||||
env.interval = self.interval
|
||||
if "num_workers" not in env.model_fields_set:
|
||||
env.num_workers = self.num_workers
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
# Resolve auto num_workers now that num_examples and rollouts_per_example are set
|
||||
if env.num_workers == "auto":
|
||||
if env.num_examples == -1:
|
||||
env.num_workers = 4
|
||||
@@ -641,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):
|
||||
@@ -674,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[
|
||||
@@ -698,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[
|
||||
@@ -715,8 +756,22 @@ class RepetitionFilterConfig(BaseModel):
|
||||
] = 0.99
|
||||
|
||||
|
||||
class ZeroAdvantageFilterConfig(BaseModel):
|
||||
"""Flags rollouts with zero advantage."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["zero_advantage"] = "zero_advantage"
|
||||
enforce: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, skip detected rollouts entirely so they are not sent to the trainer. If False, only track detection metrics."
|
||||
),
|
||||
] = True
|
||||
|
||||
|
||||
FilterConfig: TypeAlias = Annotated[
|
||||
GibberishFilterConfig | RepetitionFilterConfig,
|
||||
GibberishFilterConfig | RepetitionFilterConfig | ZeroAdvantageFilterConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
@@ -754,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)."""
|
||||
|
||||
@@ -794,6 +853,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The optimizer configuration (per-run LR for multi-run training)
|
||||
optim: OptimizerConfig = OptimizerConfig()
|
||||
|
||||
@@ -828,7 +890,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
|
||||
|
||||
# Rollout filters (monitor by default, enforce optionally)
|
||||
filters: list[FilterConfig] = [GibberishFilterConfig(), RepetitionFilterConfig()]
|
||||
filters: list[FilterConfig] = [GibberishFilterConfig(), RepetitionFilterConfig(), ZeroAdvantageFilterConfig()]
|
||||
|
||||
# The logging configuration
|
||||
log: LogConfig = LogConfig()
|
||||
@@ -839,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
|
||||
|
||||
@@ -971,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:
|
||||
@@ -994,6 +1071,14 @@ class OrchestratorConfig(BaseConfig):
|
||||
train.setdefault("sampling", data.pop("sampling"))
|
||||
return data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_tokenizer(self):
|
||||
if self.tokenizer.name is None:
|
||||
self.tokenizer.name = self.model.name
|
||||
if self.tokenizer.trust_remote_code is None:
|
||||
self.tokenizer.trust_remote_code = self.model.trust_remote_code
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_filter_types(self):
|
||||
types = [f.type for f in self.filters]
|
||||
@@ -1047,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:
|
||||
|
||||
@@ -26,6 +26,7 @@ from prime_rl.configs.shared import (
|
||||
from prime_rl.configs.trainer import (
|
||||
BenchConfig,
|
||||
FakeDataLoaderConfig,
|
||||
TokenizerConfig,
|
||||
TrainerConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
@@ -45,15 +46,25 @@ from prime_rl.utils.validation import (
|
||||
validate_shared_max_steps,
|
||||
validate_shared_model_name,
|
||||
validate_shared_output_dir,
|
||||
validate_shared_tokenizer,
|
||||
validate_shared_wandb_config,
|
||||
validate_shared_weight_broadcast,
|
||||
)
|
||||
|
||||
|
||||
class RLExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for RL training."""
|
||||
|
||||
|
||||
class SharedLogConfig(BaseConfig):
|
||||
"""Configures shared logging."""
|
||||
|
||||
level: Annotated[str | None, Field(description="The log level to use.")] = "info"
|
||||
level: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The log level to use. When unset, the trainer and orchestrator log levels are used as-is (which themselves default to the PRIME_LOG_LEVEL env var if set, else 'info').",
|
||||
),
|
||||
] = None
|
||||
|
||||
json_logging: Annotated[
|
||||
bool,
|
||||
@@ -288,6 +299,14 @@ class RLConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
tokenizer: Annotated[
|
||||
TokenizerConfig | None,
|
||||
Field(
|
||||
description="Shared tokenizer config. Propagated to trainer, orchestrator, and inference. "
|
||||
"If None, each component uses its own tokenizer config (defaulting to model name).",
|
||||
),
|
||||
] = None
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
@@ -335,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")
|
||||
@@ -542,6 +566,36 @@ class RLConfig(BaseConfig):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_tokenizer(self):
|
||||
"""Auto-setup shared tokenizer config for trainer, orchestrator, and inference."""
|
||||
if self.tokenizer is not None:
|
||||
# Shared tokenizer config: propagate to all components, then fill
|
||||
# in name/trust_remote_code from model config where still unset.
|
||||
self.trainer.tokenizer = self.tokenizer.model_copy()
|
||||
self.orchestrator.tokenizer = self.tokenizer.model_copy()
|
||||
for component in (self.trainer, self.orchestrator):
|
||||
if component.tokenizer.name is None:
|
||||
component.tokenizer.name = component.model.name
|
||||
if component.tokenizer.trust_remote_code is None:
|
||||
component.tokenizer.trust_remote_code = component.model.trust_remote_code
|
||||
else:
|
||||
# No shared tokenizer: re-derive from (now-correct) model names,
|
||||
# since auto_setup_tokenizer on sub-configs already ran with defaults.
|
||||
for component in (self.trainer, self.orchestrator):
|
||||
component.tokenizer.name = component.model.name
|
||||
component.tokenizer.trust_remote_code = component.model.trust_remote_code
|
||||
|
||||
# Propagate chat_template to inference (vLLM --chat-template)
|
||||
if self.inference is not None:
|
||||
chat_template = self.trainer.tokenizer.chat_template
|
||||
if chat_template is not None and self.inference.model.chat_template is None:
|
||||
self.inference.model.chat_template = chat_template
|
||||
|
||||
validate_shared_tokenizer(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_max_steps(self):
|
||||
"""Auto-setup shared max steps for trainer and orchestrator."""
|
||||
@@ -688,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"""
|
||||
|
||||
@@ -203,6 +207,19 @@ class SFTConfig(BaseConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
matmul_precision: Annotated[
|
||||
Literal["highest", "high", "medium"],
|
||||
Field(
|
||||
description=(
|
||||
"Precision for float32 matrix multiplications. "
|
||||
"Use 'highest' for full FP32 (required on ROCm/AMD GPUs to avoid "
|
||||
"catastrophic precision loss in softmax over large vocabularies). "
|
||||
"Use 'high' to enable TF32 on NVIDIA GPUs for a speedup with minor "
|
||||
"precision tradeoff. See torch.set_float32_matmul_precision docs."
|
||||
),
|
||||
),
|
||||
] = "high"
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(description="Maximum number of steps to run training for. If None, will run indefinitely."),
|
||||
@@ -257,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")
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
@@ -271,13 +272,19 @@ class LogConfig(BaseConfig):
|
||||
|
||||
level: Annotated[
|
||||
str,
|
||||
Field(description="Logging level for the process. Will determine the logging verbosity and format."),
|
||||
] = "info"
|
||||
Field(
|
||||
default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"),
|
||||
description="Logging level for the process. Will determine the logging verbosity and format. Defaults to the PRIME_LOG_LEVEL env var if set, else 'info'.",
|
||||
),
|
||||
]
|
||||
|
||||
vf_level: Annotated[
|
||||
str,
|
||||
Field(description="Logging level for the verifiers package. Will determine the logging verbosity and format."),
|
||||
] = "info"
|
||||
Field(
|
||||
default_factory=lambda: os.environ.get("PRIME_VF_LOG_LEVEL", "info"),
|
||||
description="Logging level for the verifiers package. Will determine the logging verbosity and format. Defaults to the PRIME_VF_LOG_LEVEL env var if set, else 'info'.",
|
||||
),
|
||||
]
|
||||
|
||||
json_logging: Annotated[
|
||||
bool,
|
||||
|
||||
@@ -17,7 +17,7 @@ from prime_rl.utils.config import BaseConfig
|
||||
|
||||
# -- Shared trainer configs (used by both SFT and RL trainers) --
|
||||
|
||||
AttnImplementation: TypeAlias = Literal["sdpa", "flash_attention_2", "flash_attention_3", "fa4"]
|
||||
AttnImplementation: TypeAlias = Literal["eager", "sdpa", "flash_attention_2", "flash_attention_3", "fa4"]
|
||||
EPCommBackend: TypeAlias = Literal["torch", "deepep"]
|
||||
|
||||
# User-facing name -> internal name. Users set `flash_attention_4` in configs,
|
||||
@@ -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
|
||||
|
||||
@@ -431,7 +431,7 @@ class TokenizerConfig(BaseConfig):
|
||||
chat_template: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The chat template to use for the tokenizer. If None, will use the tokenizer's default chat template."
|
||||
description="The chat template to use for the tokenizer. Can be a Jinja2 template string or a path to a template file. If None, will use the tokenizer's default chat template."
|
||||
),
|
||||
] = None
|
||||
|
||||
@@ -719,6 +719,10 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class TrainerExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for the trainer."""
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
"""Configures the RL trainer"""
|
||||
|
||||
@@ -760,6 +764,19 @@ class TrainerConfig(BaseConfig):
|
||||
),
|
||||
] = Path("outputs")
|
||||
|
||||
matmul_precision: Annotated[
|
||||
Literal["highest", "high", "medium"],
|
||||
Field(
|
||||
description=(
|
||||
"Precision for float32 matrix multiplications. "
|
||||
"Use 'highest' for full FP32 (required on ROCm/AMD GPUs to avoid "
|
||||
"catastrophic precision loss in softmax over large vocabularies). "
|
||||
"Use 'high' to enable TF32 on NVIDIA GPUs for a speedup with minor "
|
||||
"precision tradeoff. See torch.set_float32_matmul_precision docs."
|
||||
),
|
||||
),
|
||||
] = "high"
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
@@ -824,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:
|
||||
|
||||
@@ -34,12 +34,14 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
template = env.get_template(config.slurm.template_path.name)
|
||||
|
||||
is_disaggregated = config.deployment.type == "disaggregated"
|
||||
dp_per_node = config.deployment.gpus_per_node // config.parallel.tp
|
||||
|
||||
template_vars = dict(
|
||||
**config.slurm.template_vars,
|
||||
config_path=config_path,
|
||||
output_dir=config.output_dir,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
dp_per_node=dp_per_node,
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
port=config.server.port,
|
||||
disaggregated=is_disaggregated,
|
||||
@@ -56,14 +58,12 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
prefill_port=config.deployment.prefill_port,
|
||||
decode_port=config.deployment.decode_port,
|
||||
router_port=config.deployment.router_port,
|
||||
router_policy=config.deployment.router_policy,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
use_deep_gemm=config.use_deep_gemm,
|
||||
prefill_env_overrides=config.deployment.prefill_env_overrides,
|
||||
decode_env_overrides=config.deployment.decode_env_overrides,
|
||||
kv_offload=config.deployment.kv_cache_offload is not None,
|
||||
kv_offload_block_size=config.deployment.kv_cache_offload.block_size
|
||||
if config.deployment.kv_cache_offload
|
||||
else 64,
|
||||
kv_offload_cpu_bytes=int(config.deployment.kv_cache_offload.cpu_bytes)
|
||||
if config.deployment.kv_cache_offload
|
||||
else 0,
|
||||
@@ -72,6 +72,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
template_vars.update(
|
||||
router_port=config.deployment.router_port,
|
||||
backend_port=config.deployment.backend_port,
|
||||
router_policy=config.deployment.router_policy,
|
||||
)
|
||||
|
||||
script = template.render(**template_vars)
|
||||
|
||||
@@ -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 (
|
||||
@@ -100,7 +101,7 @@ def rl_local(config: RLConfig):
|
||||
assert config.deployment.type == "single_node"
|
||||
|
||||
logger = setup_logger(
|
||||
config.log.level or "info",
|
||||
config.log.level or os.environ.get("PRIME_LOG_LEVEL", "info"),
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
|
||||
@@ -442,8 +443,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
use_deep_gemm=config.inference.use_deep_gemm,
|
||||
prefill_env_overrides=infer_deploy.prefill_env_overrides,
|
||||
decode_env_overrides=infer_deploy.decode_env_overrides,
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
|
||||
kv_offload=infer_deploy.kv_cache_offload is not None,
|
||||
kv_offload_block_size=infer_deploy.kv_cache_offload.block_size if infer_deploy.kv_cache_offload else 64,
|
||||
kv_offload_cpu_bytes=int(infer_deploy.kv_cache_offload.cpu_bytes) if infer_deploy.kv_cache_offload else 0,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
wandb_shared=config.wandb is not None and config.wandb.shared,
|
||||
@@ -467,6 +468,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
inference_tp=config.inference.parallel.tp if config.inference else 1,
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
|
||||
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
wandb_shared=config.wandb is not None and config.wandb.shared,
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
@@ -479,7 +481,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
def rl_slurm(config: RLConfig):
|
||||
assert config.slurm is not None
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
logger = setup_logger(
|
||||
config.log.level or os.environ.get("PRIME_LOG_LEVEL", "info"), json_logging=config.log.json_logging
|
||||
)
|
||||
|
||||
config_dir = config.output_dir / "configs"
|
||||
log_dir = get_log_dir(config.output_dir)
|
||||
@@ -544,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:
|
||||
|
||||
@@ -14,8 +14,10 @@ def transformers_v5_compat():
|
||||
Qwen3VLMoeTextConfig.tie_word_embeddings = False
|
||||
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_deep_gemm_ep_scatter()
|
||||
monkey_patch_dp_engine_core_pause_resume_deadlock()
|
||||
monkey_patch_offloading_connector_cpu_block_count()
|
||||
|
||||
|
||||
@triton.jit
|
||||
@@ -223,6 +225,151 @@ def _patch_qwen35_lora():
|
||||
MergedColumnParallelLinearWithShardedLoRA.slice_lora_a = slice_lora_a
|
||||
|
||||
|
||||
def _patch_lora_key_prefix():
|
||||
"""Patch vLLM's LoRA loading to handle keys without base_model.model. prefix.
|
||||
|
||||
This is a copy of the upstream patch: https://github.com/vllm-project/vllm/pull/38522
|
||||
We can remove this patch once that PR makes it into a release.
|
||||
"""
|
||||
from vllm.lora.lora_model import (
|
||||
LoRAModel,
|
||||
PEFTHelper,
|
||||
TensorizerConfig,
|
||||
WeightsMapper,
|
||||
get_lora_id,
|
||||
is_base_embedding_weights,
|
||||
os,
|
||||
parse_fine_tuned_lora_name,
|
||||
safetensors,
|
||||
)
|
||||
|
||||
def _patched_from_local_checkpoint(
|
||||
cls,
|
||||
lora_dir: str,
|
||||
expected_lora_modules: set[str],
|
||||
peft_helper: PEFTHelper,
|
||||
*,
|
||||
lora_model_id: int | None = None,
|
||||
device: str = "cuda",
|
||||
dtype: torch.dtype | None = None,
|
||||
model_vocab_size: int | None = None,
|
||||
weights_mapper: WeightsMapper | None = None,
|
||||
tensorizer_config_dict: dict | None = None,
|
||||
skip_prefixes: list[str] | None = None,
|
||||
) -> "LoRAModel":
|
||||
"""Create a LoRAModel from a local checkpoint.
|
||||
|
||||
Args:
|
||||
lora_dir: The local path that has lora data.
|
||||
expected_lora_modules: Name of modules that are expected to be
|
||||
replaced by lora.
|
||||
peft_helper: Loaded lora configuration information.
|
||||
lora_model_id: LoRA model id. If not given, automatically set by
|
||||
a global counter.
|
||||
device: Device where the lora model is loaded.
|
||||
dtype: dtype of the lora model weights.
|
||||
skip_prefixes: List of module name prefixes to skip during loading.
|
||||
Models can define this to skip modules not used in inference
|
||||
(e.g., MTP layers). Format: ["mtp."]
|
||||
|
||||
Returns:
|
||||
Loaded LoRA Model.
|
||||
"""
|
||||
lora_tensor_path = os.path.join(lora_dir, "adapter_model.safetensors")
|
||||
lora_bin_file_path = os.path.join(lora_dir, "adapter_model.bin")
|
||||
lora_pt_file_path = os.path.join(lora_dir, "adapter_model.pt")
|
||||
|
||||
tensors: dict[str, torch.Tensor] = {}
|
||||
unexpected_modules: list[list[str] | str] = []
|
||||
|
||||
def check_unexpected_modules(modules: dict):
|
||||
for lora_module in modules.keys(): # noqa
|
||||
if is_base_embedding_weights(lora_module):
|
||||
continue
|
||||
# Handle PEFT file format where experts.base_layer is the
|
||||
# gate_up_proj and experts is the down_proj
|
||||
if "base_layer" in lora_module:
|
||||
continue
|
||||
# Skip modules based on model-defined prefixes
|
||||
if skip_prefixes and cls._should_skip_module(lora_module, skip_prefixes):
|
||||
continue
|
||||
module_name, _ = parse_fine_tuned_lora_name(lora_module, weights_mapper)
|
||||
# Case for expert lora weights.
|
||||
# For standard MoE models the name ends in "...experts",
|
||||
# so expert_idx+1 yields "experts" which is in
|
||||
# expected_lora_modules.
|
||||
# For Qwen 3.5 MoE (and similar models) the expert index
|
||||
# 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.
|
||||
# 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]
|
||||
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:
|
||||
unexpected_modules.append(module_name)
|
||||
|
||||
if unexpected_modules:
|
||||
raise ValueError(
|
||||
f"While loading {lora_dir}, expected"
|
||||
f" target modules in {expected_lora_modules}"
|
||||
f" but received {unexpected_modules}."
|
||||
f" Please verify that the loaded LoRA module is correct"
|
||||
)
|
||||
|
||||
if tensorizer_config_dict:
|
||||
from tensorizer import TensorDeserializer
|
||||
|
||||
tensorizer_config = TensorizerConfig(**tensorizer_config_dict)
|
||||
lora_tensor_path = os.path.join(tensorizer_config.tensorizer_dir, "adapter_model.tensors")
|
||||
tensorizer_args = tensorizer_config._construct_tensorizer_args()
|
||||
tensors = TensorDeserializer(
|
||||
lora_tensor_path,
|
||||
dtype=tensorizer_config.dtype,
|
||||
**tensorizer_args.deserialization_kwargs,
|
||||
)
|
||||
check_unexpected_modules(tensors)
|
||||
|
||||
elif os.path.isfile(lora_tensor_path):
|
||||
# Find unexpected modules.
|
||||
# Use safetensor key as a source of truth to find expected modules.
|
||||
# in peft if you have target_modules A, B, C and C does not exist
|
||||
# in the model it won’t error and model will be trained with A, B
|
||||
# loraified. C won’t exist in the safetensor but it will exist in
|
||||
# the target_modules of the adapter_config.json.
|
||||
unexpected_modules = []
|
||||
with safetensors.safe_open(lora_tensor_path, framework="pt") as f: # type: ignore
|
||||
# Load tensors if there are only expected modules.
|
||||
check_unexpected_modules(f)
|
||||
for module in f.keys(): # noqa
|
||||
tensors[module] = f.get_tensor(module)
|
||||
elif os.path.isfile(lora_bin_file_path) or os.path.isfile(lora_pt_file_path):
|
||||
lora_file_path = lora_bin_file_path if os.path.isfile(lora_bin_file_path) else lora_pt_file_path
|
||||
tensors = torch.load(lora_file_path, map_location=device, weights_only=True)
|
||||
check_unexpected_modules(tensors)
|
||||
else:
|
||||
raise ValueError(f"{lora_dir} doesn't contain tensors")
|
||||
|
||||
return cls.from_lora_tensors(
|
||||
lora_model_id=get_lora_id() if lora_model_id is None else lora_model_id,
|
||||
tensors=tensors,
|
||||
peft_helper=peft_helper,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
model_vocab_size=model_vocab_size,
|
||||
weights_mapper=weights_mapper,
|
||||
skip_prefixes=skip_prefixes,
|
||||
)
|
||||
|
||||
LoRAModel.from_local_checkpoint = classmethod(_patched_from_local_checkpoint)
|
||||
|
||||
|
||||
# Monkeypatch LoadLoRAAdapter to allow loading the same adapter multiple times
|
||||
# TODO: may be removable if we pass load_inplace=True (supported since vLLM 0.18, PR #31326)
|
||||
def monkey_patch_load_lora_adapter():
|
||||
@@ -811,6 +958,46 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
DPEngineCoreProc._has_global_unfinished_reqs = _patched_has_global_unfinished_reqs
|
||||
|
||||
|
||||
def monkey_patch_offloading_connector_cpu_block_count():
|
||||
"""Fix CPU block count miscalculation in OffloadingConnector.
|
||||
|
||||
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: 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/39617
|
||||
"""
|
||||
from vllm.v1.kv_offload.cpu.spec import CPUOffloadingSpec
|
||||
|
||||
_original_init = CPUOffloadingSpec.__init__
|
||||
|
||||
def _patched_init(self, vllm_config, kv_cache_config):
|
||||
_original_init(self, vllm_config, kv_cache_config)
|
||||
|
||||
cpu_bytes_to_use = self.extra_config.get("cpu_bytes_to_use")
|
||||
if not cpu_bytes_to_use:
|
||||
return
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
CPUOffloadingSpec.__init__ = _patched_init
|
||||
|
||||
|
||||
def monkey_patch_no_moe_lora():
|
||||
"""This disables LoRA for MoE layers and makes them pick better kernels.
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ from http import HTTPStatus
|
||||
from typing import Any
|
||||
|
||||
import uvloop
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from starlette.datastructures import State
|
||||
from vllm.engine.protocol import EngineClient
|
||||
@@ -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"}
|
||||
|
||||
|
||||
@@ -247,10 +243,7 @@ async def _chat_with_tokens(request: ChatCompletionRequestWithTokens, raw_reques
|
||||
handler = chat_with_tokens(raw_request)
|
||||
if handler is None:
|
||||
return base(raw_request).create_error_response(message="The model does not support Chat Completions API")
|
||||
try:
|
||||
generator = await handler.create_chat_completion_with_tokens(request, raw_request)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=str(e)) from e
|
||||
generator = await handler.create_chat_completion_with_tokens(request, raw_request)
|
||||
if isinstance(generator, ErrorResponse):
|
||||
return JSONResponse(content=generator.model_dump(), status_code=generator.error.code)
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@ from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
|
||||
import torch
|
||||
import verifiers as vf
|
||||
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_model_completion_len
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -35,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):
|
||||
@@ -64,31 +99,35 @@ 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
|
||||
|
||||
|
||||
def compute_advantages(
|
||||
rewards: list[float],
|
||||
completion_lengths: list[int],
|
||||
rollouts: list[vf.RolloutOutput],
|
||||
samples_per_problem: int,
|
||||
advantage_config: AdvantageConfig | None,
|
||||
) -> list[float]:
|
||||
) -> None:
|
||||
"""
|
||||
Computes advantages from a flattened list of rewards, grouped by problem.
|
||||
Computes advantages from rollouts, grouped by problem.
|
||||
Stores advantages in-place on the rollouts.
|
||||
|
||||
Args:
|
||||
rewards: Flattened list of rewards where first `samples_per_problem` rewards are for the first problem
|
||||
completion_lengths: List of completion lengths for each reward
|
||||
rollouts: List of rollouts to store advantages on
|
||||
samples_per_problem: Number of samples (and thus, rewards) per problem
|
||||
advantage_config: Configuration for advantage computation (DefaultAdvantageConfig or CustomAdvantageConfig)
|
||||
"""
|
||||
rewards = [r["reward"] for r in rollouts]
|
||||
|
||||
if not advantage_config:
|
||||
return rewards
|
||||
for rollout, reward in zip(rollouts, rewards):
|
||||
rollout["advantage"] = reward
|
||||
return
|
||||
|
||||
advantage_fn = setup_advantage_fn(advantage_config)
|
||||
completion_lengths = [get_model_completion_len(r) for r in rollouts]
|
||||
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor(rewards).view(-1, samples_per_problem),
|
||||
@@ -96,4 +135,7 @@ def compute_advantages(
|
||||
)
|
||||
|
||||
result = advantage_fn(inputs)
|
||||
return result.advantages.flatten().tolist()
|
||||
advantages = result.advantages.flatten().tolist()
|
||||
|
||||
for rollout, advantage in zip(rollouts, advantages):
|
||||
rollout["advantage"] = advantage
|
||||
|
||||
@@ -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,7 +179,8 @@ class EvalEnv(Env):
|
||||
get_client: Callable[[], Awaitable[vf.ClientConfig]],
|
||||
ckpt_step: int,
|
||||
step: int,
|
||||
) -> None:
|
||||
cache_salt: str,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
num_examples = len(self.examples)
|
||||
rollouts_per_example = self.config.rollouts_per_example
|
||||
get_logger().info(f"Evaluating {self.name} ({num_examples=}, {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:
|
||||
@@ -240,7 +252,7 @@ class EvalEnv(Env):
|
||||
},
|
||||
step=step,
|
||||
)
|
||||
return
|
||||
return []
|
||||
|
||||
# Log metrics
|
||||
monitor = get_monitor()
|
||||
@@ -304,6 +316,8 @@ class EvalEnv(Env):
|
||||
monitor.log(eval_metrics, step=step)
|
||||
monitor.log_eval_samples(successful_outputs, env_name=self.name, step=step)
|
||||
|
||||
return successful_outputs
|
||||
|
||||
|
||||
EnvT = TypeVar("EnvT", bound=Env)
|
||||
|
||||
@@ -336,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
|
||||
@@ -95,6 +94,24 @@ class RepetitionFilter:
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ZeroAdvantageFilter:
|
||||
"""Flags rollouts with zero advantage.
|
||||
|
||||
This filter is applied after advantages are computed and checks if the
|
||||
rollout's advantage field is zero.
|
||||
"""
|
||||
|
||||
name: str
|
||||
enforce: bool = True
|
||||
|
||||
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
|
||||
advantage = rollout.get("advantage")
|
||||
if advantage is not None and advantage == 0.0:
|
||||
return FilterResult(detected=True)
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
def setup_filter(config: FilterConfig, vocab_size: int) -> RolloutFilter:
|
||||
"""Create a RolloutFilter from a filter config."""
|
||||
if config.type == "gibberish":
|
||||
@@ -111,71 +128,61 @@ def setup_filter(config: FilterConfig, vocab_size: int) -> RolloutFilter:
|
||||
logprob_threshold=math.log(config.prob_threshold),
|
||||
enforce=config.enforce,
|
||||
)
|
||||
elif config.type == "zero_advantage":
|
||||
return ZeroAdvantageFilter(
|
||||
name="zero_advantage",
|
||||
enforce=config.enforce,
|
||||
)
|
||||
raise ValueError(f"Unknown filter type: {config.type}")
|
||||
|
||||
|
||||
def setup_filters(configs: list[FilterConfig], vocab_size: int) -> list[RolloutFilter]:
|
||||
"""Create RolloutFilters from a list of filter configs."""
|
||||
return [setup_filter(config, vocab_size) for config in configs]
|
||||
filters = [setup_filter(config, vocab_size) for config in configs]
|
||||
if filters:
|
||||
get_logger().info(f"Configured {len(filters)} rollout filter(s):")
|
||||
for config, filt in zip(configs, filters):
|
||||
mode = "Enforcing" if filt.enforce else "Monitoring"
|
||||
params = ", ".join(f"{k}={v}" for k, v in config.model_dump().items())
|
||||
get_logger().info(f" {mode} {filt.name} filter ({params})")
|
||||
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
|
||||
@@ -2,13 +2,13 @@ import asyncio
|
||||
import gc
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
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,
|
||||
@@ -17,7 +17,7 @@ from prime_rl.orchestrator.trajectories import (
|
||||
pretokenize_rollout_trajectory,
|
||||
)
|
||||
from prime_rl.transport import TrainingBatch, TrainingSample, setup_training_batch_sender
|
||||
from prime_rl.utils.pathing import get_log_dir
|
||||
from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
|
||||
from prime_rl.utils.usage_reporter import UsageReporter
|
||||
|
||||
# This monkey patch is necessary to avoid Pydantic validating fields using typing.Iterable (e.g. in multimodal or tool call messages) lazily which leads to tokenization errors, for more info see https://github.com/PrimeIntellect-ai/prime-rl/pull/1249
|
||||
@@ -31,25 +31,27 @@ monkey_patch_chat_completion_logprobs()
|
||||
|
||||
import pandas as pd
|
||||
import verifiers as vf
|
||||
from transformers import AutoProcessor, AutoTokenizer
|
||||
from transformers import AutoProcessor
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.buffer import Buffer
|
||||
from prime_rl.orchestrator.ckpt import Progress, setup_ckpt_manager
|
||||
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.envs import EvalEnv, EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.filters import apply_filters, setup_filters
|
||||
from prime_rl.orchestrator.scheduler import Scheduler
|
||||
from prime_rl.orchestrator.utils import (
|
||||
compute_teacher_logprobs,
|
||||
get_weight_dir,
|
||||
print_benchmark,
|
||||
set_default_executor,
|
||||
setup_external_rollout_model,
|
||||
)
|
||||
from prime_rl.orchestrator.vf_utils import (
|
||||
get_completion_len,
|
||||
get_seq_len,
|
||||
intercept_vf_logging,
|
||||
save_rollouts,
|
||||
)
|
||||
from prime_rl.trainer.model import setup_tokenizer
|
||||
from prime_rl.utils.client import (
|
||||
init_nccl_broadcast,
|
||||
setup_inference_pool,
|
||||
@@ -74,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):
|
||||
@@ -84,6 +91,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
)
|
||||
intercept_vf_logging(logger="verifiers.serve", level="WARN") # show logs from env clients
|
||||
logger.info("Starting orchestrator")
|
||||
set_default_executor()
|
||||
|
||||
event_loop_lag_monitor = EventLoopLagMonitor()
|
||||
event_loop_lag_monitor_task = asyncio.create_task(event_loop_lag_monitor.run())
|
||||
@@ -105,19 +113,17 @@ 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)
|
||||
|
||||
client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
|
||||
if config.use_token_client:
|
||||
logger.warning(
|
||||
"Token-in-token-out (TITO) client is enabled. Only use this if your environment has a linear "
|
||||
"history and the chat template has the extension property."
|
||||
)
|
||||
train_client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config, model_name=rollout_model_name, client_type=client_type
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type="openai_chat_completions",
|
||||
)
|
||||
|
||||
# Setup teacher inference pool if configured
|
||||
@@ -127,7 +133,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
f"model={config.teacher_model.model.name})"
|
||||
)
|
||||
teacher_inference_pool = await setup_inference_pool(
|
||||
config.teacher_model.client, model_name=config.teacher_model.model.name
|
||||
config.teacher_model.client,
|
||||
model_name=config.teacher_model.model.name,
|
||||
train_client_type="openai_chat_completions",
|
||||
)
|
||||
else:
|
||||
teacher_inference_pool = None
|
||||
@@ -136,8 +144,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
is_vlm = config.model.vlm is not None
|
||||
|
||||
# Load tokenizer and processor (processor only for VLM models)
|
||||
logger.info(f"Initializing tokenizer for {config.model.name}")
|
||||
tokenizer = AutoTokenizer.from_pretrained(config.model.name, trust_remote_code=config.model.trust_remote_code)
|
||||
logger.info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
processor = None
|
||||
if is_vlm:
|
||||
@@ -180,8 +188,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Build rollout filters
|
||||
rollout_filters = setup_filters(config.filters, vocab_size=tokenizer.vocab_size)
|
||||
if rollout_filters:
|
||||
logger.info(f"Initialized {len(rollout_filters)} rollout filter(s): {[f.name for f in rollout_filters]}")
|
||||
|
||||
# Load environments
|
||||
logger.info("Loading training environments")
|
||||
@@ -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")
|
||||
@@ -273,8 +285,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info(f"Initializing training batch sender ({config.rollout_transport})")
|
||||
training_batch_sender = setup_training_batch_sender(config.output_dir, config.rollout_transport)
|
||||
|
||||
# Track last online eval checkpoint step for this process
|
||||
last_eval_step = -1
|
||||
# Track last online eval checkpoint step per eval env
|
||||
last_eval_steps: dict[str, int] = {env.name: -1 for env in eval_envs} if eval_envs else {}
|
||||
# Track previous ckpt_step to detect when ckpt_step jumps over eval interval boundaries
|
||||
prev_ckpt_step = -1
|
||||
|
||||
@@ -287,7 +299,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
scheduler.ckpt_step = progress.step # Always resume from the latest checkpoint
|
||||
if config.eval and config.eval.skip_eval_on_resume:
|
||||
prev_ckpt_step = scheduler.ckpt_step
|
||||
last_eval_step = scheduler.ckpt_step
|
||||
last_eval_steps = {name: scheduler.ckpt_step for name in last_eval_steps}
|
||||
logger.info(f"Skipping online eval on resume (ckpt_step={scheduler.ckpt_step})")
|
||||
else:
|
||||
# Allow eval at resumed step by setting prev_ckpt_step one behind
|
||||
@@ -309,9 +321,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info(f"Starting orchestrator loop (max_steps={config.max_steps or 'infinite'})")
|
||||
is_first_step = True
|
||||
|
||||
# Persistent ThreadPoolExecutor for parallel rollout processing
|
||||
rollout_executor = ThreadPoolExecutor(max_workers=64)
|
||||
|
||||
while True:
|
||||
# Check if this run has been evicted by the trainer
|
||||
evicted_path = config.output_dir / "control" / "evicted.txt"
|
||||
@@ -346,24 +355,25 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Run evals BEFORE training (blocking). Weight updates are paused via
|
||||
# scheduler.checkpoint_ready during eval to ensure consistent weights.
|
||||
# Use range check to handle ckpt_step jumping over interval boundaries.
|
||||
eval_ckpt_step = None
|
||||
# Each eval env has its own interval, so we check each independently.
|
||||
envs_to_eval: list[EvalEnv] = []
|
||||
if config.eval:
|
||||
assert eval_envs is not None
|
||||
eval_ckpt_step = compute_eval_ckpt_step(
|
||||
ckpt_step=ckpt_step,
|
||||
prev_ckpt_step=prev_ckpt_step,
|
||||
last_eval_step=last_eval_step,
|
||||
interval=config.eval.interval,
|
||||
eval_base_model=config.eval.eval_base_model,
|
||||
)
|
||||
for eval_env in eval_envs:
|
||||
eval_ckpt_step = compute_eval_ckpt_step(
|
||||
ckpt_step=ckpt_step,
|
||||
prev_ckpt_step=prev_ckpt_step,
|
||||
last_eval_step=last_eval_steps[eval_env.name],
|
||||
interval=eval_env.config.interval,
|
||||
eval_base_model=config.eval.eval_base_model,
|
||||
)
|
||||
if eval_ckpt_step is not None:
|
||||
last_eval_steps[eval_env.name] = ckpt_step
|
||||
envs_to_eval.append(eval_env)
|
||||
|
||||
if eval_ckpt_step is not None:
|
||||
last_eval_step = ckpt_step
|
||||
if eval_ckpt_step != ckpt_step:
|
||||
logger.info(f"Running evals for interval step {eval_ckpt_step} (current ckpt_step={ckpt_step})")
|
||||
else:
|
||||
logger.info(f"Running evals for checkpoint step {ckpt_step}")
|
||||
if envs_to_eval:
|
||||
env_names = ", ".join(e.name for e in envs_to_eval)
|
||||
logger.info(f"Running evals at {ckpt_step=} for {env_names}")
|
||||
|
||||
# Pause weight updates and re-scheduling of training rollouts during eval
|
||||
# to avoid evaluating across different checkpoints and avoid congestion
|
||||
@@ -374,31 +384,88 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info("Cancelling in-flight training rollouts before starting evals to avoid congestion.")
|
||||
await scheduler.cancel_inflight_rollouts()
|
||||
|
||||
await asyncio.gather(
|
||||
eval_results = await asyncio.gather(
|
||||
*[
|
||||
eval_env.evaluate(
|
||||
model_name=scheduler.model_name,
|
||||
get_client=inference_pool.get_next_client,
|
||||
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
|
||||
for eval_env in envs_to_eval
|
||||
]
|
||||
)
|
||||
|
||||
# Save eval rollouts to disk (fire-and-forget background thread)
|
||||
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", exclude_keys={"trajectory"}
|
||||
)
|
||||
|
||||
# Resume weight updates
|
||||
scheduler.checkpoint_ready.set()
|
||||
|
||||
# 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", exclude_keys={"trajectory"}
|
||||
)
|
||||
|
||||
# VLM: offload base64 images to disk immediately to free memory
|
||||
if is_vlm:
|
||||
@@ -409,22 +476,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
f"VLM offloaded {num_offloaded} unique images to disk in {time.perf_counter() - offload_start:.2f}s"
|
||||
)
|
||||
|
||||
# Apply rollout filters (zeros reward/mask for degenerate generations)
|
||||
filter_metrics = apply_filters(rollout_filters, train_rollouts)
|
||||
|
||||
# Compute advantages
|
||||
example_ids = [r["example_id"] for r in train_rollouts]
|
||||
num_rollouts = len(train_rollouts)
|
||||
num_unique_examples = len(set(example_ids))
|
||||
rewards = [r["reward"] for r in train_rollouts]
|
||||
completion_lens = [get_completion_len(r) for r in train_rollouts]
|
||||
advantages = compute_advantages(
|
||||
rewards,
|
||||
completion_lens,
|
||||
config.rollouts_per_example,
|
||||
config.advantage,
|
||||
)
|
||||
|
||||
# Convert rollouts to training samples
|
||||
parallel_preprocess_start = time.perf_counter()
|
||||
|
||||
@@ -436,49 +487,54 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# This lets the scheduler continue servicing inflight rollout requests
|
||||
# and — with max_async_level >= 2 — overlap with the next batch's inference.
|
||||
if is_vlm:
|
||||
vlm_cache = await asyncio.get_event_loop().run_in_executor(
|
||||
rollout_executor, build_vlm_image_cache, train_rollouts, processor
|
||||
)
|
||||
vlm_cache = await asyncio.to_thread(build_vlm_image_cache, train_rollouts, processor)
|
||||
mm_token_type_ids_mapping = {}
|
||||
if hasattr(processor, "image_token_id") and processor.image_token_id is not None:
|
||||
mm_token_type_ids_mapping[processor.image_token_id] = 1
|
||||
if hasattr(processor, "video_token_id") and processor.video_token_id is not None:
|
||||
mm_token_type_ids_mapping[processor.video_token_id] = 2
|
||||
|
||||
logger.info(
|
||||
f"VLM timing: extract={vlm_cache.extract_time:.2f}s, preprocess={vlm_cache.preprocess_time:.2f}s "
|
||||
f"({vlm_cache.num_unique_images} unique images from {vlm_cache.num_unique_examples} examples)"
|
||||
)
|
||||
else:
|
||||
vlm_cache = None
|
||||
mm_token_type_ids_mapping = None
|
||||
|
||||
# Process rollouts in parallel
|
||||
def process_rollout(rollout: vf.RolloutOutput, rollout_idx: int) -> list[TrainingSample] | None:
|
||||
return interleave_rollout(rollout, vlm_cache=vlm_cache, cache_key=rollout_idx)
|
||||
return interleave_rollout(
|
||||
rollout, vlm_cache=vlm_cache, cache_key=rollout_idx, mm_token_type_ids_mapping=mm_token_type_ids_mapping
|
||||
)
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
futures = [
|
||||
loop.run_in_executor(rollout_executor, process_rollout, r, rollout_idx)
|
||||
for rollout_idx, r in enumerate(train_rollouts)
|
||||
]
|
||||
results = await asyncio.gather(*futures)
|
||||
results = await asyncio.gather(
|
||||
*(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] = []
|
||||
rollout_samples_per_rollout: list[int] = []
|
||||
num_prefill_tokens = 0
|
||||
num_decode_tokens = 0
|
||||
for rollout, advantage, samples in zip(train_rollouts, advantages, results):
|
||||
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 = 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
|
||||
@@ -496,7 +552,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info(f"Computing teacher logprobs for {len(train_examples)} training examples")
|
||||
teacher_logprobs_start_time = time.perf_counter()
|
||||
teacher_logprobs_list = await compute_teacher_logprobs(
|
||||
clients=teacher_inference_pool.clients,
|
||||
clients=teacher_inference_pool.train_clients,
|
||||
model_name=config.teacher_model.model.name,
|
||||
samples=train_examples,
|
||||
)
|
||||
@@ -521,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,
|
||||
@@ -532,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())
|
||||
@@ -615,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,
|
||||
}
|
||||
@@ -655,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)
|
||||
@@ -665,8 +728,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Log distributions (rewards, advantages) if enabled
|
||||
monitor.log_distributions(
|
||||
distributions={
|
||||
"rewards": rewards,
|
||||
"advantages": advantages,
|
||||
"rewards": [r["reward"] for r in train_rollouts],
|
||||
"advantages": [r["advantage"] for r in train_rollouts],
|
||||
},
|
||||
step=progress.step,
|
||||
)
|
||||
@@ -699,18 +762,27 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
if config.eval and eval_envs is not None:
|
||||
logger.info("Running final evals")
|
||||
await asyncio.gather(
|
||||
eval_results = await asyncio.gather(
|
||||
*[
|
||||
eval_env.evaluate(
|
||||
model_name=scheduler.model_name,
|
||||
get_client=inference_pool.get_next_client,
|
||||
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
|
||||
]
|
||||
)
|
||||
|
||||
# Save final eval rollouts to disk
|
||||
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", exclude_keys={"trajectory"}
|
||||
)
|
||||
|
||||
# Log final (immutable) samples and distributions to monitor(s)
|
||||
monitor.log_final_samples()
|
||||
monitor.save_final_summary()
|
||||
@@ -729,8 +801,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# failure mode we're guarding against.
|
||||
async def _graceful_shutdown() -> None:
|
||||
training_batch_sender.close()
|
||||
rollout_executor.shutdown(wait=False)
|
||||
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()
|
||||
|
||||
@@ -156,10 +156,10 @@ class Scheduler:
|
||||
Uses (api_base_url, dp_rank) as identity rather than client_idx so that
|
||||
load tracking survives elastic pool refreshes (which reassign indices).
|
||||
"""
|
||||
clients = self.inference_pool.clients
|
||||
clients = self.inference_pool.train_clients
|
||||
while not clients:
|
||||
await asyncio.sleep(1)
|
||||
clients = self.inference_pool.clients
|
||||
clients = self.inference_pool.train_clients
|
||||
inflight = Counter(self._client_identity(info.client_config) for info in self.inflight_requests.values())
|
||||
return min(clients, key=lambda c: inflight[self._client_identity(c)])
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -231,6 +231,7 @@ def interleave_rollout(
|
||||
output: vf.RolloutOutput,
|
||||
vlm_cache: "VLMImageCache | None" = None,
|
||||
cache_key: int | None = None,
|
||||
mm_token_type_ids_mapping: dict[int, int] | None = None,
|
||||
) -> list[TrainingSample] | None:
|
||||
"""
|
||||
Convert vf.RolloutOutput to trainable rollouts by interleaving trajectory steps
|
||||
@@ -304,9 +305,9 @@ def interleave_rollout(
|
||||
tokens.get("routed_experts"),
|
||||
len(tokens["prompt_ids"]) + len(tokens["completion_ids"]),
|
||||
)
|
||||
|
||||
prompt_ids = list(tokens["prompt_ids"])
|
||||
return TrainingSample(
|
||||
prompt_ids=list(tokens["prompt_ids"]),
|
||||
prompt_ids=prompt_ids,
|
||||
prompt_mask=[bool(i) for i in tokens["prompt_mask"]],
|
||||
completion_ids=completion_ids,
|
||||
completion_mask=completion_mask,
|
||||
@@ -315,6 +316,7 @@ def interleave_rollout(
|
||||
teacher_logprobs=None,
|
||||
advantage=None,
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=None,
|
||||
)
|
||||
|
||||
def extend_sample(sample: TrainingSample, prefix_len: int, step_idx: int) -> None:
|
||||
@@ -351,11 +353,11 @@ def interleave_rollout(
|
||||
sample.routed_experts = _align_routed_experts(sample.routed_experts, expected_len)
|
||||
|
||||
# Track [prefix_tokens, sample, last_step_idx] per active sample
|
||||
active_samples: list[list] = []
|
||||
active_samples: list[tuple[list[int], TrainingSample, int]] = []
|
||||
|
||||
first_tokens = prepared_steps[0]
|
||||
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
|
||||
active_samples.append([first_prefix, make_sample(first_tokens), 0])
|
||||
active_samples.append((first_prefix, make_sample(first_tokens), 0))
|
||||
|
||||
for step_idx, _step in enumerate(trajectory[1:], start=1):
|
||||
tokens = prepared_steps[step_idx]
|
||||
@@ -372,8 +374,7 @@ def interleave_rollout(
|
||||
# Extension holds - merge into matched sample
|
||||
prefix_tokens, sample, _ = active_samples[matched_idx]
|
||||
extend_sample(sample, len(prefix_tokens), step_idx=step_idx)
|
||||
active_samples[matched_idx][0] = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
active_samples[matched_idx][2] = step_idx
|
||||
active_samples[matched_idx] = (tokens["prompt_ids"] + tokens["completion_ids"], sample, step_idx)
|
||||
else:
|
||||
# No prefix matches - start a new sample
|
||||
logger.debug(
|
||||
@@ -381,7 +382,7 @@ def interleave_rollout(
|
||||
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
|
||||
)
|
||||
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
active_samples.append([new_prefix, make_sample(tokens), step_idx])
|
||||
active_samples.append((new_prefix, make_sample(tokens), step_idx))
|
||||
|
||||
# Attach images once per sample using only the last merged step
|
||||
if vlm_cache is not None:
|
||||
@@ -391,6 +392,10 @@ def interleave_rollout(
|
||||
sample.pixel_values = pv
|
||||
sample.pixel_values_shape = shape
|
||||
sample.image_grid_thw = grids
|
||||
if mm_token_type_ids_mapping is not None:
|
||||
sample.mm_token_type_ids = [
|
||||
mm_token_type_ids_mapping.get(token_id, 0) for token_id in sample.prompt_ids + sample.completion_ids
|
||||
]
|
||||
|
||||
return [sample for _, sample, _ in active_samples]
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import asyncio
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from itertools import cycle
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -13,6 +14,7 @@ from verifiers.utils.client_utils import setup_openai_client
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import (
|
||||
format_time,
|
||||
get_broadcast_dir,
|
||||
@@ -21,6 +23,12 @@ from prime_rl.utils.utils import (
|
||||
)
|
||||
|
||||
|
||||
def set_default_executor(max_workers: int = 64) -> None:
|
||||
"""Scale the default asyncio thread pool so asyncio.to_thread has enough capacity."""
|
||||
get_logger().info(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
|
||||
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
|
||||
|
||||
|
||||
def print_benchmark(history: dict[str, list[Any]]) -> None:
|
||||
"""
|
||||
Print benchmark results as rich table. Shows formatted step time values.
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
import verifiers as vf
|
||||
from verifiers.utils.save_utils import make_serializable
|
||||
|
||||
from prime_rl.utils.logger import InterceptHandler
|
||||
|
||||
@@ -47,6 +50,25 @@ def get_completion_len(output: vf.RolloutOutput) -> int:
|
||||
return get_seq_len(output) - get_prompt_len(output)
|
||||
|
||||
|
||||
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:
|
||||
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")
|
||||
|
||||
|
||||
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
|
||||
"""Intercepts verifiers logging and routes through prime-rl logger with optional prefix."""
|
||||
vf_logger = logging.getLogger(logger)
|
||||
|
||||
Regular → Executable
+14
-6
@@ -145,11 +145,18 @@ srun bash -c '
|
||||
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
|
||||
|
||||
{%- if kv_offload %}
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"block_size":{{ kv_offload_block_size }},"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
ulimit -l unlimited
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
{%- else %}
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
|
||||
{%- endif %}
|
||||
|
||||
{%- if kv_offload %}
|
||||
DECODE_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
{%- else %}
|
||||
DECODE_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
|
||||
{%- endif %}
|
||||
|
||||
DECODE_COMPILE_CFG='"'"'{"cudagraph_mode":"FULL_DECODE_ONLY"}'"'"'
|
||||
|
||||
# Determine outer replica (P/D pair) and role
|
||||
@@ -212,13 +219,13 @@ srun bash -c '
|
||||
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
|
||||
|
||||
vllm-router \
|
||||
--policy consistent_hash \
|
||||
--policy {{ router_policy }} \
|
||||
--vllm-pd-disaggregation \
|
||||
$REPLICA_ROUTER_ARGS \
|
||||
--host 0.0.0.0 \
|
||||
--port $ROUTER_PORT \
|
||||
--intra-node-data-parallel-size 1 \
|
||||
--worker-startup-timeout-secs 1200 \
|
||||
--intra-node-data-parallel-size {{ dp_per_node }} \
|
||||
--worker-startup-timeout-secs 4200 \
|
||||
--log-level debug \
|
||||
>> $ROUTER_LOG 2>&1 &
|
||||
fi
|
||||
@@ -243,11 +250,12 @@ srun bash -c '
|
||||
echo "Starting vllm-router on $LOCAL_IP:$ROUTER_PORT" | tee $ROUTER_LOG
|
||||
|
||||
vllm-router \
|
||||
--policy consistent_hash \
|
||||
--policy {{ router_policy }} \
|
||||
--worker-urls $ROUTER_ARGS \
|
||||
--host 0.0.0.0 \
|
||||
--port $ROUTER_PORT \
|
||||
--worker-startup-timeout-secs 1200 \
|
||||
--intra-node-data-parallel-size {{ dp_per_node }} \
|
||||
--worker-startup-timeout-secs 4200 \
|
||||
--log-level debug \
|
||||
>> $ROUTER_LOG 2>&1 &
|
||||
fi
|
||||
|
||||
Regular → Executable
+11
-4
@@ -197,11 +197,17 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
export VLLM_NIXL_SIDE_CHANNEL_PORT=5600
|
||||
|
||||
{%- if kv_offload %}
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"block_size":{{ kv_offload_block_size }},"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
ulimit -l unlimited
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
{%- else %}
|
||||
PREFILL_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
|
||||
{%- endif %}
|
||||
|
||||
{%- if kv_offload %}
|
||||
DECODE_KV_CFG='"'"'{"kv_connector":"MultiConnector","kv_role":"kv_both","kv_connector_extra_config":{"connectors":[{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}},{"kv_connector":"OffloadingConnector","kv_role":"kv_both","kv_connector_extra_config":{"cpu_bytes_to_use":{{ kv_offload_cpu_bytes }}}}]}}'"'"'
|
||||
{%- else %}
|
||||
DECODE_KV_CFG='"'"'{"kv_connector":"NixlConnector","kv_role":"kv_both","kv_connector_extra_config":{"num_threads":1}}'"'"'
|
||||
{%- endif %}
|
||||
DECODE_COMPILE_CFG='"'"'{"cudagraph_mode":"FULL_DECODE_ONLY"}'"'"'
|
||||
|
||||
REPLICA_BASE=$((REPLICA_IDX * NODES_PER_INFER_REPLICA))
|
||||
@@ -270,8 +276,8 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
$REPLICA_ROUTER_ARGS \
|
||||
--host 0.0.0.0 \
|
||||
--port $ROUTER_PORT \
|
||||
--intra-node-data-parallel-size 1 \
|
||||
--worker-startup-timeout-secs 1200 \
|
||||
--intra-node-data-parallel-size {{ dp_per_node }} \
|
||||
--worker-startup-timeout-secs 4200 \
|
||||
>> $ROUTER_LOG 2>&1 &
|
||||
fi
|
||||
|
||||
@@ -296,7 +302,8 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
--worker-urls $REPLICA_ROUTER_ARGS \
|
||||
--host 0.0.0.0 \
|
||||
--port $ROUTER_PORT \
|
||||
--worker-startup-timeout-secs 1200 \
|
||||
--intra-node-data-parallel-size {{ dp_per_node }} \
|
||||
--worker-startup-timeout-secs 4200 \
|
||||
>> $ROUTER_LOG 2>&1 &
|
||||
fi
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
inference_logprobs = [0.0] * len(training_example.prompt_ids) + training_example.completion_logprobs
|
||||
advantages = [training_example.advantage] * len(input_ids)
|
||||
position_ids = list(range(len(input_ids)))
|
||||
mm_token_type_ids = training_example.mm_token_type_ids
|
||||
|
||||
# Per-token temperatures: prompt tokens use first completion temp (masked out anyway)
|
||||
# Default to 1.0 if completion is empty (e.g., model generated only tool calls with no text)
|
||||
@@ -35,6 +36,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
teacher_logprobs = teacher_logprobs[:seq_len]
|
||||
if routed_experts is not None:
|
||||
routed_experts = routed_experts[:seq_len]
|
||||
if mm_token_type_ids is not None:
|
||||
mm_token_type_ids = mm_token_type_ids[:seq_len]
|
||||
|
||||
assert (
|
||||
len(input_ids)
|
||||
@@ -54,6 +57,11 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
f"routed_experts: {len(routed_experts)}, input_ids: {len(input_ids)}"
|
||||
)
|
||||
|
||||
if mm_token_type_ids is not None:
|
||||
assert len(mm_token_type_ids) == len(input_ids), (
|
||||
f"mm_token_type_ids: {len(mm_token_type_ids)}, input_ids: {len(input_ids)}"
|
||||
)
|
||||
|
||||
return MicroBatch(
|
||||
input_ids=input_ids,
|
||||
advantages=advantages,
|
||||
@@ -63,6 +71,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
teacher_logprobs=teacher_logprobs,
|
||||
temperatures=temperatures,
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
# Multimodal fields (Qwen3-VL) - passed through without modification
|
||||
pixel_values=training_example.pixel_values,
|
||||
pixel_values_shape=training_example.pixel_values_shape,
|
||||
@@ -120,6 +129,10 @@ def packed_samples_into_micro_bs(
|
||||
if bin_content.routed_experts is None:
|
||||
bin_content.routed_experts = []
|
||||
bin_content.routed_experts.extend(sample.routed_experts)
|
||||
if sample.mm_token_type_ids is not None:
|
||||
if bin_content.mm_token_type_ids is None:
|
||||
bin_content.mm_token_type_ids = []
|
||||
bin_content.mm_token_type_ids.extend(sample.mm_token_type_ids)
|
||||
bin_content.position_ids.extend(sample.position_ids)
|
||||
bin_content.lora_num_tokens[idx] += len(sample.input_ids)
|
||||
break
|
||||
@@ -159,6 +172,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
|
||||
micro_batch.lora_num_tokens[-1] += (
|
||||
padding_size # We send padding to the last lora so that tokens have ascending lora idx
|
||||
)
|
||||
if micro_batch.mm_token_type_ids is not None:
|
||||
micro_batch.mm_token_type_ids.extend([0] * padding_size)
|
||||
|
||||
return micro_batch
|
||||
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
# Disable transformers hub kernel interception by default. The `kernels` package, when installed,
|
||||
# causes transformers to auto-replace modules (e.g. mamba-ssm) with hub kernel versions that may
|
||||
# have incompatible CUDA requirements. We only enable it explicitly for models that need it (GPT-OSS).
|
||||
os.environ.setdefault("USE_HUB_KERNELS", "NO")
|
||||
|
||||
import torch
|
||||
import torch._dynamo
|
||||
import torch.nn as nn
|
||||
@@ -47,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.
|
||||
|
||||
@@ -235,6 +255,23 @@ def get_model(
|
||||
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
|
||||
)
|
||||
|
||||
# GPT-OSS only supports FlashAttention via kernels-community/vllm-flash-attn3, which requires Hopper (SM 90).
|
||||
# On other architectures (e.g. Blackwell), users must fall back to eager attention.
|
||||
HOPPER_MAJOR = 9
|
||||
if getattr(model_config, "model_type", "") == "gpt_oss":
|
||||
if config.attn != "eager":
|
||||
major, minor = torch.cuda.get_device_capability()
|
||||
if major != HOPPER_MAJOR:
|
||||
raise ValueError(
|
||||
f"GPT-OSS requires 'attn = \"eager\"' on non-Hopper GPUs (detected SM {major}{minor}). "
|
||||
f"The only flash attention kernel supported by GPT-OSS (kernels-community/vllm-flash-attn3) is Hopper-only. "
|
||||
f'Set [trainer.model] attn = "eager" in your config.'
|
||||
)
|
||||
# Enable hub kernels for GPT-OSS (disabled by default to avoid interfering with other models).
|
||||
import transformers.integrations.hub_kernels as _hub_kernels
|
||||
|
||||
_hub_kernels._kernels_enabled = True
|
||||
|
||||
# Fallback Qwen3.5 patch detection from loaded config model_type
|
||||
if getattr(model_config, "model_type", "").startswith("qwen3_5_moe"):
|
||||
_patch_qwen3_5_text_position_ids()
|
||||
@@ -258,10 +295,15 @@ def get_model(
|
||||
),
|
||||
None,
|
||||
)
|
||||
# Some HF configs (e.g. Llama 3.2) set pad_token_id to a list, which
|
||||
# crashes both huggingface_hub's strict setter and transformers'
|
||||
# GenerationConfig.validate(). Unwrap before assigning.
|
||||
if isinstance(pad_token_id, list):
|
||||
pad_token_id = pad_token_id[0]
|
||||
model_config.pad_token_id = pad_token_id
|
||||
|
||||
# Some HF configs (e.g. Llama 3.2) set pad_token_id to a list, which crashes
|
||||
# transformers' GenerationConfig.validate() when it does `pad_token_id < 0`.
|
||||
# Handle list pad_token_id that was already set on the config (not from our
|
||||
# fallback above, but directly in the model's config.json).
|
||||
if isinstance(getattr(model_config, "pad_token_id", None), list):
|
||||
model_config.pad_token_id = model_config.pad_token_id[0]
|
||||
|
||||
@@ -333,9 +375,17 @@ def get_model(
|
||||
|
||||
|
||||
def setup_tokenizer(config: TokenizerConfig) -> PreTrainedTokenizer:
|
||||
logger = get_logger()
|
||||
tokenizer = AutoTokenizer.from_pretrained(config.name, trust_remote_code=config.trust_remote_code)
|
||||
if config.chat_template is not None:
|
||||
tokenizer.chat_template = config.chat_template
|
||||
path = Path(config.chat_template)
|
||||
if path.is_file():
|
||||
logger.info(f"Loading custom chat template from file: {path}")
|
||||
tokenizer.chat_template = path.read_text()
|
||||
logger.debug(f"Chat template content:\n{tokenizer.chat_template}")
|
||||
else:
|
||||
logger.info("Using inline custom chat template")
|
||||
tokenizer.chat_template = config.chat_template
|
||||
tokenizer.pad_token_id = tokenizer.eos_token_id
|
||||
|
||||
return tokenizer
|
||||
@@ -585,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:
|
||||
@@ -599,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
|
||||
@@ -846,6 +914,7 @@ def forward(
|
||||
# Multimodal fields (Qwen3-VL)
|
||||
pixel_values: Float[Tensor, "num_patches patch_dim"] | None = None,
|
||||
image_grid_thw: Int[Tensor, "num_images 3"] | None = None,
|
||||
mm_token_type_ids: Int[Tensor, "batch seq"] | None = None,
|
||||
) -> PrimeLmOutput:
|
||||
# Build kwargs for model forward
|
||||
kwargs = {
|
||||
@@ -860,6 +929,7 @@ def forward(
|
||||
assert image_grid_thw is not None, "pixel_values requires image_grid_thw for MRoPE computation"
|
||||
kwargs["pixel_values"] = pixel_values
|
||||
kwargs["image_grid_thw"] = image_grid_thw
|
||||
kwargs["mm_token_type_ids"] = mm_token_type_ids
|
||||
else:
|
||||
kwargs["position_ids"] = position_ids
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -36,6 +36,8 @@ class TensorMicroBatch(TypedDict):
|
||||
pixel_values: Float[Tensor, "num_patches patch_dim"] | None
|
||||
# image_grid_thw: grid dimensions [num_images, 3] where each entry is [temporal, height, width]
|
||||
image_grid_thw: Int[Tensor, "num_images 3"] | None
|
||||
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
|
||||
mm_token_type_ids: Int[Tensor, "batch seq"] | None
|
||||
|
||||
|
||||
class FakeDataLoader:
|
||||
@@ -108,6 +110,7 @@ class FakeDataLoader:
|
||||
"routed_experts": None,
|
||||
"pixel_values": None,
|
||||
"image_grid_thw": None,
|
||||
"mm_token_type_ids": None,
|
||||
}
|
||||
|
||||
def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch:
|
||||
@@ -133,6 +136,7 @@ class FakeDataLoader:
|
||||
"routed_experts": None,
|
||||
"pixel_values": None,
|
||||
"image_grid_thw": None,
|
||||
"mm_token_type_ids": None,
|
||||
}
|
||||
|
||||
|
||||
@@ -206,6 +210,9 @@ class DataLoader:
|
||||
image_grid_thw=torch.tensor(micro_batch.image_grid_thw, dtype=torch.long)
|
||||
if micro_batch.image_grid_thw is not None
|
||||
else None,
|
||||
mm_token_type_ids=torch.tensor(micro_batch.mm_token_type_ids, dtype=torch.long).unsqueeze(0)
|
||||
if micro_batch.mm_token_type_ids is not None
|
||||
else None,
|
||||
routed_experts=torch.tensor(micro_batch.routed_experts, dtype=torch.int32).unsqueeze(
|
||||
0
|
||||
) # [1, seq_len, layers, topk]
|
||||
|
||||
@@ -109,7 +109,10 @@ def train(config: TrainerConfig):
|
||||
setup_torch_distributed(
|
||||
timeout=timedelta(seconds=config.dist_timeout_seconds), enable_gloo=config.model.fsdp_cpu_offload
|
||||
)
|
||||
torch.set_float32_matmul_precision("high")
|
||||
# Configurable to support ROCm/AMD GPUs where reduced precision
|
||||
# matmul corrupts softmax over large vocabularies. Override via config
|
||||
# (e.g. matmul_precision = "highest") on ROCm.
|
||||
torch.set_float32_matmul_precision(config.matmul_precision)
|
||||
|
||||
# Setup multi run manager and offsets (including LoRA validation/scaling hooks if applicable)
|
||||
multi_run_manager = setup_multi_run_manager(
|
||||
@@ -185,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()
|
||||
@@ -354,6 +358,11 @@ def train(config: TrainerConfig):
|
||||
image_grid_thw = (
|
||||
micro_batch["image_grid_thw"].to("cuda") if micro_batch.get("image_grid_thw") is not None else None
|
||||
)
|
||||
mm_token_type_ids = (
|
||||
micro_batch["mm_token_type_ids"].to("cuda")
|
||||
if micro_batch.get("mm_token_type_ids") is not None
|
||||
else None
|
||||
)
|
||||
|
||||
labels = shift_tensor_left(input_ids)
|
||||
|
||||
@@ -397,6 +406,7 @@ def train(config: TrainerConfig):
|
||||
temperature=temperatures,
|
||||
pixel_values=pixel_values,
|
||||
image_grid_thw=image_grid_thw,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
routed_experts=routed_experts,
|
||||
)
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from prime_rl.configs.sft import DataConfig, LossMaskConfig, SFTDataConfig
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.chat_template import (
|
||||
IncrementalTokenizationError,
|
||||
build_incremental_token_mask,
|
||||
deserialize_tool_calls,
|
||||
normalize_messages,
|
||||
@@ -205,14 +206,18 @@ class SFTDataset(StatefulIterableDataset):
|
||||
case _:
|
||||
raise ValueError(f"Invalid message role: {message['role']}")
|
||||
|
||||
input_ids, loss_mask = build_incremental_token_mask(
|
||||
self.tokenizer,
|
||||
messages,
|
||||
role_to_mask=should_mask,
|
||||
tools=tools,
|
||||
chat_template_kwargs=example.get("chat_template_kwargs", {}),
|
||||
collapse_consecutive_tool_messages=True,
|
||||
)
|
||||
try:
|
||||
input_ids, loss_mask = build_incremental_token_mask(
|
||||
self.tokenizer,
|
||||
messages,
|
||||
role_to_mask=should_mask,
|
||||
tools=tools,
|
||||
chat_template_kwargs=example.get("chat_template_kwargs", {}),
|
||||
collapse_consecutive_tool_messages=True,
|
||||
)
|
||||
except IncrementalTokenizationError as e:
|
||||
self.logger.warning(f"Skipping example {example.get('__index', '')}: {e}")
|
||||
return None
|
||||
|
||||
# If EOS token is not found, manually append it
|
||||
if not self.tokenizer.eos_token_id in input_ids:
|
||||
|
||||
@@ -84,7 +84,10 @@ def train(config: SFTConfig):
|
||||
setup_torch_distributed(
|
||||
timeout=timedelta(seconds=config.dist_timeout_seconds), enable_gloo=config.model.fsdp_cpu_offload
|
||||
)
|
||||
torch.set_float32_matmul_precision("high")
|
||||
# Configurable to support ROCm/AMD GPUs where reduced precision
|
||||
# matmul corrupts softmax over large vocabularies. Override via config
|
||||
# (e.g. matmul_precision = "highest") on ROCm.
|
||||
torch.set_float32_matmul_precision(config.matmul_precision)
|
||||
|
||||
if config.model.lora is not None:
|
||||
setup_multi_run_manager(config.output_dir, 1, torch.device("cuda", world.local_rank), config.model.lora)
|
||||
@@ -106,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})")
|
||||
@@ -128,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()
|
||||
|
||||
@@ -6,8 +6,8 @@ from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender, Traini
|
||||
from prime_rl.transport.types import MicroBatch, TrainingBatch
|
||||
from prime_rl.utils.pathing import get_rollout_dir, get_step_path, sync_wait_for_path
|
||||
|
||||
BATCH_FILE_TMP_NAME = "rollouts.bin.tmp"
|
||||
BATCH_FILE_NAME = "rollouts.bin"
|
||||
BATCH_FILE_TMP_NAME = "train_rollouts.bin.tmp"
|
||||
BATCH_FILE_NAME = "train_rollouts.bin"
|
||||
LOG_FREQ_SECONDS = 10
|
||||
|
||||
|
||||
|
||||
@@ -23,6 +23,9 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
|
||||
|
||||
routed_experts: list[list[list[int]]] | None = None # [seq_len, layers, topk]
|
||||
|
||||
# mm_token_type_ids: token type ids per token [batch seq], int64 (0=text, 1=image, 2=video)
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
|
||||
|
||||
class TrainingBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
"""A batch of training examples with metadata for transport."""
|
||||
@@ -51,3 +54,5 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
pixel_values_shape: list[int] | None = None # [num_patches, patch_dim]
|
||||
# image_grid_thw: grid dimensions [num_images, 3] where each entry is [temporal, height, width]
|
||||
image_grid_thw: list[list[int]] | None = None
|
||||
# mm_token_type_ids: token type ids per token [batch seq], int64 (0=text, 1=image, 2=video)
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
|
||||
@@ -4,6 +4,12 @@ from typing import Any, Callable
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
|
||||
class IncrementalTokenizationError(ValueError):
|
||||
"""Raised when incremental tokenization produces inconsistent token prefixes."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def common_prefix_len(a: list[int], b: list[int]) -> int:
|
||||
max_len = min(len(a), len(b))
|
||||
for idx in range(max_len):
|
||||
@@ -130,7 +136,12 @@ def build_incremental_token_mask(
|
||||
processor=processor,
|
||||
)
|
||||
|
||||
assert prev_ids == cur_ids[:prev_len], "Mismatch in incremental tokenization with chat template."
|
||||
if prev_ids != cur_ids[:prev_len]:
|
||||
raise IncrementalTokenizationError(
|
||||
f"Mismatch in incremental tokenization with chat template at message {idx} (role={role}). "
|
||||
"This usually means the chat template is not stable under incremental application. "
|
||||
"The sample will be skipped."
|
||||
)
|
||||
|
||||
token_mask.extend([role_to_mask(message)] * (len(cur_ids) - prev_len))
|
||||
prev_ids = cur_ids
|
||||
|
||||
@@ -21,7 +21,7 @@ class InferencePool(Protocol):
|
||||
"""Protocol for inference pools (static or elastic)."""
|
||||
|
||||
@property
|
||||
def clients(self) -> list[vf.ClientConfig]:
|
||||
def train_clients(self) -> list[vf.ClientConfig]:
|
||||
"""Get inference clients."""
|
||||
...
|
||||
|
||||
@@ -34,8 +34,8 @@ class InferencePool(Protocol):
|
||||
"""Update the model name."""
|
||||
...
|
||||
|
||||
async def get_next_client(self) -> vf.ClientConfig:
|
||||
"""Get next client in round-robin fashion."""
|
||||
async def get_eval_client(self) -> vf.ClientConfig:
|
||||
"""Get next eval client in round-robin fashion."""
|
||||
...
|
||||
|
||||
async def wait_for_ready(self, model_name: str, timeout: int = 1800) -> None:
|
||||
@@ -59,18 +59,22 @@ class StaticInferencePool:
|
||||
"""Static inference pool with fixed client list."""
|
||||
|
||||
def __init__(
|
||||
self, clients: list[vf.ClientConfig], admin_clients: list[AsyncClient], skip_model_check: bool = False
|
||||
self,
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
):
|
||||
self._clients = clients
|
||||
self._admin_clients = admin_clients
|
||||
self._skip_model_check = skip_model_check
|
||||
self._idx_to_client = {client.client_idx: client for client in clients}
|
||||
self._client_cycle = cycle(clients)
|
||||
self.model_name = None # unused
|
||||
self._train_clients = setup_clients(client_config, client_type=train_client_type)
|
||||
self._eval_clients = setup_clients(client_config, client_type=eval_client_type)
|
||||
self._admin_clients = setup_admin_clients(client_config)
|
||||
self._skip_model_check = client_config.skip_model_check
|
||||
self._eval_cycle = cycle(self._eval_clients)
|
||||
self.model_name = model_name
|
||||
|
||||
@property
|
||||
def clients(self) -> list[vf.ClientConfig]:
|
||||
return self._clients
|
||||
def train_clients(self) -> list[vf.ClientConfig]:
|
||||
return self._train_clients
|
||||
|
||||
@property
|
||||
def admin_clients(self) -> list[AsyncClient]:
|
||||
@@ -79,8 +83,12 @@ class StaticInferencePool:
|
||||
def update_model_name(self, model_name: str) -> None:
|
||||
self.model_name = model_name
|
||||
|
||||
async def get_next_client(self) -> vf.ClientConfig:
|
||||
return next(self._client_cycle)
|
||||
@property
|
||||
def eval_clients(self) -> list[vf.ClientConfig]:
|
||||
return self._eval_clients
|
||||
|
||||
async def get_eval_client(self) -> vf.ClientConfig:
|
||||
return next(self._eval_cycle)
|
||||
|
||||
async def wait_for_ready(self, model_name: str, timeout: int = 1800) -> None:
|
||||
await check_health(self._admin_clients, timeout=timeout)
|
||||
@@ -97,15 +105,27 @@ class StaticInferencePool:
|
||||
|
||||
|
||||
async def setup_inference_pool(
|
||||
client_config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
) -> InferencePool:
|
||||
"""Create an inference pool from config (static or elastic)."""
|
||||
logger = get_logger()
|
||||
|
||||
if train_client_type == "openai_chat_completions_token":
|
||||
logger.warning(
|
||||
"Token-in-token-out (TITO) client is enabled for training. Only use "
|
||||
"this if your environment has a linear history and the chat "
|
||||
"template has the extension property."
|
||||
)
|
||||
|
||||
if client_config.is_elastic:
|
||||
from prime_rl.utils.elastic import ElasticInferencePool
|
||||
|
||||
return await ElasticInferencePool.from_config(client_config, model_name=model_name, client_type=client_type)
|
||||
return await ElasticInferencePool.from_config(
|
||||
client_config, model_name=model_name, train_client_type=train_client_type, eval_client_type=eval_client_type
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Initializing static inference pool (base_url={', '.join(client_config.base_url)}, "
|
||||
@@ -113,9 +133,7 @@ async def setup_inference_pool(
|
||||
f"api_key_var={client_config.api_key_var}, headers={client_config.headers})"
|
||||
)
|
||||
return StaticInferencePool(
|
||||
clients=setup_clients(client_config, client_type=client_type),
|
||||
admin_clients=setup_admin_clients(client_config),
|
||||
skip_model_check=client_config.skip_model_check,
|
||||
client_config, model_name=model_name, train_client_type=train_client_type, eval_client_type=eval_client_type
|
||||
)
|
||||
|
||||
|
||||
@@ -167,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."""
|
||||
|
||||
|
||||
@@ -102,50 +102,48 @@ class ElasticInferencePool:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hostname: str,
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
port: int = 8000,
|
||||
sync_interval: float = 5.0,
|
||||
client_type: str = "openai_chat_completions",
|
||||
router_url: str | None = None,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.hostname = hostname
|
||||
self.client_config = client_config
|
||||
self.model_name = model_name
|
||||
self.base_model_name = model_name # Keep original for health checks
|
||||
self.port = port
|
||||
self.sync_interval = sync_interval
|
||||
self.client_type = client_type
|
||||
self.router_url = router_url
|
||||
self.hostname = client_config.elastic.hostname
|
||||
self.port = client_config.elastic.port
|
||||
self.sync_interval = client_config.elastic.sync_interval
|
||||
self.train_client_type = train_client_type
|
||||
self.eval_client_type = eval_client_type
|
||||
self.router_url = client_config.router_url
|
||||
|
||||
self._servers: dict[str, ServerState] = {}
|
||||
self._admin_clients: dict[str, AsyncClient] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
self._desired: AdapterState = AdapterState()
|
||||
|
||||
self._clients: list[vf.ClientConfig] = []
|
||||
self._train_clients: list[vf.ClientConfig] = []
|
||||
self._eval_clients: list[vf.ClientConfig] = []
|
||||
self._client_urls: list[str] = []
|
||||
self._client_index = 0
|
||||
|
||||
self._eval_index = 0
|
||||
|
||||
self._sync_task: asyncio.Task | None = None
|
||||
self._started = False
|
||||
|
||||
@classmethod
|
||||
async def from_config(
|
||||
cls, config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
|
||||
cls,
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
) -> ElasticInferencePool:
|
||||
if config.elastic is None:
|
||||
if client_config.elastic is None:
|
||||
raise ValueError("Elastic inference pool requires elastic config")
|
||||
pool = cls(
|
||||
hostname=config.elastic.hostname,
|
||||
client_config=config,
|
||||
model_name=model_name,
|
||||
port=config.elastic.port,
|
||||
sync_interval=config.elastic.sync_interval,
|
||||
client_type=client_type,
|
||||
router_url=config.router_url,
|
||||
client_config, model_name=model_name, train_client_type=train_client_type, eval_client_type=eval_client_type
|
||||
)
|
||||
await pool.start()
|
||||
return pool
|
||||
@@ -163,8 +161,8 @@ class ElasticInferencePool:
|
||||
def ready_urls(self) -> list[str]:
|
||||
return [self._build_inference_url(ip) for ip, s in self._servers.items() if s.status == "ready"]
|
||||
|
||||
@property
|
||||
def clients(self) -> list[vf.ClientConfig]:
|
||||
def _rebuild_clients(self) -> None:
|
||||
"""Rebuild inference clients when the set of ready URLs changes."""
|
||||
# When a router URL is configured, route inference requests through it
|
||||
# instead of directly to discovered pods. Admin operations still use
|
||||
# individual pod IPs via admin_clients.
|
||||
@@ -176,34 +174,36 @@ class ElasticInferencePool:
|
||||
urls = self.ready_urls
|
||||
if set(urls) != set(self._client_urls):
|
||||
self._client_urls = urls
|
||||
self._client_index = 0
|
||||
self._clients = (
|
||||
setup_clients(
|
||||
ClientConfig(
|
||||
timeout=self.client_config.timeout,
|
||||
connect_timeout=self.client_config.connect_timeout,
|
||||
base_url=urls,
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
dp_rank_count=self.client_config.dp_rank_count,
|
||||
),
|
||||
client_type=self.client_type,
|
||||
)
|
||||
if urls
|
||||
else []
|
||||
|
||||
self._eval_index = 0
|
||||
url_config = ClientConfig(
|
||||
timeout=self.client_config.timeout,
|
||||
connect_timeout=self.client_config.connect_timeout,
|
||||
base_url=urls,
|
||||
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,
|
||||
)
|
||||
return self._clients
|
||||
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 []
|
||||
|
||||
@property
|
||||
def has_clients(self) -> bool:
|
||||
return len(self.clients) > 0
|
||||
def train_clients(self) -> list[vf.ClientConfig]:
|
||||
self._rebuild_clients()
|
||||
return self._train_clients
|
||||
|
||||
async def get_next_client(self) -> vf.ClientConfig:
|
||||
"""Get next client in round-robin fashion."""
|
||||
while not self.has_clients:
|
||||
@property
|
||||
def eval_clients(self) -> list[vf.ClientConfig]:
|
||||
self._rebuild_clients()
|
||||
return self._eval_clients
|
||||
|
||||
async def get_eval_client(self) -> vf.ClientConfig:
|
||||
"""Get next eval client in round-robin fashion."""
|
||||
while not self.eval_clients:
|
||||
await asyncio.sleep(self.sync_interval)
|
||||
client = self._clients[self._client_index % len(self._clients)]
|
||||
self._client_index += 1
|
||||
client = self._eval_clients[self._eval_index % len(self._eval_clients)]
|
||||
self._eval_index += 1
|
||||
return client
|
||||
|
||||
@property
|
||||
@@ -439,7 +439,8 @@ class ElasticInferencePool:
|
||||
for ip in list(self._servers.keys()):
|
||||
await self._remove_server(ip)
|
||||
|
||||
self._clients = []
|
||||
self._train_clients = []
|
||||
self._eval_clients = []
|
||||
self._client_urls = []
|
||||
self._started = False
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -12,6 +12,7 @@ from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from wandb.errors import CommError
|
||||
|
||||
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
|
||||
from prime_rl.utils.chat_template import deserialize_tool_calls
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
|
||||
@@ -195,7 +196,10 @@ class WandbMonitor(Monitor):
|
||||
if not completion:
|
||||
continue
|
||||
if isinstance(completion, list):
|
||||
completion = self.tokenizer.apply_chat_template(completion, tokenize=False)
|
||||
try:
|
||||
completion = self.tokenizer.apply_chat_template(deserialize_tool_calls(completion), tokenize=False)
|
||||
except Exception:
|
||||
completion = str(completion)
|
||||
sample = {
|
||||
"step": step,
|
||||
"env": env_name,
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -104,6 +104,30 @@ def validate_shared_max_async_level(
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_tokenizer(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
inference: Optional[InferenceConfig] = None,
|
||||
) -> None:
|
||||
# Validate chat_template is consistent across all components.
|
||||
# We only check chat_template (not name/trust_remote_code) because those
|
||||
# are auto-derived from model names which may legitimately differ (e.g.
|
||||
# when inference uses an FP8 quantized variant of the same model).
|
||||
if trainer.tokenizer.chat_template != orchestrator.tokenizer.chat_template:
|
||||
raise ValueError(
|
||||
f"Trainer chat_template ({trainer.tokenizer.chat_template!r}) and orchestrator "
|
||||
f"chat_template ({orchestrator.tokenizer.chat_template!r}) do not match. "
|
||||
f"Use the shared [tokenizer] config to set chat_template for both."
|
||||
)
|
||||
if inference is not None:
|
||||
if trainer.tokenizer.chat_template != inference.model.chat_template:
|
||||
raise ValueError(
|
||||
f"Inference chat_template ({inference.model.chat_template!r}) does not match "
|
||||
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
|
||||
f"Use the shared [tokenizer] config to set chat_template for all components."
|
||||
)
|
||||
|
||||
|
||||
def validate_shared_weight_broadcast(
|
||||
trainer: TrainerConfig,
|
||||
orchestrator: OrchestratorConfig,
|
||||
|
||||
@@ -22,40 +22,188 @@ 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."""
|
||||
return {
|
||||
"reward": reward,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(completion_len))}}],
|
||||
}
|
||||
|
||||
|
||||
def test_compute_advantages_with_config():
|
||||
rewards = [1.0, 0.5, 0.8, 0.2, 0.9, 0.1]
|
||||
lengths = [10, 12, 8, 15, 11, 9]
|
||||
rollouts = [_make_rollout(r, l) for r, l in zip(rewards, lengths)]
|
||||
|
||||
result = compute_advantages(rewards, lengths, samples_per_problem=3, advantage_config=DefaultAdvantageConfig())
|
||||
compute_advantages(rollouts, samples_per_problem=3, advantage_config=DefaultAdvantageConfig())
|
||||
|
||||
assert len(result) == 6
|
||||
# First 3 should sum to ~0 (mean subtracted)
|
||||
assert abs(sum(result[:3])) < 1e-5
|
||||
# Last 3 should sum to ~0
|
||||
assert abs(sum(result[3:])) < 1e-5
|
||||
advantages = [r["advantage"] for r in rollouts]
|
||||
assert len(advantages) == 6
|
||||
assert abs(sum(advantages[:3])) < 1e-5
|
||||
assert abs(sum(advantages[3:])) < 1e-5
|
||||
|
||||
|
||||
def test_compute_advantages_without_config():
|
||||
rewards = [1.0, 0.5, 0.8]
|
||||
lengths = [10, 12, 8]
|
||||
rollouts = [_make_rollout(r, l) for r, l in zip(rewards, lengths)]
|
||||
|
||||
result = compute_advantages(rewards, lengths, samples_per_problem=3, advantage_config=None)
|
||||
compute_advantages(rollouts, samples_per_problem=3, advantage_config=None)
|
||||
|
||||
# Without config, returns raw rewards
|
||||
assert result == rewards
|
||||
advantages = [r["advantage"] for r in rollouts]
|
||||
assert advantages == rewards
|
||||
|
||||
|
||||
def test_setup_advantage_fn_with_custom_config():
|
||||
@@ -72,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
|
||||
|
||||
@@ -1078,7 +1078,9 @@ def test_interleave_rollout_with_vlm_cache():
|
||||
error=None,
|
||||
)
|
||||
|
||||
rollouts = interleave_rollout(output, vlm_cache=cache)
|
||||
# Token 2 is an image token, token 5 is a video token
|
||||
mm_mapping = {2: 1, 5: 2}
|
||||
rollouts = interleave_rollout(output, vlm_cache=cache, mm_token_type_ids_mapping=mm_mapping)
|
||||
|
||||
# Extension holds (step 1 prompt [1,2,3,4,5] extends prefix [1,2,3,4])
|
||||
# so both steps merge into a single sample with cumulative images from step 1
|
||||
@@ -1092,6 +1094,8 @@ def test_interleave_rollout_with_vlm_cache():
|
||||
# Images: cumulative from last merged step (step 1 has 2 images)
|
||||
assert _decode_pixels(rollout.pixel_values, rollout.pixel_values_shape) == [[1.0], [2.0]]
|
||||
assert rollout.image_grid_thw == [[1, 2, 3], [1, 4, 4]]
|
||||
# mm_token_type_ids: full sequence [1,2,3,4,5,6,7] → [0,1,0,0,2,0,0]
|
||||
assert rollout.mm_token_type_ids == [0, 1, 0, 0, 2, 0, 0]
|
||||
|
||||
|
||||
def test_interleave_rollout_uses_cache_key_override():
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -185,12 +185,12 @@ def test_adapter_state_creation():
|
||||
|
||||
def test_adapter_matches_when_no_adapter_desired():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
# No adapter desired (base model inference)
|
||||
assert pool._adapter_matches_desired(None) is True
|
||||
assert pool._adapter_matches_desired(AdapterState("x", Path("/x"), 0)) is True
|
||||
@@ -198,12 +198,12 @@ def test_adapter_matches_when_no_adapter_desired():
|
||||
|
||||
def test_adapter_matches_by_path():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
pool._desired.path = Path("/weights/step_100")
|
||||
pool._desired.step = 100
|
||||
|
||||
@@ -216,12 +216,12 @@ def test_adapter_matches_by_path():
|
||||
|
||||
def test_adapter_matches_by_step_when_nonzero():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
pool._desired.path = Path("/weights/step_100")
|
||||
pool._desired.step = 100
|
||||
|
||||
@@ -232,12 +232,12 @@ def test_adapter_matches_by_step_when_nonzero():
|
||||
|
||||
def test_adapter_does_not_match_by_zero_step():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
pool._desired.path = Path("/weights/step_0")
|
||||
pool._desired.step = 0
|
||||
|
||||
@@ -248,12 +248,12 @@ def test_adapter_does_not_match_by_zero_step():
|
||||
|
||||
def test_adapter_returns_false_when_no_adapter_loaded():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
pool._desired.path = Path("/weights/step_100")
|
||||
pool._desired.step = 100
|
||||
|
||||
@@ -266,12 +266,12 @@ def test_adapter_returns_false_when_no_adapter_loaded():
|
||||
def test_get_loaded_adapter_finds_correct_adapter_when_multiple_loaded():
|
||||
"""Test that _get_loaded_adapter returns the adapter matching desired name, not the first one."""
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
|
||||
# Set the desired adapter name
|
||||
pool._desired.name = "rft-target-run"
|
||||
@@ -317,12 +317,12 @@ def test_get_loaded_adapter_finds_correct_adapter_when_multiple_loaded():
|
||||
def test_get_loaded_adapter_returns_none_when_desired_adapter_not_found():
|
||||
"""Test that _get_loaded_adapter returns None when desired adapter is not in the list."""
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
|
||||
pool._desired.name = "rft-missing-run"
|
||||
pool._desired.path = Path("/data/outputs/missing_run/broadcasts/step_5")
|
||||
@@ -348,12 +348,12 @@ def test_get_loaded_adapter_returns_none_when_desired_adapter_not_found():
|
||||
def test_get_loaded_adapter_parses_step_from_path():
|
||||
"""Test that _get_loaded_adapter correctly parses step number from path."""
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
|
||||
pool._desired.name = "my-lora"
|
||||
|
||||
@@ -377,12 +377,12 @@ def test_get_loaded_adapter_parses_step_from_path():
|
||||
def test_get_loaded_adapter_handles_step_dash_format():
|
||||
"""Test that _get_loaded_adapter parses step-N format (with dash)."""
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
|
||||
pool._desired.name = "my-lora"
|
||||
|
||||
|
||||
@@ -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"
|
||||
@@ -1461,6 +1467,20 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/43/6a/ca128561b22b60bd5a0c4ea26649e68c8556b82bc70a0c396eebc977fe86/jupyterlab_widgets-3.0.15-py3-none-any.whl", hash = "sha256:d59023d7d7ef71400d51e6fee9a88867f6e65e10a4201605d2d7f3e8f012a31c", size = 216571, upload-time = "2025-05-05T12:32:29.534Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kernels"
|
||||
version = "0.12.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "packaging", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "pyyaml", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/b3/84/9f68f355f6ce99e977872021fbdbafadcf2820f51d3f7bd697ec3801cb7a/kernels-0.12.3.tar.gz", hash = "sha256:87e29716578e7e71dc5a7578e0132bfdae305bedaeb602698f87c88ca6c60e32", size = 57407, upload-time = "2026-03-20T10:20:42.166Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e7/3e/778e4a86830e9139df2d16d86c4488fce426ec19daa83cbd2854ef389030/kernels-0.12.3-py3-none-any.whl", hash = "sha256:5d1d33fcb774e03bb7f0688ac24d91ef6b963692f80f0a85ddd2286e69f3cf2f", size = 55501, upload-time = "2026-03-20T10:20:40.643Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kubernetes"
|
||||
version = "35.0.0"
|
||||
@@ -1574,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]]
|
||||
@@ -2586,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')" },
|
||||
@@ -2601,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]]
|
||||
@@ -2662,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')" },
|
||||
@@ -2699,6 +2722,9 @@ flash-attn-3 = [
|
||||
flash-attn-cute = [
|
||||
{ name = "flash-attn-4", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
gpt-oss = [
|
||||
{ name = "kernels", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
quack = [
|
||||
{ name = "quack-kernels", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
@@ -2734,6 +2760,7 @@ requires-dist = [
|
||||
{ name = "flash-attn-4", marker = "extra == 'flash-attn-cute'", git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=abd9943b" },
|
||||
{ name = "flash-linear-attention", git = "https://github.com/fla-org/flash-linear-attention" },
|
||||
{ name = "jaxtyping", specifier = ">=0.3.2" },
|
||||
{ name = "kernels", marker = "extra == 'gpt-oss'" },
|
||||
{ name = "liger-kernel", specifier = ">=0.5.10" },
|
||||
{ name = "logic-env", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
|
||||
{ name = "loguru", specifier = ">=0.7.3" },
|
||||
@@ -2746,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" },
|
||||
@@ -2769,13 +2798,13 @@ 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/" },
|
||||
]
|
||||
provides-extras = ["flash-attn", "flash-attn-3", "flash-attn-cute", "envs", "disagg", "quack", "all"]
|
||||
provides-extras = ["flash-attn", "flash-attn-3", "flash-attn-cute", "envs", "disagg", "gpt-oss", "quack", "all"]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [
|
||||
@@ -2806,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]]
|
||||
@@ -4006,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')" },
|
||||
@@ -4127,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'" },
|
||||
@@ -4138,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