Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ff21d97e7 | ||
|
|
5e6f7ebae8 | ||
|
|
7d7bd92333 | ||
|
|
d8d214cbab | ||
|
|
a50b4079de | ||
|
|
0403c097a2 | ||
|
|
0b8c35e9b3 | ||
|
|
ca5e02c24c | ||
|
|
c37e2ca71b | ||
|
|
b1e9c7bdd2 | ||
|
|
af17a555fe | ||
|
|
a87badd65f | ||
|
|
5061b8d88e | ||
|
|
a8575d6f1c | ||
|
|
e75d8ca47f | ||
|
|
daedc1dbc6 | ||
|
|
3719abcfbb |
@@ -32,6 +32,7 @@ Namespaces are one honking great idea -- let's do more of those!
|
||||
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
|
||||
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
|
||||
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
|
||||
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
|
||||
|
||||
## Skills
|
||||
|
||||
@@ -54,4 +55,5 @@ Write tests as plain functions with pytest fixtures. Don't use class-based tests
|
||||
|
||||
- **Draft PRs**: always create PRs as drafts (`gh pr create --draft`) to avoid triggering CI unnecessarily.
|
||||
- **Pull requests**: do not include a "test plan" section in PR descriptions unless you actually ran tests to verify the changes or the user explicitly asked for one.
|
||||
- **Keep PR descriptions in sync**: every time you push commits to a PR, also update the PR description (`gh pr edit <num> --body-file ...`) so it reflects the current state of the branch — not just what was true when the PR was opened. Preserve any auto-generated blocks (e.g. `<!-- CURSOR_SUMMARY -->`).
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
|
||||
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
|
||||
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
|
||||
- **`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)
|
||||
|
||||
@@ -86,10 +86,12 @@ def my_custom_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
|
||||
```python
|
||||
@dataclass
|
||||
class AdvantageInputs:
|
||||
rewards: Float[Tensor, "num_examples rollouts_per_example"]
|
||||
completion_lengths: Int[Tensor, "num_examples rollouts_per_example"]
|
||||
# Rollouts grouped by problem: rollouts[i][j] is the j-th rollout for problem i.
|
||||
rollouts: list[list[vf.RolloutOutput]]
|
||||
```
|
||||
|
||||
Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.), so custom advantages can read any metadata they need (e.g. completion-token counts, turn counts, tool calls).
|
||||
|
||||
#### AdvantageOutputs
|
||||
|
||||
```python
|
||||
@@ -106,9 +108,10 @@ from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
|
||||
|
||||
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
|
||||
"""Normalize advantages to zero mean and unit variance per example."""
|
||||
mean = inputs.rewards.mean(dim=1, keepdim=True)
|
||||
std = inputs.rewards.std(dim=1, keepdim=True)
|
||||
advantages = (inputs.rewards - mean) / (std + eps)
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
|
||||
mean = rewards.mean(dim=1, keepdim=True)
|
||||
std = rewards.std(dim=1, keepdim=True)
|
||||
advantages = (rewards - mean) / (std + eps)
|
||||
return AdvantageOutputs(advantages=advantages)
|
||||
```
|
||||
|
||||
|
||||
@@ -207,7 +207,7 @@ spec:
|
||||
timeoutSeconds: {{ .Values.inference.probes.startup.timeoutSeconds }}
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
path: /liveness
|
||||
port: {{ .Values.inference.service.port }}
|
||||
periodSeconds: {{ .Values.inference.probes.liveness.periodSeconds }}
|
||||
failureThreshold: {{ .Values.inference.probes.liveness.failureThreshold }}
|
||||
|
||||
@@ -75,7 +75,7 @@ inference:
|
||||
|
||||
runtimeClassName: nvidia
|
||||
|
||||
# Health probes for inference server (requires /health endpoint)
|
||||
# Health probes for inference server (/health for startup/readiness, /liveness for engine liveness)
|
||||
probes:
|
||||
enabled: false
|
||||
# Startup probe: allows long model loading time (up to 45 min by default)
|
||||
@@ -86,7 +86,7 @@ inference:
|
||||
liveness:
|
||||
periodSeconds: 10
|
||||
failureThreshold: 3
|
||||
timeoutSeconds: 60
|
||||
timeoutSeconds: 10
|
||||
readiness:
|
||||
periodSeconds: 5
|
||||
failureThreshold: 2
|
||||
|
||||
+37
-3
@@ -20,7 +20,7 @@ dependencies = [
|
||||
"torchdata>=0.11.0",
|
||||
"transformers",
|
||||
"vllm>=0.19.0",
|
||||
"wandb>=0.24.2",
|
||||
"wandb>=0.26.1",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.5.73",
|
||||
"pyzmq>=27.1.0",
|
||||
@@ -109,6 +109,7 @@ dev = [
|
||||
|
||||
|
||||
[tool.uv]
|
||||
exclude-newer = "7 days"
|
||||
preview = true
|
||||
no-build-isolation-package = ["flash-attn"]
|
||||
environments = [
|
||||
@@ -123,13 +124,46 @@ override-dependencies = [
|
||||
"transformers>=5.1.0.dev0",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# pytorch-cu128 / pytorch-cu128-test indexes don't publish upload dates
|
||||
torch = false
|
||||
flash_attn_3 = false
|
||||
# Self-vendored packages on our primeintellect index
|
||||
reverse-text = false
|
||||
alphabet-sort = false
|
||||
wiki-search = false
|
||||
math-python = false
|
||||
math-env = false
|
||||
code-env = false
|
||||
science-env = false
|
||||
logic-env = false
|
||||
color-codeword = false
|
||||
math500 = false
|
||||
aime2024 = false
|
||||
aime2025 = false
|
||||
deepdive = false
|
||||
mini_swe_agent_plus = false
|
||||
# PrimeIntellect-published on PyPI (trusted publisher)
|
||||
prime = false
|
||||
prime-sandboxes = false
|
||||
prime-tunnel = false
|
||||
prime-evals = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
verifiers = false
|
||||
vllm-router = false
|
||||
dion = false
|
||||
pydantic-config = false
|
||||
deep-ep = false
|
||||
deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cu128" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "77a9f28" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "3b77145" }
|
||||
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" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
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.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
reverse-text = { index = "primeintellect" }
|
||||
|
||||
@@ -14,7 +14,7 @@ export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
|
||||
|
||||
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
|
||||
uv pip install --reinstall --no-deps \
|
||||
"flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
|
||||
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
|
||||
|
||||
# TODO: remove once flash-attn gates the ampere_helpers import or cutlass-dsl re-adds it.
|
||||
echo "=== copying ampere_helpers.py from flashinfer vendor ==="
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
set -e
|
||||
|
||||
echo "Reinstalling flash-attn-cute to fix namespace conflict with flash-attn..."
|
||||
uv pip install --reinstall --no-deps "flash-attn-cute @ git+https://github.com/Dao-AILab/flash-attention.git@2b5db43#subdirectory=flash_attn/cute"
|
||||
uv pip install --reinstall --no-deps "flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
|
||||
|
||||
# Verify installation
|
||||
LINES=$(wc -l < "$(python -c 'import flash_attn.cute.interface as m; print(m.__file__)')")
|
||||
|
||||
@@ -11,6 +11,7 @@ from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
PrimeMonitorConfig,
|
||||
RendererConfig,
|
||||
TransportConfig,
|
||||
WandbWithExtrasConfig,
|
||||
)
|
||||
@@ -324,6 +325,14 @@ class EnvConfig(BaseConfig):
|
||||
),
|
||||
] = -1
|
||||
|
||||
timeout: Annotated[
|
||||
float | None,
|
||||
Field(
|
||||
validation_alias=AliasChoices("timeout", "timeout_seconds"),
|
||||
description="Per-rollout wall-clock timeout in seconds. Set to None (default) to disable.",
|
||||
),
|
||||
] = None
|
||||
|
||||
@property
|
||||
def stripped_id(self) -> str:
|
||||
"""Environment ID without the @version suffix."""
|
||||
@@ -346,6 +355,12 @@ class EnvConfig(BaseConfig):
|
||||
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_total_completion_tokens
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_timeout(self):
|
||||
if self.timeout is not None:
|
||||
self.extra_env_kwargs["timeout_seconds"] = self.timeout
|
||||
return self
|
||||
|
||||
|
||||
class TrainEnvConfig(EnvConfig):
|
||||
"""Configures a training environment."""
|
||||
@@ -676,16 +691,18 @@ class DefaultAdvantageConfig(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
length_shaping: Annotated[
|
||||
bool,
|
||||
length_penalty: Annotated[
|
||||
Literal["tokens", "turns"] | None,
|
||||
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."
|
||||
"Cost metric for correctness-gated length penalty. `tokens` shapes by completion-token "
|
||||
"count, `turns` shapes by trajectory turn count, `None` disables shaping. In mixed "
|
||||
"groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct "
|
||||
"rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost "
|
||||
"rollouts get advantage in [0, 1], others get 0."
|
||||
)
|
||||
),
|
||||
] = False
|
||||
] = None
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseModel):
|
||||
@@ -856,6 +873,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The renderer configuration (only used when use_renderer=True)
|
||||
renderer: RendererConfig = RendererConfig()
|
||||
|
||||
# The optimizer configuration (per-run LR for multi-run training)
|
||||
optim: OptimizerConfig = OptimizerConfig()
|
||||
|
||||
@@ -1043,10 +1063,24 @@ class OrchestratorConfig(BaseConfig):
|
||||
use_token_client: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
|
||||
description="Whether to use the token-in-token-out (TITO) client for training across all environments. "
|
||||
"WARNING: Only use this if your environment has a linear history and the chat template has the extension "
|
||||
"property (i.e. no tokens are ever removed or inserted by the chat template). Mutually exclusive with "
|
||||
"``use_renderer``."
|
||||
),
|
||||
] = True
|
||||
|
||||
use_renderer: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use the renderer client (client-side tokenization via the ``renderers`` package, "
|
||||
"served by ``/v1/generate``). Mutually exclusive with ``use_token_client``. When True, the "
|
||||
"``[orchestrator.renderer]`` block (name / tool_parser / reasoning_parser / pool_size) "
|
||||
"applies; when False those fields must be left at their defaults. Not supported for VLMs — "
|
||||
"VLMs must use the token client (TITO) so image preprocessing and chat templating stay server-side."
|
||||
),
|
||||
] = False
|
||||
|
||||
env_install_prerelease: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
@@ -1116,6 +1150,69 @@ class OrchestratorConfig(BaseConfig):
|
||||
raise ValueError(
|
||||
"orchestrator.use_token_client must be false when orchestrator.teacher_rollout_model is configured."
|
||||
)
|
||||
if has_teacher and self.use_renderer:
|
||||
raise ValueError(
|
||||
"orchestrator.use_renderer must be false when orchestrator.teacher_rollout_model is configured "
|
||||
"(external rollout uses MITO)."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_client_mode(self):
|
||||
"""The two client toggles select among three exclusive modes:
|
||||
|
||||
- ``use_token_client=True`` + ``use_renderer=False`` → TITO (default)
|
||||
- ``use_token_client=False`` + ``use_renderer=True`` → renderer
|
||||
- ``use_token_client=False`` + ``use_renderer=False`` → MITO
|
||||
|
||||
Both True is invalid: TITO and renderer are different wire protocols
|
||||
(server-side templating vs client-side tokenization).
|
||||
"""
|
||||
if self.use_token_client and self.use_renderer:
|
||||
raise ValueError(
|
||||
"orchestrator.use_token_client and orchestrator.use_renderer are mutually exclusive. "
|
||||
"Pick one: token client (TITO, server-side templating) or renderer client (client-side "
|
||||
"tokenization)."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_vs_vlm(self):
|
||||
"""The renderer client takes plain message dicts and tokenizes
|
||||
them client-side. VLMs need server-side image preprocessing and
|
||||
chat templating, so they must use the token client (TITO) — fail
|
||||
loudly when both are set."""
|
||||
if self.use_renderer and self.model.vlm is not None:
|
||||
raise ValueError(
|
||||
"orchestrator.use_renderer is not supported for VLMs. Use the token client "
|
||||
"(``use_token_client=true``, the default) so image preprocessing and chat "
|
||||
"templating stay on the inference server."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_args(self):
|
||||
"""``[orchestrator.renderer]`` knobs are only meaningful when
|
||||
``use_renderer=True``. Reject otherwise so callers don't silently
|
||||
pass them and wonder why they're ignored."""
|
||||
if self.use_renderer:
|
||||
return self
|
||||
|
||||
renderer_args_set = []
|
||||
if self.renderer.name != "auto":
|
||||
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
|
||||
if self.renderer.tool_parser is not None:
|
||||
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
|
||||
if self.renderer.reasoning_parser is not None:
|
||||
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
|
||||
if self.renderer.pool_size is not None:
|
||||
renderer_args_set.append(f"renderer.pool_size={self.renderer.pool_size!r}")
|
||||
|
||||
if renderer_args_set:
|
||||
raise ValueError(
|
||||
"Renderer-specific args set without orchestrator.use_renderer=True: "
|
||||
f"{', '.join(renderer_args_set)}. Either enable the renderer client or remove these knobs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -132,6 +132,61 @@ class BaseModelConfig(BaseConfig):
|
||||
] = None
|
||||
|
||||
|
||||
class RendererConfig(BaseConfig):
|
||||
"""Configures the client-side renderer (chat-template + response parsing).
|
||||
|
||||
Only consumed when ``orchestrator.use_renderer = true``. The renderer
|
||||
owns both directions: render messages → token ids on the client, and
|
||||
parse model output tokens → structured ``content`` / ``reasoning_content``
|
||||
/ ``tool_calls``.
|
||||
"""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description=(
|
||||
"Renderer to use for chat template tokenization. "
|
||||
"Options: 'auto' (detect from tokenizer), 'qwen3', 'qwen3_vl', "
|
||||
"'qwen3.5', 'glm5', 'glm4.5', 'minimax-m2', 'deepseek_v3', "
|
||||
"'kimi_k2', 'kimi_k25', 'nemotron3', 'gpt_oss', 'default'."
|
||||
),
|
||||
),
|
||||
] = "auto"
|
||||
|
||||
tool_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description=(
|
||||
"Name of a tool parser in renderers.parsers. Only consumed by "
|
||||
"DefaultRenderer (model-specific renderers bake their own parsing "
|
||||
"in). Options today: 'qwen3', 'qwen3.5', 'glm', 'deepseek_v3'."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
reasoning_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description=(
|
||||
"Name of a reasoning parser in renderers.parsers. Only consumed "
|
||||
"by DefaultRenderer. Options today: 'think'."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
pool_size: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Number of renderer slots shared across concurrent rollouts. "
|
||||
"None keeps the verifiers default (1). Bump for long multi-turn "
|
||||
"prompts where client-side jinja tokenization serializes."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class ElasticConfig(BaseConfig):
|
||||
"""Configures elastic inference pool with DNS-based service discovery.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from argparse import Namespace
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
@@ -20,6 +21,7 @@ from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.inference.vllm.serving_generate import GenerateRequest
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
|
||||
@@ -158,6 +160,7 @@ logger = init_logger("vllm.entrypoints.openai.api_server")
|
||||
|
||||
# Create our own router for custom endpoints
|
||||
router = APIRouter()
|
||||
LIVENESS_TIMEOUT_SECONDS = 5.0
|
||||
|
||||
|
||||
def engine_client(request: Request) -> EngineClient:
|
||||
@@ -178,10 +181,62 @@ WORKER_EXTENSION_CLS = {
|
||||
}
|
||||
|
||||
|
||||
def generate_handler(request: Request):
|
||||
return request.app.state.openai_serving_generate
|
||||
|
||||
|
||||
def chat_with_tokens(request: Request) -> OpenAIServingChatWithTokens | None:
|
||||
return request.app.state.openai_serving_chat_with_tokens
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/generate",
|
||||
dependencies=[Depends(validate_json_request)],
|
||||
responses={
|
||||
HTTPStatus.OK.value: {"content": {"application/json": {}}},
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
@load_aware_call
|
||||
async def _generate(request: GenerateRequest, raw_request: Request):
|
||||
handler = generate_handler(raw_request)
|
||||
if handler is None:
|
||||
return JSONResponse({"error": "generate endpoint not available"}, status_code=503)
|
||||
result = await handler.generate(request, raw_request)
|
||||
if isinstance(result, dict) and "error" in result:
|
||||
return JSONResponse(result, status_code=500)
|
||||
return JSONResponse(content=result.model_dump())
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/chat/completions/tokens",
|
||||
dependencies=[Depends(validate_json_request)],
|
||||
responses={
|
||||
HTTPStatus.OK.value: {"content": {"text/event-stream": {}}},
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
@load_aware_call
|
||||
async def _chat_with_tokens(request: ChatCompletionRequestWithTokens, raw_request: Request):
|
||||
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")
|
||||
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)
|
||||
|
||||
elif isinstance(generator, ChatCompletionResponse):
|
||||
return JSONResponse(content=generator.model_dump())
|
||||
|
||||
return StreamingResponse(content=generator, media_type="text/event-stream")
|
||||
|
||||
|
||||
@router.post("/pause")
|
||||
async def pause(request: Request):
|
||||
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
|
||||
@@ -211,6 +266,19 @@ async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: R
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/liveness")
|
||||
async def liveness(raw_request: Request):
|
||||
"""Check that the engine event loop can service a no-op worker RPC."""
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
engine_client(raw_request).collective_rpc("liveness_probe"),
|
||||
timeout=LIVENESS_TIMEOUT_SECONDS,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
return JSONResponse({"status": "engine_unresponsive"}, status_code=503)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/init_broadcaster")
|
||||
async def init_broadcaster(request: Request):
|
||||
data = await request.json()
|
||||
@@ -227,32 +295,6 @@ async def init_broadcaster(request: Request):
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/chat/completions/tokens",
|
||||
dependencies=[Depends(validate_json_request)],
|
||||
responses={
|
||||
HTTPStatus.OK.value: {"content": {"text/event-stream": {}}},
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
@load_aware_call
|
||||
async def _chat_with_tokens(request: ChatCompletionRequestWithTokens, raw_request: Request):
|
||||
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")
|
||||
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)
|
||||
|
||||
elif isinstance(generator, ChatCompletionResponse):
|
||||
return JSONResponse(content=generator.model_dump())
|
||||
|
||||
return StreamingResponse(content=generator, media_type="text/event-stream")
|
||||
|
||||
|
||||
async def custom_init_app_state(
|
||||
engine_client: EngineClient,
|
||||
state: State,
|
||||
@@ -262,10 +304,16 @@ async def custom_init_app_state(
|
||||
"""
|
||||
Modifies init_app_state:
|
||||
1. Call the original init_app_state to set up standard state.
|
||||
2. Replace the serving_chat with our OpenAIServingChatWithTokens wrapper.
|
||||
2. Replace ``serving_chat`` with our ``OpenAIServingChatWithTokens`` wrapper
|
||||
so the ``/v1/chat/completions/tokens`` (TITO) endpoint can stream
|
||||
token IDs alongside the rendered chat completion.
|
||||
3. Add ``/v1/generate`` endpoint for renderer-based token-level inference.
|
||||
"""
|
||||
await init_app_state(engine_client, state, args, supported_tasks)
|
||||
|
||||
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
|
||||
|
||||
# TITO: server-side chat templating + token IDs.
|
||||
if "generate" in supported_tasks and state.openai_serving_chat is not None:
|
||||
original_chat = state.openai_serving_chat
|
||||
serving_chat = object.__new__(OpenAIServingChatWithTokens)
|
||||
@@ -275,6 +323,12 @@ async def custom_init_app_state(
|
||||
else:
|
||||
state.openai_serving_chat_with_tokens = None
|
||||
|
||||
# /v1/generate endpoint — tokens + optional images, no chat template
|
||||
from prime_rl.inference.vllm.serving_generate import OpenAIServingGenerate
|
||||
|
||||
chat_handler = state.openai_serving_chat if "generate" in supported_tasks else None
|
||||
state.openai_serving_generate = OpenAIServingGenerate(engine_client, chat_handler=chat_handler)
|
||||
|
||||
|
||||
import vllm.entrypoints.openai.api_server
|
||||
import vllm.v1.utils
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
"""/v1/generate endpoint — accepts pre-tokenized inputs.
|
||||
|
||||
Text-only tokens in, tokens out. The Renderer does all tokenization client-side.
|
||||
No Jinja rendering, no server-side chat template application.
|
||||
|
||||
VLMs do not use this endpoint. The orchestrator routes VLMs to MITO
|
||||
(/v1/chat/completions) where vLLM handles image preprocessing and chat
|
||||
templating server-side.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
import numpy as np
|
||||
from fastapi import Request
|
||||
from pydantic import BaseModel
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.inputs.engine import tokens_input
|
||||
from vllm.logger import init_logger
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
# ── Request / Response schemas ───────────────────────────────────────
|
||||
|
||||
|
||||
class GenerateRequest(BaseModel):
|
||||
model: str | None = None
|
||||
prompt_token_ids: list[int]
|
||||
|
||||
# When unset, fill from max_model_len - prompt_len at request time so we
|
||||
# match /v1/chat/completions behavior. The previous 4096 hard default
|
||||
# silently truncated long completions on 8k+ context runs (e.g. hendrycks
|
||||
# reasoning rollouts capped at 4096 tokens, making rendered rollouts look
|
||||
# shorter than main's for the same model).
|
||||
max_tokens: int | None = None
|
||||
temperature: float = 1.0
|
||||
top_p: float = 1.0
|
||||
top_k: int = -1
|
||||
min_p: float = 0.0
|
||||
seed: int | None = None
|
||||
n: int = 1
|
||||
stop_token_ids: list[int] | None = None
|
||||
repetition_penalty: float = 1.0
|
||||
min_tokens: int = 0
|
||||
prompt_logprobs: bool = False
|
||||
priority: int = 0
|
||||
# Prefix-cache invalidation salt. Must match main's
|
||||
# /v1/chat/completions/tokens path: the orchestrator sets
|
||||
# `extra_body["cache_salt"] = str(ckpt_step)` on every rollout
|
||||
# request. vLLM's KV cache hashes include this salt, so when the
|
||||
# step changes the cache misses and KV is recomputed with fresh
|
||||
# weights. Without this, renderers path silently reuses stale KV
|
||||
# from before the latest weight update and its logprobs drift from
|
||||
# the trainer's forward pass (mismatch_kl grows 3x over training).
|
||||
cache_salt: str | None = None
|
||||
|
||||
|
||||
class GenerateChoiceResponse(BaseModel):
|
||||
index: int
|
||||
token_ids: list[int]
|
||||
logprobs: list[float]
|
||||
finish_reason: str | None = None
|
||||
routed_experts: dict | None = None
|
||||
|
||||
|
||||
class GenerateResponse(BaseModel):
|
||||
id: str
|
||||
model: str
|
||||
prompt_token_ids: list[int]
|
||||
choices: list[GenerateChoiceResponse]
|
||||
usage: dict
|
||||
prompt_logprobs: list[float | None] | None = None
|
||||
|
||||
|
||||
# ── Handler ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class OpenAIServingGenerate:
|
||||
"""Lightweight generate handler — tokens in, tokens out."""
|
||||
|
||||
def __init__(self, engine_client: EngineClient, chat_handler: Any | None = None):
|
||||
self.engine_client = engine_client
|
||||
self.chat_handler = chat_handler
|
||||
|
||||
async def generate(self, request: GenerateRequest, raw_request: Request) -> GenerateResponse | dict:
|
||||
# Pre-rendered TokensInput shape (type="token") — avoids vLLM's
|
||||
# "raw prompt" deprecation that targets plain lists/strings.
|
||||
engine_prompt = tokens_input(request.prompt_token_ids, cache_salt=request.cache_salt)
|
||||
|
||||
# Match /v1/chat/completions: if the client didn't ask for a specific
|
||||
# cap, let the model generate up to whatever room is left in context.
|
||||
# vLLM v1 AsyncLLM exposes model_config directly (no async getter).
|
||||
max_tokens = request.max_tokens
|
||||
if max_tokens is None:
|
||||
max_model_len = self.engine_client.model_config.max_model_len
|
||||
max_tokens = max(1, max_model_len - len(request.prompt_token_ids))
|
||||
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=max_tokens,
|
||||
temperature=request.temperature,
|
||||
top_p=request.top_p,
|
||||
top_k=request.top_k,
|
||||
min_p=request.min_p,
|
||||
seed=request.seed,
|
||||
n=request.n,
|
||||
stop_token_ids=request.stop_token_ids or [],
|
||||
repetition_penalty=request.repetition_penalty,
|
||||
min_tokens=request.min_tokens,
|
||||
logprobs=1,
|
||||
prompt_logprobs=1 if request.prompt_logprobs else None,
|
||||
skip_special_tokens=False,
|
||||
)
|
||||
|
||||
request_id = f"gen-{uuid4().hex[:16]}"
|
||||
routed_experts_map: dict[int, dict] = {}
|
||||
final_output: RequestOutput | None = None
|
||||
data_parallel_rank = None
|
||||
lora_request = None
|
||||
trace_headers = None
|
||||
if self.chat_handler is not None:
|
||||
data_parallel_rank = self.chat_handler._get_data_parallel_rank(raw_request)
|
||||
trace_headers = await self.chat_handler._get_trace_headers(raw_request.headers)
|
||||
lora_request = self.chat_handler._maybe_get_adapters(request)
|
||||
|
||||
generator = self.engine_client.generate(
|
||||
engine_prompt,
|
||||
sampling_params,
|
||||
request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
data_parallel_rank=data_parallel_rank,
|
||||
)
|
||||
|
||||
# Drain the generator without polling ``raw_request.is_disconnected``
|
||||
# per decode step. That poll is one ASGI ``receive()`` await per
|
||||
# yielded token — at ~2k concurrent rollouts each producing dozens of
|
||||
# tokens, it was the single largest per-step overhead on the /generate
|
||||
# path (vLLM's own chat completions handler uses the CancelledError
|
||||
# pattern for the same reason). Starlette cancels this coroutine on
|
||||
# client disconnect, so the except branch still catches it.
|
||||
try:
|
||||
async for output in generator:
|
||||
for comp_output in output.outputs:
|
||||
if comp_output.routed_experts is not None:
|
||||
routed_experts_map[comp_output.index] = _encode_routed_experts(comp_output.routed_experts)
|
||||
final_output = output
|
||||
except asyncio.CancelledError:
|
||||
await self.engine_client.abort(request_id)
|
||||
raise
|
||||
|
||||
if final_output is None:
|
||||
return {"error": "No output generated"}
|
||||
|
||||
choices = []
|
||||
for output in final_output.outputs:
|
||||
token_ids = list(output.token_ids)
|
||||
logprobs_list: list[float] = []
|
||||
if output.logprobs:
|
||||
for i, lp_dict in enumerate(output.logprobs):
|
||||
if i < len(token_ids) and token_ids[i] in lp_dict:
|
||||
logprobs_list.append(lp_dict[token_ids[i]].logprob)
|
||||
else:
|
||||
logprobs_list.append(0.0)
|
||||
|
||||
choices.append(
|
||||
GenerateChoiceResponse(
|
||||
index=output.index,
|
||||
token_ids=token_ids,
|
||||
logprobs=logprobs_list,
|
||||
finish_reason=output.finish_reason,
|
||||
routed_experts=routed_experts_map.get(output.index),
|
||||
)
|
||||
)
|
||||
|
||||
prompt_len = len(final_output.prompt_token_ids)
|
||||
completion_len = sum(len(c.token_ids) for c in choices)
|
||||
prompt_logprobs = _extract_prompt_logprobs(final_output.prompt_logprobs)
|
||||
|
||||
return GenerateResponse(
|
||||
id=request_id,
|
||||
model=request.model or "",
|
||||
prompt_token_ids=list(final_output.prompt_token_ids),
|
||||
choices=choices,
|
||||
usage={
|
||||
"prompt_tokens": prompt_len,
|
||||
"completion_tokens": completion_len,
|
||||
"total_tokens": prompt_len + completion_len,
|
||||
},
|
||||
prompt_logprobs=prompt_logprobs,
|
||||
)
|
||||
|
||||
|
||||
def _encode_routed_experts(arr: np.ndarray) -> dict:
|
||||
return {
|
||||
"data": base64.b85encode(arr.tobytes()).decode("ascii"),
|
||||
"shape": list(arr.shape),
|
||||
}
|
||||
|
||||
|
||||
def _extract_prompt_logprobs(
|
||||
prompt_logprobs: list[dict[int, Any] | None] | Mapping[int, Any] | None,
|
||||
) -> list[float | None] | None:
|
||||
if prompt_logprobs is None:
|
||||
return None
|
||||
if isinstance(prompt_logprobs, Mapping):
|
||||
prompt_logprobs = [prompt_logprobs]
|
||||
|
||||
extracted: list[float | None] = []
|
||||
for token_logprobs in prompt_logprobs:
|
||||
if not token_logprobs:
|
||||
extracted.append(None)
|
||||
continue
|
||||
selected = next(iter(token_logprobs.values()))
|
||||
logprob = selected.logprob if hasattr(selected, "logprob") else selected.get("logprob")
|
||||
extracted.append(float(logprob) if logprob is not None else None)
|
||||
return extracted
|
||||
@@ -20,6 +20,10 @@ class FileSystemWeightUpdateWorker(Worker):
|
||||
"""Initialize the broadcaster."""
|
||||
...
|
||||
|
||||
def liveness_probe(self) -> None:
|
||||
"""No-op RPC used by the API server liveness endpoint."""
|
||||
return None
|
||||
|
||||
def update_weights_from_path(self, weight_path: str) -> None:
|
||||
"""Update weights from a specified path in shared filesystem containing a HF-compatible checkpoint."""
|
||||
# Get vLLM model runner and model
|
||||
|
||||
@@ -130,6 +130,10 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
def liveness_probe(self) -> None:
|
||||
"""No-op RPC used by the API server liveness endpoint."""
|
||||
return None
|
||||
|
||||
def update_weights_from_path(self, weight_dir: str) -> None:
|
||||
"""Update weights with the nccl communicator."""
|
||||
model_runner = self.model_runner
|
||||
|
||||
@@ -1,22 +1,27 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable
|
||||
from typing import Callable, Literal
|
||||
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from jaxtyping import Float, Int
|
||||
from jaxtyping import Float
|
||||
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.orchestrator.vf_utils import get_model_completion_len, get_num_turns
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
LengthPenalty = Literal["tokens", "turns"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class AdvantageInputs:
|
||||
"""Inputs for advantage computation."""
|
||||
"""Inputs for advantage computation.
|
||||
|
||||
rewards: Float[Tensor, "num_problems rollouts_per_example"]
|
||||
completion_lengths: Int[Tensor, "num_problems rollouts_per_example"]
|
||||
`rollouts` is grouped by problem: `rollouts[i][j]` is the j-th rollout for problem i,
|
||||
so `len(rollouts) == num_problems` and `len(rollouts[0]) == rollouts_per_example`.
|
||||
"""
|
||||
|
||||
rollouts: list[list[vf.RolloutOutput]]
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -37,30 +42,40 @@ Expected signature:
|
||||
|
||||
def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_shaping: bool = False,
|
||||
length_penalty: LengthPenalty | None = None,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage: reward minus per-problem baseline."""
|
||||
rewards = inputs.rewards
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
|
||||
|
||||
if length_shaping:
|
||||
completion_lengths = inputs.completion_lengths.to(dtype=rewards.dtype)
|
||||
return AdvantageOutputs(advantages=_efficiency_length_shaping(rewards, completion_lengths))
|
||||
if length_penalty == "tokens":
|
||||
costs = torch.tensor(
|
||||
[[get_model_completion_len(r) for r in group] for group in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
|
||||
if length_penalty == "turns":
|
||||
costs = torch.tensor(
|
||||
[[get_num_turns(r) for r in group] for group in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
|
||||
|
||||
baseline = rewards.mean(dim=1, keepdim=True)
|
||||
return AdvantageOutputs(advantages=rewards - baseline)
|
||||
|
||||
|
||||
def _efficiency_length_shaping(
|
||||
def _efficiency_shaping(
|
||||
rewards: Float[Tensor, "num_problems rollouts_per_example"],
|
||||
completion_lengths: Float[Tensor, "num_problems rollouts_per_example"],
|
||||
costs: Float[Tensor, "num_problems rollouts_per_example"],
|
||||
) -> Float[Tensor, "num_problems rollouts_per_example"]:
|
||||
"""Correctness-gated length shaping with bounded advantages.
|
||||
"""Correctness-gated efficiency shaping with bounded advantages.
|
||||
|
||||
Shapes rewards with a bounded brevity bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages per group.
|
||||
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages per group. `costs` is a per-rollout cost (e.g.,
|
||||
completion length in tokens or number of turns).
|
||||
|
||||
Correct rollouts get reward amplified by up to 2x based on relative brevity.
|
||||
Incorrect rollouts are untouched. Shorter correct rollouts get higher advantage.
|
||||
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
|
||||
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
|
||||
"""
|
||||
max_reward = rewards.max(dim=1, keepdim=True).values
|
||||
correct_mask = rewards >= max_reward
|
||||
@@ -69,12 +84,12 @@ def _efficiency_length_shaping(
|
||||
# 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)
|
||||
# Mean cost of correct rollouts per problem
|
||||
correct_costs = costs * correct_mask
|
||||
mean_correct_cost = correct_costs.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)
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above
|
||||
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
|
||||
|
||||
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
|
||||
shaped_rewards = rewards * (1 + bonus * correct_mask)
|
||||
@@ -99,7 +114,7 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
|
||||
return default_advantage_fn(
|
||||
inputs,
|
||||
length_shaping=config.length_shaping,
|
||||
length_penalty=config.length_penalty,
|
||||
)
|
||||
|
||||
return advantage_fn
|
||||
@@ -127,12 +142,8 @@ def compute_advantages(
|
||||
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),
|
||||
completion_lengths=torch.tensor(completion_lengths).view(-1, samples_per_problem),
|
||||
)
|
||||
grouped = [rollouts[i : i + samples_per_problem] for i in range(0, len(rollouts), samples_per_problem)]
|
||||
inputs = AdvantageInputs(rollouts=grouped)
|
||||
|
||||
result = advantage_fn(inputs)
|
||||
advantages = result.advantages.flatten().tolist()
|
||||
|
||||
@@ -31,6 +31,7 @@ monkey_patch_chat_completion_logprobs()
|
||||
|
||||
import pandas as pd
|
||||
import verifiers as vf
|
||||
from renderers.base import create_renderer
|
||||
from transformers import AutoProcessor
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
@@ -118,14 +119,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# 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)
|
||||
|
||||
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,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type="openai_chat_completions",
|
||||
)
|
||||
|
||||
# Setup teacher inference pool if configured
|
||||
if config.teacher_model:
|
||||
logger.info(
|
||||
@@ -154,6 +147,14 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
config.model.name, trust_remote_code=config.model.trust_remote_code, use_fast=True
|
||||
)
|
||||
|
||||
renderer, inference_pool = await setup_rollout_inference_pool(
|
||||
config=config,
|
||||
rollout_client_config=rollout_client_config,
|
||||
rollout_model_name=rollout_model_name,
|
||||
tokenizer=tokenizer,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
# Setup monitor (may register the run and set RUN_ID in the environment)
|
||||
logger.info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
|
||||
monitor = setup_monitor(
|
||||
@@ -162,6 +163,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
output_dir=config.output_dir,
|
||||
tokenizer=tokenizer,
|
||||
run_config=config,
|
||||
keep_full_history=config.bench,
|
||||
)
|
||||
|
||||
# Read run_id AFTER setup_monitor so that newly registered runs are captured
|
||||
@@ -424,7 +426,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Compute advantages (in-place)
|
||||
num_rollouts = len(train_rollouts)
|
||||
num_unique_examples = len({r["example_id"] for r in train_rollouts})
|
||||
num_unique_examples = len({(r["env_name"], 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"]
|
||||
@@ -479,33 +481,53 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Convert rollouts to training samples
|
||||
parallel_preprocess_start = time.perf_counter()
|
||||
|
||||
# Pretokenize before VLM image cache build (which strips image data from messages)
|
||||
for rollout in train_rollouts:
|
||||
pretokenize_rollout_trajectory(rollout, tokenizer, processor=processor)
|
||||
# Stage 1: pretokenize + (for VLM) build image cache concurrently.
|
||||
# Pretokenize is a no-op when the renderer client already populated
|
||||
# `tokens` on each trajectory step, but the fallback-tokenizer path
|
||||
# and image-cache build are both CPU-heavy. Running them on threads
|
||||
# and awaiting a single gather lets whichever finishes first free
|
||||
# the event loop immediately and, with max_async_level >= 2, overlaps
|
||||
# this whole stage with inference for the next batch.
|
||||
async def _pretokenize_all() -> None:
|
||||
await asyncio.gather(
|
||||
*(
|
||||
asyncio.to_thread(
|
||||
pretokenize_rollout_trajectory,
|
||||
rollout,
|
||||
tokenizer,
|
||||
processor=processor,
|
||||
renderer=renderer,
|
||||
)
|
||||
for rollout in train_rollouts
|
||||
)
|
||||
)
|
||||
|
||||
# VLM: build image cache in a thread so it doesn't block the event loop.
|
||||
# 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.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
|
||||
|
||||
_, vlm_cache = await asyncio.gather(
|
||||
_pretokenize_all(),
|
||||
asyncio.to_thread(build_vlm_image_cache, train_rollouts, processor),
|
||||
)
|
||||
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:
|
||||
await _pretokenize_all()
|
||||
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, mm_token_type_ids_mapping=mm_token_type_ids_mapping
|
||||
rollout,
|
||||
vlm_cache=vlm_cache,
|
||||
cache_key=rollout_idx,
|
||||
mm_token_type_ids_mapping=mm_token_type_ids_mapping,
|
||||
)
|
||||
|
||||
results = await asyncio.gather(
|
||||
@@ -586,14 +608,27 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"decode_len": rollout_decode_lens,
|
||||
"samples_per_rollout": rollout_samples_per_rollout,
|
||||
"num_turns": [len(rollout["trajectory"]) for rollout in train_rollouts],
|
||||
"generation_ms": [rollout["timing"]["generation_ms"] for rollout in train_rollouts],
|
||||
"scoring_ms": [rollout["timing"]["scoring_ms"] for rollout in train_rollouts],
|
||||
}
|
||||
)
|
||||
|
||||
# Separate DataFrames for env reward function metrics and filter flags to avoid column name collisions
|
||||
# Separate DataFrames for env reward function metrics, filter flags, and per-rollout timings
|
||||
# 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])
|
||||
timing_df = pd.DataFrame(
|
||||
[
|
||||
{
|
||||
"total": rollout["timing"]["total"],
|
||||
"setup": rollout["timing"]["setup"]["duration"],
|
||||
"generation": rollout["timing"]["generation"]["duration"],
|
||||
"model": rollout["timing"]["model"]["duration"],
|
||||
"env": rollout["timing"]["env"]["duration"],
|
||||
"scoring": rollout["timing"]["scoring"]["duration"],
|
||||
"overhead": rollout["timing"]["overhead"],
|
||||
}
|
||||
for rollout in train_rollouts
|
||||
]
|
||||
)
|
||||
|
||||
# Update progress metrics
|
||||
num_tokens = int(results_df.seq_len.sum())
|
||||
@@ -603,13 +638,13 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
def compute_solve_rates(df):
|
||||
"""Compute solve_none, solve_all, effective_batch_size for a set of rollouts."""
|
||||
reward_per_problem = df.groupby("example_id").reward.sum()
|
||||
reward_per_problem = df.groupby(["env_name", "example_id"]).reward.sum()
|
||||
solve_none = (reward_per_problem == 0).mean()
|
||||
solve_all = (reward_per_problem == config.rollouts_per_example).mean()
|
||||
return solve_none, solve_all, 1 - solve_none - solve_all
|
||||
|
||||
# Group by example_id to average across rollouts within each problem
|
||||
by_example = results_df.groupby("example_id")
|
||||
# Group by (env_name, example_id) to average across rollouts within each problem
|
||||
by_example = results_df.groupby(["env_name", "example_id"])
|
||||
|
||||
solve_none, solve_all, effective_batch_size = compute_solve_rates(results_df)
|
||||
to_log = {
|
||||
@@ -648,12 +683,14 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"num_turns/all/mean": by_example.num_turns.mean().mean(),
|
||||
"num_turns/all/max": by_example.num_turns.mean().max(),
|
||||
"num_turns/all/min": by_example.num_turns.mean().min(),
|
||||
"generation_ms/all/mean": by_example.generation_ms.mean().mean(),
|
||||
"generation_ms/all/max": by_example.generation_ms.mean().max(),
|
||||
"generation_ms/all/min": by_example.generation_ms.mean().min(),
|
||||
"scoring_ms/all/mean": by_example.scoring_ms.mean().mean(),
|
||||
"scoring_ms/all/max": by_example.scoring_ms.mean().max(),
|
||||
"scoring_ms/all/min": by_example.scoring_ms.mean().min(),
|
||||
**{
|
||||
f"timing/all/{key}/{stat}": getattr(
|
||||
timing_df[key].groupby([results_df.env_name, results_df.example_id]).mean(),
|
||||
stat,
|
||||
)()
|
||||
for key in timing_df.columns
|
||||
for stat in ("mean", "max", "min")
|
||||
},
|
||||
# Train reward
|
||||
"reward/all/mean": by_example.reward.mean().mean(),
|
||||
"reward/all/max": by_example.reward.mean().max(),
|
||||
@@ -690,8 +727,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"is_truncated",
|
||||
"samples_per_rollout",
|
||||
"num_turns",
|
||||
"generation_ms",
|
||||
"scoring_ms",
|
||||
]
|
||||
|
||||
for env, env_df in results_df.groupby("env_name"):
|
||||
@@ -701,6 +736,12 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
to_log[f"{col}/{env}/max"] = env_by_example[col].mean().max()
|
||||
if col != "is_truncated":
|
||||
to_log[f"{col}/{env}/min"] = env_by_example[col].mean().min()
|
||||
env_timing_df = timing_df.loc[env_df.index]
|
||||
for key in timing_df.columns:
|
||||
per_example = env_timing_df.groupby(env_df["example_id"])[key].mean()
|
||||
to_log[f"timing/{env}/{key}/mean"] = per_example.mean()
|
||||
to_log[f"timing/{env}/{key}/max"] = per_example.max()
|
||||
to_log[f"timing/{env}/{key}/min"] = per_example.min()
|
||||
to_log[f"reward/{env}/mean"] = env_by_example.reward.mean().mean()
|
||||
to_log[f"reward/{env}/max"] = env_by_example.reward.mean().max()
|
||||
to_log[f"reward/{env}/min"] = env_by_example.reward.mean().min()
|
||||
@@ -785,8 +826,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
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()
|
||||
|
||||
# Write final checkpoint
|
||||
@@ -846,5 +885,74 @@ def main():
|
||||
asyncio.run(orchestrate(cli(OrchestratorConfig)))
|
||||
|
||||
|
||||
async def setup_rollout_inference_pool(
|
||||
*,
|
||||
config: OrchestratorConfig,
|
||||
rollout_client_config,
|
||||
rollout_model_name: str,
|
||||
tokenizer,
|
||||
logger,
|
||||
):
|
||||
"""Set up rollout inference.
|
||||
|
||||
Routing policy is driven by ``config.use_token_client`` and
|
||||
``config.use_renderer`` (mutually exclusive — config-level validators
|
||||
block both being True):
|
||||
|
||||
- external teacher rollout → MITO (``openai_chat_completions``),
|
||||
forced regardless of the toggles (config-level validator
|
||||
rejects ``use_token_client`` / ``use_renderer`` in that case)
|
||||
- ``use_renderer=True`` → renderer client (``/v1/generate``).
|
||||
Not allowed for VLMs (validated at config time).
|
||||
- ``use_token_client=True`` → TITO
|
||||
(``openai_chat_completions_token``, ``/v1/chat/completions/tokens``).
|
||||
Default. VLMs land here too.
|
||||
- both False → MITO (``openai_chat_completions``).
|
||||
"""
|
||||
if config.teacher_rollout_model is not None:
|
||||
logger.info("Using external rollout model (MITO) without renderer client")
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
train_client_type="openai_chat_completions",
|
||||
eval_client_type="openai_chat_completions",
|
||||
)
|
||||
return None, inference_pool
|
||||
|
||||
if config.use_renderer:
|
||||
renderer = create_renderer(
|
||||
tokenizer,
|
||||
renderer=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
)
|
||||
logger.info(f"Initialized {type(renderer).__name__} for {config.model.name}")
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_name=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
renderer_pool_size=config.renderer.pool_size,
|
||||
)
|
||||
logger.info("Using direct renderer rollout client")
|
||||
return renderer, inference_pool
|
||||
|
||||
train_client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
|
||||
if config.use_token_client:
|
||||
logger.info("Using token client (TITO) for rollouts — server-side templating, /v1/chat/completions/tokens")
|
||||
else:
|
||||
logger.info("Using MITO (openai_chat_completions) for rollouts")
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type="openai_chat_completions",
|
||||
)
|
||||
return None, inference_pool
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -148,7 +148,10 @@ class Scheduler:
|
||||
|
||||
@staticmethod
|
||||
def _client_identity(c: vf.ClientConfig) -> tuple[str, str | None]:
|
||||
return (c.api_base_url, c.extra_headers.get("X-data-parallel-rank"))
|
||||
return (
|
||||
c.api_base_url,
|
||||
c.extra_headers.get("X-data-parallel-rank"),
|
||||
)
|
||||
|
||||
async def _select_least_loaded_client(self) -> vf.ClientConfig:
|
||||
"""Select the client with the fewest in-flight tasks.
|
||||
|
||||
@@ -199,12 +199,32 @@ def _convert_tools_to_oai_format(tool_defs: list) -> list[dict[str, Any]] | None
|
||||
]
|
||||
|
||||
|
||||
def _tokenize_step_with_renderer(
|
||||
step: vf.TrajectoryStep,
|
||||
renderer,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Tokenize a trajectory step using a Renderer."""
|
||||
from renderers.base import build_trajectory_step
|
||||
|
||||
prompt = _normalize_messages(step.get("prompt"), default_role="user")
|
||||
completion = _normalize_messages(step.get("completion"), default_role="assistant")
|
||||
prompt = _strip_message_content(_deserialize_tool_calls(prompt))
|
||||
completion = _strip_message_content(_deserialize_tool_calls(completion))
|
||||
return build_trajectory_step(renderer, prompt, completion, tools=tools)
|
||||
|
||||
|
||||
def pretokenize_rollout_trajectory(
|
||||
output: vf.RolloutOutput,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
processor=None,
|
||||
renderer=None,
|
||||
) -> bool:
|
||||
"""Populate missing step tokens from prompt/completion messages."""
|
||||
"""Populate missing step tokens from prompt/completion messages.
|
||||
|
||||
When a renderer is provided, uses it for tokenization (faster, deterministic).
|
||||
Otherwise falls back to the tokenizer + apply_chat_template path.
|
||||
"""
|
||||
logger = get_logger()
|
||||
tools = _convert_tools_to_oai_format(output.get("tool_defs", []))
|
||||
|
||||
@@ -212,17 +232,19 @@ def pretokenize_rollout_trajectory(
|
||||
if step["tokens"] is not None:
|
||||
continue
|
||||
|
||||
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools, processor=processor)
|
||||
if reconstructed["prompt_prefix_len"] < reconstructed["original_prompt_len"]:
|
||||
logger.debug(
|
||||
f"Prompt tokenization was non-prefix for example {output['example_id']} step {step_idx}. "
|
||||
f"Using longest common prefix length {reconstructed['prompt_prefix_len']} "
|
||||
f"(original prompt had {reconstructed['original_prompt_len']} tokens)."
|
||||
)
|
||||
|
||||
reconstructed.pop("prompt_prefix_len")
|
||||
reconstructed.pop("original_prompt_len")
|
||||
step["tokens"] = reconstructed
|
||||
if renderer is not None:
|
||||
step["tokens"] = _tokenize_step_with_renderer(step, renderer, tools=tools)
|
||||
else:
|
||||
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools, processor=processor)
|
||||
if reconstructed["prompt_prefix_len"] < reconstructed["original_prompt_len"]:
|
||||
logger.debug(
|
||||
f"Prompt tokenization was non-prefix for example {output['example_id']} step {step_idx}. "
|
||||
f"Using longest common prefix length {reconstructed['prompt_prefix_len']} "
|
||||
f"(original prompt had {reconstructed['original_prompt_len']} tokens)."
|
||||
)
|
||||
reconstructed.pop("prompt_prefix_len")
|
||||
reconstructed.pop("original_prompt_len")
|
||||
step["tokens"] = reconstructed
|
||||
|
||||
return True
|
||||
|
||||
@@ -384,7 +406,11 @@ def interleave_rollout(
|
||||
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
active_samples.append((new_prefix, make_sample(tokens), step_idx))
|
||||
|
||||
# Attach images once per sample using only the last merged step
|
||||
# Attach images once per sample using only the last merged step. Prompt
|
||||
# tokens already contain fully expanded <|image_pad|> placeholders because
|
||||
# VLMs go through MITO (chat completions), which runs apply_chat_template
|
||||
# server-side; the orchestrator re-tokenizes via the same processor in the
|
||||
# fallback path so features and tokens stay 1:1.
|
||||
if vlm_cache is not None:
|
||||
key = output["example_id"] if cache_key is None else cache_key
|
||||
for _, sample, last_step_idx in active_samples:
|
||||
@@ -797,7 +823,7 @@ def build_vlm_image_cache(rollouts: list[vf.RolloutOutput], processor) -> VLMIma
|
||||
Caches per rollout to keep images aligned with divergent multi-turn trajectories.
|
||||
"""
|
||||
examples = [(idx, rollout) for idx, rollout in enumerate(rollouts)]
|
||||
unique_example_ids = {rollout["example_id"] for rollout in rollouts}
|
||||
unique_example_ids = {(rollout.get("env_name"), rollout["example_id"]) for rollout in rollouts}
|
||||
|
||||
# Extract images (also strips base64 data from rollout prompts to free memory)
|
||||
extract_start = time.perf_counter()
|
||||
|
||||
@@ -7,7 +7,6 @@ from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
import verifiers as vf
|
||||
from openai.types.chat.chat_completion import ChatCompletion
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from verifiers.utils.client_utils import setup_openai_client
|
||||
@@ -85,28 +84,24 @@ async def compute_teacher_logprobs(
|
||||
samples: list[TrainingSample],
|
||||
) -> list[list[float]]:
|
||||
"""Compute teacher model logprobs for a batch of training samples via prefill."""
|
||||
from prime_rl.inference.vllm.serving_generate import GenerateResponse
|
||||
|
||||
async def _compute_single(client_config: vf.ClientConfig, sample: TrainingSample) -> list[float]:
|
||||
client = setup_openai_client(client_config)
|
||||
|
||||
response = await client.post(
|
||||
"/chat/completions/tokens",
|
||||
"/generate",
|
||||
cast_to=GenerateResponse,
|
||||
body={
|
||||
"model": model_name,
|
||||
"messages": [{"role": "user", "content": ""}],
|
||||
"tokens": sample.prompt_ids + sample.completion_ids,
|
||||
"prompt_token_ids": sample.prompt_ids + sample.completion_ids,
|
||||
"max_tokens": 1,
|
||||
"temperature": 1.0,
|
||||
"top_p": 1.0,
|
||||
"skip_special_tokens": False,
|
||||
"prompt_logprobs": True,
|
||||
},
|
||||
cast_to=ChatCompletion,
|
||||
)
|
||||
return [
|
||||
0.0 if lp is None else float(next(iter(lp.values()))["logprob"])
|
||||
for lp in getattr(response, "prompt_logprobs", [])
|
||||
]
|
||||
return [0.0 if lp is None else float(lp) for lp in response.prompt_logprobs or []]
|
||||
|
||||
return await asyncio.gather(*[_compute_single(client, sample) for client, sample in zip(cycle(clients), samples)])
|
||||
|
||||
|
||||
@@ -59,6 +59,11 @@ def get_model_completion_len(output: vf.RolloutOutput) -> int:
|
||||
return sum(len(step["tokens"]["completion_ids"]) for step in output["trajectory"] if step.get("tokens"))
|
||||
|
||||
|
||||
def get_num_turns(output: vf.RolloutOutput) -> int:
|
||||
"""Number of turns (trajectory steps) in a rollout."""
|
||||
return len(output["trajectory"])
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@@ -53,6 +53,7 @@ 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.sequence import get_cu_seqlens_from_position_ids
|
||||
from prime_rl.utils.utils import format_time
|
||||
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
|
||||
|
||||
@@ -275,9 +276,7 @@ def _patch_qwen3_5_linear_attn_varlen():
|
||||
pids = position_ids
|
||||
if pids.ndim == 3:
|
||||
pids = pids[0]
|
||||
flat = pids.view(-1)
|
||||
seqlens = torch.cat([flat[0:1], flat[:-1][(flat == 0)[1:]] + 1, flat[-1:] + 1])
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, _ = get_cu_seqlens_from_position_ids(pids)
|
||||
kwargs["cu_seqlens"] = cu_seqlens
|
||||
return _text_orig(
|
||||
self,
|
||||
@@ -1096,6 +1095,24 @@ def setup_model(
|
||||
return model
|
||||
|
||||
|
||||
def _get_qwen3_vl_mm_token_type_ids(model: nn.Module, input_ids: Tensor) -> Tensor | None:
|
||||
config = getattr(model, "config", None)
|
||||
if getattr(config, "model_type", None) != "qwen3_vl":
|
||||
return None
|
||||
|
||||
mm_token_type_ids = torch.zeros_like(input_ids)
|
||||
|
||||
image_token_id = getattr(config, "image_token_id", None)
|
||||
if image_token_id is not None:
|
||||
mm_token_type_ids = mm_token_type_ids.masked_fill(input_ids == image_token_id, 1)
|
||||
|
||||
video_token_id = getattr(config, "video_token_id", None)
|
||||
if video_token_id is not None:
|
||||
mm_token_type_ids = mm_token_type_ids.masked_fill(input_ids == video_token_id, 2)
|
||||
|
||||
return mm_token_type_ids
|
||||
|
||||
|
||||
@jaxtyped(typechecker=typechecker)
|
||||
def forward(
|
||||
model: nn.Module,
|
||||
@@ -1122,7 +1139,9 @@ 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
|
||||
mm_token_type_ids = _get_qwen3_vl_mm_token_type_ids(model, input_ids)
|
||||
if mm_token_type_ids is not None:
|
||||
kwargs["mm_token_type_ids"] = mm_token_type_ids
|
||||
else:
|
||||
kwargs["position_ids"] = position_ids
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ from prime_rl.trainer.models.layers.rotary_emb import (
|
||||
RotaryEmbeddingConfig,
|
||||
apply_rotary_pos_emb,
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
try:
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
@@ -489,16 +490,7 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
use_flash = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
|
||||
|
||||
if use_flash:
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
causal_mask_mapping = None
|
||||
else:
|
||||
|
||||
@@ -39,6 +39,7 @@ from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
@@ -215,16 +216,7 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -27,7 +27,6 @@ from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.utils.cp import gather_for_cp, shard_for_cp
|
||||
|
||||
|
||||
def _sparse_mla_attention_args(config: GlmMoeDsaConfig) -> SparseMlaAttentionArgs:
|
||||
@@ -86,22 +85,7 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
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") and hasattr(self, "_cp_rank") and hasattr(self, "_cp_world_size")
|
||||
|
||||
def shard_to_cp(self, t: torch.Tensor) -> torch.Tensor:
|
||||
if not self.cp_enabled:
|
||||
return t
|
||||
|
||||
return shard_for_cp(t, self._cp_rank, self._cp_world_size)
|
||||
|
||||
def gather_for_cp(self, t: torch.Tensor) -> torch.Tensor:
|
||||
if not self.cp_enabled:
|
||||
return t
|
||||
|
||||
return gather_for_cp(t, self._cp_group)
|
||||
self.self_attn.set_context_parallel_attributes(cp_group, cp_rank, cp_world_size)
|
||||
|
||||
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
||||
def forward(
|
||||
@@ -114,14 +98,12 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states = self.gather_for_cp(hidden_states)
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
ks=ks,
|
||||
ke=ke,
|
||||
)
|
||||
hidden_states = self.shard_to_cp(hidden_states)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
residual = hidden_states
|
||||
@@ -246,19 +228,32 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
cp_group, _, cp_world_size = self._context_parallel_state()
|
||||
cp_group, cp_rank, cp_world_size = self._context_parallel_state()
|
||||
if cp_group is not None and cp_world_size > 1:
|
||||
position_ids_for_attn = self._gather_position_ids_for_cp(position_ids, cp_group, cp_world_size)
|
||||
position_ids_full = self._gather_position_ids_for_cp(position_ids, cp_group, cp_world_size)
|
||||
else:
|
||||
position_ids_for_attn = position_ids
|
||||
position_ids_full = position_ids
|
||||
|
||||
flat_position_ids = position_ids_for_attn.view(-1)
|
||||
S = flat_position_ids.shape[0]
|
||||
ks = torch.arange(S, dtype=torch.int32, device=flat_position_ids.device) - flat_position_ids.to(torch.int32)
|
||||
ke = torch.arange(1, S + 1, dtype=torch.int32, device=flat_position_ids.device)
|
||||
flat_position_ids = position_ids_full.view(-1)
|
||||
S_full = flat_position_ids.shape[0]
|
||||
ks_full = torch.arange(S_full, dtype=torch.int32, device=flat_position_ids.device) - flat_position_ids.to(
|
||||
torch.int32
|
||||
)
|
||||
ke_full = torch.arange(1, S_full + 1, dtype=torch.int32, device=flat_position_ids.device)
|
||||
|
||||
# Position embeddings are computed over the full sequence: K uses cos/sin[0:S_full]
|
||||
# while Q uses the local CP slice. ks/ke are computed in K's global coordinate
|
||||
# system and then sharded to the local Q range so the indexer's per-token
|
||||
# causal/varlen mask aligns with the gathered K.
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids_for_attn)
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids_full)
|
||||
|
||||
if cp_world_size > 1:
|
||||
s_local = S_full // cp_world_size
|
||||
ks = ks_full[cp_rank * s_local : (cp_rank + 1) * s_local].contiguous()
|
||||
ke = ke_full[cp_rank * s_local : (cp_rank + 1) * s_local].contiguous()
|
||||
else:
|
||||
ks, ke = ks_full, ke_full
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
|
||||
from prime_rl.trainer.models.layers.norms import LayerNorm, RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb_interleave
|
||||
from prime_rl.trainer.models.layers.rotary_emb import rotate_half
|
||||
from prime_rl.utils.cp import gather_for_cp
|
||||
|
||||
try:
|
||||
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_bwd
|
||||
@@ -49,6 +51,16 @@ class _SparseMLA(torch.autograd.Function):
|
||||
return dq, dkv, None, None
|
||||
|
||||
|
||||
def apply_rope_interleave_single(
|
||||
t: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
|
||||
) -> torch.Tensor:
|
||||
cos = cos.unsqueeze(unsqueeze_dim)
|
||||
sin = sin.unsqueeze(unsqueeze_dim)
|
||||
b, h, s, d = t.shape
|
||||
t = t.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
|
||||
return (t * cos) + (rotate_half(t) * sin)
|
||||
|
||||
|
||||
class Indexer(nn.Module):
|
||||
def __init__(self, args: SparseMlaAttentionArgs):
|
||||
super().__init__()
|
||||
@@ -64,37 +76,56 @@ class Indexer(nn.Module):
|
||||
@torch.no_grad()
|
||||
def compute_sparse_indices(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
q_latent: torch.Tensor,
|
||||
hidden_states_local: torch.Tensor,
|
||||
q_latent_local: torch.Tensor,
|
||||
ks: torch.Tensor,
|
||||
ke: torch.Tensor,
|
||||
index_topk: int,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
position_embeddings_full: tuple[torch.Tensor, torch.Tensor],
|
||||
cp_group: dist.ProcessGroup | None,
|
||||
cp_world_size: int,
|
||||
cp_rank: int,
|
||||
) -> torch.Tensor:
|
||||
total_tokens = hidden_states.shape[1]
|
||||
assert index_topk % 64 == 0, f"index_topk must be divisible by 64 (block_I), got {index_topk}"
|
||||
|
||||
q_idx = self.wq_b(q_latent[0]).view(total_tokens, self.n_head, self.head_dim)
|
||||
k_idx = self.k_norm(self.wk(hidden_states[0]))
|
||||
w = self.weights_proj(hidden_states[0])
|
||||
s_local = hidden_states_local.shape[1]
|
||||
|
||||
q_idx = self.wq_b(q_latent_local[0]).view(s_local, self.n_head, self.head_dim)
|
||||
k_idx_local = self.k_norm(self.wk(hidden_states_local[0]))
|
||||
w = self.weights_proj(hidden_states_local[0])
|
||||
|
||||
if cp_world_size > 1:
|
||||
k_idx = gather_for_cp(k_idx_local.unsqueeze(0), cp_group).squeeze(0)
|
||||
else:
|
||||
k_idx = k_idx_local
|
||||
|
||||
cos_full, sin_full = position_embeddings_full
|
||||
if cp_world_size > 1:
|
||||
cos_local = cos_full[:, cp_rank * s_local : (cp_rank + 1) * s_local, :]
|
||||
sin_local = sin_full[:, cp_rank * s_local : (cp_rank + 1) * s_local, :]
|
||||
else:
|
||||
cos_local, sin_local = cos_full, sin_full
|
||||
|
||||
q_pe = q_idx[..., : self.rope_dim]
|
||||
q_nope = q_idx[..., self.rope_dim :]
|
||||
k_pe = k_idx[..., : self.rope_dim]
|
||||
k_nope = k_idx[..., self.rope_dim :]
|
||||
|
||||
cos, sin = position_embeddings
|
||||
q_pe = q_pe.unsqueeze(0).transpose(1, 2)
|
||||
k_pe = k_pe.unsqueeze(0).unsqueeze(1)
|
||||
q_pe, k_pe = apply_rotary_pos_emb_interleave(q_pe, k_pe, cos, sin)
|
||||
q_pe = q_pe.unsqueeze(0).transpose(1, 2) # [1, H, S_local, rope_dim]
|
||||
q_pe = apply_rope_interleave_single(q_pe, cos_local, sin_local)
|
||||
q_pe = q_pe.transpose(1, 2).squeeze(0)
|
||||
|
||||
k_pe = k_pe.unsqueeze(0).unsqueeze(1) # [1, 1, S_full, rope_dim]
|
||||
k_pe = apply_rope_interleave_single(k_pe, cos_full, sin_full)
|
||||
k_pe = k_pe.squeeze(1).squeeze(0)
|
||||
|
||||
q_idx = torch.cat([q_pe, q_nope], dim=-1)
|
||||
k_idx = torch.cat([k_pe, k_nope], dim=-1)
|
||||
|
||||
indices = fp8_indexer(q_idx, k_idx, w, ks, ke, index_topk, self.weight_scale)
|
||||
return indices.view(1, total_tokens, 1, index_topk)
|
||||
# indices shape: [S_local, topk] in K's coordinate space (sentinel = s_full)
|
||||
# KV passed to sparse MLA has length s_full + 1 (sentinel zeros at index s_full).
|
||||
return indices.view(1, s_local, 1, index_topk)
|
||||
|
||||
|
||||
class GlmMoeDsaAttention(nn.Module):
|
||||
@@ -128,6 +159,19 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
self.indexer = Indexer(args)
|
||||
self.scaling = self.qk_head_dim ** (-0.5)
|
||||
|
||||
self._cp_group: dist.ProcessGroup | None = None
|
||||
self._cp_rank: int = 0
|
||||
self._cp_world_size: int = 1
|
||||
|
||||
def set_context_parallel_attributes(self, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
self._cp_group = cp_group
|
||||
self._cp_rank = cp_rank
|
||||
self._cp_world_size = cp_world_size
|
||||
|
||||
@property
|
||||
def cp_enabled(self) -> bool:
|
||||
return self._cp_world_size > 1
|
||||
|
||||
def attn_projections(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
|
||||
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
|
||||
@@ -136,21 +180,31 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
|
||||
def mla_up_proj(
|
||||
self,
|
||||
q_latent: torch.Tensor,
|
||||
k_compressed_normed: torch.Tensor,
|
||||
k_rope: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
q_latent_local: torch.Tensor,
|
||||
k_compressed_normed_full: torch.Tensor,
|
||||
k_rope_full: torch.Tensor,
|
||||
position_embeddings_full: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
batch_size, total_tokens, _ = q_latent.shape
|
||||
q_full = self.q_b_proj(q_latent).view(batch_size, total_tokens, self.num_heads, self.qk_head_dim)
|
||||
batch_size, s_local, _ = q_latent_local.shape
|
||||
s_full = k_compressed_normed_full.shape[1]
|
||||
|
||||
q_full = self.q_b_proj(q_latent_local).view(batch_size, s_local, self.num_heads, self.qk_head_dim)
|
||||
q_nope, q_rope = q_full.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
||||
|
||||
q_rope_r = q_rope.transpose(1, 2)
|
||||
k_rope_r = k_rope.unsqueeze(1)
|
||||
cos, sin = position_embeddings
|
||||
q_rope_r, k_rope_r = apply_rotary_pos_emb_interleave(q_rope_r, k_rope_r, cos, sin)
|
||||
cos_full, sin_full = position_embeddings_full
|
||||
if self.cp_enabled:
|
||||
cos_local = cos_full[:, self._cp_rank * s_local : (self._cp_rank + 1) * s_local, :]
|
||||
sin_local = sin_full[:, self._cp_rank * s_local : (self._cp_rank + 1) * s_local, :]
|
||||
else:
|
||||
cos_local, sin_local = cos_full, sin_full
|
||||
|
||||
q_rope_r = q_rope.transpose(1, 2) # [B, H, S_local, rope_dim]
|
||||
q_rope_r = apply_rope_interleave_single(q_rope_r, cos_local, sin_local)
|
||||
q_rope = q_rope_r.transpose(1, 2)
|
||||
k_rope = k_rope_r.squeeze(1)
|
||||
|
||||
k_rope_r = k_rope_full.unsqueeze(1) # [B, 1, S_full, rope_dim]
|
||||
k_rope_r = apply_rope_interleave_single(k_rope_r, cos_full, sin_full)
|
||||
k_rope_full = k_rope_r.squeeze(1)
|
||||
|
||||
kv_b_w = self.kv_b_proj.weight.view(self.num_heads, self.qk_nope_head_dim + self.v_head_dim, self.kv_lora_rank)
|
||||
w_k_nope = kv_b_w[:, : self.qk_nope_head_dim, :]
|
||||
@@ -158,10 +212,11 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
q_absorbed = torch.einsum("bshd,hdk->bshk", q_nope, w_k_nope)
|
||||
|
||||
sparse_q = torch.cat([q_absorbed, q_rope], dim=-1)
|
||||
sparse_kv = torch.cat([k_compressed_normed, k_rope], dim=-1).unsqueeze(2)
|
||||
sparse_kv = torch.cat([k_compressed_normed_full, k_rope_full], dim=-1).unsqueeze(2)
|
||||
|
||||
sentinel = torch.zeros(batch_size, 1, 1, sparse_kv.shape[-1], dtype=sparse_kv.dtype, device=sparse_kv.device)
|
||||
sparse_kv = torch.cat([sparse_kv, sentinel], dim=1)
|
||||
assert sparse_kv.shape[1] == s_full + 1
|
||||
return sparse_q, sparse_kv, w_v
|
||||
|
||||
def _mla_unabsorb(self, out: torch.Tensor, w_v: torch.Tensor) -> torch.Tensor:
|
||||
@@ -182,15 +237,27 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
q_latent, k_compressed_normed, k_rope = self.attn_projections(hidden_states)
|
||||
|
||||
if self.cp_enabled:
|
||||
k_compressed_normed = gather_for_cp(k_compressed_normed, self._cp_group)
|
||||
k_rope = gather_for_cp(k_rope, self._cp_group)
|
||||
|
||||
indices = self.indexer.compute_sparse_indices(
|
||||
hidden_states, q_latent, ks, ke, self.args.index_topk, position_embeddings
|
||||
hidden_states_local=hidden_states,
|
||||
q_latent_local=q_latent,
|
||||
ks=ks,
|
||||
ke=ke,
|
||||
index_topk=self.args.index_topk,
|
||||
position_embeddings_full=position_embeddings,
|
||||
cp_group=self._cp_group,
|
||||
cp_world_size=self._cp_world_size,
|
||||
cp_rank=self._cp_rank,
|
||||
)
|
||||
|
||||
sparse_q, sparse_kv, w_v = self.mla_up_proj(
|
||||
q_latent,
|
||||
k_compressed_normed,
|
||||
k_rope,
|
||||
position_embeddings=position_embeddings,
|
||||
q_latent_local=q_latent,
|
||||
k_compressed_normed_full=k_compressed_normed,
|
||||
k_rope_full=k_rope,
|
||||
position_embeddings_full=position_embeddings,
|
||||
)
|
||||
|
||||
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
|
||||
|
||||
@@ -97,7 +97,7 @@ def per_token_group_quant_fp8(
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=8, num_stages=3),
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=8, num_stages=3),
|
||||
],
|
||||
key=["S"],
|
||||
key=["S_Q", "S_K"],
|
||||
)
|
||||
@triton.jit
|
||||
def _triton_fp8_indexer_kernel(
|
||||
@@ -108,7 +108,8 @@ def _triton_fp8_indexer_kernel(
|
||||
Out,
|
||||
KS,
|
||||
KE,
|
||||
S,
|
||||
S_Q,
|
||||
S_K,
|
||||
stride_qh,
|
||||
stride_qs,
|
||||
stride_ks,
|
||||
@@ -125,15 +126,15 @@ def _triton_fp8_indexer_kernel(
|
||||
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
||||
offs_d = tl.arange(0, D)
|
||||
|
||||
mask_m = offs_m < S
|
||||
mask_n = offs_n < S
|
||||
mask_m = offs_m < S_Q
|
||||
mask_n = offs_n < S_K
|
||||
|
||||
ks_vals = tl.load(KS + offs_m, mask=mask_m, other=S)
|
||||
ks_vals = tl.load(KS + offs_m, mask=mask_m, other=S_K)
|
||||
ke_vals = tl.load(KE + offs_m, mask=mask_m, other=0)
|
||||
|
||||
offs_m_64 = offs_m.to(tl.int64)
|
||||
offs_n_64 = offs_n.to(tl.int64)
|
||||
out_ptrs = Out + offs_m_64[:, None] * S + offs_n_64[None, :]
|
||||
out_ptrs = Out + offs_m_64[:, None] * S_K + offs_n_64[None, :]
|
||||
out_mask = mask_m[:, None] & mask_n[None, :]
|
||||
|
||||
ks_min = tl.min(ks_vals)
|
||||
@@ -145,8 +146,8 @@ def _triton_fp8_indexer_kernel(
|
||||
return
|
||||
|
||||
# Clamp indices for FP8 loads (can't use mask+other with fp8 dtype)
|
||||
offs_n_safe = tl.minimum(offs_n, S - 1)
|
||||
offs_m_safe = tl.minimum(offs_m, S - 1)
|
||||
offs_n_safe = tl.minimum(offs_n, S_K - 1)
|
||||
offs_m_safe = tl.minimum(offs_m, S_Q - 1)
|
||||
|
||||
k_block = tl.load(K_fp8 + offs_n_safe[:, None] * stride_ks + offs_d[None, :])
|
||||
k_sc = tl.load(K_scales + offs_n_safe, mask=mask_n, other=0.0).to(tl.float32)
|
||||
@@ -171,38 +172,39 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
|
||||
"""Triton FP8 indexer: UE8M0 quantization + fused scoring kernel + topk.
|
||||
|
||||
Args:
|
||||
q: [S, H, D] bf16 query vectors per head
|
||||
k: [S, D] bf16 key vectors (shared across heads)
|
||||
w: [S, H] bf16 per-head weights
|
||||
ks: [S] int32 sequence start per token
|
||||
ke: [S] int32 causal end per token (= position + 1)
|
||||
q: [S_q, H, D] bf16 query vectors per head
|
||||
k: [S_k, D] bf16 key vectors (shared across heads)
|
||||
w: [S_q, H] bf16 per-head weights
|
||||
ks: [S_q] int32 sequence start per token (in K's coordinate system)
|
||||
ke: [S_q] int32 causal end per token (in K's coordinate system, = global position + 1)
|
||||
topk: number of top indices to return
|
||||
weight_scale: constant scaling factor for weights
|
||||
|
||||
Returns:
|
||||
[S, topk] int32 selected token indices per query
|
||||
[S_q, topk] int32 selected token indices per query (sentinel = S_k)
|
||||
"""
|
||||
# NOTE: We don't use weight scale in this kernel as it produces higher KL mismatch for some reason
|
||||
# This is not a problem result-wise, as it is a constant multiplier
|
||||
_weight_scale = weight_scale
|
||||
S, H, D = q.shape
|
||||
S_q, H, D = q.shape
|
||||
S_k = k.shape[0]
|
||||
device = q.device
|
||||
|
||||
q_flat = q.reshape(S * H, D).contiguous()
|
||||
q_flat = q.reshape(S_q * H, D).contiguous()
|
||||
q_fp8, q_scales = per_token_group_quant_fp8(q_flat, group_size=D, use_ue8m0=True)
|
||||
k_fp8, k_scales = per_token_group_quant_fp8(k.contiguous(), group_size=D, use_ue8m0=True)
|
||||
|
||||
q_fp8 = q_fp8.view(S, H, D).permute(1, 0, 2).contiguous()
|
||||
q_fp8 = q_fp8.view(S_q, H, D).permute(1, 0, 2).contiguous()
|
||||
|
||||
# Fold q_scale into weights
|
||||
q_scales = q_scales.view(S, H)
|
||||
q_scales = q_scales.view(S_q, H)
|
||||
w = w * q_scales
|
||||
|
||||
logits = torch.empty(S, S, dtype=torch.float32, device=device)
|
||||
logits = torch.empty(S_q, S_k, dtype=torch.float32, device=device)
|
||||
|
||||
grid = lambda meta: (
|
||||
triton.cdiv(S, meta["BLOCK_M"]),
|
||||
triton.cdiv(S, meta["BLOCK_N"]),
|
||||
triton.cdiv(S_q, meta["BLOCK_M"]),
|
||||
triton.cdiv(S_k, meta["BLOCK_N"]),
|
||||
)
|
||||
_triton_fp8_indexer_kernel[grid](
|
||||
q_fp8,
|
||||
@@ -212,7 +214,8 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
|
||||
logits,
|
||||
ks,
|
||||
ke,
|
||||
S,
|
||||
S_q,
|
||||
S_k,
|
||||
q_fp8.stride(0),
|
||||
q_fp8.stride(1),
|
||||
k_fp8.stride(0),
|
||||
@@ -221,16 +224,16 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
|
||||
D=D,
|
||||
)
|
||||
|
||||
actual_topk = min(topk, S)
|
||||
actual_topk = min(topk, S_k)
|
||||
_, indices = torch.topk(logits, actual_topk, dim=-1)
|
||||
if actual_topk < topk:
|
||||
padding = torch.full((S, topk - actual_topk), S, dtype=indices.dtype, device=device)
|
||||
padding = torch.full((S_q, topk - actual_topk), S_k, dtype=indices.dtype, device=device)
|
||||
indices = torch.cat([indices, padding], dim=-1)
|
||||
|
||||
# Replace cross-sequence indices with sentinel S (maps to zero-valued KV)
|
||||
# Replace cross-sequence indices with sentinel S_k (maps to zero-valued KV)
|
||||
ks_exp = ks.unsqueeze(1).expand_as(indices)
|
||||
ke_exp = ke.unsqueeze(1).expand_as(indices)
|
||||
out_of_range = (indices < ks_exp) | (indices >= ke_exp)
|
||||
indices = indices.masked_fill(out_of_range, S)
|
||||
indices = indices.masked_fill(out_of_range, S_k)
|
||||
|
||||
return indices.to(torch.int32)
|
||||
|
||||
@@ -161,7 +161,10 @@ def bwd(
|
||||
acc_dkv_shared = T.alloc_shared([BS // split_store, D], accum_dtype)
|
||||
acc_dkv_tail_shared = T.alloc_shared([BS // split_store, D_tail], accum_dtype)
|
||||
|
||||
max_kv_i = s_i
|
||||
# See sparse_mla_fwd: sentinel is at index S_kv - 1 (zero KV), valid indices
|
||||
# live in [0, S_kv - 1). Using this single bound makes the kernel work for
|
||||
# both full and CP-sharded Q without needing a global Q offset.
|
||||
max_kv_i = S_kv - 2
|
||||
|
||||
T.copy(Q[by, s_i, bz * block_H : (bz + 1) * block_H, :D], Q_shared)
|
||||
T.copy(Q[by, s_i, bz * block_H : (bz + 1) * block_H, D:], Q_tail_shared)
|
||||
|
||||
@@ -104,8 +104,12 @@ def sparse_mla_fwd(
|
||||
|
||||
b_i, g_i = by, bz
|
||||
s_i = bx if REPLICATE_H == 1 else (bx // REPLICATE_H)
|
||||
q_i = s_i
|
||||
max_kv_i = q_i
|
||||
# The indexer pre-filters indices using per-token `ke` and replaces out-of-range
|
||||
# entries with the sentinel value `seq_len_kv - 1` (the last KV slot is a
|
||||
# zero sentinel; valid K indices live in [0, seq_len_kv - 1)). This single
|
||||
# bound preserves causality + varlen masking for both full and CP-sharded Q
|
||||
# (where local q_i no longer matches the global K position).
|
||||
max_kv_i = seq_len_kv - 2
|
||||
|
||||
H0 = g_i * padded_H + (0 if REPLICATE_H == 1 else (bx % REPLICATE_H) * 64)
|
||||
H1 = H0 + H_per_block
|
||||
|
||||
@@ -40,6 +40,7 @@ from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
@@ -188,16 +189,7 @@ class LlamaModel(LlamaPreTrainedModel):
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -22,6 +22,7 @@ from prime_rl.trainer.models.minimax_m2.converting_minimax_m2 import (
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
@@ -176,16 +177,7 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -30,6 +30,7 @@ from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import (
|
||||
convert_prime_layer_to_hf,
|
||||
convert_prime_to_hf,
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
@@ -505,16 +506,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
|
||||
# Compute cu_seqlens and max_seqlen for flash attention
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -18,6 +18,7 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig, apply_rotary_pos_emb
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
from .configuration_qwen3_5_moe import Qwen3_5MoeConfig
|
||||
from .converting_qwen3_5_moe import (
|
||||
@@ -480,11 +481,19 @@ class Qwen3_5MoeGatedFlashAttention(Qwen3_5MoeGatedAttentionBase):
|
||||
self._flash_attn_call = torch._dynamo.disable(self.func)
|
||||
|
||||
def _compute_attention(self, q, k, v, cu_seqlens, max_seqlen):
|
||||
args = [q, k, v, cu_seqlens, cu_seqlens]
|
||||
if self._flash_attn_version != 4:
|
||||
args.extend([max_seqlen, max_seqlen])
|
||||
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
|
||||
kwargs: dict = {"causal": True}
|
||||
out = self._flash_attn_call(*args, **kwargs)
|
||||
sliding_window = getattr(self, "sliding_window", None)
|
||||
if sliding_window is not None:
|
||||
kwargs["window_size"] = (sliding_window - 1, 0)
|
||||
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
|
||||
@@ -755,16 +764,7 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -40,6 +40,7 @@ from prime_rl.trainer.models.qwen3_moe.converting_qwen3_moe import (
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
@@ -216,16 +217,7 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -12,16 +12,22 @@ from prime_rl.utils.logger import get_logger
|
||||
|
||||
class PerfCounter:
|
||||
"""
|
||||
A class to count throughput (tokens/s) with a rolling window to obtain
|
||||
precise throughput and MFU estimates.
|
||||
Computes throughput (tokens/s) and MFU.
|
||||
|
||||
Inspired from https://github.com/pytorch/torchtitan/blob/4b3f2e41a084bf79a8540068ed525539d1244edd/torchtitan/utils.py#L119
|
||||
Two modes:
|
||||
- Sliding window over full-step wall time: `count_tokens(tokens)` each step,
|
||||
read smoothed values via `get_tokens_per_second()` / `get_mfu()`.
|
||||
Time is measured between successive `count_tokens` calls (full step).
|
||||
- Single point on a caller-provided duration: `get_step_tokens_per_second(tokens, fwd_bwd_time)`
|
||||
/ `get_step_mfu(tokens, fwd_bwd_time)`. No smoothing.
|
||||
|
||||
Sliding window inspired by https://github.com/pytorch/torchtitan/blob/4b3f2e41a084bf79a8540068ed525539d1244edd/torchtitan/utils.py#L119
|
||||
"""
|
||||
|
||||
def __init__(self, model: nn.Module, seq_len: int, window_size: int):
|
||||
def __init__(self, model: nn.Module, seq_len: int, window_size: int = 10):
|
||||
self.window_size = window_size
|
||||
self.tokens = []
|
||||
self.times = []
|
||||
self.tokens: list[int] = []
|
||||
self.times: list[float] = []
|
||||
self.model = model
|
||||
|
||||
self._world = get_world()
|
||||
@@ -36,7 +42,8 @@ class PerfCounter:
|
||||
self.num_params = self._get_num_params(model, exclude_embedding=not model.config.tie_word_embeddings)
|
||||
self.num_flop_per_token = self._get_num_flop_per_token(model.config, seq_len=seq_len)
|
||||
|
||||
def count_tokens(self, tokens: int):
|
||||
def count_tokens(self, tokens: int) -> None:
|
||||
"""Push a step into the sliding window. Time is recorded internally."""
|
||||
self.tokens.append(tokens)
|
||||
self.times.append(time.perf_counter())
|
||||
if len(self.tokens) > self.window_size:
|
||||
@@ -52,6 +59,16 @@ class PerfCounter:
|
||||
tokens_per_second = self.get_tokens_per_second()
|
||||
if tokens_per_second is None:
|
||||
return None
|
||||
return self._mfu_from_tps(tokens_per_second)
|
||||
|
||||
def get_step_tokens_per_second(self, tokens: int, fwd_bwd_time: float) -> float:
|
||||
"""Single-step throughput from a caller-provided duration."""
|
||||
return tokens / fwd_bwd_time
|
||||
|
||||
def get_step_mfu(self, tokens: int, fwd_bwd_time: float) -> float:
|
||||
return self._mfu_from_tps(self.get_step_tokens_per_second(tokens, fwd_bwd_time))
|
||||
|
||||
def _mfu_from_tps(self, tokens_per_second: float) -> float:
|
||||
return 100 * self.num_flop_per_token * tokens_per_second / self.gpu_peak_flops / self._world.world_size
|
||||
|
||||
def _get_peak_flops(self, device_name: str) -> float:
|
||||
|
||||
@@ -512,9 +512,8 @@ def train(config: TrainerConfig):
|
||||
progress.total_tokens += num_tokens
|
||||
progress.total_samples += batch_size
|
||||
perf_counter = get_perf_counter(model, seq_len)
|
||||
perf_counter.count_tokens(num_tokens)
|
||||
throughput = perf_counter.get_tokens_per_second() or 0
|
||||
mfu = perf_counter.get_mfu() or 0
|
||||
throughput = perf_counter.get_step_tokens_per_second(num_tokens, forward_backward_time)
|
||||
mfu = perf_counter.get_step_mfu(num_tokens, forward_backward_time)
|
||||
peak_memory = torch.cuda.max_memory_reserved() / 1024**3 # GiB
|
||||
|
||||
# Log step metrics
|
||||
|
||||
@@ -64,8 +64,21 @@ class StaticInferencePool:
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
):
|
||||
self._train_clients = setup_clients(client_config, client_type=train_client_type)
|
||||
renderer_model_name = model_name if train_client_type == "renderer" else None
|
||||
self._train_clients = setup_clients(
|
||||
client_config,
|
||||
client_type=train_client_type,
|
||||
renderer_name=renderer_name,
|
||||
renderer_model_name=renderer_model_name,
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
)
|
||||
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
|
||||
@@ -112,6 +125,10 @@ async def setup_inference_pool(
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
) -> InferencePool:
|
||||
"""Create an inference pool from config (static or elastic)."""
|
||||
logger = get_logger()
|
||||
@@ -127,7 +144,14 @@ async def setup_inference_pool(
|
||||
from prime_rl.utils.elastic import ElasticInferencePool
|
||||
|
||||
return await ElasticInferencePool.from_config(
|
||||
client_config, model_name=model_name, train_client_type=train_client_type, eval_client_type=eval_client_type
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type=eval_client_type,
|
||||
renderer_name=renderer_name,
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
@@ -136,11 +160,26 @@ async def setup_inference_pool(
|
||||
f"api_key_var={client_config.api_key_var}, headers={client_config.headers})"
|
||||
)
|
||||
return StaticInferencePool(
|
||||
client_config, model_name=model_name, train_client_type=train_client_type, eval_client_type=eval_client_type
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type=eval_client_type,
|
||||
renderer_name=renderer_name,
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
)
|
||||
|
||||
|
||||
def setup_clients(client_config: ClientConfig, client_type: str = "openai_chat_completions") -> list[vf.ClientConfig]:
|
||||
def setup_clients(
|
||||
client_config: ClientConfig,
|
||||
client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
renderer_model_name: str | None = None,
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
) -> list[vf.ClientConfig]:
|
||||
clients = []
|
||||
client_idx = 0
|
||||
for base_url in client_config.base_url:
|
||||
@@ -152,6 +191,11 @@ def setup_clients(client_config: ClientConfig, client_type: str = "openai_chat_c
|
||||
vf.ClientConfig(
|
||||
client_idx=client_idx,
|
||||
client_type=client_type,
|
||||
renderer=renderer_name,
|
||||
renderer_model_name=renderer_model_name,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
api_base_url=base_url,
|
||||
api_key_var=client_config.api_key_var,
|
||||
timeout=client_config.timeout,
|
||||
|
||||
@@ -6,6 +6,8 @@ import torch.distributed.nn as dist_nn
|
||||
import torch.nn as nn
|
||||
from ring_flash_attn import update_ring_flash_attn_params
|
||||
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
def setup_hybrid_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
"""Configure DeltaNet modules in Qwen3.5 hybrid models for native fla CP."""
|
||||
@@ -139,15 +141,7 @@ def get_padding_logit_from_prev_cp_rank(
|
||||
|
||||
|
||||
def _get_cu_seqlens_for_cp(position_ids: torch.Tensor) -> torch.Tensor:
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, _ = get_cu_seqlens_from_position_ids(position_ids)
|
||||
return cu_seqlens
|
||||
|
||||
|
||||
|
||||
@@ -106,16 +106,25 @@ class ElasticInferencePool:
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.client_config = client_config
|
||||
self.model_name = model_name
|
||||
self.base_model_name = model_name # Keep original for health checks
|
||||
self.renderer_model_name = model_name if train_client_type == "renderer" else None
|
||||
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.renderer_name = renderer_name
|
||||
self.tool_parser = tool_parser
|
||||
self.reasoning_parser = reasoning_parser
|
||||
self.renderer_pool_size = renderer_pool_size
|
||||
self.router_url = client_config.router_url
|
||||
|
||||
self._servers: dict[str, ServerState] = {}
|
||||
@@ -139,11 +148,22 @@ class ElasticInferencePool:
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
) -> ElasticInferencePool:
|
||||
if client_config.elastic is None:
|
||||
raise ValueError("Elastic inference pool requires elastic config")
|
||||
pool = cls(
|
||||
client_config, model_name=model_name, train_client_type=train_client_type, eval_client_type=eval_client_type
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type=eval_client_type,
|
||||
renderer_name=renderer_name,
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
)
|
||||
await pool.start()
|
||||
return pool
|
||||
@@ -185,7 +205,19 @@ class ElasticInferencePool:
|
||||
dp_rank_count=self.client_config.dp_rank_count,
|
||||
extra_headers_from_state=self.client_config.extra_headers_from_state,
|
||||
)
|
||||
self._train_clients = setup_clients(url_config, client_type=self.train_client_type) if urls else []
|
||||
self._train_clients = (
|
||||
setup_clients(
|
||||
url_config,
|
||||
client_type=self.train_client_type,
|
||||
renderer_name=self.renderer_name,
|
||||
renderer_model_name=self.renderer_model_name,
|
||||
tool_parser=self.tool_parser,
|
||||
reasoning_parser=self.reasoning_parser,
|
||||
renderer_pool_size=self.renderer_pool_size,
|
||||
)
|
||||
if urls
|
||||
else []
|
||||
)
|
||||
self._eval_clients = setup_clients(url_config, client_type=self.eval_client_type) if urls else []
|
||||
|
||||
@property
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Message utilities — normalize, deserialize tool calls, strip content."""
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
|
||||
def normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
|
||||
if messages is None:
|
||||
return []
|
||||
if isinstance(messages, str):
|
||||
return [{"role": default_role, "content": messages}]
|
||||
if isinstance(messages, dict):
|
||||
return [dict(messages)]
|
||||
if isinstance(messages, list):
|
||||
normalized: list[dict[str, Any]] = []
|
||||
for message in messages:
|
||||
if isinstance(message, str):
|
||||
normalized.append({"role": default_role, "content": message})
|
||||
elif isinstance(message, dict):
|
||||
normalized.append(dict(message))
|
||||
else:
|
||||
raise TypeError(f"Unsupported message type: {type(message)}")
|
||||
return normalized
|
||||
raise TypeError(f"Unsupported messages container type: {type(messages)}")
|
||||
|
||||
|
||||
def deserialize_tool_calls(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
def _deserialize_tool_call(tool_call: dict[str, Any]) -> dict[str, Any]:
|
||||
function = tool_call.get("function", {})
|
||||
arguments = function.get("arguments")
|
||||
if isinstance(arguments, str):
|
||||
arguments = json.loads(arguments)
|
||||
return {
|
||||
**tool_call,
|
||||
"function": {**function, "arguments": arguments},
|
||||
}
|
||||
|
||||
deserialized_messages: list[dict[str, Any]] = []
|
||||
for message in messages:
|
||||
if "tool_calls" not in message:
|
||||
deserialized_messages.append(dict(message))
|
||||
continue
|
||||
|
||||
tool_calls = message.get("tool_calls") or []
|
||||
deserialized_messages.append(
|
||||
{
|
||||
**message,
|
||||
"tool_calls": [_deserialize_tool_call(tc) for tc in tool_calls],
|
||||
}
|
||||
)
|
||||
|
||||
return deserialized_messages
|
||||
|
||||
|
||||
def strip_message_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
def _strip(message: dict[str, Any]) -> dict[str, Any]:
|
||||
content = message.get("content")
|
||||
if isinstance(content, str):
|
||||
return {**message, "content": content.strip()}
|
||||
return message
|
||||
|
||||
return [_strip(message) for message in messages]
|
||||
@@ -37,11 +37,16 @@ def setup_monitor(
|
||||
run_config: BaseConfig | None = None,
|
||||
*,
|
||||
prime_config: PrimeMonitorConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
# Backward compatibility: support old 'config' keyword argument
|
||||
config: WandbWithExtrasConfig | None = None,
|
||||
) -> Monitor:
|
||||
"""
|
||||
Sets up monitors to log metrics.
|
||||
|
||||
`keep_full_history`: when False, monitors retain only the most recent
|
||||
metrics dict. The orchestrator passes False outside `--bench` mode to
|
||||
avoid an unbounded list growing for the lifetime of the run.
|
||||
"""
|
||||
global _MONITOR
|
||||
if _MONITOR is not None:
|
||||
@@ -59,6 +64,7 @@ def setup_monitor(
|
||||
output_dir=output_dir,
|
||||
tokenizer=tokenizer,
|
||||
run_config=run_config,
|
||||
keep_full_history=keep_full_history,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -69,11 +75,12 @@ def setup_monitor(
|
||||
output_dir=output_dir,
|
||||
tokenizer=tokenizer,
|
||||
run_config=run_config,
|
||||
keep_full_history=keep_full_history,
|
||||
)
|
||||
)
|
||||
|
||||
if len(monitors) == 0:
|
||||
_MONITOR = NoOpMonitor()
|
||||
_MONITOR = NoOpMonitor(keep_full_history=keep_full_history)
|
||||
elif len(monitors) == 1:
|
||||
_MONITOR = monitors[0]
|
||||
else:
|
||||
|
||||
@@ -46,10 +46,6 @@ class Monitor(ABC):
|
||||
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def log_final_samples(self) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def save_final_summary(self, filename: str = "final_summary.json") -> None:
|
||||
pass
|
||||
@@ -66,11 +62,15 @@ class Monitor(ABC):
|
||||
class NoOpMonitor(Monitor):
|
||||
"""Monitor that does nothing. Used when no monitors are configured."""
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, keep_full_history: bool = True):
|
||||
self.history: list[dict[str, Any]] = []
|
||||
self._keep_full_history = keep_full_history
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
self.history.append(metrics)
|
||||
if self._keep_full_history:
|
||||
self.history.append(metrics)
|
||||
else:
|
||||
self.history = [metrics]
|
||||
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
pass
|
||||
@@ -78,9 +78,6 @@ class NoOpMonitor(Monitor):
|
||||
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
|
||||
pass
|
||||
|
||||
def log_final_samples(self) -> None:
|
||||
pass
|
||||
|
||||
def save_final_summary(self, filename: str = "final_summary.json") -> None:
|
||||
pass
|
||||
|
||||
|
||||
@@ -40,13 +40,6 @@ class MultiMonitor(Monitor):
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to log eval samples to {monitor.__class__.__name__}: {e}")
|
||||
|
||||
def log_final_samples(self) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
monitor.log_final_samples()
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to log final samples to {monitor.__class__.__name__}: {e}")
|
||||
|
||||
def save_final_summary(self, filename: str = "final_summary.json") -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
|
||||
@@ -113,10 +113,12 @@ class PrimeMonitor(Monitor):
|
||||
output_dir: Path | None = None,
|
||||
tokenizer: PreTrainedTokenizer | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
):
|
||||
self.config = config
|
||||
self.logger = get_logger()
|
||||
self.history: list[dict[str, Any]] = []
|
||||
self._keep_full_history = keep_full_history
|
||||
self.output_dir = output_dir
|
||||
self._registered = False
|
||||
self._finalized = False
|
||||
@@ -268,7 +270,10 @@ class PrimeMonitor(Monitor):
|
||||
self.logger.info(f"Platform run {self.run_id} marked as {status_label}")
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
self.history.append(metrics)
|
||||
if self._keep_full_history:
|
||||
self.history.append(metrics)
|
||||
else:
|
||||
self.history = [metrics]
|
||||
if not self.is_master:
|
||||
return
|
||||
if not self.enabled:
|
||||
@@ -490,10 +495,6 @@ class PrimeMonitor(Monitor):
|
||||
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
|
||||
pass
|
||||
|
||||
def log_final_samples(self) -> None:
|
||||
"""Log final samples (no-op - samples are logged per-step only)."""
|
||||
pass
|
||||
|
||||
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
|
||||
"""Log distributions to Prime Intellect API."""
|
||||
if not self.is_master:
|
||||
|
||||
@@ -5,7 +5,6 @@ import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
import verifiers as vf
|
||||
import wandb
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
@@ -27,10 +26,12 @@ class WandbMonitor(Monitor):
|
||||
output_dir: Path | None = None,
|
||||
tokenizer: PreTrainedTokenizer | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
):
|
||||
self.config = config
|
||||
self.logger = get_logger()
|
||||
self.history: list[dict[str, Any]] = []
|
||||
self._keep_full_history = keep_full_history
|
||||
self.output_dir = output_dir
|
||||
|
||||
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
|
||||
@@ -82,15 +83,21 @@ class WandbMonitor(Monitor):
|
||||
config=run_config.model_dump() if run_config else None,
|
||||
settings=settings,
|
||||
)
|
||||
except CommError:
|
||||
except CommError as e:
|
||||
if attempt + 1 == max_retries:
|
||||
raise
|
||||
self.logger.info(
|
||||
f"Shared W&B run not yet created by primary, retrying in 10s ({attempt + 1}/{max_retries})"
|
||||
)
|
||||
if shared_mode and not primary:
|
||||
msg = (
|
||||
f"Shared W&B run not yet created by primary - retrying in 10s ({attempt + 1}/{max_retries})"
|
||||
)
|
||||
else:
|
||||
msg = f"Transient W&B init error ({e}) - retrying in 10s ({attempt + 1}/{max_retries})"
|
||||
self.logger.info(msg)
|
||||
time.sleep(10)
|
||||
|
||||
max_retries = 1 if not shared_mode or primary else 30
|
||||
# Non-primary processes in shared mode wait for the primary to create the run.
|
||||
# Everyone else still retries to absorb transient W&B server errors (e.g. 404 on upsertBucket).
|
||||
max_retries = 30 if shared_mode and not primary else 5
|
||||
self.wandb = init_wandb(max_retries)
|
||||
|
||||
wandb.define_metric("*", step_metric="step")
|
||||
@@ -105,7 +112,6 @@ class WandbMonitor(Monitor):
|
||||
log_mode="INCREMENTAL",
|
||||
)
|
||||
self.tokenizer = tokenizer
|
||||
self.samples = []
|
||||
self.eval_samples_cols = ["step", "env", "task", "example_id", "completion", "reward"]
|
||||
self.eval_samples_table = wandb.Table(
|
||||
columns=self.eval_samples_cols,
|
||||
@@ -120,7 +126,10 @@ class WandbMonitor(Monitor):
|
||||
sys.argv = json.loads(wandb_args)
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
self.history.append(metrics)
|
||||
if self._keep_full_history:
|
||||
self.history.append(metrics)
|
||||
else:
|
||||
self.history = [metrics]
|
||||
if not self.is_master:
|
||||
return
|
||||
if not self.enabled:
|
||||
@@ -176,7 +185,6 @@ class WandbMonitor(Monitor):
|
||||
"Order of columns in the table must be the same as order of the keys here"
|
||||
)
|
||||
self.samples_table.add_data(*sample.values())
|
||||
self.samples.append(sample)
|
||||
|
||||
wandb.log({"samples": self.samples_table, "step": step})
|
||||
self.last_log_samples_step = step
|
||||
@@ -215,23 +223,6 @@ class WandbMonitor(Monitor):
|
||||
|
||||
wandb.log({"eval/samples": self.eval_samples_table, "step": step})
|
||||
|
||||
def log_final_samples(self) -> None:
|
||||
"""Log final samples to W&B table."""
|
||||
if not self.is_master:
|
||||
return
|
||||
if (
|
||||
not self.config
|
||||
or not isinstance(self.config, WandbWithExtrasConfig)
|
||||
or not self.config.log_extras
|
||||
or not self.config.log_extras.samples
|
||||
):
|
||||
return
|
||||
|
||||
self.logger.info("Logging final samples to W&B table")
|
||||
df = pd.DataFrame(self.samples)
|
||||
table = wandb.Table(dataframe=df)
|
||||
wandb.log({"final-samples": table})
|
||||
|
||||
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
|
||||
"""Log distributions (no-op for W&B)."""
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def get_cu_seqlens_from_position_ids(position_ids: torch.Tensor) -> tuple[torch.Tensor, int]:
|
||||
"""Build local-relative cumulative sequence lengths from packed position ids.
|
||||
|
||||
``position_ids`` may be a full packed sequence or a context-parallel local shard.
|
||||
In the shard case, the first local token can be a continuation with a non-zero
|
||||
position id, so cumulative offsets must be anchored to the local tensor rather
|
||||
than to the absolute position id value.
|
||||
"""
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
total_tokens = flat_position_ids.numel()
|
||||
assert total_tokens > 0, "Cannot build cu_seqlens for an empty position_ids tensor"
|
||||
|
||||
zero_starts = (flat_position_ids == 0).nonzero(as_tuple=True)[0]
|
||||
starts = torch.cat(
|
||||
[torch.zeros(1, dtype=zero_starts.dtype, device=zero_starts.device), zero_starts]
|
||||
).unique_consecutive()
|
||||
|
||||
ends = torch.cat(
|
||||
[
|
||||
starts[1:],
|
||||
torch.tensor([total_tokens], dtype=starts.dtype, device=starts.device),
|
||||
]
|
||||
)
|
||||
seqlens = ends - starts
|
||||
|
||||
cu_seqlens = torch.empty(seqlens.numel() + 1, dtype=torch.int32, device=position_ids.device)
|
||||
cu_seqlens[0] = 0
|
||||
cu_seqlens[1:] = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
|
||||
return cu_seqlens, seqlens.max().item()
|
||||
@@ -0,0 +1,93 @@
|
||||
import asyncio
|
||||
|
||||
from vllm.logprobs import Logprob
|
||||
from vllm.outputs import CompletionOutput, RequestOutput
|
||||
|
||||
from prime_rl.inference.vllm.serving_generate import GenerateRequest, OpenAIServingGenerate
|
||||
|
||||
|
||||
class _FakeChatHandler:
|
||||
def __init__(self):
|
||||
self.lora_request = object()
|
||||
|
||||
def _get_data_parallel_rank(self, raw_request):
|
||||
assert raw_request.headers["X-data-parallel-rank"] == "3"
|
||||
return 3
|
||||
|
||||
async def _get_trace_headers(self, headers):
|
||||
assert headers["traceparent"] == "trace"
|
||||
return {"traceparent": headers["traceparent"]}
|
||||
|
||||
def _maybe_get_adapters(self, request):
|
||||
assert request.model == "test-model"
|
||||
return self.lora_request
|
||||
|
||||
|
||||
class _FakeEngineClient:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
async def generate(self, engine_prompt, sampling_params, request_id, **kwargs):
|
||||
self.calls.append(
|
||||
{
|
||||
"engine_prompt": engine_prompt,
|
||||
"sampling_params": sampling_params,
|
||||
"request_id": request_id,
|
||||
"kwargs": kwargs,
|
||||
}
|
||||
)
|
||||
yield RequestOutput(
|
||||
request_id=request_id,
|
||||
prompt=None,
|
||||
prompt_token_ids=list(engine_prompt["prompt_token_ids"]),
|
||||
prompt_logprobs=[None, {11: Logprob(-0.2)}, {12: Logprob(-0.4)}],
|
||||
outputs=[
|
||||
CompletionOutput(
|
||||
index=0,
|
||||
text="done",
|
||||
token_ids=[99],
|
||||
cumulative_logprob=-0.6,
|
||||
logprobs=[{99: Logprob(-0.6)}],
|
||||
finish_reason="stop",
|
||||
)
|
||||
],
|
||||
finished=True,
|
||||
)
|
||||
|
||||
|
||||
class _FakeRawRequest:
|
||||
def __init__(self):
|
||||
self.headers = {"X-data-parallel-rank": "3", "traceparent": "trace"}
|
||||
|
||||
async def is_disconnected(self):
|
||||
return False
|
||||
|
||||
|
||||
def test_generate_returns_prompt_logprobs_and_forwards_request_metadata():
|
||||
async def _run():
|
||||
engine_client = _FakeEngineClient()
|
||||
handler = OpenAIServingGenerate(engine_client, chat_handler=_FakeChatHandler())
|
||||
request = GenerateRequest(
|
||||
model="test-model",
|
||||
prompt_token_ids=[10, 11, 12],
|
||||
max_tokens=1,
|
||||
prompt_logprobs=True,
|
||||
priority=7,
|
||||
)
|
||||
|
||||
response = await handler.generate(request, _FakeRawRequest())
|
||||
|
||||
assert response.prompt_token_ids == [10, 11, 12]
|
||||
assert response.prompt_logprobs == [None, -0.2, -0.4]
|
||||
assert response.choices[0].token_ids == [99]
|
||||
assert response.choices[0].logprobs == [-0.6]
|
||||
|
||||
call = engine_client.calls[0]
|
||||
assert call["engine_prompt"] == {"type": "token", "prompt_token_ids": [10, 11, 12]}
|
||||
assert call["sampling_params"].prompt_logprobs == 1
|
||||
assert call["kwargs"]["lora_request"] is handler.chat_handler.lora_request
|
||||
assert call["kwargs"]["priority"] == 7
|
||||
assert call["kwargs"]["data_parallel_rank"] == 3
|
||||
assert call["kwargs"]["trace_headers"] == {"traceparent": "trace"}
|
||||
|
||||
asyncio.run(_run())
|
||||
@@ -10,10 +10,38 @@ from prime_rl.orchestrator.advantage import (
|
||||
)
|
||||
|
||||
|
||||
def _make_rollout(reward: float, completion_len: int = 0, num_turns: int = 1) -> dict:
|
||||
"""Create a minimal rollout dict for advantage testing.
|
||||
|
||||
`completion_len` tokens are split across `num_turns` trajectory steps.
|
||||
"""
|
||||
per_turn, rem = divmod(completion_len, max(num_turns, 1))
|
||||
trajectory = [
|
||||
{"tokens": {"prompt_ids": [0], "completion_ids": list(range(per_turn + (rem if i == 0 else 0)))}}
|
||||
for i in range(num_turns)
|
||||
]
|
||||
return {"reward": reward, "trajectory": trajectory}
|
||||
|
||||
|
||||
def _make_inputs(rewards, completion_lengths=None, num_turns=None) -> AdvantageInputs:
|
||||
"""Build AdvantageInputs from 2D arrays of rewards/lengths/turns."""
|
||||
rewards_t = torch.as_tensor(rewards, dtype=torch.float32)
|
||||
num_problems, rollouts_per_example = rewards_t.shape
|
||||
rollouts = []
|
||||
for i in range(num_problems):
|
||||
group = []
|
||||
for j in range(rollouts_per_example):
|
||||
cl = int(completion_lengths[i][j]) if completion_lengths is not None else 0
|
||||
nt = int(num_turns[i][j]) if num_turns is not None else 1
|
||||
group.append(_make_rollout(float(rewards_t[i, j]), cl, nt))
|
||||
rollouts.append(group)
|
||||
return AdvantageInputs(rollouts=rollouts)
|
||||
|
||||
|
||||
def test_default_advantage_fn_simple_mean():
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor([[1.0, 0.5, 0.8], [0.2, 0.9, 0.1]]),
|
||||
completion_lengths=torch.tensor([[10, 12, 8], [15, 11, 9]]),
|
||||
inputs = _make_inputs(
|
||||
rewards=[[1.0, 0.5, 0.8], [0.2, 0.9, 0.1]],
|
||||
completion_lengths=[[10, 12, 8], [15, 11, 9]],
|
||||
)
|
||||
result = default_advantage_fn(inputs)
|
||||
|
||||
@@ -24,11 +52,11 @@ def test_default_advantage_fn_simple_mean():
|
||||
|
||||
def test_efficiency_mixed_group():
|
||||
"""Mixed group: reward shaping preserves zero-mean, shorter correct gets higher advantage."""
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor([[1.0, 1.0, 0.0, 1.0]]),
|
||||
completion_lengths=torch.tensor([[10, 30, 20, 20]]),
|
||||
inputs = _make_inputs(
|
||||
rewards=[[1.0, 1.0, 0.0, 1.0]],
|
||||
completion_lengths=[[10, 30, 20, 20]],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
result = default_advantage_fn(inputs, length_penalty="tokens")
|
||||
|
||||
# mean_correct_len = (10+30+20)/3 = 20
|
||||
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
|
||||
@@ -42,17 +70,18 @@ def test_efficiency_mixed_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
|
||||
rewards = torch.tensor([r["reward"] for r in inputs.rollouts[0]])
|
||||
correct_mask = rewards >= 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]]),
|
||||
inputs = _make_inputs(
|
||||
rewards=[[1.0, 1.0, 1.0]],
|
||||
completion_lengths=[[10, 20, 40]],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
result = default_advantage_fn(inputs, length_penalty="tokens")
|
||||
|
||||
# mean_len = 70/3 ≈ 23.33
|
||||
# bonus = clamp(1 - [10, 20, 40] / (70/3), 0, 1) = [4/7, 1/7, 0]
|
||||
@@ -73,11 +102,11 @@ def test_efficiency_all_correct_group():
|
||||
|
||||
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]]),
|
||||
inputs = _make_inputs(
|
||||
rewards=[[0.0, 0.0, 0.0]],
|
||||
completion_lengths=[[10, 20, 15]],
|
||||
)
|
||||
result_with = default_advantage_fn(inputs, length_shaping=True)
|
||||
result_with = default_advantage_fn(inputs, length_penalty="tokens")
|
||||
result_without = default_advantage_fn(inputs)
|
||||
|
||||
assert torch.allclose(result_with.advantages, result_without.advantages, atol=1e-6)
|
||||
@@ -85,11 +114,11 @@ def test_efficiency_all_zero_rewards():
|
||||
|
||||
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]]),
|
||||
inputs = _make_inputs(
|
||||
rewards=[[1.0, 0.0, 0.0, 0.0]],
|
||||
completion_lengths=[[100, 50, 200, 150]],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
result = default_advantage_fn(inputs, length_penalty="tokens")
|
||||
|
||||
expected = torch.tensor([[0.75, -0.25, -0.25, -0.25]])
|
||||
assert torch.allclose(result.advantages, expected, atol=1e-6)
|
||||
@@ -97,11 +126,11 @@ def test_efficiency_single_correct():
|
||||
|
||||
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]]),
|
||||
inputs = _make_inputs(
|
||||
rewards=[[1.0, 1.0, 1.0, 0.0, 0.0]],
|
||||
completion_lengths=[[50, 100, 200, 80, 120]],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
result = default_advantage_fn(inputs, length_penalty="tokens")
|
||||
|
||||
advs = result.advantages[0]
|
||||
assert advs[0] > advs[1] > advs[2]
|
||||
@@ -111,32 +140,28 @@ def test_efficiency_shorter_correct_higher_advantage():
|
||||
|
||||
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],
|
||||
]
|
||||
),
|
||||
inputs = _make_inputs(
|
||||
rewards=[
|
||||
[1.0, 1.0, 0.0, 1.0], # mixed
|
||||
[1.0, 1.0, 1.0, 1.0], # all correct
|
||||
],
|
||||
completion_lengths=[
|
||||
[10, 30, 20, 20],
|
||||
[10, 20, 40, 80],
|
||||
],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
result = default_advantage_fn(inputs, length_penalty="tokens")
|
||||
|
||||
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]]),
|
||||
inputs = _make_inputs(
|
||||
rewards=[[1.0, 1.0, 0.0]],
|
||||
completion_lengths=[[1, 10000, 5000]],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
result = default_advantage_fn(inputs, length_penalty="tokens")
|
||||
|
||||
# Shortest correct gets bonus ≈ 1, so shaped_reward ≈ 2
|
||||
# Standard reward = 1, so amplification ≈ 2x
|
||||
@@ -146,21 +171,17 @@ def test_efficiency_amplification_bounded():
|
||||
|
||||
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],
|
||||
]
|
||||
),
|
||||
inputs = _make_inputs(
|
||||
rewards=[
|
||||
[1.0, 1.0, 0.0], # mixed
|
||||
[1.0, 1.0, 1.0], # all correct
|
||||
],
|
||||
completion_lengths=[
|
||||
[10, 20, 15],
|
||||
[10, 20, 40],
|
||||
],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_shaping=True)
|
||||
result = default_advantage_fn(inputs, length_penalty="tokens")
|
||||
|
||||
# Row 0: mixed group — shorter correct > longer correct
|
||||
assert result.advantages[0, 0] > result.advantages[0, 1]
|
||||
@@ -174,12 +195,20 @@ def test_efficiency_multiple_problems():
|
||||
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_efficiency_turns_penalty():
|
||||
"""`length_penalty='turns'` shapes by trajectory turn count rather than token count."""
|
||||
inputs = _make_inputs(
|
||||
rewards=[[1.0, 1.0, 0.0, 1.0]],
|
||||
# token counts identical, but turns differ — turns penalty should still differentiate
|
||||
completion_lengths=[[100, 100, 100, 100]],
|
||||
num_turns=[[1, 3, 2, 2]],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_penalty="turns")
|
||||
|
||||
# mean_correct_turns = (1+3+2)/3 = 2
|
||||
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
|
||||
expected = torch.tensor([[0.625, 0.125, -0.875, 0.125]])
|
||||
assert torch.allclose(result.advantages, expected, atol=1e-6)
|
||||
|
||||
|
||||
def test_compute_advantages_with_config():
|
||||
@@ -195,6 +224,25 @@ def test_compute_advantages_with_config():
|
||||
assert abs(sum(advantages[3:])) < 1e-5
|
||||
|
||||
|
||||
def test_compute_advantages_no_cross_group_leakage():
|
||||
"""Per-problem grouping: each problem must be centered against its own mean, in-order.
|
||||
|
||||
Two problems with very different reward scales — cross-group leakage would pull the
|
||||
small-scale group's advantages toward the large-scale group's mean (and vice versa).
|
||||
Distinct positional values also catch slicing/transpose bugs in the flat→grouped→flat
|
||||
round-trip.
|
||||
"""
|
||||
rewards = [10.0, 20.0, 30.0, 0.0, 0.1, 0.2]
|
||||
rollouts = [_make_rollout(r) for r in rewards]
|
||||
|
||||
compute_advantages(rollouts, samples_per_problem=3, advantage_config=DefaultAdvantageConfig())
|
||||
|
||||
advantages = [r["advantage"] for r in rollouts]
|
||||
expected = [-10.0, 0.0, 10.0, -0.1, 0.0, 0.1]
|
||||
for got, want in zip(advantages, expected):
|
||||
assert abs(got - want) < 1e-5, (advantages, expected)
|
||||
|
||||
|
||||
def test_compute_advantages_without_config():
|
||||
rewards = [1.0, 0.5, 0.8]
|
||||
lengths = [10, 12, 8]
|
||||
@@ -213,9 +261,9 @@ def test_setup_advantage_fn_with_custom_config():
|
||||
)
|
||||
advantage_fn = setup_advantage_fn(config)
|
||||
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor([[1.0, 0.5, 0.8]]),
|
||||
completion_lengths=torch.tensor([[10, 12, 8]]),
|
||||
inputs = _make_inputs(
|
||||
rewards=[[1.0, 0.5, 0.8]],
|
||||
completion_lengths=[[10, 12, 8]],
|
||||
)
|
||||
|
||||
result = advantage_fn(inputs)
|
||||
@@ -225,4 +273,5 @@ def test_setup_advantage_fn_with_custom_config():
|
||||
|
||||
def _dummy_custom_advantage(inputs: AdvantageInputs, scale: float = 1.0) -> AdvantageOutputs:
|
||||
"""A simple custom advantage for testing."""
|
||||
return AdvantageOutputs(advantages=inputs.rewards * scale)
|
||||
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
|
||||
return AdvantageOutputs(advantages=rewards * scale)
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from prime_rl.orchestrator.orchestrator import setup_rollout_inference_pool
|
||||
|
||||
|
||||
def test_setup_rollout_inference_pool_uses_plain_client_for_external_teacher_rollout():
|
||||
async def run() -> None:
|
||||
tokenizer = object()
|
||||
config = SimpleNamespace(
|
||||
teacher_rollout_model=SimpleNamespace(),
|
||||
model=SimpleNamespace(renderer="auto", name="student-model"),
|
||||
)
|
||||
rollout_client_config = SimpleNamespace(base_url=["https://api.pinference.ai/api/v1"])
|
||||
logger = MagicMock()
|
||||
inference_pool = object()
|
||||
|
||||
with (
|
||||
patch(
|
||||
"prime_rl.orchestrator.orchestrator.setup_inference_pool", new=AsyncMock(return_value=inference_pool)
|
||||
),
|
||||
patch("prime_rl.orchestrator.orchestrator.create_renderer") as create_renderer_mock,
|
||||
):
|
||||
renderer, returned_pool = await setup_rollout_inference_pool(
|
||||
config=config,
|
||||
rollout_client_config=rollout_client_config,
|
||||
rollout_model_name="teacher-model",
|
||||
tokenizer=tokenizer,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
assert renderer is None
|
||||
assert returned_pool is inference_pool
|
||||
create_renderer_mock.assert_not_called()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_setup_rollout_inference_pool_uses_direct_renderer_client_for_local_vllm():
|
||||
async def run() -> None:
|
||||
tokenizer = object()
|
||||
config = SimpleNamespace(
|
||||
teacher_rollout_model=None,
|
||||
use_renderer=True,
|
||||
use_token_client=False,
|
||||
model=SimpleNamespace(name="student-model"),
|
||||
renderer=SimpleNamespace(
|
||||
name="qwen3_vl",
|
||||
tool_parser=None,
|
||||
reasoning_parser=None,
|
||||
pool_size=None,
|
||||
),
|
||||
)
|
||||
rollout_client_config = SimpleNamespace(base_url=["http://localhost:8000/v1"])
|
||||
logger = MagicMock()
|
||||
renderer = object()
|
||||
inference_pool = object()
|
||||
|
||||
with (
|
||||
patch("prime_rl.orchestrator.orchestrator.create_renderer", return_value=renderer) as create_renderer_mock,
|
||||
patch(
|
||||
"prime_rl.orchestrator.orchestrator.setup_inference_pool",
|
||||
new=AsyncMock(return_value=inference_pool),
|
||||
) as setup_pool_mock,
|
||||
):
|
||||
returned_renderer, returned_pool = await setup_rollout_inference_pool(
|
||||
config=config,
|
||||
rollout_client_config=rollout_client_config,
|
||||
rollout_model_name="student-model",
|
||||
tokenizer=tokenizer,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
assert returned_renderer is renderer
|
||||
assert returned_pool is inference_pool
|
||||
create_renderer_mock.assert_called_once_with(
|
||||
tokenizer,
|
||||
renderer="qwen3_vl",
|
||||
tool_parser=None,
|
||||
reasoning_parser=None,
|
||||
)
|
||||
setup_pool_mock.assert_awaited_once_with(
|
||||
rollout_client_config,
|
||||
model_name="student-model",
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_name="qwen3_vl",
|
||||
tool_parser=None,
|
||||
reasoning_parser=None,
|
||||
renderer_pool_size=None,
|
||||
)
|
||||
|
||||
asyncio.run(run())
|
||||
@@ -3,6 +3,8 @@ from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import verifiers as vf
|
||||
|
||||
from prime_rl.orchestrator.scheduler import InflightRequest, Scheduler
|
||||
from prime_rl.utils.async_utils import safe_cancel
|
||||
|
||||
@@ -159,3 +161,16 @@ def test_stop_cancels_inflight_policy_update_task():
|
||||
assert scheduler.inflight_policy_update_task is None
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_client_identity_distinguishes_base_url_and_dp_rank():
|
||||
client_a = vf.ClientConfig(
|
||||
api_base_url="http://worker-a:8000/v1",
|
||||
extra_headers={"X-data-parallel-rank": "0"},
|
||||
)
|
||||
client_b = vf.ClientConfig(
|
||||
api_base_url="http://worker-a:8000/v1",
|
||||
extra_headers={"X-data-parallel-rank": "1"},
|
||||
)
|
||||
|
||||
assert Scheduler._client_identity(client_a) != Scheduler._client_identity(client_b)
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import asyncio
|
||||
|
||||
import verifiers as vf
|
||||
|
||||
from prime_rl.inference.vllm.serving_generate import GenerateResponse
|
||||
from prime_rl.orchestrator import utils as orchestrator_utils
|
||||
from prime_rl.transport import TrainingSample
|
||||
|
||||
|
||||
class _FakeOpenAIClient:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
async def post(self, path, *, cast_to, body):
|
||||
self.calls.append({"path": path, "cast_to": cast_to, "body": body})
|
||||
return GenerateResponse(
|
||||
id="gen-test",
|
||||
model=body["model"],
|
||||
prompt_token_ids=list(body["prompt_token_ids"]),
|
||||
choices=[],
|
||||
usage={"prompt_tokens": 3, "completion_tokens": 0, "total_tokens": 3},
|
||||
prompt_logprobs=[None, -0.7, -0.3],
|
||||
)
|
||||
|
||||
|
||||
def test_compute_teacher_logprobs_uses_generate_endpoint(monkeypatch):
|
||||
async def _run():
|
||||
fake_client = _FakeOpenAIClient()
|
||||
monkeypatch.setattr(orchestrator_utils, "setup_openai_client", lambda _: fake_client)
|
||||
|
||||
sample = TrainingSample(
|
||||
prompt_ids=[1],
|
||||
prompt_mask=[True],
|
||||
completion_ids=[2, 3],
|
||||
completion_mask=[True, True],
|
||||
completion_logprobs=[-0.1, -0.2],
|
||||
completion_temperatures=[1.0, 1.0],
|
||||
)
|
||||
|
||||
result = await orchestrator_utils.compute_teacher_logprobs(
|
||||
clients=[vf.ClientConfig()],
|
||||
model_name="teacher-model",
|
||||
samples=[sample],
|
||||
)
|
||||
|
||||
assert result == [[0.0, -0.7, -0.3]]
|
||||
assert fake_client.calls == [
|
||||
{
|
||||
"path": "/generate",
|
||||
"cast_to": GenerateResponse,
|
||||
"body": {
|
||||
"model": "teacher-model",
|
||||
"prompt_token_ids": [1, 2, 3],
|
||||
"max_tokens": 1,
|
||||
"temperature": 1.0,
|
||||
"top_p": 1.0,
|
||||
"prompt_logprobs": True,
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
asyncio.run(_run())
|
||||
@@ -0,0 +1,50 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from prime_rl.trainer.model import forward
|
||||
|
||||
|
||||
class _CaptureModel(nn.Module):
|
||||
def __init__(self, config: SimpleNamespace):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.kwargs = None
|
||||
|
||||
def forward(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
input_ids = kwargs["input_ids"]
|
||||
return {"logits": torch.zeros(*input_ids.shape, 4)}
|
||||
|
||||
|
||||
def test_forward_adds_qwen3_vl_mm_token_type_ids():
|
||||
image_token_id = 10
|
||||
video_token_id = 20
|
||||
model = _CaptureModel(
|
||||
SimpleNamespace(model_type="qwen3_vl", image_token_id=image_token_id, video_token_id=video_token_id)
|
||||
)
|
||||
input_ids = torch.tensor([[1, image_token_id, image_token_id, 2, video_token_id]])
|
||||
position_ids = torch.arange(input_ids.shape[1]).unsqueeze(0)
|
||||
pixel_values = torch.ones(2, 3)
|
||||
image_grid_thw = torch.tensor([[1, 1, 2]])
|
||||
|
||||
forward(model, input_ids, position_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw)
|
||||
|
||||
assert model.kwargs is not None
|
||||
assert "position_ids" not in model.kwargs
|
||||
torch.testing.assert_close(model.kwargs["pixel_values"], pixel_values)
|
||||
torch.testing.assert_close(model.kwargs["image_grid_thw"], image_grid_thw)
|
||||
torch.testing.assert_close(model.kwargs["mm_token_type_ids"], torch.tensor([[0, 1, 1, 0, 2]]))
|
||||
|
||||
|
||||
def test_forward_skips_mm_token_type_ids_for_other_vlm_models():
|
||||
model = _CaptureModel(SimpleNamespace(model_type="qwen3_5_moe", image_token_id=10))
|
||||
input_ids = torch.tensor([[1, 10, 10, 2]])
|
||||
position_ids = torch.arange(input_ids.shape[1]).unsqueeze(0)
|
||||
|
||||
forward(model, input_ids, position_ids, pixel_values=torch.ones(2, 3), image_grid_thw=torch.tensor([[1, 1, 2]]))
|
||||
|
||||
assert model.kwargs is not None
|
||||
assert "position_ids" not in model.kwargs
|
||||
assert "mm_token_type_ids" not in model.kwargs
|
||||
@@ -25,7 +25,7 @@ def test_perf_counter(model_name: str, active_params: int, flops_per_token: int)
|
||||
None,
|
||||
)
|
||||
model = AutoModelForCausalLM.from_config(config)
|
||||
perf_counter = PerfCounter(model, seq_len=1024, window_size=10)
|
||||
perf_counter = PerfCounter(model, seq_len=1024)
|
||||
|
||||
assert perf_counter.get_active_mm_params(config) == active_params, (
|
||||
f"Expected {active_params:,} active parameters, got {perf_counter.get_active_mm_params(config):,} active parameters"
|
||||
|
||||
@@ -3,9 +3,10 @@ from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
import verifiers as vf
|
||||
|
||||
from prime_rl.utils.client import _is_retryable_lora_error, load_lora_adapter
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.client import _is_retryable_lora_error, load_lora_adapter, setup_clients
|
||||
|
||||
|
||||
def test_is_retryable_lora_error_returns_true_for_404():
|
||||
@@ -48,39 +49,68 @@ def test_load_lora_adapter_succeeds_on_first_attempt():
|
||||
)
|
||||
|
||||
|
||||
def test_load_lora_adapter_retries_on_404_then_succeeds():
|
||||
mock_client = AsyncMock()
|
||||
def test_setup_clients_assigns_renderer_and_dp_rank_headers():
|
||||
client_config = ClientConfig(
|
||||
base_url=["http://worker-a:8000/v1"],
|
||||
api_key_var="PRIME_API_KEY",
|
||||
headers={"X-Test": "test"},
|
||||
dp_rank_count=2,
|
||||
extra_headers_from_state={"X-Session-ID": "session_id"},
|
||||
)
|
||||
|
||||
error_response = MagicMock()
|
||||
error_response.status_code = 404
|
||||
success_response = MagicMock()
|
||||
success_response.raise_for_status = MagicMock()
|
||||
clients = setup_clients(
|
||||
client_config,
|
||||
client_type="renderer",
|
||||
renderer_name="qwen3_vl",
|
||||
)
|
||||
|
||||
call_count = 0
|
||||
|
||||
async def mock_post(*args, **kwargs):
|
||||
nonlocal call_count
|
||||
call_count += 1
|
||||
if call_count == 1:
|
||||
raise httpx.HTTPStatusError("Not found", request=MagicMock(), response=error_response)
|
||||
return success_response
|
||||
|
||||
mock_client.post = mock_post
|
||||
|
||||
asyncio.run(load_lora_adapter([mock_client], "test-lora", Path("/test/path")))
|
||||
|
||||
assert call_count == 2
|
||||
assert [client.client_type for client in clients] == ["renderer", "renderer"]
|
||||
assert [client.renderer for client in clients] == ["qwen3_vl", "qwen3_vl"]
|
||||
assert [client.renderer_model_name for client in clients] == [None, None]
|
||||
assert [client.api_base_url for client in clients] == ["http://worker-a:8000/v1"] * 2
|
||||
assert [client.extra_headers["X-data-parallel-rank"] for client in clients] == ["0", "1"]
|
||||
assert clients[0].extra_headers["X-Test"] == "test"
|
||||
assert clients[0].extra_headers_from_state == {"X-Session-ID": "session_id"}
|
||||
|
||||
|
||||
def test_load_lora_adapter_raises_non_retryable_error_immediately():
|
||||
mock_client = AsyncMock()
|
||||
def test_setup_clients_assigns_renderer_model_name():
|
||||
client_config = ClientConfig(
|
||||
base_url=["http://worker-a:8000/v1"],
|
||||
api_key_var="PRIME_API_KEY",
|
||||
)
|
||||
|
||||
error_response = MagicMock()
|
||||
error_response.status_code = 400
|
||||
mock_client.post.side_effect = httpx.HTTPStatusError("Bad request", request=MagicMock(), response=error_response)
|
||||
clients = setup_clients(
|
||||
client_config,
|
||||
client_type="renderer",
|
||||
renderer_name="qwen3_vl",
|
||||
renderer_model_name="Qwen/Qwen3-VL-4B-Instruct",
|
||||
)
|
||||
|
||||
with pytest.raises(httpx.HTTPStatusError) as exc_info:
|
||||
asyncio.run(load_lora_adapter([mock_client], "test-lora", Path("/test/path")))
|
||||
assert clients[0].renderer_model_name == "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
assert exc_info.value.response.status_code == 400
|
||||
assert mock_client.post.call_count == 1
|
||||
|
||||
def test_setup_clients_preserves_chat_client_defaults():
|
||||
client_config = ClientConfig(
|
||||
base_url=["http://worker-a:8000/v1"],
|
||||
api_key_var="PRIME_API_KEY",
|
||||
)
|
||||
|
||||
clients = setup_clients(client_config)
|
||||
|
||||
assert clients == [
|
||||
vf.ClientConfig(
|
||||
client_idx=0,
|
||||
client_type="openai_chat_completions",
|
||||
renderer="auto",
|
||||
renderer_model_name=None,
|
||||
api_key_var="PRIME_API_KEY",
|
||||
api_base_url="http://worker-a:8000/v1",
|
||||
timeout=client_config.timeout,
|
||||
connect_timeout=client_config.connect_timeout,
|
||||
max_connections=8192,
|
||||
max_keepalive_connections=8192,
|
||||
max_retries=10,
|
||||
extra_headers={},
|
||||
extra_headers_from_state={},
|
||||
)
|
||||
]
|
||||
|
||||
@@ -4,6 +4,7 @@ from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import httpx
|
||||
import verifiers as vf
|
||||
|
||||
from prime_rl.utils.elastic import (
|
||||
AdapterState,
|
||||
@@ -401,3 +402,49 @@ def test_get_loaded_adapter_handles_step_dash_format():
|
||||
|
||||
assert result is not None
|
||||
assert result.step == 99
|
||||
|
||||
|
||||
def test_elastic_clients_preserve_renderer_model_name_when_model_name_updates():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
client_config = MagicMock()
|
||||
client_config.elastic.hostname = "test.hostname"
|
||||
client_config.elastic.port = 8000
|
||||
client_config.elastic.sync_interval = 5.0
|
||||
client_config.router_url = None
|
||||
client_config.timeout = 1200
|
||||
client_config.connect_timeout = 30.0
|
||||
client_config.api_key_var = "PRIME_API_KEY"
|
||||
client_config.headers = {}
|
||||
client_config.extra_headers_from_state = {}
|
||||
client_config.dp_rank_count = 1
|
||||
|
||||
pool = ElasticInferencePool(
|
||||
client_config=client_config,
|
||||
model_name="Qwen/Qwen3-VL-4B-Instruct",
|
||||
train_client_type="renderer",
|
||||
renderer_name="qwen3_vl",
|
||||
)
|
||||
pool._servers = {
|
||||
"10.0.0.1": MagicMock(status="ready"),
|
||||
}
|
||||
|
||||
pool.update_model_name("r8-smoke")
|
||||
clients = pool.train_clients
|
||||
|
||||
assert clients == [
|
||||
vf.ClientConfig(
|
||||
client_idx=0,
|
||||
client_type="renderer",
|
||||
renderer="qwen3_vl",
|
||||
renderer_model_name="Qwen/Qwen3-VL-4B-Instruct",
|
||||
api_key_var="PRIME_API_KEY",
|
||||
api_base_url="http://10.0.0.1:8000/v1",
|
||||
timeout=1200,
|
||||
connect_timeout=30.0,
|
||||
max_connections=8192,
|
||||
max_keepalive_connections=8192,
|
||||
max_retries=10,
|
||||
extra_headers={},
|
||||
extra_headers_from_state={},
|
||||
)
|
||||
]
|
||||
|
||||
@@ -37,7 +37,7 @@ def _build_rollout(*, example_id: int, reward: float, task: str) -> dict:
|
||||
"reward": reward,
|
||||
"advantage": reward / 2,
|
||||
"metrics": {"accuracy": reward},
|
||||
"timing": {"generation_ms": 12.5},
|
||||
"timing": {"generation": {"start": 0.0, "end": 12.5, "duration": 12.5}},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("position_ids", "expected_cu_seqlens", "expected_max_seqlen"),
|
||||
[
|
||||
(torch.arange(8).unsqueeze(0), [0, 8], 8),
|
||||
(torch.arange(8, 16).unsqueeze(0), [0, 8], 8),
|
||||
(torch.tensor([[0, 1, 2, 3, 0, 1, 2]]), [0, 4, 7], 4),
|
||||
(torch.tensor([[5, 6, 7, 0, 1, 2]]), [0, 3, 6], 3),
|
||||
],
|
||||
)
|
||||
def test_get_cu_seqlens_from_position_ids_is_local_relative(
|
||||
position_ids: torch.Tensor,
|
||||
expected_cu_seqlens: list[int],
|
||||
expected_max_seqlen: int,
|
||||
) -> None:
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
|
||||
assert cu_seqlens.dtype == torch.int32
|
||||
assert cu_seqlens.tolist() == expected_cu_seqlens
|
||||
assert max_seqlen == expected_max_seqlen
|
||||
@@ -10,6 +10,39 @@ supported-markers = [
|
||||
"platform_machine == 'aarch64' and sys_platform == 'linux'",
|
||||
]
|
||||
|
||||
[options]
|
||||
exclude-newer = "2026-04-23T20:00:49.639641409Z"
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
verifiers = false
|
||||
vllm-router = false
|
||||
dion = false
|
||||
torch = false
|
||||
alphabet-sort = false
|
||||
science-env = false
|
||||
color-codeword = false
|
||||
nixl-cu12 = false
|
||||
flash-attn-3 = false
|
||||
prime-tunnel = false
|
||||
prime = false
|
||||
deep-gemm = false
|
||||
aime2024 = false
|
||||
prime-evals = false
|
||||
deepdive = false
|
||||
reverse-text = false
|
||||
code-env = false
|
||||
mini-swe-agent-plus = false
|
||||
deep-ep = false
|
||||
pydantic-config = false
|
||||
math-env = false
|
||||
logic-env = false
|
||||
wiki-search = false
|
||||
math-python = false
|
||||
math500 = false
|
||||
aime2025 = false
|
||||
prime-sandboxes = false
|
||||
|
||||
[manifest]
|
||||
overrides = [
|
||||
{ name = "nvidia-cudnn-cu12", specifier = ">=9.15" },
|
||||
@@ -879,8 +912,8 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "flash-attn-4"
|
||||
version = "4.0.0b6.dev7+gabd9943"
|
||||
source = { git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=abd9943b#abd9943b66704f650ea1485a17126cd3817d1b1d" }
|
||||
version = "4.0.0b11.dev11+g96bd151"
|
||||
source = { git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=96bd151#96bd151b00add1dc5744115cfc350c0a809c3fa2" }
|
||||
dependencies = [
|
||||
{ name = "apache-tvm-ffi", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "einops", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -2306,17 +2339,17 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "openai-harmony"
|
||||
version = "0.0.4"
|
||||
version = "0.0.8"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pydantic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/92/94/01509d510bebf6606614e51113e5a415ced15b8f34aa98a8bf2539314650/openai_harmony-0.0.4.tar.gz", hash = "sha256:5c67ac6df349236fb7b64f57c3dbb0273efcdca24314daa108f2a482c427106c", size = 279848, upload-time = "2025-08-09T01:43:24.974Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/3e/92/2d038d096f29179c7c9571b431f9e739f87a487121901725e23fe338dd9d/openai_harmony-0.0.8.tar.gz", hash = "sha256:6e43f98e6c242fa2de6f8ea12eab24af63fa2ed3e89c06341fb9d92632c5cbdf", size = 284777, upload-time = "2025-11-05T19:07:06.727Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/05/88/ade63bd8f36603610040e7cc086bc134d57a99a742e05f7fcddfdf822ee1/openai_harmony-0.0.4-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3cf2344366f10981bbc0f6d9949a0b2bb87151d209ed295943ed6ad8eda37932", size = 2963206, upload-time = "2025-08-09T01:43:02.433Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1f/ec/dcdcace0ffcf3a532cca910e0c351b62d3a7decf0b091ea8cf856d2a67a6/openai_harmony-0.0.4-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:31e9bcac0902a309e2fc688e52f247eec7fffcd00d17e958b9a83a8fea6519c2", size = 3049306, upload-time = "2025-08-09T01:43:11.019Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/39/172f1048d935db1523a82b45fee5231ad6c622645e566706e6bcf3731da8/openai_harmony-0.0.4-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:96a63199c0d81095b5d5d1ae8ca82b64c1c13d18d4e30323ae9e8ab31bc80a3d", size = 3121347, upload-time = "2025-08-09T01:43:16.705Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/bd/aa9e6e5cf140716dbcae17402fac2a81a9ebb3f934059ac0eec61cb447fc/openai_harmony-0.0.4-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:15e6d53a66502491a3675a536df30e271f976e6c5efe68250a65191efcb85c4f", size = 3221129, upload-time = "2025-08-09T01:43:23.146Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d3/d2/ce6953ca87db9cae3e775024184da7d1c5cb88cead19a2d75b42f00a959c/openai_harmony-0.0.8-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e4f709815924ec325b9a890e6ab2bbb0ceec8e319a4e257328eb752cf36b2efc", size = 2948463, upload-time = "2025-11-05T19:06:48.17Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/25/3f/1a192b93bb47c6b44cd98ba8cc1d3d2a9308f1bb700c3017e6352da11bda/openai_harmony-0.0.8-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c007d277218a50db8839e599ed78e0fffe5130f614c3f6d93ae257f282071a29", size = 2953260, upload-time = "2025-11-05T19:06:55.406Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5b/f8/93b582cad3531797c3db7c2db5400fd841538ccddfd9f5e3df61be99a630/openai_harmony-0.0.8-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:8565d4f5a0638da1bffde29832ed63c9e695c558611053add3b2dc0b56c92dbc", size = 3127044, upload-time = "2025-11-05T19:06:59.553Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/60/c3/3d1e01e2dba517a91760e4a03e4f20ffc75039a6fe584d0e6f9b5c78fd15/openai_harmony-0.0.8-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:007b0476a1f331f8130783f901f1da6f5a7057af1a4891f1b6a31dec364189b5", size = 3205080, upload-time = "2025-11-05T19:07:05.078Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2757,7 +2790,7 @@ requires-dist = [
|
||||
{ name = "dion", git = "https://github.com/samsja/dion.git?rev=d891eeb" },
|
||||
{ name = "flash-attn", marker = "platform_machine == 'x86_64' and extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3+cu128torch2.10-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "flash-attn-3", marker = "extra == 'flash-attn-3'", index = "https://download.pytorch.org/whl/test/cu128" },
|
||||
{ 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-attn-4", marker = "extra == 'flash-attn-cute'", git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=96bd151" },
|
||||
{ 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'" },
|
||||
@@ -2798,10 +2831,10 @@ 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=77a9f28" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=3b77145" },
|
||||
{ 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.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" },
|
||||
{ name = "wandb", specifier = ">=0.24.2" },
|
||||
{ name = "wandb", specifier = ">=0.26.1" },
|
||||
{ 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", "gpt-oss", "quack", "all"]
|
||||
@@ -2818,7 +2851,7 @@ mamba-ssm = [{ name = "mamba-ssm", specifier = ">=2.3.0" }]
|
||||
|
||||
[[package]]
|
||||
name = "prime-sandboxes"
|
||||
version = "0.2.19"
|
||||
version = "0.2.22"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiofiles", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -2828,9 +2861,9 @@ dependencies = [
|
||||
{ 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/2c/8c/7d8b8013f65d8394094a922bc493eaae09e5e88058f80bd009637ffeff63/prime_sandboxes-0.2.19.tar.gz", hash = "sha256:081cd9ef246d397b4a2fdd77a94679a5f08115ecbbe3f90f320e5f4a7988820e", size = 60558, upload-time = "2026-04-01T00:46:28.212Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/dc/a7/eb9cb01ce7fa812022ec7c2ffaeb379e1103e07f093a4b85e879b2d0143d/prime_sandboxes-0.2.22.tar.gz", hash = "sha256:7901adca4ff7fff1e7f08c06c4b76765cd90791965216655eb3a87d459588f5e", size = 64970, upload-time = "2026-04-22T18:32:12.973Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/79/56/9bd4b3733773e6c122ebfe92144476c143666d09d9e8cccb9d1349d4d43c/prime_sandboxes-0.2.19-py3-none-any.whl", hash = "sha256:ce5db7314c007aae796e1ce274181eaa1370000a478bcd55c26149edfee580c1", size = 31617, upload-time = "2026-04-01T00:46:27.216Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/90/b8/46bf98c06826fc26d982c53e10d9d4f086a4c322993a6c51188e5bd6fd30/prime_sandboxes-0.2.22-py3-none-any.whl", hash = "sha256:0a75bb02049c16b55aae7475cc4082e8559ffa6d65181b238077771a95b57855", size = 33182, upload-time = "2026-04-22T18:32:11.739Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3246,6 +3279,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/18/f4/04ed04ebf335a44083695c22772be6a42efa31900415555563acf02cb4de/regex-2026.3.32-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b56993a7aeb4140c4770f4f7965c9e5af4f024457d06e23c01b0d47501cb18ed", size = 788332, upload-time = "2026-03-28T21:46:50.454Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "renderers"
|
||||
version = "0.1.0"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?subdirectory=packages%2Frenderers&rev=3b77145#3b77145e14a9bcdaf180a49e7df97dbf2d7bb150" }
|
||||
dependencies = [
|
||||
{ name = "openai-harmony", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "transformers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "requests"
|
||||
version = "2.32.5"
|
||||
@@ -4035,13 +4077,14 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "verifiers"
|
||||
version = "0.1.12.dev6"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=77a9f28#77a9f282bdea2c09b34e726a1e6c7b5e55bab8be" }
|
||||
version = "0.1.13.dev8"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=3b77145#3b77145e14a9bcdaf180a49e7df97dbf2d7bb150" }
|
||||
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')" },
|
||||
{ name = "datasets", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "gepa", 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 = "jinja2", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "math-verify", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "mcp", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -4055,6 +4098,7 @@ dependencies = [
|
||||
{ name = "pydantic", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "pyzmq", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "regex", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "renderers", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "requests", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "rich", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "setproctitle", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -4195,7 +4239,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "wandb"
|
||||
version = "0.24.2"
|
||||
version = "0.26.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "click", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -4209,12 +4253,12 @@ dependencies = [
|
||||
{ name = "sentry-sdk", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "typing-extensions", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/97/5c/53cf9f74b89e90facc8c7892d1449f7b39527e50e5cd577346baeb97e423/wandb-0.24.2.tar.gz", hash = "sha256:968b5b91d0a164dfb2f8c604cdf69e6fb09de6596b85b9f9d3c916b71ae86198", size = 44237317, upload-time = "2026-02-05T00:12:16.739Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/6a/a4/72a6640e1f566e81f184a426e3e45298d4c6672664de41adb7eb6f64370a/wandb-0.26.1.tar.gz", hash = "sha256:eef2dbaea06f0b1c0cdc5d76f544ae4c2b8848fc512442a00bd59f0502fc8aa1", size = 42159814, upload-time = "2026-04-23T16:27:34.033Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/3e/99/33b0281ac9a0b0c251195e6ce6cb310efa2f84ee117a15e9997fc2f9503b/wandb-0.24.2-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:85861f9b3e54a07b84bade0aa5f4caa156028ab959351d98816a45e3b1411d35", size = 21286409, upload-time = "2026-02-05T00:12:00.584Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/70/c8/1b758bd903afee000f023cd03f335ff328a21b3914f9f9deda49b1e57723/wandb-0.24.2-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:38661c666e70d7e1f460fc0a0edab8a393eaaa5f8773c17be534961a7022779d", size = 23026085, upload-time = "2026-02-05T00:12:02.682Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/60/87/724583f258aaeb2c368c79d7412167ce628f8a5ca667faed3cd427dd3be2/wandb-0.24.2-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:656a4272000999569eb8e0773f1259403bc6bd3e7d1c7d2238d3e359874da9c4", size = 21342088, upload-time = "2026-02-05T00:12:05.375Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1e/5c/e9b36ddc9beb2745a4fb1ec67ae7f995c31f7305a6d17837b72b228360ff/wandb-0.24.2-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:33cba098d95fd46720cc9023bd23e4a38e9b11836a836b4a57b8d41cff8985f2", size = 23120819, upload-time = "2026-02-05T00:12:07.487Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/56/af/400d84a3bdce0b062b4baa70acb6becd2c8018697f4fbf5af9a9e1e406e5/wandb-0.26.1-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:7c78bc2454cfe1ffa1c3a256060a387356eed8a4488e024d9d2eba8f2b5bd51d", size = 25421317, upload-time = "2026-04-23T16:27:06.411Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7b/e9/b4bf8f3509dcea1cec52233a38991459654635b5a8e6a494eb912e1b9cfb/wandb-0.26.1-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:a2c8eeec8706dcd2872e69c3b4d20ec523082fdb4440295491556e219ad2aa67", size = 27192831, upload-time = "2026-04-23T16:27:10.308Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/62/cf/4a6dce0c782223ef0eeea7139daee73418a7322befcf083512c31cebaa18/wandb-0.26.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:2fa768ee0636a569afb7541cf996e56309c47070566a38916823f94e02afe586", size = 25593326, upload-time = "2026-04-23T16:27:14.259Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/df/99/58c3d8c36ae8e2b7d70bf6493eb5daa1cca0231a04b025717b4cd1a78f1e/wandb-0.26.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:5854928725cfeff1f284d5c043cd353f810e5da02eead2c120ef5056ad026fea", size = 27535542, upload-time = "2026-04-23T16:27:18.473Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in New Issue
Block a user