Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
060f25bb3a | ||
|
|
77af037537 | ||
|
|
9281c5589a | ||
|
|
9dbb523933 | ||
|
|
5789850d4d | ||
|
|
146fcd0136 | ||
|
|
b0612a0e1f | ||
|
|
c0a026c0d4 | ||
|
|
7c9c1308dc | ||
|
|
941019f2e3 | ||
|
|
9e1f0521e3 |
+3
-2
@@ -23,7 +23,8 @@ configs/endpoints.py
|
||||
final_summary.json
|
||||
.pydantic_config
|
||||
.chroma_db
|
||||
|
||||
deps/nixl_*
|
||||
nixl_workspace/*
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
@@ -202,4 +203,4 @@ debug_I2_zero_band
|
||||
|
||||
outputs/
|
||||
|
||||
third_party/
|
||||
third_party/
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
|
||||
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
|
||||
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
|
||||
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Trainer config for multi-run RL integration test
|
||||
max_concurrent_runs = 2
|
||||
enable_token_export = true
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
Vendored
+1
-1
Submodule deps/research-environments updated: 4c08260f07...841f9a54df
Vendored
+1
-1
Submodule deps/verifiers updated: 0ad8b4d523...78c1b3c545
@@ -2,7 +2,7 @@
|
||||
|
||||
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `token_export` flag) that aren't surfaced here.
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
|
||||
@@ -167,6 +167,9 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Training nodes per FSDP island. Auto-sets ``trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
|
||||
orchestrator_on_inference: bool = False
|
||||
"""Run the orchestrator on the last inference node instead of trainer rank 0 (frees host RAM on the trainer node)."""
|
||||
|
||||
@property
|
||||
def total_infer_nodes(self) -> int:
|
||||
return self.num_infer_nodes * self.num_infer_replicas
|
||||
|
||||
@@ -425,6 +425,18 @@ class DefaultLossConfig(BaseConfig):
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class IPOLossConfig(BaseConfig):
|
||||
type: Literal["ipo"] = "ipo"
|
||||
ipo_threshold: float = Field(0.1, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
kl_tau: float = Field(1e-3, ge=0)
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
class CustomLossConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
@@ -435,7 +447,7 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -490,15 +502,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class TokenExportConfig(BaseConfig):
|
||||
"""Configures per-token rollout exports from the RL trainer."""
|
||||
|
||||
|
||||
class TrainerExperimentalConfig(BaseConfig):
|
||||
token_export: TokenExportConfig | None = None
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
|
||||
class TrainerConfig(BaseConfig):
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
@@ -562,7 +565,8 @@ class TrainerConfig(BaseConfig):
|
||||
max_concurrent_runs: int = Field(1, ge=1)
|
||||
"""Maximum number of concurrent runs to allow. If 1, only one run may run at a time."""
|
||||
|
||||
experimental: TrainerExperimentalConfig = TrainerExperimentalConfig()
|
||||
enable_token_export: bool = False
|
||||
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def deepep_disables_grad_clipping(self):
|
||||
|
||||
@@ -22,6 +22,8 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
(re.compile(r"^zai-org/GLM-"), "glm45"),
|
||||
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
|
||||
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
|
||||
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
|
||||
# Only Qwen3 Thinking models reason — Instruct/base models do not.
|
||||
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
|
||||
|
||||
@@ -87,6 +87,7 @@ envs = [
|
||||
"opencode-swe",
|
||||
"reverse-text",
|
||||
"rlm-swe",
|
||||
"rlm-search",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
@@ -226,6 +227,7 @@ opencode-science = { path = "deps/research-environments/environments/opencode_sc
|
||||
opencode-swe = { path = "deps/research-environments/environments/opencode_swe", editable = true }
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
|
||||
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
|
||||
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
|
||||
|
||||
@@ -10,6 +10,19 @@ PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
VENV_BIN="$PROJECT_DIR/.venv/bin"
|
||||
PYTHON="$VENV_BIN/python"
|
||||
|
||||
# UCX's --with-verbs silently disables IB/RoCE support when the rdma-core *dev*
|
||||
# headers (verbs.h / rdma_cma.h) are missing, yielding a TCP-only build. On hosts
|
||||
# with RDMA devices, require the headers up front instead of failing at runtime.
|
||||
HAVE_RDMA=0
|
||||
if compgen -G "/sys/class/infiniband/*" > /dev/null; then
|
||||
HAVE_RDMA=1
|
||||
if [ ! -f /usr/include/infiniband/verbs.h ] || [ ! -f /usr/include/rdma/rdma_cma.h ]; then
|
||||
echo "ERROR: host has RDMA devices but the rdma-core dev headers are missing." >&2
|
||||
echo "Install them first, e.g.: apt-get install -y libibverbs-dev librdmacm-dev" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
WORKSPACE="$PROJECT_DIR/nixl_workspace"
|
||||
mkdir -p "$WORKSPACE"
|
||||
UCX_SRC="$WORKSPACE/ucx_source"
|
||||
@@ -40,11 +53,23 @@ if [ ! -f "$UCX_INSTALL/lib/libucs.so" ]; then
|
||||
--enable-devel-headers \
|
||||
--enable-mt \
|
||||
--with-verbs \
|
||||
--with-rdmacm \
|
||||
--with-cuda="$CUDA_PATH" \
|
||||
--with-ze=no
|
||||
make -j"$NPROC"
|
||||
make install
|
||||
echo "=== UCX installed to $UCX_INSTALL ==="
|
||||
|
||||
# Fail loudly if the IB transports didn't make it into the build.
|
||||
if [ "$HAVE_RDMA" = 1 ]; then
|
||||
ucx_transports=$(LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}" \
|
||||
"$UCX_INSTALL/bin/ucx_info" -d)
|
||||
if ! grep -q "Transport: rc_verbs" <<< "$ucx_transports"; then
|
||||
echo "ERROR: UCX built without IB (rc_verbs) transport despite RDMA devices being present." >&2
|
||||
echo "Check that libibverbs-dev / librdmacm-dev were present at configure time." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo "=== UCX already built, skipping ==="
|
||||
fi
|
||||
|
||||
@@ -62,10 +62,10 @@ In TOML, an empty section header (`[ckpt]`) does the same.
|
||||
|
||||
## RL trainer token exports
|
||||
|
||||
For rollout debugging, enable trainer-side token export under `trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence. Single-run/fallback exports go under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`; multi-run trainer exports with packer metadata go under the owning run directory, `output_dir/<run_id>/token_exports/step_<run_step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
|
||||
|
||||
```toml
|
||||
[trainer.experimental.token_export]
|
||||
enable_token_export = true
|
||||
```
|
||||
|
||||
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
|
||||
|
||||
@@ -383,6 +383,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
@@ -405,6 +406,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -17,11 +17,29 @@ def transformers_v5_compat():
|
||||
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
|
||||
|
||||
def monkey_patch_nano_v3_reasoning_parser():
|
||||
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
|
||||
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
|
||||
|
||||
class NanoV3ReasoningParser(DeepSeekR1ReasoningParser):
|
||||
def extract_reasoning(self, model_output, request):
|
||||
reasoning_content, final_content = super().extract_reasoning(model_output, request)
|
||||
chat_template_kwargs = getattr(request, "chat_template_kwargs", None)
|
||||
|
||||
if chat_template_kwargs and chat_template_kwargs.get("enable_thinking") is False and final_content is None:
|
||||
reasoning_content, final_content = final_content, reasoning_content
|
||||
|
||||
return reasoning_content, final_content
|
||||
|
||||
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
|
||||
|
||||
|
||||
def monkey_patch_return_routed_experts_with_nixl_connector():
|
||||
from vllm import envs
|
||||
from vllm.config.vllm import VllmConfig
|
||||
@@ -836,3 +854,36 @@ def monkey_patch_fp32_lm_head():
|
||||
LogitsProcessor.__init__ = _patched_init
|
||||
LogitsProcessor._get_logits = _patched_get_logits
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 30s.
|
||||
|
||||
The coordinator child process is spawned on the DP-rank-0 API server while
|
||||
every engine-core rank on the node is importing and loading weights, so its
|
||||
own spawn-time re-import can take well over 30s under that CPU/IO
|
||||
contention (seen on multi-node disaggregated GLM-5.1 launches). Configurable
|
||||
via PRIME_DP_COORDINATOR_STARTUP_TIMEOUT (seconds, default 300).
|
||||
"""
|
||||
import multiprocessing.connection
|
||||
import os
|
||||
|
||||
from vllm.v1.engine.coordinator import DPCoordinator
|
||||
|
||||
timeout = float(os.environ.get("PRIME_DP_COORDINATOR_STARTUP_TIMEOUT", "300"))
|
||||
|
||||
def _patched_wait_for_zmq_addrs(self, zmq_addr_pipe):
|
||||
try:
|
||||
ready = multiprocessing.connection.wait([zmq_addr_pipe, self.proc.sentinel], timeout=timeout)
|
||||
if not ready:
|
||||
raise RuntimeError(
|
||||
f"DP Coordinator process failed to report ZMQ addresses within {timeout}s during startup."
|
||||
)
|
||||
try:
|
||||
return zmq_addr_pipe.recv()
|
||||
except EOFError:
|
||||
raise RuntimeError("DP Coordinator process failed during startup.") from None
|
||||
finally:
|
||||
zmq_addr_pipe.close()
|
||||
|
||||
DPCoordinator._wait_for_zmq_addrs = _patched_wait_for_zmq_addrs
|
||||
|
||||
@@ -20,8 +20,10 @@ from prime_rl.utils.logger import get_logger
|
||||
|
||||
logger = get_logger()
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_dp_coordinator_startup_timeout,
|
||||
monkey_patch_harmony_stop_token_propagation,
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
monkey_patch_vllm_padded_input_scrub,
|
||||
)
|
||||
@@ -35,9 +37,16 @@ monkey_patch_load_lora_adapter()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
|
||||
# is available in our pinned runtime.
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
# NOTE: vLLM hard-codes a 30s DP coordinator startup timeout, which the rank-0
|
||||
# API server blows through when all engine-core ranks on the node are loading
|
||||
# weights concurrently (multi-node disaggregated deployments).
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.openai.api_server")
|
||||
|
||||
|
||||
@@ -30,12 +30,17 @@ delegates to upstream so we track future vLLM changes for free.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncGenerator
|
||||
from collections.abc import AsyncGenerator, AsyncIterable
|
||||
from functools import cached_property
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
|
||||
from vllm.entrypoints.openai.engine.protocol import (
|
||||
ErrorResponse,
|
||||
PromptTokenUsageInfo,
|
||||
RequestResponseMetadata,
|
||||
UsageInfo,
|
||||
)
|
||||
from vllm.entrypoints.serve.disagg.protocol import (
|
||||
GenerateRequest,
|
||||
GenerateResponse,
|
||||
@@ -55,6 +60,12 @@ class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
|
||||
|
||||
class PrimeRlGenerateResponse(GenerateResponse):
|
||||
choices: list[PrimeRlGenerateResponseChoice]
|
||||
# Upstream ``GenerateResponse`` doesn't declare a ``usage`` field, so the
|
||||
# parent ``ServingTokens.serve_tokens_full_generator`` constructs it and
|
||||
# Pydantic silently drops it on serialization. Declare it here so the
|
||||
# router can extract per-run token counts (and cached-prefix tokens) for
|
||||
# platform billing — see https://github.com/PrimeIntellect-ai/router/pull/43.
|
||||
usage: UsageInfo | None = None
|
||||
|
||||
|
||||
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
@@ -74,6 +85,49 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
)
|
||||
|
||||
|
||||
class _FinalOutputCapture:
|
||||
"""Wraps a ``RequestOutput`` async generator to record the last yielded item.
|
||||
|
||||
Needed so the response builder can construct a ``usage`` block from
|
||||
``final_res.prompt_token_ids`` / ``output.token_ids`` / ``num_cached_tokens``
|
||||
after delegating iteration to upstream.
|
||||
"""
|
||||
|
||||
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
|
||||
# ``source`` may be any async-iterable — including
|
||||
# ``_GenerateRoutedExpertsCapture``, which exposes the protocol via
|
||||
# ``async def __aiter__`` (an async generator function) and has no
|
||||
# ``__anext__`` method. Drive it through ``async for`` rather than
|
||||
# poking ``__anext__`` directly so both shapes work.
|
||||
self._source = source
|
||||
self.final_res: RequestOutput | None = None
|
||||
|
||||
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
|
||||
async for item in self._source:
|
||||
self.final_res = item
|
||||
yield item
|
||||
|
||||
|
||||
def _build_usage(final_res: RequestOutput) -> UsageInfo:
|
||||
assert final_res.prompt_token_ids is not None
|
||||
num_prompt_tokens = len(final_res.prompt_token_ids)
|
||||
if final_res.encoder_prompt_token_ids is not None:
|
||||
num_prompt_tokens += len(final_res.encoder_prompt_token_ids)
|
||||
num_generated_tokens = sum(len(output.token_ids) for output in final_res.outputs)
|
||||
usage = UsageInfo(
|
||||
prompt_tokens=num_prompt_tokens,
|
||||
completion_tokens=num_generated_tokens,
|
||||
total_tokens=num_prompt_tokens + num_generated_tokens,
|
||||
)
|
||||
# Always emit cached tokens when vLLM reports any. Upstream gates this on
|
||||
# ``enable_prompt_tokens_details`` (default False) for OpenAI-API compat,
|
||||
# but ``/inference/v1/generate`` is prime-rl internal — the cache-discount
|
||||
# billing pipeline always wants the cached subset surfaced.
|
||||
if final_res.num_cached_tokens:
|
||||
usage.prompt_tokens_details = PromptTokenUsageInfo(cached_tokens=final_res.num_cached_tokens)
|
||||
return usage
|
||||
|
||||
|
||||
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
|
||||
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
|
||||
|
||||
@@ -273,11 +327,33 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
)
|
||||
result_generator = capture
|
||||
|
||||
# Always capture the final ``RequestOutput`` so we can attach a
|
||||
# ``usage`` block to the response. The router parses ``usage`` for
|
||||
# per-run billing metrics; without it the cache-discount counter
|
||||
# (``vllm_router_run_cached_prompt_tokens_total``) stays at zero.
|
||||
final_capture = _FinalOutputCapture(result_generator)
|
||||
result_generator = final_capture
|
||||
|
||||
response = await super().serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
)
|
||||
|
||||
if capture is not None and isinstance(response, GenerateResponse):
|
||||
if not isinstance(response, GenerateResponse):
|
||||
return response
|
||||
|
||||
if capture is not None:
|
||||
response = capture.post_process(response)
|
||||
elif not isinstance(response, PrimeRlGenerateResponse):
|
||||
# Upgrade to the prime-rl subclass so the declared ``usage`` field
|
||||
# actually surfaces in JSON (the parent class would drop it).
|
||||
response = PrimeRlGenerateResponse(
|
||||
request_id=response.request_id,
|
||||
choices=[PrimeRlGenerateResponseChoice(**choice.model_dump()) for choice in response.choices],
|
||||
prompt_logprobs=response.prompt_logprobs,
|
||||
kv_transfer_params=response.kv_transfer_params,
|
||||
)
|
||||
|
||||
if final_capture.final_res is not None:
|
||||
response.usage = _build_usage(final_capture.final_res)
|
||||
|
||||
return response
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
"""MetricsBuilder: assembles the per-step W&B dict. No I/O, no side effects."""
|
||||
"""MetricsBuilder: assembles the per-step W&B dict.
|
||||
|
||||
The only I/O / state is the trainer's token-export metrics, which lag the
|
||||
orchestrator: ``build`` folds in the oldest unlogged stable step it finds on
|
||||
disk and tracks the last step logged so it never re-logs one.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,12 +12,16 @@ from typing import Any
|
||||
import pandas as pd
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.token_export_metrics import collect_next_token_export_metrics
|
||||
from prime_rl.orchestrator.types import Progress, TrainBatchMetrics, TrainRollout
|
||||
|
||||
|
||||
class MetricsBuilder:
|
||||
def __init__(self, config: OrchestratorConfig) -> None:
|
||||
def __init__(self, config: OrchestratorConfig, start_step: int = 0) -> None:
|
||||
self.config = config
|
||||
# Token exports are read back one step behind the orchestrator; track the
|
||||
# last run step whose metrics we've folded in so we never re-log a step.
|
||||
self._last_token_export_step_logged = start_step - 1
|
||||
|
||||
def build(
|
||||
self,
|
||||
@@ -179,8 +188,29 @@ class MetricsBuilder:
|
||||
for name, count in pre_filter_dropped_by_name.items():
|
||||
to_log[f"pre_filters/all/{name}/rate"] = count / pre_filter_seen
|
||||
|
||||
# Fold in the trainer's token-export metrics for the oldest unlogged stable
|
||||
# step (exports always lag the orchestrator, so this is a past step).
|
||||
to_log.update(self.next_token_export_metrics())
|
||||
|
||||
return to_log
|
||||
|
||||
@property
|
||||
def last_token_export_step_logged(self) -> int:
|
||||
return self._last_token_export_step_logged
|
||||
|
||||
def next_token_export_metrics(self) -> dict[str, float | int]:
|
||||
"""Log-ready token-export metrics for the next unlogged stable step (empty if
|
||||
none), advancing the cursor. They arrive under trainer/, including trainer/step
|
||||
(the run step they belong to) for plotting against a lag-corrected axis. Shared
|
||||
by build() and the orchestrator's end-of-run drain."""
|
||||
token_export = collect_next_token_export_metrics(
|
||||
self.config.output_dir,
|
||||
last_logged_step=self._last_token_export_step_logged,
|
||||
)
|
||||
if token_export:
|
||||
self._last_token_export_step_logged = token_export["trainer/step"]
|
||||
return token_export
|
||||
|
||||
@staticmethod
|
||||
def timing_df(rollouts: list[TrainRollout]) -> pd.DataFrame:
|
||||
return pd.DataFrame(
|
||||
|
||||
@@ -108,6 +108,11 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
|
||||
# resumed when the watcher advances ``policy.version``.
|
||||
TARGET_LAG = 1
|
||||
|
||||
# After max_steps, how long to wait for the trainer to finalize the trailing
|
||||
# token-export steps it hadn't flushed yet, and how often to poll for them.
|
||||
TOKEN_EXPORT_DRAIN_TIMEOUT_S = 300.0
|
||||
TOKEN_EXPORT_DRAIN_POLL_S = 2.0
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
# Set in ``__init__``
|
||||
@@ -382,7 +387,7 @@ class Orchestrator:
|
||||
training_mode=config.training_mode,
|
||||
use_cache_salt=use_cache_salt,
|
||||
)
|
||||
self.metrics = MetricsBuilder(config)
|
||||
self.metrics = MetricsBuilder(config, start_step=self.progress.step)
|
||||
self.train_sink = TrainSink(
|
||||
config,
|
||||
tokenizer=self.tokenizer,
|
||||
@@ -460,6 +465,7 @@ class Orchestrator:
|
||||
clean_exit = False
|
||||
try:
|
||||
await self.main_loop()
|
||||
await self._drain_token_export_metrics()
|
||||
clean_exit = True
|
||||
finally:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
@@ -510,6 +516,35 @@ class Orchestrator:
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
|
||||
async def _drain_token_export_metrics(self) -> None:
|
||||
"""Token exports lag the orchestrator, so once the loop ends the trainer is
|
||||
still finalizing the last shipped steps and ``build`` no longer runs to pick
|
||||
them up. Poll for the remaining stable steps up to ``max_steps - 1`` and log
|
||||
each under its own ``trainer/step`` (a local W&B step axis, so the final
|
||||
checkpoint's ``progress.step`` is untouched)."""
|
||||
if self.config.max_steps is None:
|
||||
return
|
||||
if not (self.config.output_dir / "token_exports").exists():
|
||||
return # token export not enabled for this run — don't block shutdown
|
||||
target = self.config.max_steps - 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return # build() already kept up — nothing trailing to flush
|
||||
wandb_step = self.progress.step
|
||||
deadline = time.perf_counter() + TOKEN_EXPORT_DRAIN_TIMEOUT_S
|
||||
while time.perf_counter() < deadline:
|
||||
token_export = self.metrics.next_token_export_metrics()
|
||||
if not token_export:
|
||||
await asyncio.sleep(TOKEN_EXPORT_DRAIN_POLL_S)
|
||||
continue
|
||||
self.monitor.log(token_export, step=wandb_step)
|
||||
wandb_step += 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return
|
||||
get_logger().warning(
|
||||
f"Token-export drain timed out before step {target} "
|
||||
f"(last logged {self.metrics.last_token_export_step_logged})"
|
||||
)
|
||||
|
||||
async def finalize_train_batch(self, batch: TrainBatch) -> None:
|
||||
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
|
||||
side-effects (ckpt, save_rollouts, teacher logprobs, sender.send,
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
TOKEN_EXPORT_METRIC_FIELDS = ("mismatch_kl", "entropy")
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Stats:
|
||||
total: float = 0.0
|
||||
count: int = 0
|
||||
maximum: float = -math.inf
|
||||
|
||||
def add(self, value: Any) -> None:
|
||||
if not isinstance(value, int | float):
|
||||
return
|
||||
value = float(value)
|
||||
if not math.isfinite(value):
|
||||
return
|
||||
self.total += value
|
||||
self.count += 1
|
||||
self.maximum = max(self.maximum, value)
|
||||
|
||||
def as_metrics(self, prefix: str) -> dict[str, float]:
|
||||
if self.count == 0:
|
||||
return {}
|
||||
return {
|
||||
f"{prefix}/mean": self.total / self.count,
|
||||
f"{prefix}/max": self.maximum,
|
||||
}
|
||||
|
||||
|
||||
def collect_next_token_export_metrics(output_dir: Path, *, last_logged_step: int) -> dict[str, float | int]:
|
||||
"""Log-ready metrics for the oldest unlogged stable step, namespaced under
|
||||
``trainer/`` and stamped with ``trainer/step`` (the run step they belong to).
|
||||
Empty when there is no new stable step."""
|
||||
stable_steps = [step for step in _stable_token_export_steps(output_dir) if step > last_logged_step]
|
||||
if not stable_steps:
|
||||
return {}
|
||||
|
||||
step = min(stable_steps)
|
||||
metrics: dict[str, float | int] = {
|
||||
f"trainer/{key}": value for key, value in collect_token_export_metrics(output_dir, step).items()
|
||||
}
|
||||
metrics["trainer/step"] = step
|
||||
return metrics
|
||||
|
||||
|
||||
def collect_token_export_metrics(output_dir: Path, step: int) -> dict[str, float | int]:
|
||||
step_dir = output_dir / "token_exports" / f"step_{step}"
|
||||
if not (step_dir / "STABLE").exists():
|
||||
return {}
|
||||
|
||||
stats_by_key: dict[str, _Stats] = {}
|
||||
sequence_count = 0
|
||||
skipped_count = 0
|
||||
|
||||
for export_file in sorted(step_dir.glob("rank_*.jsonl")):
|
||||
with export_file.open(encoding="utf-8") as file:
|
||||
for line in file:
|
||||
if not line.strip():
|
||||
continue
|
||||
# Token exports are best-effort monitoring; a malformed line or a
|
||||
# length-mismatched record shouldn't abort the orchestrator step.
|
||||
try:
|
||||
record = json.loads(line)
|
||||
values_by_field = {field: _loss_token_values(record, field) for field in TOKEN_EXPORT_METRIC_FIELDS}
|
||||
except ValueError:
|
||||
skipped_count += 1
|
||||
continue
|
||||
sequence_count += 1
|
||||
for field, values in values_by_field.items():
|
||||
for value in values:
|
||||
stats_by_key.setdefault(field, _Stats()).add(value)
|
||||
|
||||
if skipped_count:
|
||||
get_logger().warning(f"Skipped {skipped_count} malformed token-export record(s) in {step_dir}")
|
||||
|
||||
metrics: dict[str, float | int] = {}
|
||||
if sequence_count == 0:
|
||||
return metrics
|
||||
for key, stats in sorted(stats_by_key.items()):
|
||||
metrics.update(stats.as_metrics(key))
|
||||
return metrics
|
||||
|
||||
|
||||
def _stable_token_export_steps(output_dir: Path) -> list[int]:
|
||||
token_exports_dir = output_dir / "token_exports"
|
||||
if not token_exports_dir.exists():
|
||||
return []
|
||||
|
||||
steps = []
|
||||
for step_dir in token_exports_dir.glob("step_*"):
|
||||
if not (step_dir / "STABLE").exists():
|
||||
continue
|
||||
try:
|
||||
steps.append(int(step_dir.name.removeprefix("step_")))
|
||||
except ValueError:
|
||||
continue
|
||||
return sorted(steps)
|
||||
|
||||
|
||||
def _loss_token_values(record: dict[str, Any], field: str) -> list[Any]:
|
||||
loss_mask = record.get("loss_mask", [])
|
||||
values = record.get(field, [])
|
||||
if len(loss_mask) != len(values):
|
||||
raise ValueError(
|
||||
f"Token export record has mismatched loss_mask and {field} lengths: {len(loss_mask)} != {len(values)}"
|
||||
)
|
||||
return [value for value, keep in zip(values, loss_mask) if keep]
|
||||
@@ -353,15 +353,6 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
|
||||
else
|
||||
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
|
||||
|
||||
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
|
||||
fi
|
||||
{%- else %}
|
||||
TRAIN_NODE_RANK=$SLURM_PROCID
|
||||
{%- endif %}
|
||||
@@ -388,6 +379,21 @@ else
|
||||
@ $CONFIG_DIR/trainer.toml \
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
|
||||
{% if num_infer_nodes > 0 %} fi{% endif %}
|
||||
{% if num_infer_nodes > 0 %}
|
||||
# Launch the orchestrator on one node. Default is trainer rank 0 (SLURM_PROCID ==
|
||||
# NUM_INFER_NODES). With orchestrator_on_inference it moves to the last inference node
|
||||
# (a decode node) to keep its rollout buffer + env workers off host-RAM-saturated
|
||||
# trainer nodes. Top-level (after the role if/else) so the wait -n teardown covers it.
|
||||
{% if orchestrator_on_inference %}ORCH_PROCID=$((NUM_INFER_NODES - 1)){% else %}ORCH_PROCID=$NUM_INFER_NODES{% endif %}
|
||||
if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
|
||||
fi
|
||||
{% endif %}
|
||||
|
||||
# Wait for the first background job to exit and propagate its exit code. This
|
||||
# turns background process crashes (router, orchestrator) into task failures
|
||||
|
||||
@@ -37,6 +37,7 @@ from prime_rl.trainer.models import (
|
||||
get_custom_vlm_cls,
|
||||
supports_custom_impl,
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import Indexer
|
||||
from prime_rl.trainer.models.layers.checkpointing import (
|
||||
get_supported_targets,
|
||||
set_selective_activation_checkpointing,
|
||||
@@ -350,6 +351,29 @@ def freeze_moe_router(model: nn.Module) -> None:
|
||||
logger.info(f"Froze {num_frozen} MoE router parameters")
|
||||
|
||||
|
||||
def freeze_sparse_indexer(model: nn.Module) -> None:
|
||||
"""Freeze DSA sparse-attention indexer parameters.
|
||||
|
||||
The indexer's `compute_sparse_indices` forward runs under `torch.no_grad()`, so its
|
||||
params never receive a gradient and cannot be trained. Left with requires_grad=True
|
||||
they stay stateless in the optimizer, which breaks strict checkpoint resume: DCP
|
||||
materializes optimizer state for every requires_grad param at load time, but the
|
||||
stateless params were never saved -> "Missing key in checkpoint state_dict". Freezing
|
||||
them keeps the saved and loaded optimizer state symmetric.
|
||||
"""
|
||||
logger = get_logger()
|
||||
num_frozen = 0
|
||||
|
||||
for module in model.modules():
|
||||
if isinstance(module, Indexer):
|
||||
for param in module.parameters():
|
||||
param.requires_grad = False
|
||||
num_frozen += 1
|
||||
|
||||
if num_frozen > 0:
|
||||
logger.info(f"Froze {num_frozen} sparse indexer parameters")
|
||||
|
||||
|
||||
def apply_force_balanced_routing(model: nn.Module) -> None:
|
||||
"""Force MoE token-choice routers into round-robin assignment for fake-data smoke tests."""
|
||||
logger = get_logger()
|
||||
@@ -1075,6 +1099,11 @@ def setup_model(
|
||||
if config.freeze_moe_router:
|
||||
freeze_moe_router(model)
|
||||
|
||||
# The DSA sparse-attention indexer runs its forward under torch.no_grad(), so it is
|
||||
# never trainable. Freeze it so optimizer state stays symmetric across checkpoint
|
||||
# save/resume. No-op for models without a sparse indexer.
|
||||
freeze_sparse_indexer(model)
|
||||
|
||||
if config.debug.force_balanced_routing:
|
||||
apply_force_balanced_routing(model)
|
||||
|
||||
|
||||
@@ -149,10 +149,15 @@ def _create_optimizer(
|
||||
"""Create optimizer. If lr is None, uses config.lr."""
|
||||
if lr is None:
|
||||
lr = config.lr
|
||||
# Only hand trainable params to the optimizer. Frozen params (e.g. the DSA sparse
|
||||
# indexer, which runs under no_grad) carry no optimizer state, and including them
|
||||
# breaks strict checkpoint resume (DCP materializes state for every requires_grad
|
||||
# param at load time, mismatching the saved state). Muon filters internally below.
|
||||
trainable_params = [p for _, p in named_params if p.requires_grad]
|
||||
match config.type:
|
||||
case "sgd":
|
||||
return SGD(
|
||||
params=[p for _, p in named_params],
|
||||
params=trainable_params,
|
||||
lr=lr,
|
||||
weight_decay=config.weight_decay,
|
||||
momentum=config.momentum,
|
||||
@@ -160,7 +165,7 @@ def _create_optimizer(
|
||||
)
|
||||
case "adamw":
|
||||
return AdamW(
|
||||
params=[p for _, p in named_params],
|
||||
params=trainable_params,
|
||||
lr=lr,
|
||||
weight_decay=config.weight_decay,
|
||||
betas=(config.betas1, config.betas2),
|
||||
@@ -169,7 +174,7 @@ def _create_optimizer(
|
||||
return _create_muon_optimizer(config, named_params, parallel_dims, lr)
|
||||
case "sign_sgd":
|
||||
return SignSGD(
|
||||
params=[p for _, p in named_params],
|
||||
params=trainable_params,
|
||||
lr=lr,
|
||||
weight_decay=config.weight_decay,
|
||||
)
|
||||
|
||||
@@ -10,7 +10,12 @@ from prime_rl.configs.trainer import FakeDataLoaderConfig
|
||||
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.transport import MicroBatch, MicroBatchReceiver, TransportConfig, setup_micro_batch_receiver
|
||||
from prime_rl.transport import (
|
||||
MicroBatch,
|
||||
MicroBatchReceiver,
|
||||
TransportConfig,
|
||||
setup_micro_batch_receiver,
|
||||
)
|
||||
|
||||
|
||||
class TensorMicroBatch(TypedDict):
|
||||
@@ -46,6 +51,10 @@ class TensorMicroBatch(TypedDict):
|
||||
# sft → sft loss). All samples in a micro batch share the same mode.
|
||||
training_mode: str
|
||||
|
||||
# Packer-derived metadata used for run-local debug exports.
|
||||
run_id: str | None
|
||||
run_step: int | None
|
||||
|
||||
|
||||
class FakeDataLoader:
|
||||
def __init__(self, config: FakeDataLoaderConfig, seq_len: int, dp_world_size: int):
|
||||
@@ -120,6 +129,8 @@ class FakeDataLoader:
|
||||
"mm_kwargs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"training_mode": "rl",
|
||||
"run_id": None,
|
||||
"run_step": None,
|
||||
}
|
||||
|
||||
def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch:
|
||||
@@ -148,6 +159,8 @@ class FakeDataLoader:
|
||||
"mm_kwargs": None,
|
||||
"mm_token_type_ids": None,
|
||||
"training_mode": "rl",
|
||||
"run_id": None,
|
||||
"run_step": None,
|
||||
}
|
||||
|
||||
|
||||
@@ -243,6 +256,8 @@ class DataLoader:
|
||||
else None,
|
||||
routed_experts=routed_experts,
|
||||
training_mode=micro_batch.training_mode,
|
||||
run_id=micro_batch.run_id,
|
||||
run_step=micro_batch.run_step,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
|
||||
from jaxtyping import Bool, Float, Int, jaxtyped
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, IPOLossConfig, LossConfig
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -165,6 +165,35 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def ipo_loss_fn(inputs: LossInputs, loss_config: IPOLossConfig) -> LossOutputs:
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
advantages = inputs.advantages
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
|
||||
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
|
||||
|
||||
is_masked = abs_probs_diff > loss_config.ipo_threshold
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
pg_loss = keep_mask * advantages * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
loss = (-pg_loss + loss_config.kl_tau * kl_loss).sum()
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
}
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def opd_loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
"""
|
||||
On-policy distillation loss: the default DPPO+KL math with the tau knobs
|
||||
@@ -240,7 +269,8 @@ def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
|
||||
- ``"opd"`` → ``opd_loss_fn`` (teacher KL as gradient signal, hardcoded
|
||||
DPPO + KL knobs)
|
||||
- ``"rl"`` → ``default_loss_fn(loss_config)`` for ``DefaultLossConfig``,
|
||||
or the imported function for ``CustomLossConfig``.
|
||||
``ipo_loss_fn(loss_config)`` for ``IPOLossConfig``, or the imported
|
||||
function for ``CustomLossConfig``.
|
||||
|
||||
``trainer.loss`` only affects the rl path - opd and sft are independent.
|
||||
"""
|
||||
@@ -250,6 +280,10 @@ def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return custom_fn(inputs, **kwargs)
|
||||
elif isinstance(loss_config, IPOLossConfig):
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return ipo_loss_fn(inputs, loss_config)
|
||||
else:
|
||||
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
|
||||
@@ -111,6 +111,12 @@ class SinglePacker(BasePacker):
|
||||
idxs=[0] * len(batch.examples),
|
||||
num_loras=self.multi_run_manager.max_runs,
|
||||
)
|
||||
# The receiver always stamps run_idx from used_idxs (a key of idx_2_id).
|
||||
run_id = self.multi_run_manager.idx_2_id[batch.run_idx]
|
||||
for worker_batches in micro_batch_grid:
|
||||
for micro_batch in worker_batches:
|
||||
micro_batch.run_id = run_id
|
||||
micro_batch.run_step = batch.step
|
||||
|
||||
self.sender.send(micro_batch_grid)
|
||||
|
||||
@@ -300,10 +306,14 @@ class MultiPacker(BasePacker):
|
||||
# Group samples by run_idx - each microbatch must contain samples from only ONE run
|
||||
# because MultiLoRAGroupedExperts (MoE) only supports one adapter per microbatch
|
||||
samples_by_run: dict[int, list[TrainingSample]] = {}
|
||||
steps_by_run: dict[int, int] = {}
|
||||
per_run_stats: dict[int, tuple[int, int]] = {}
|
||||
for run_idx, sample, step in selected_samples:
|
||||
if run_idx not in samples_by_run:
|
||||
samples_by_run[run_idx] = []
|
||||
steps_by_run[run_idx] = step
|
||||
else:
|
||||
assert steps_by_run[run_idx] == step, "Micro batches for a run must come from a single run step"
|
||||
samples_by_run[run_idx].append(sample)
|
||||
|
||||
num_tokens = len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
@@ -328,8 +338,13 @@ class MultiPacker(BasePacker):
|
||||
idxs=[run_idx] * len(run_samples),
|
||||
num_loras=self.multi_run_manager.max_runs,
|
||||
)
|
||||
run_id = self.multi_run_manager.idx_2_id[run_idx]
|
||||
run_step = steps_by_run[run_idx]
|
||||
# Merge into combined grid
|
||||
for worker_idx, worker_batches in enumerate(run_micro_batch_grid):
|
||||
for micro_batch in worker_batches:
|
||||
micro_batch.run_id = run_id
|
||||
micro_batch.run_step = run_step
|
||||
all_micro_batches[worker_idx].extend(worker_batches)
|
||||
|
||||
self.sender.send(all_micro_batches)
|
||||
|
||||
@@ -18,6 +18,9 @@ class DisabledTokenExporter:
|
||||
def export(self, *args: Any, **kwargs: Any) -> None:
|
||||
return
|
||||
|
||||
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
|
||||
return
|
||||
|
||||
def close(self) -> None:
|
||||
return
|
||||
|
||||
@@ -30,10 +33,10 @@ class TokenExporter:
|
||||
) -> None:
|
||||
self.rank = rank
|
||||
self.output_dir = output_dir / "token_exports"
|
||||
self._file: Any | None = None
|
||||
self._closed = False
|
||||
self._current_step: int | None = None
|
||||
self._sequences_this_step = 0
|
||||
self._initialized_files: set[tuple[str | None, int, int]] = set()
|
||||
self._sequences_by_file: dict[tuple[str | None, int, int], int] = {}
|
||||
self._pending_stable_dirs: dict[str | None, set[Path]] = {}
|
||||
atexit.register(self.close)
|
||||
|
||||
def export(
|
||||
@@ -45,11 +48,11 @@ class TokenExporter:
|
||||
response_lengths: list[int],
|
||||
loss_config: Any,
|
||||
) -> None:
|
||||
if self._current_step != step:
|
||||
self._start_step(step)
|
||||
|
||||
columns = _export_columns(micro_batch, model_output, loss_config)
|
||||
_check_lengths(columns)
|
||||
run_id = micro_batch.get("run_id")
|
||||
export_step = micro_batch.get("run_step") if micro_batch.get("run_step") is not None else step
|
||||
file_key = (run_id, export_step, self.rank)
|
||||
|
||||
start = 0
|
||||
for micro_sequence_idx, length in enumerate(response_lengths):
|
||||
@@ -60,54 +63,73 @@ class TokenExporter:
|
||||
{
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"step": step,
|
||||
"export_step": export_step,
|
||||
"rank": self.rank,
|
||||
"micro_step": micro_step,
|
||||
"micro_sequence_idx": micro_sequence_idx,
|
||||
"export_sequence_idx": self._sequences_this_step,
|
||||
"export_sequence_idx": self._sequences_by_file.get(file_key, 0),
|
||||
"run_id": run_id,
|
||||
"env_name": _first_non_empty(columns["env_names"][start:end]),
|
||||
"training_mode": str(micro_batch["training_mode"]),
|
||||
**_slice_columns(columns, start, end),
|
||||
}
|
||||
},
|
||||
run_id,
|
||||
export_step,
|
||||
)
|
||||
self._sequences_this_step += 1
|
||||
self._sequences_by_file[file_key] = self._sequences_by_file.get(file_key, 0) + 1
|
||||
start = raw_end
|
||||
|
||||
def close(self) -> None:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._file = None
|
||||
|
||||
def _start_step(self, step: int) -> None:
|
||||
def mark_stable(self, ready_run_ids: set[str] | None = None) -> None:
|
||||
# A single run step's sequences can span multiple trainer steps (the packer
|
||||
# splits a run step across packs when it exceeds the token budget). Only
|
||||
# finalize a run's export dir once that run step is fully consumed — the same
|
||||
# `ready_to_update` signal that gates its optimizer step. ``run_id is None``
|
||||
# is single-run export, where a step never spans trainer steps, so mark it now.
|
||||
# The caller barriers first so a STABLE only lands after every rank flushed.
|
||||
ready_run_ids = ready_run_ids or set()
|
||||
for run_id in [rid for rid in self._pending_stable_dirs if rid is None or rid in ready_run_ids]:
|
||||
for stable_dir in self._pending_stable_dirs.pop(run_id):
|
||||
(stable_dir / "STABLE").touch()
|
||||
|
||||
def _export_dir(self, export_step: int, run_id: str | None) -> Path:
|
||||
if run_id is not None:
|
||||
return self.output_dir.parent / run_id / "token_exports" / f"step_{export_step}"
|
||||
return self.output_dir / f"step_{export_step}"
|
||||
|
||||
def _export_file(self, export_step: int, run_id: str | None) -> Path:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._current_step = step
|
||||
self._sequences_this_step = 0
|
||||
step_dir = self.output_dir / f"step_{step}"
|
||||
|
||||
step_dir = self._export_dir(export_step, run_id)
|
||||
try:
|
||||
step_dir.mkdir(parents=True, exist_ok=True)
|
||||
except FileExistsError:
|
||||
if not step_dir.is_dir():
|
||||
raise
|
||||
self._file = (step_dir / f"rank_{self.rank}.jsonl").open("w", encoding="utf-8")
|
||||
return step_dir / f"rank_{self.rank}.jsonl"
|
||||
|
||||
def _write(self, record: dict[str, Any]) -> None:
|
||||
def _write(self, record: dict[str, Any], run_id: str | None, export_step: int) -> None:
|
||||
if self._closed:
|
||||
raise RuntimeError(f"Token exporter is closed for {self.output_dir}")
|
||||
if self._file is None:
|
||||
raise RuntimeError("Token exporter has no active step file")
|
||||
self._file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
|
||||
|
||||
file_key = (run_id, export_step, self.rank)
|
||||
mode = "a" if file_key in self._initialized_files else "w"
|
||||
export_file = self._export_file(export_step, run_id)
|
||||
with export_file.open(mode, encoding="utf-8") as file:
|
||||
file.write(json.dumps(record, separators=(",", ":"), allow_nan=False) + "\n")
|
||||
self._initialized_files.add(file_key)
|
||||
self._pending_stable_dirs.setdefault(run_id, set()).add(export_file.parent)
|
||||
|
||||
|
||||
def setup_token_exporter(
|
||||
config: TrainerConfig, parallel_dims: Any, world: Any, logger: Any
|
||||
) -> TokenExporter | DisabledTokenExporter:
|
||||
token_export_config = config.experimental.token_export
|
||||
if token_export_config is None:
|
||||
if not config.enable_token_export:
|
||||
return DisabledTokenExporter()
|
||||
if parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0:
|
||||
return DisabledTokenExporter()
|
||||
|
||||
@@ -512,7 +512,14 @@ def train(config: TrainerConfig):
|
||||
for env_name, indices in env_to_indices.items():
|
||||
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
|
||||
|
||||
token_exporter.export(progress.step, micro_step, micro_batch, out, response_lengths, config.loss)
|
||||
token_exporter.export(
|
||||
progress.step,
|
||||
micro_step,
|
||||
micro_batch,
|
||||
out,
|
||||
response_lengths,
|
||||
config.loss,
|
||||
)
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
load_balance_stats = get_load_balance_stats(model)
|
||||
@@ -534,6 +541,15 @@ def train(config: TrainerConfig):
|
||||
micro_step_message += f" | Routing Conf. {tensors['routing_confidence'][-1].mean().item():.4f}"
|
||||
logger.debug(micro_step_message)
|
||||
|
||||
if config.enable_token_export:
|
||||
dist.barrier()
|
||||
ready_run_ids = {
|
||||
multi_run_manager.idx_2_id[idx]
|
||||
for idx in multi_run_manager.ready_to_update_idxs
|
||||
if idx in multi_run_manager.idx_2_id
|
||||
}
|
||||
token_exporter.mark_stable(ready_run_ids)
|
||||
|
||||
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
|
||||
# across dp_cp so the final gradient is the true per-token mean over the global batch.
|
||||
for param in model.parameters():
|
||||
|
||||
@@ -8,7 +8,12 @@ from prime_rl.transport.filesystem import (
|
||||
FileSystemTrainingBatchReceiver,
|
||||
FileSystemTrainingBatchSender,
|
||||
)
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingBatch, TrainingSample
|
||||
from prime_rl.transport.types import (
|
||||
MicroBatch,
|
||||
RoutedExperts,
|
||||
TrainingBatch,
|
||||
TrainingSample,
|
||||
)
|
||||
from prime_rl.transport.zmq import (
|
||||
ZMQMicroBatchReceiver,
|
||||
ZMQMicroBatchSender,
|
||||
|
||||
@@ -89,3 +89,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
# sft → sft loss). All samples packed into a micro batch share the same mode.
|
||||
training_mode: TrainingMode = "rl"
|
||||
rewards: list[float] | None = None
|
||||
|
||||
# Packer-derived metadata used for run-local token exports.
|
||||
run_id: str | None = None
|
||||
run_step: int | None = None
|
||||
|
||||
@@ -16,8 +16,8 @@ import verifiers as vf
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig
|
||||
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
|
||||
|
||||
@@ -112,7 +112,7 @@ class PrimeMonitor(Monitor):
|
||||
config: PrimeMonitorConfig | None,
|
||||
output_dir: Path | None = None,
|
||||
tokenizer: PreTrainedTokenizer | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
run_config: OrchestratorConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
):
|
||||
self.config = config
|
||||
@@ -185,7 +185,7 @@ class PrimeMonitor(Monitor):
|
||||
if config.log_extras.distributions:
|
||||
self.last_log_distributions_step = -1
|
||||
|
||||
def _register_run(self, config: PrimeMonitorConfig, run_config: BaseConfig | None) -> str | None:
|
||||
def _register_run(self, config: PrimeMonitorConfig, run_config: OrchestratorConfig | None) -> str | None:
|
||||
"""Register an external run with the platform. Returns run_id on success, None on failure."""
|
||||
prime_config = None
|
||||
team_id = config.team_id
|
||||
@@ -197,22 +197,23 @@ class PrimeMonitor(Monitor):
|
||||
if frontend_url is None:
|
||||
frontend_url = prime_config.frontend_url
|
||||
|
||||
model = getattr(run_config, "model", None) if run_config else None
|
||||
environments = getattr(run_config, "env", None) if run_config else None
|
||||
wandb = getattr(run_config, "wandb", None) if run_config else None
|
||||
|
||||
payload: dict = {
|
||||
"base_model": model.name if model else "unknown",
|
||||
"max_steps": getattr(run_config, "max_steps", None) or 0,
|
||||
payload: dict[str, Any] = {
|
||||
"base_model": run_config.student.model.name if run_config else "unknown",
|
||||
"max_steps": (run_config.max_steps if run_config else None) or 0,
|
||||
}
|
||||
if run_config:
|
||||
if run_config.batch_size is not None:
|
||||
payload["batch_size"] = run_config.batch_size
|
||||
payload["rollouts_per_example"] = run_config.group_size
|
||||
payload["seq_len"] = run_config.seq_len
|
||||
payload["environments"] = [{"id": env.id} for env in run_config.train.env]
|
||||
payload["run_config"] = run_config.model_dump(exclude_none=True, mode="json")
|
||||
if run_config.wandb:
|
||||
payload["wandb_project"] = run_config.wandb.project
|
||||
if config.run_name:
|
||||
payload["name"] = config.run_name
|
||||
if team_id:
|
||||
payload["team_id"] = team_id
|
||||
if environments:
|
||||
payload["environments"] = [{"id": env.id} for env in environments if hasattr(env, "id")]
|
||||
if wandb and getattr(wandb, "project", None):
|
||||
payload["wandb_project"] = wandb.project
|
||||
|
||||
try:
|
||||
response = httpx.post(
|
||||
|
||||
@@ -14,12 +14,17 @@ import asyncio
|
||||
|
||||
import numpy as np
|
||||
import pybase64
|
||||
from vllm.entrypoints.openai.engine.protocol import UsageInfo
|
||||
from vllm.entrypoints.serve.disagg.protocol import GenerateResponse, GenerateResponseChoice
|
||||
|
||||
from prime_rl.inference.vllm.routed_experts import serialize_routed_experts
|
||||
from prime_rl.inference.vllm.serving_tokens import (
|
||||
PrimeRlGenerateResponse,
|
||||
PrimeRlGenerateResponseChoice,
|
||||
PrimeRlServingTokens,
|
||||
_build_usage,
|
||||
_client_set_max_tokens,
|
||||
_FinalOutputCapture,
|
||||
_GenerateRoutedExpertsCapture,
|
||||
)
|
||||
|
||||
@@ -105,6 +110,153 @@ def test_client_set_max_tokens_detects_unset():
|
||||
assert asyncio.run(_client_set_max_tokens(_FakeRawRequest(body_without_sp))) is False
|
||||
|
||||
|
||||
class _FakeOutput:
|
||||
def __init__(self, token_ids):
|
||||
self.token_ids = token_ids
|
||||
|
||||
|
||||
class _FakeRequestOutput:
|
||||
"""Minimal stand-in for ``vllm.outputs.RequestOutput``.
|
||||
|
||||
``_build_usage`` only touches four attributes; constructing a real
|
||||
``RequestOutput`` would require a full ``CompletionOutput`` graph and
|
||||
isn't worth it for a serialization-shape test.
|
||||
"""
|
||||
|
||||
def __init__(self, prompt_token_ids, output_token_ids_list, num_cached_tokens=0, encoder_prompt_token_ids=None):
|
||||
self.prompt_token_ids = prompt_token_ids
|
||||
self.encoder_prompt_token_ids = encoder_prompt_token_ids
|
||||
self.outputs = [_FakeOutput(t) for t in output_token_ids_list]
|
||||
self.num_cached_tokens = num_cached_tokens
|
||||
|
||||
|
||||
def test_prime_rl_generate_response_serializes_usage_block():
|
||||
# Regression for prime-rl PR #2408: parent ``GenerateResponse`` doesn't
|
||||
# declare ``usage``, so the field must be declared on the subclass for
|
||||
# Pydantic to emit it in JSON. Without this the router can't extract
|
||||
# per-run token / cache counts for billing.
|
||||
response = PrimeRlGenerateResponse(
|
||||
request_id="req-1",
|
||||
choices=[PrimeRlGenerateResponseChoice(index=0, token_ids=[1, 2, 3])],
|
||||
usage=UsageInfo(prompt_tokens=4, completion_tokens=3, total_tokens=7),
|
||||
)
|
||||
payload = response.model_dump(mode="json")
|
||||
assert payload["usage"] == {
|
||||
"prompt_tokens": 4,
|
||||
"completion_tokens": 3,
|
||||
"total_tokens": 7,
|
||||
"prompt_tokens_details": None,
|
||||
}
|
||||
|
||||
|
||||
def test_build_usage_sums_prompt_and_completion_tokens():
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4, 5],
|
||||
output_token_ids_list=[[10, 11], [20, 21, 22]],
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens == 5
|
||||
assert usage.completion_tokens == 5 # 2 + 3
|
||||
assert usage.total_tokens == 10
|
||||
assert usage.prompt_tokens_details is None
|
||||
|
||||
|
||||
def test_build_usage_includes_encoder_prompt_tokens():
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3],
|
||||
output_token_ids_list=[[10]],
|
||||
encoder_prompt_token_ids=[100, 101],
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens == 5 # 3 + 2
|
||||
assert usage.total_tokens == 6
|
||||
|
||||
|
||||
def test_build_usage_reports_cached_tokens_unconditionally():
|
||||
# Unlike upstream's ``enable_prompt_tokens_details`` gate, prime-rl always
|
||||
# surfaces cached tokens — the cache-discount billing pipeline needs them.
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4],
|
||||
output_token_ids_list=[[10, 11]],
|
||||
num_cached_tokens=3,
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens_details is not None
|
||||
assert usage.prompt_tokens_details.cached_tokens == 3
|
||||
|
||||
|
||||
def test_build_usage_skips_cached_tokens_when_zero():
|
||||
# Don't emit a details block with cached=0, which would be misleading
|
||||
# to the router's billing extractor.
|
||||
final_res = _FakeRequestOutput(
|
||||
prompt_token_ids=[1, 2, 3, 4],
|
||||
output_token_ids_list=[[10, 11]],
|
||||
num_cached_tokens=0,
|
||||
)
|
||||
usage = _build_usage(final_res)
|
||||
assert usage.prompt_tokens_details is None
|
||||
|
||||
|
||||
def test_final_output_capture_records_last_item():
|
||||
async def _gen():
|
||||
for r in [
|
||||
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2, 3], output_token_ids_list=[[1, 2, 3]]),
|
||||
]:
|
||||
yield r
|
||||
|
||||
async def _drain(capture):
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
capture = _FinalOutputCapture(_gen())
|
||||
asyncio.run(_drain(capture))
|
||||
assert capture.final_res is not None
|
||||
assert capture.final_res.prompt_token_ids == [1, 2, 3]
|
||||
|
||||
|
||||
def test_final_output_capture_works_over_async_def_aiter_source():
|
||||
# ``_GenerateRoutedExpertsCapture`` exposes the async-iterator protocol
|
||||
# via ``async def __aiter__`` (an async generator function) and has no
|
||||
# ``__anext__``. The wrapper must drive it through ``async for`` rather
|
||||
# than poking ``__anext__`` directly, or routed-experts runs raise
|
||||
# AttributeError before the response is built.
|
||||
|
||||
class _AsyncGenAiterSource:
|
||||
def __init__(self, items):
|
||||
self._items = items
|
||||
|
||||
async def __aiter__(self):
|
||||
for item in self._items:
|
||||
yield item
|
||||
|
||||
items = [
|
||||
_FakeRequestOutput(prompt_token_ids=[1], output_token_ids_list=[[1]]),
|
||||
_FakeRequestOutput(prompt_token_ids=[1, 2], output_token_ids_list=[[1, 2]]),
|
||||
]
|
||||
capture = _FinalOutputCapture(_AsyncGenAiterSource(items))
|
||||
|
||||
async def _drain():
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
asyncio.run(_drain())
|
||||
assert capture.final_res is not None
|
||||
assert capture.final_res.prompt_token_ids == [1, 2]
|
||||
|
||||
|
||||
def test_final_output_capture_handles_empty_stream():
|
||||
capture = _FinalOutputCapture(_empty_request_outputs())
|
||||
|
||||
async def _drain():
|
||||
async for _ in capture:
|
||||
pass
|
||||
|
||||
asyncio.run(_drain())
|
||||
assert capture.final_res is None
|
||||
|
||||
|
||||
def test_client_set_max_tokens_assumes_set_when_body_unreadable():
|
||||
# No raw_request → can't tell, don't override.
|
||||
assert asyncio.run(_client_set_max_tokens(None)) is True
|
||||
|
||||
@@ -167,6 +167,11 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
|
||||
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
|
||||
|
||||
|
||||
def test_trainer_enable_token_export_cli_flag():
|
||||
assert not cli(TrainerConfig, args=[]).enable_token_export
|
||||
assert cli(TrainerConfig, args=["--enable-token-export"]).enable_token_export
|
||||
|
||||
|
||||
def test_orchestrator_vlm_requires_renderer():
|
||||
with pytest.raises(ValidationError, match="orchestrator.renderer must be set when model.vlm is set"):
|
||||
OrchestratorConfig.model_validate(
|
||||
|
||||
@@ -38,8 +38,8 @@ EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
|
||||
("PrimeIntellect/INTELLECT-3-FP8", "qwen3_coder", "deepseek_r1"),
|
||||
("PrimeIntellect/INTELLECT-3.1", "qwen3_coder", "deepseek_r1"),
|
||||
# NemotronH
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "qwen3_coder", None),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "qwen3_coder", None),
|
||||
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "qwen3_coder", "nemotron_v3"),
|
||||
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "qwen3_coder", "nano_v3"),
|
||||
# StepFun
|
||||
("stepfun-ai/Step-3.5-Flash", "step3p5", "step3p5"),
|
||||
# Qwen3 dense
|
||||
|
||||
@@ -110,3 +110,6 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
|
||||
sender = sender_holder["sender"]
|
||||
assert len(sender.sent) == 1
|
||||
assert len(sender.sent[0][0]) == 1
|
||||
micro_batch = sender.sent[0][0][0]
|
||||
assert micro_batch.run_id == "run_test123"
|
||||
assert micro_batch.run_step == 0
|
||||
|
||||
@@ -11,7 +11,7 @@ supported-markers = [
|
||||
]
|
||||
|
||||
[options]
|
||||
exclude-newer = "2026-06-01T23:58:54.614773201Z"
|
||||
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
@@ -1234,6 +1234,7 @@ dependencies = [
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/c8/33/c97b2bcbe06e0f011eedee0f41d4060f6344901a53c2703acc3dd7429713/fastsafetensors-0.3.2.tar.gz", hash = "sha256:9e358fce238684613a5c3ebb7800c52c5b3270c0bb5e4ed2191ee8f3d0431de1", size = 70409, upload-time = "2026-05-22T05:39:34.787Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c9/bb/9f821eac9bddd41ea1c5cd9b6a597c002741f022ecf6f3ba5cfcc3e9c950/fastsafetensors-0.3.2-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:69f4d8cbd3b542e5ddf7fee8136cf35e1524f9c30e118f64a0e846dab7e8de6b", size = 1877989, upload-time = "2026-06-04T09:02:56.11Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/68/a31c1661adf4d1b5ec29470ff991bde9094e4f347b0e6d1af8ba6b560d32/fastsafetensors-0.3.2-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6a932d7166c9e17e48aca3e5503d326bc6fc73fce6dc985ae6bd2ccc0f308b14", size = 1907188, upload-time = "2026-05-22T05:39:30.242Z" },
|
||||
]
|
||||
|
||||
@@ -4013,6 +4014,7 @@ envs = [
|
||||
{ name = "opencode-science", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "opencode-swe", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "reverse-text", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "rlm-search", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "rlm-swe", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "science-env", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "simpleqa-verified", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -4114,6 +4116,7 @@ requires-dist = [
|
||||
{ name = "reverse-text", marker = "extra == 'envs'", editable = "deps/verifiers/environments/reverse_text" },
|
||||
{ name = "rich", specifier = ">=14.0.0" },
|
||||
{ name = "ring-flash-attn", specifier = ">=0.1.8" },
|
||||
{ name = "rlm-search", marker = "extra == 'envs'", editable = "deps/research-environments/environments/rlm_search" },
|
||||
{ name = "rlm-swe", marker = "extra == 'envs'", editable = "deps/research-environments/environments/rlm_swe" },
|
||||
{ name = "science-env", marker = "extra == 'envs'", editable = "deps/research-environments/environments/science_env" },
|
||||
{ name = "setproctitle", specifier = ">=1.3.0" },
|
||||
@@ -4190,16 +4193,16 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "prime-tunnel"
|
||||
version = "0.1.7"
|
||||
version = "0.1.9"
|
||||
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/91/63/900dbb168a0f49dd9b6c510520a8c9b2b7ecb2c5863caac7757f12ea16e5/prime_tunnel-0.1.7.tar.gz", hash = "sha256:0fd296a78645c95c4474cf418321bac2ad6ba6816701e8823baf6ab718a68a5a", size = 13024, upload-time = "2026-05-20T06:38:40.444Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/36/de/0d17589b232708d1f5985372d1ca49e73493e0b08f860e6540d4885ce229/prime_tunnel-0.1.9.tar.gz", hash = "sha256:8d6c7fd7f5a98c47f50707edd606c4e7110e9dd1a08a1008b073be466408ac8d", size = 15162, upload-time = "2026-06-11T18:10:03.513Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/60/32/3270dba4c7c402372d25faf8f633f571fe2be8692d720e0eb717ed6ab44e/prime_tunnel-0.1.7-py3-none-any.whl", hash = "sha256:226a08ef9cc4c13503f4e1a687d4fa733ab72626725538b822edbaf8064c40fd", size = 14912, upload-time = "2026-05-20T06:38:38.986Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/50/2a/4b370d5d7cf7cbd98ce2714b7d877d2a184cc1b00d599df498aca04bce2d/prime_tunnel-0.1.9-py3-none-any.whl", hash = "sha256:9ad888e26ba4d81e96c643d9d27687ed4737c873f3b80ed3da8f92d6d7a2a615", size = 16274, upload-time = "2026-06-11T18:10:01.463Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4921,9 +4924,30 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/02/18ba0727a1c755c528d6a52b363d62c0b7a8e64cf961b3030c046107db4d/ring_flash_attn-0.1.8-py3-none-any.whl", hash = "sha256:296c929516c3b21f7bcdaeca44a99bb541779a7b63979eb0f67837dcb18a2bb9", size = 25437, upload-time = "2025-09-10T11:53:07.565Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rlm-search"
|
||||
version = "0.1.2"
|
||||
source = { editable = "deps/research-environments/environments/rlm_search" }
|
||||
dependencies = [
|
||||
{ name = "datasets", 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 = "openai", 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')" },
|
||||
{ name = "verifiers", extra = ["packages"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets", specifier = ">=4.0.0" },
|
||||
{ name = "httpx" },
|
||||
{ name = "openai", specifier = ">=1.0" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.19" },
|
||||
{ name = "verifiers", specifier = ">=0.1.15.dev171" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rlm-swe"
|
||||
version = "0.4.4"
|
||||
version = "0.5.1"
|
||||
source = { editable = "deps/research-environments/environments/rlm_swe" }
|
||||
dependencies = [
|
||||
{ name = "multi-swe-bench", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -4937,7 +4961,7 @@ requires-dist = [
|
||||
{ name = "multi-swe-bench", specifier = ">=1.1.2" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.19" },
|
||||
{ name = "swebench", specifier = "==4.1.0" },
|
||||
{ name = "verifiers", extras = ["packages"], specifier = ">=0.1.15.dev17" },
|
||||
{ name = "verifiers", extras = ["packages"], specifier = ">=0.1.15.dev17,<0.1.15.dev156" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6002,7 +6026,7 @@ requires-dist = [
|
||||
{ name = "pillow" },
|
||||
{ name = "prime-pydantic-config", extras = ["toml"] },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.25" },
|
||||
{ name = "prime-tunnel", specifier = ">=0.1.6" },
|
||||
{ name = "prime-tunnel", specifier = ">=0.1.8" },
|
||||
{ name = "pydantic", specifier = ">=2.11.9" },
|
||||
{ name = "pymupdf" },
|
||||
{ name = "python-dotenv", marker = "extra == 'browser'", specifier = ">=1.0.0" },
|
||||
|
||||
Reference in New Issue
Block a user