Compare commits

...
Author SHA1 Message Date
4beb553525 feat: default per-env ratio to 1, drop natural-distribution mode (#2935)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Env sampling weight (`ratio`) now defaults to 1 (equal weight per env)
and no longer accepts unset/None. The None-for-all-envs mode that
sampled proportional to each env's dataset size is removed, along with
the all-or-none constraint — any subset of envs may set `ratio`, the
rest default to 1.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 09:50:56 -07:00
halleriteandGitHub 51dc60a895 chore: dead-code sweep across trainer, orchestrator, utils, and configs (#2932)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 09:49:14 +02:00
halleriteandGitHub a8f090b444 chore: delete dead get_adapter_state_dict from trainer/weights.py (#2929)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 03:51:09 +02:00
halleriteandGitHub cdea189e3d chore(configs): remove dead max_retries knob from Env/Train/EvalConfig (#2930)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 03:50:54 +02:00
halleriteandGitHub d5f218f708 chore(configs): remove empty *ExperimentalConfig placeholders (#2931)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 03:14:56 +02:00
halleriteandGitHub a03c70f55b chore: delete dead utils/tensor_hashing.py (#2928)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 02:21:33 +02:00
e48a53853e fix: weight-sync hardening + dead-code / get_max_layer_num cleanup (#2922)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: correct weight-broadcast validation + prefix-cache docs

- validate_shared_weight_broadcast: the chained comparison
  `trainer.type != orchestrator.type != inference.type` only compared
  adjacent pairs, so a mismatched inference weight_broadcast type
  (e.g. trainer/orchestrator=nccl, inference=filesystem) passed validation
  silently. Check trainer vs orchestrator, then inference vs both.
- update_weights / load_lora_adapter docstrings claimed the server resets
  the prefix cache on weight update; it doesn't — the orchestrator salts
  the prefix cache per weight version (cache_salt, see orchestrator/envs.py).
  Fix the docs and drop the dead reset_prefix_cache_after_update state flag
  (set but never read).
- heartbeat: docstring said "2s timeout"; the request uses timeout=1.

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

* chore: remove dead code in trainer/utils

Grep-verified as unused across src/:
- qwen3_moe: load_balancing_loss_func (aux-loss-free routing is used instead)
- rl/loss.py: shift_logits
- perf.py: _count_trainable_params
- kernels/fp8_utils.py: align()
- kernels/fp8_indexer.py: dead `_weight_scale = weight_scale` assignment
  (kernel intentionally ignores weight_scale, per its NOTE)
- layers/moe.py: leftover commented-out forward variant
- utils/utils.py: capitalize, to_row_format, mean_normalize
- broadcast/nccl.py: import NCCL_READY_MARKER from utils.client instead of
  redefining the same constant

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

* refactor: consolidate get_max_layer_num into trainer/weights

Seven converting_*.py modules each defined their own get_max_layer_num —
six as a fragile `int(key.split(".")[2])` one-liner and afmoe as a regex
variant that returned the max index (its callers compensated with
`range(max_layer + 1)`). Replace all seven with the canonical, robust
implementation in trainer/weights.py (handles an arbitrary layer_prefix,
guards non-digit segments, already used by the NCCL broadcaster).

- afmoe: the canonical returns a count (max+1), so its two callers switch
  from `range(max_layer + 1)` to `range(num_layers)` — behavior-identical.
- No import cycle: weights.py imports neither trainer.models nor the
  converting modules.

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

* refactor: centralize flash-attn varlen import guard

afmoe and qwen3_5_moe each re-declared the identical three-way
try/except import guard for flash_attn_varlen_func / _3_ / _4_ that
already exists in trainer/models/layers/attn.py. Import the (None-able)
module-level names from attn.py instead; each model's `_funcs` dispatch
table is unchanged.

Note: their attention classes are genuinely model-specific (gated output,
local/global split, MRoPE, GatedDeltaNet), so they legitimately do NOT
subclass the shared FlashAttention — only the optional-dependency import
guard was duplicated.

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

* fix: break circular import from get_max_layer_num consolidation

The consolidation made the converting_*.py modules import trainer/weights.py,
but weights.py imports trainer/lora.py, which (via trainer/models/__init__)
imports the model modules and their converting_*.py — closing a cycle:

  lora -> models/__init__ -> afmoe/modeling -> converting_afmoe
    -> weights -> lora (partially initialized) -> ImportError

Move get_max_layer_num into a dependency-free leaf module
trainer/conversion_utils.py (imports only torch) and point the seven
converting modules + the NCCL broadcaster at it. weights.py no longer
defines it (it never used it internally). Keeps the single-source dedup
without the cycle.

Caught by the reverse_text integration tests (trainer crashed at import).

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
2026-07-01 19:12:57 +01:00
f3c85a947a exp: update swe ablation (#2925)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* exp: add glm45air scaleswe length-penalty ablation config

Length-penalty variant of configs/debug/v1/glm45air_scaleswe.toml: enables the
GRPO linear length penalty with output-token, input-token, and turns coefficients
all set to 0.1, using the current [orchestrator.algo.length_penalty] schema on main.
Distinct -lp SLURM job name, wandb run name, and prime sandbox labels.

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

* exp: move scaleswe length-penalty config to configs/glm45air/swe.toml

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

* exp: move glm45air scaleswe config to configs/glm45air/swe.toml, use rlm harness

Promote configs/debug/v1/glm45air_scaleswe.toml to configs/glm45air/swe.toml as a
move + update: switch the train and eval harness from default to rlm, enable the
GRPO linear length penalty (all coefs 0.1), and drop the -lp suffix from the SLURM
job name and prime sandbox labels (labels can't reference $SLURM_JOB_NAME — that
field is passed verbatim to the sandbox API — so the literal must match the job name
that the pre-launch cleanup deletes by).

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

* exp: drop -lp from wandb run name

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:53:58 -07:00
f19ba721a9 chore(configs): bump dist_timeout_seconds default to 3600 (#2924)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The 600s default torch/NCCL distributed timeout was too tight for
large multi-node runs — startup collectives (step-0 evals, slow first
SWE batches) tripped the watchdog and SIGABRT'd the trainer. Bump the
default to 3600s for both RL and SFT trainer configs.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:23:35 -07:00
44 changed files with 97 additions and 570 deletions
+1
View File
@@ -2,6 +2,7 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`[[orchestrator.train.env]].ratio` now defaults to `1` and no longer accepts unset/`None`**: Each train env's sampling weight defaults to `1` (equal weight per env) instead of `None`. The `None`-for-all-envs mode — which sampled proportional to each env's dataset size (the "natural task distribution") — is removed, along with the all-or-none constraint (any subset of envs may now set `ratio`; the rest default to `1`). Multi-env configs that relied on the old default now sample each env equally rather than proportional to dataset size; set each env's `ratio` explicitly to restore a proportional (or any other) mix. (2026-07-02)
- **`orchestrator.algo.length_penalty` restructured to a single `linear` shape; `tokens`/`turns` length penalties removed**: The `grpo`-family length penalty keeps the `[orchestrator.algo.length_penalty]` key but is collapsed to a single `type = "linear"` shape; the discriminated `type = "tokens" | "turns"` efficiency-shaping variants (and the `efficiency_shaping` helper) are removed. The linear penalty subtracts a `pass_rate`-scaled penalty from each reward before the GRPO baseline, summing three terms — `num_output_tokens_weight` × output tokens, `num_input_tokens_weight` × input (non-output) tokens, and `num_turns_weight` × turns — each normalized by the group's own max for that quantity. Field renames within the penalty: `coef` → `num_output_tokens_weight` (default `0.25`), `context_coef` → `num_input_tokens_weight` (default `0.1`), `turns_coef` → `num_turns_weight` (default `0.1`); the `gate_by_correctness` flag is removed. `extra="forbid"` rejects the old keys, so existing configs must migrate. (2026-06-29)
- **`model.fused_lm_head_token_chunk_size` `"auto"` option removed**: The `"auto"` value is no longer accepted. Use an explicit integer (e.g. `8192`) or `"disabled"`. The `"auto"` value previously resolved to `8192` for RL training — set `fused_lm_head_token_chunk_size = 8192` explicitly to get the same behavior.
- **Memory-saving defaults enabled**: `trainer.model.ac`, `trainer.model.ac_offloading`, `trainer.model.compile`, `trainer.model.optim_cpu_offload`, and `trainer.model.fused_lm_head_token_chunk_size` are now enabled by default to provide sane memory-efficient defaults out of the box. Specifically: `ac` defaults to `ActivationCheckpointConfig()` (full mode), `ac_offloading` defaults to `ActivationOffloadingConfig()`, `compile` defaults to `CompileConfig()` (`fullgraph=false`), `optim_cpu_offload` defaults to `true`, and `fused_lm_head_token_chunk_size` defaults to `1024`. SFT training silently disables `fused_lm_head_token_chunk_size` (sets it to `"disabled"`). Configs using `max_concurrent_runs > 1` must explicitly set `optim_cpu_offload = false`. To disable any of these, set the field to `None` / `"None"` / `false` / `"disabled"` as appropriate.
@@ -1,7 +1,11 @@
# v1 RL ablation: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, default (bash+edit) harness on
# a prime sandbox runtime; eval on SWE-Bench Verified. Router replay is enabled
# (trainer.enable_router_replay replays the routed-expert decisions returned by inference via
# enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe model, which supports routed_experts.
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
# a glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the output-token, input-token, and turns coefficients all
# set to 0.1. Each term is pass_rate-scaled and normalized by the group's own max before the GRPO
# baseline subtraction.
#
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
@@ -82,6 +86,15 @@ group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
[orchestrator.algo]
type = "grpo"
# Linear length penalty at coef 0.1 on all three terms (output tokens, input tokens, turns).
[orchestrator.algo.length_penalty]
num_output_tokens_weight = 0.1
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
@@ -89,11 +102,11 @@ thinking_retention = "all"
[[orchestrator.train.env]]
name = "scaleswe"
taskset = { id = "scaleswe-v1" }
harness = { id = "default", runtime = { type = "prime", labels = ["glm45air-swe"] } }
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
[orchestrator.prime_monitor]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, default (bash+edit) harness on prime ---
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
[orchestrator.eval]
interval = 20
@@ -102,7 +115,7 @@ skip_first_step = false
[[orchestrator.eval.env]]
name = "swebench-verified"
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
harness = { id = "default", runtime = { type = "prime", labels = ["glm45air-swe"] } }
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
timeout = { rollout = 3600 }
# --- Inference ---
+4 -1
View File
@@ -151,10 +151,11 @@ Training environments are an array of tables — set one per env, optionally wit
id = "math-env"
name = "gsm8k"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
ratio = 3 # 75% of batches
[[orchestrator.train.env]]
id = "reverse-text"
ratio = 0.25 # 25% of batches; remaining 75% goes to math-env
ratio = 1 # default — 25% of batches
[[orchestrator.eval.env]]
id = "math-env"
@@ -162,6 +163,8 @@ name = "gsm8k-eval"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
`args` is forwarded verbatim to the environment's `load_environment(**args)`.
The same `id` can appear multiple times across train and eval (or with different `args`) — useful for evaluating on a held-out split of the env you're training on, or comparing two configurations of the same env side by side. When `id` is reused, set a distinct `name` on each entry; `name` defaults to `id` and must be unique across all envs in the same group.
@@ -337,10 +337,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
]
class InferenceExperimentalConfig(BaseConfig):
pass
class InferenceConfig(BaseConfig):
server: ServerConfig = ServerConfig()
@@ -436,8 +432,6 @@ class InferenceConfig(BaseConfig):
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: InferenceExperimentalConfig = InferenceExperimentalConfig()
@model_validator(mode="after")
def validate_multi_node_requires_slurm(self):
if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None:
@@ -157,11 +157,8 @@ class EnvConfig(vf.EnvServerConfig):
address: str | None = None
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
ratio: float | None = Field(None, gt=0)
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
max_retries: int = Field(3, ge=0)
"""Times the env server retries a failed rollout before returning an error."""
ratio: float = Field(1.0, gt=0)
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
@model_validator(mode="before")
@classmethod
@@ -248,13 +245,10 @@ class TrainConfig(BaseConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling and max_retries (the
worker ``pool`` is configured per env, defaulting to elastic)."""
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
is configured per env, defaulting to elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
if "sampling" not in env.model_fields_set:
@@ -262,8 +256,6 @@ class TrainConfig(BaseConfig):
else:
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
env.sampling = TrainSamplingConfig(**merged)
if "max_retries" not in env.model_fields_set:
env.max_retries = self.max_retries
return self
@model_validator(mode="after")
@@ -276,15 +268,6 @@ class TrainConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_env_ratios(self):
ratios = [env.ratio for env in self.env]
if all(r is None for r in ratios):
return self
if any(r is None for r in ratios):
raise ValueError("Either all envs must have a ratio or none of them. Got a mix of set and unset ratios.")
return self
class EvalConfig(BaseConfig):
env: list[EvalEnvConfig] = Field(default_factory=list)
@@ -299,9 +282,6 @@ class EvalConfig(BaseConfig):
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
"""Default rollouts per example. Can be overridden per env."""
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
interval: int = Field(100, ge=1)
"""Step interval at which to evaluate the model."""
@@ -311,7 +291,7 @@ class EvalConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, max_retries, num_examples,
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
@@ -326,8 +306,6 @@ class EvalConfig(BaseConfig):
env.group_size = self.group_size
if "interval" not in env.model_fields_set:
env.interval = self.interval
if "max_retries" not in env.model_fields_set:
env.max_retries = self.max_retries
return self
@model_validator(mode="after")
@@ -443,10 +421,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
]
class OrchestratorExperimentalConfig(BaseConfig):
pass
class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
@@ -563,8 +537,6 @@ class OrchestratorConfig(BaseConfig):
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
experimental: OrchestratorExperimentalConfig = OrchestratorExperimentalConfig()
@model_validator(mode="before")
@classmethod
def _env_to_train(cls, data: Any) -> Any:
@@ -46,10 +46,6 @@ from prime_rl.utils.validation import (
)
class RLExperimentalConfig(BaseConfig):
pass
class SharedLogConfig(BaseConfig):
level: str | None = None
"""Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
@@ -234,8 +230,6 @@ class RLConfig(BaseConfig):
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: RLExperimentalConfig = RLExperimentalConfig()
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
@@ -167,10 +167,6 @@ SFTDeploymentConfig: TypeAlias = Annotated[
]
class SFTExperimentalConfig(BaseConfig):
pass
class SFTConfig(BaseConfig):
model: ModelConfig = ModelConfig()
@@ -226,7 +222,7 @@ class SFTConfig(BaseConfig):
trace_path: Path | None = None
"""Path to write the PyTorch profiler trace to."""
dist_timeout_seconds: int = 600
dist_timeout_seconds: int = 3600
"""Timeout in seconds for torch distributed ops."""
loss_impl: Literal["liger", "torch", "liger_fused", "quack_fused"] = "torch"
@@ -243,8 +239,6 @@ class SFTConfig(BaseConfig):
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: SFTExperimentalConfig = SFTExperimentalConfig()
### Pre-validation normalization
@model_validator(mode="before")
@@ -554,7 +554,7 @@ class TrainerConfig(BaseConfig):
trace_path: Path | None = None
"""Path to write the PyTorch profiler trace to."""
dist_timeout_seconds: int = 600
dist_timeout_seconds: int = 3600
"""Timeout in seconds for torch distributed ops."""
heartbeat: HeartbeatConfig | None = None
@@ -1,7 +1,6 @@
from pathlib import Path
from typing import Any
from pydantic import BaseModel
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
@@ -38,19 +37,3 @@ def rsetattr(obj: Any, attr_path: str, value: Any) -> None:
return setattr(obj, attr_path, value)
parent_path, attr = attr_path.rsplit(".", 1)
setattr(rgetattr(obj, parent_path), attr, value)
def get_all_fields(model: BaseModel | type) -> list[str]:
if isinstance(model, BaseModel):
model_cls = model.__class__
else:
model_cls = model
fields = []
for name, field in model_cls.model_fields.items():
field_type = field.annotation
fields.append(name)
if field_type is not None and hasattr(field_type, "model_fields"):
sub_fields = get_all_fields(field_type)
fields.extend(f"{name}.{sub}" for sub in sub_fields)
return fields
@@ -317,14 +317,11 @@ def validate_shared_weight_broadcast(
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
if (
inference
and trainer.weight_broadcast.type != orchestrator.weight_broadcast.type != inference.weight_broadcast.type
):
raise ValueError(
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
)
elif trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
if trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
raise ValueError(
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
)
if inference is not None and inference.weight_broadcast.type != trainer.weight_broadcast.type:
raise ValueError(
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and trainer/orchestrator weight broadcast type ({trainer.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for all components."
)
-15
View File
@@ -2,7 +2,6 @@ import logging.config
import os
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli
def setup_vllm_env(config: InferenceConfig):
@@ -41,17 +40,3 @@ def setup_vllm_env(config: InferenceConfig):
os.environ["VLLM_CONFIGURE_LOGGING"] = "1"
os.environ["VLLM_LOGGING_CONFIG_PATH"] = str(config_path)
logging.config.dictConfig(build_dict_config(config.log.level))
def main():
config = cli(InferenceConfig)
setup_vllm_env(config)
# We import here to be able to set environment variables before importing vLLM
from prime_rl.inference.vllm.server import server # pyright: ignore
server(config, vllm_extra=config.vllm_extra)
if __name__ == "__main__":
main()
-1
View File
@@ -150,7 +150,6 @@ async def custom_init_app_state(
"""
await init_app_state(engine_client, state, args, supported_tasks)
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
state.liveness_timeout_seconds = args.liveness_timeout_seconds
# Swap in our ServingTokens subclass for /inference/v1/generate so the
+3 -7
View File
@@ -1,7 +1,7 @@
"""TrainSource: weighted round-robin across train envs, infinite pull.
Weights default to configured ``ratio`` (when every env sets one) or to
per-env dataset size. ``next_example`` reshuffles on cursor exhaustion."""
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
per env). ``next_example`` reshuffles on cursor exhaustion."""
from __future__ import annotations
@@ -37,11 +37,7 @@ class TrainSource:
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
self.env_names = [e.name for e in self.envs]
configured_ratios = [e.config.ratio for e in self.envs]
if all(r is not None for r in configured_ratios):
self.weights: list[float] = [float(r) for r in configured_ratios] # type: ignore[arg-type]
else:
self.weights = [float(len(self.examples[name])) for name in self.env_names]
self.weights: list[float] = [float(e.config.ratio) for e in self.envs]
def next_example(self, available_permits: int) -> dict | None:
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
+7 -7
View File
@@ -75,12 +75,12 @@ def trace_to_samples(
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
the trainable (model-sampled) tokens, the context tokens between completions stay masked
out. On a rollout error the whole completion is masked out. A branch carrying images also
gets `mm_kwargs` (the concatenated pixel tensors) and `mm_token_type_ids` (the renderer's
`mm_token_type_id_map` applied to the branch tokens). Branches with no sampled tokens
(e.g. an openai client carrying none) yield nothing.
out. Errored rollouts are dropped upstream (`TrainSink.process_rollout`), so no error
handling happens here. A branch carrying images also gets `mm_kwargs` (the concatenated
pixel tensors) and `mm_token_type_ids` (the renderer's `mm_token_type_id_map` applied to
the branch tokens). Branches with no sampled tokens (e.g. an openai client carrying none)
yield nothing.
"""
has_error = trace.has_error
samples: list[TrainingSample] = []
for branch in trace.branches:
mask = branch.sampled_mask
@@ -97,7 +97,7 @@ def trace_to_samples(
samples.append(
TrainingSample(
token_ids=token_ids,
mask=[m and not has_error for m in mask],
mask=mask,
logprobs=branch.logprobs,
temperatures=[], # filled by TrainSink.process_group
env_name=env_name,
@@ -108,6 +108,6 @@ def trace_to_samples(
)
if not samples:
get_logger().warning(
f"No trainable samples (error={has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
f"No trainable samples (error={trace.has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
)
return samples
+2 -14
View File
@@ -8,7 +8,6 @@ from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import orjson
import verifiers.v1 as vf
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.utils.client import setup_inference_pool
@@ -51,14 +50,13 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
return renderer, inference_pool
def save_rollouts(rollouts: list[dict], path: Path, exclude_keys: set[str] | None = None) -> None:
def save_rollouts(rollouts: list[dict], path: Path) -> None:
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
path.parent.mkdir(parents=True, exist_ok=True)
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "wb") as f:
for rollout in rollouts:
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
f.write(orjson.dumps(row, default=str, option=opts))
f.write(orjson.dumps(rollout, default=str, option=opts))
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
@@ -94,16 +92,6 @@ def trim_process_memory() -> None:
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
def get_tool_response_len(trace: vf.Trace) -> int:
"""Total tool-response tokens consumed across the whole rollout, read from a
harness-emitted metric (e.g. RLM's `rlm_total_tool_response_tokens`, deduped
across turns/branches/sub-RLMs). Returns 0 when no such metric is present."""
for key, value in (trace.metrics or {}).items():
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
return int(value)
return 0
def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_timeout: int | None = None) -> Path:
"""Get the weight directory for a given checkpoint step.
+13
View File
@@ -0,0 +1,13 @@
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
"""Get the maximum number of layers in the model."""
max_num = -1
for key in state_dict:
if not key.startswith(layer_prefix):
continue
layer_num_str = key[len(layer_prefix) :].split(".")[0]
if layer_num_str.isdigit():
max_num = max(max_num, int(layer_num_str))
return max_num + 1
@@ -3,6 +3,8 @@ import re
import torch
from torch import Tensor
from prime_rl.trainer.conversion_utils import get_max_layer_num
def get_num_experts_from_state_dict(state_dict: dict[str, Tensor], layer_idx: int) -> int:
"""Get the number of experts from the HF state dict for a given layer."""
@@ -122,26 +124,15 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> Non
del state_dict[key]
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum layer number from the state dict."""
max_layer = -1
for key in state_dict.keys():
match = re.search(r"model\.layers\.(\d+)\.", key)
if match:
layer_idx = int(match.group(1))
max_layer = max(max_layer, layer_idx)
return max_layer
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]) -> None:
"""Convert all MoE layers from HF format to TT format in-place."""
max_layer = get_max_layer_num(state_dict)
for layer_idx in range(max_layer + 1):
num_layers = get_max_layer_num(state_dict)
for layer_idx in range(num_layers):
convert_hf_layer_to_tt(state_dict, layer_idx)
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]) -> None:
"""Convert all MoE layers from TT format to HF format in-place."""
max_layer = get_max_layer_num(state_dict)
for layer_idx in range(max_layer + 1):
num_layers = get_max_layer_num(state_dict)
for layer_idx in range(num_layers):
convert_tt_layer_to_hf(state_dict, layer_idx)
@@ -19,6 +19,11 @@ from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import (
flash_attn_3_varlen_func,
flash_attn_4_varlen_func,
flash_attn_varlen_func,
)
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.moe import MoE, MoEArgs
@@ -30,21 +35,6 @@ from prime_rl.trainer.models.layers.rotary_emb import (
)
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
try:
from flash_attn import flash_attn_varlen_func
except ImportError:
flash_attn_varlen_func = None # type: ignore
try:
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
except ImportError:
flash_attn_3_varlen_func = None # type: ignore
try:
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
except ImportError:
flash_attn_4_varlen_func = None # type: ignore
from .configuration_afmoe import AfmoeConfig
from .converting_afmoe import (
convert_hf_layer_to_tt,
@@ -1,10 +1,7 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
from prime_rl.trainer.conversion_utils import get_max_layer_num
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
@@ -1,13 +1,10 @@
import torch
from torch import Tensor
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
def _is_moe_layer(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
"""Check if a layer is an MoE layer by looking for the router gate weight."""
return f"model.layers.{layer_idx}.mlp.gate.weight" in state_dict
@@ -185,7 +185,6 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
"""
# 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_q, H, D = q.shape
S_k = k.shape[0]
device = q.device
@@ -15,10 +15,6 @@ def ceil_div(x: int, y: int) -> int:
return (x + y - 1) // y
def align(x: int, y: int) -> int:
return ceil_div(x, y) * y
# ---------------------------------------------------------------------------
# Layout building
# ---------------------------------------------------------------------------
@@ -1,9 +1,7 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
return max(int(key.split(".")[2]) for key in state_dict if key.startswith("model.layers.")) + 1
from prime_rl.trainer.conversion_utils import get_max_layer_num
def _pop_first(state_dict: dict[str, Tensor], keys: tuple[str, ...]) -> Tensor | None:
@@ -77,7 +77,6 @@ class BCFeedForward(nn.Module):
self.w3 = nn.Parameter(torch.empty(hidden_dim, dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
# return torch.matmul(self.w2, F.silu(torch.matmul(self.w1, x.T)) * torch.matmul(self.w3, x.T))
return torch.matmul(F.silu(torch.matmul(x, self.w1.T)) * torch.matmul(x, self.w3.T), self.w2.T)
def init_weights(self, init_std: float):
@@ -115,34 +115,3 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
q_embed = torch.cat([q_embed, q_pass], dim=-1)
k_embed = torch.cat([k_embed, k_pass], dim=-1)
return q_embed, k_embed
def apply_rotary_pos_emb_interleave(q, k, cos, sin, unsqueeze_dim=1):
"""Interleaved RoPE: converts from [r0, i0, r1, i1, ...] layout before applying rotation.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
b, h, s, d = q.shape
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
b, h, s, d = k.shape
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
@@ -1,10 +1,7 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
from prime_rl.trainer.conversion_utils import get_max_layer_num
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
@@ -1,10 +1,7 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
from prime_rl.trainer.conversion_utils import get_max_layer_num
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
@@ -16,6 +16,11 @@ from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, logging
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import (
flash_attn_3_varlen_func,
flash_attn_4_varlen_func,
flash_attn_varlen_func,
)
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 apply_rotary_pos_emb
@@ -30,22 +35,6 @@ from .converting_qwen3_5_moe import (
)
from .mrope import build_qwen3_5_mrope_position_ids
# Flash attention imports
try:
from flash_attn import flash_attn_varlen_func
except ImportError:
flash_attn_varlen_func = None # type: ignore
try:
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
except ImportError:
flash_attn_3_varlen_func = None # type: ignore
try:
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
except ImportError:
flash_attn_4_varlen_func = None # type: ignore
# Flash linear attention imports (for GatedDeltaNet fast path)
try:
from causal_conv1d import causal_conv1d_fn
@@ -1,10 +1,7 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
from prime_rl.trainer.conversion_utils import get_max_layer_num
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
@@ -242,88 +242,6 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
def load_balancing_loss_func(
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
num_experts: Optional[int] = None,
top_k=2,
attention_mask: Optional[torch.Tensor] = None,
) -> Union[torch.Tensor, int]:
r"""
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
experts is too unbalanced.
Args:
gate_logits:
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
shape [batch_size X sequence_length, num_experts].
num_experts:
Number of experts
top_k:
The number of experts to route per-token, can be also interpreted as the `top-k` routing
parameter.
attention_mask (`torch.Tensor`, *optional*):
The attention_mask used in forward function
shape [batch_size X sequence_length] if not None.
Returns:
The auxiliary loss.
"""
if gate_logits is None or not isinstance(gate_logits, tuple):
return 0
if isinstance(gate_logits, tuple):
compute_device = gate_logits[0].device
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
if attention_mask is None:
# Compute the percentage of tokens routed to each experts
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
# Compute the average probability of routing to these experts
router_prob_per_expert = torch.mean(routing_weights, dim=0)
else:
batch_size, sequence_length = attention_mask.shape
num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
expert_attention_mask = (
attention_mask[None, :, :, None, None]
.expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
.reshape(-1, top_k, num_experts)
.to(compute_device)
)
# Compute the percentage of tokens routed to each experts
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
expert_attention_mask, dim=0
)
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
router_per_expert_attention_mask = (
attention_mask[None, :, :, None]
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
.reshape(-1, num_experts)
.to(compute_device)
)
# Compute the average probability of routing to these experts
router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
router_per_expert_attention_mask, dim=0
)
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
return overall_loss * num_experts
@auto_docstring
class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
-20
View File
@@ -37,9 +37,6 @@ class PerfCounter:
self.gpu_peak_flops = self._get_peak_flops(torch.cuda.get_device_name(torch.device("cuda")))
else:
self.gpu_peak_flops = 0
# If not tie_word_embeddings, we exclude the embedding parameters from the total number of parameters
# If tie_word_embeddings, the embedding parameters are already excluded (shared with the LM head)
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) -> None:
@@ -209,23 +206,6 @@ class PerfCounter:
return flop_per_token
def _get_num_params(self, model: nn.Module, exclude_embedding: bool = False) -> int:
num_params = sum(p.numel() for p in model.parameters())
if exclude_embedding:
if hasattr(model.lm_head, "weight"):
num_params -= model.lm_head.weight.numel()
elif hasattr(model.lm_head, "base_layer"): # MultiLoRAModule
num_params -= model.lm_head.base_layer.weight.numel()
return num_params
def _count_trainable_params(self) -> int:
"""Count trainable parameters (LoRA adapters + modules_to_save)."""
trainable_params = 0
for param in self.model.parameters():
if param.requires_grad:
trainable_params += param.numel()
return trainable_params
def _count_lora_adapter_params(self) -> int:
"""Count LoRA adapter parameters (sum of lora_A and lora_B across all MultiLoRAModules)."""
params = 0
+2 -3
View File
@@ -11,19 +11,18 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.utils import get_world
from prime_rl.trainer.weights import get_max_layer_num
from prime_rl.utils.client import NCCL_READY_MARKER
from prime_rl.utils.logger import get_logger
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
from prime_rl.utils.pathing import sync_wait_for_path
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
from prime_rl.utils.vlm import get_layer_prefix
NCCL_READY_MARKER = "NCCL_READY"
def broadcast_integer(integer: int, communicator: PyNcclCommunicator) -> None:
"""Broadcast an integer to a process group using NCCL communicator."""
-3
View File
@@ -5,7 +5,6 @@ from typing import TypedDict
import torch
from jaxtyping import Bool, Float, Int
from torch import Tensor
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.configs.trainer import FakeDataLoaderConfig
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
@@ -183,7 +182,6 @@ class DataLoader:
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
bin_cost: Callable[[Sequence[int]], int],
config: TransportConfig,
):
@@ -193,7 +191,6 @@ class DataLoader:
self.packer: BasePacker = setup_packer(
dp_world_size=dp_world_size,
seq_len=seq_len,
tokenizer=tokenizer,
transport_config=config,
pad_to_multiple_of=pad_to_multiple_of,
bin_cost=bin_cost,
-14
View File
@@ -63,20 +63,6 @@ def compute_entropy(shifted_logits: Float[Tensor, "batch seq vocab"]) -> Float[T
return entropy
@jaxtyped(typechecker=typechecker)
def shift_logits(
logits: Float[Tensor, "batch seq vocab"], left_pad_logit: Float[Tensor, "batch 1 vocab"] | None = None
) -> Float[Tensor, "batch seq vocab"]:
"""Removes final token logits and adds a left pad logit for the first token."""
# We drop the last logit because it corresponds to the next token that will be sampled but is not here yet
batch, seq, vocab = logits.shape
logits = logits[:, :-1, :] # (batch, seq-1, vocab)
if left_pad_logit is None:
left_pad_logit = torch.zeros(batch, 1, vocab, device=logits.device, dtype=logits.dtype) # (batch, 1, vocab)
logits = torch.cat([left_pad_logit, logits], dim=1) # (batch, seq, vocab)
return logits
def shift_tensor_left(t: Float[Tensor, "batch seq"]) -> Float[Tensor, "batch seq"]:
"""Shifts the tensor one token to the left.
+4 -15
View File
@@ -6,8 +6,6 @@ from abc import ABC, abstractmethod
from collections import deque
from collections.abc import Callable, Sequence
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.batch import prepare_batch
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.transport import (
@@ -31,7 +29,6 @@ class BasePacker(ABC):
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
@@ -41,7 +38,6 @@ class BasePacker(ABC):
self.dp_world_size = dp_world_size
self.seq_len = seq_len
self.pad_to_multiple_of = pad_to_multiple_of
self.tokenizer = tokenizer
self.bin_cost = bin_cost
self.receiver = setup_training_batch_receiver(config)
shutil.rmtree(get_rollout_dir(self.multi_run_manager.output_dir), ignore_errors=True)
@@ -85,12 +81,11 @@ class SinglePacker(BasePacker):
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, config, bin_cost, start_step)
assert self.multi_run_manager.max_runs == 1, "SinglePacker only supports one run"
def pack(self):
@@ -132,12 +127,11 @@ class MultiPacker(BasePacker):
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, config, bin_cost, start_step)
# Per-run buffer: stores (TrainingSample, step) tuples
self.buffers: list[deque[tuple[TrainingSample, int]]] = [
deque() for _ in range(self.multi_run_manager.max_runs)
@@ -351,17 +345,12 @@ def setup_packer(
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
transport_config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
) -> BasePacker:
multi_run_manager = get_multi_run_manager()
if multi_run_manager.max_runs == 1:
return SinglePacker(
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
)
return SinglePacker(dp_world_size, seq_len, pad_to_multiple_of, transport_config, bin_cost, start_step)
else:
return MultiPacker(
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
)
return MultiPacker(dp_world_size, seq_len, pad_to_multiple_of, transport_config, bin_cost, start_step)
-1
View File
@@ -239,7 +239,6 @@ def train(config: TrainerConfig):
parallel_dims.get_mesh("dp").size(),
config.model.seq_len,
config.model.cp,
tokenizer,
build_bin_cost(model.config),
config.rollout_transport,
)
-52
View File
@@ -24,26 +24,6 @@ from prime_rl.trainer.lora import (
)
from prime_rl.utils.logger import get_logger
PYTORCH_WRAPPER_PREFIXES = ["_fsdp_wrapped_module.", "_orig_module.", "_checkpoint_wrapped_module."]
def _strip_pytorch_wrapper_prefix(key: str) -> str:
for prefix in PYTORCH_WRAPPER_PREFIXES:
key = key.replace(prefix, "")
return key
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
"""Get the maximum number of layers in the model."""
max_num = -1
for key in state_dict:
if not key.startswith(layer_prefix):
continue
layer_num_str = key[len(layer_prefix) :].split(".")[0]
if layer_num_str.isdigit():
max_num = max(max_num, int(layer_num_str))
return max_num + 1
def load_state_dict_keys(save_dir: Path) -> list[str]:
"""Load only the key names from safetensor files without reading tensor data."""
@@ -152,35 +132,3 @@ def gather_weights_on_master(
cpu_state = clean_lora_state_dict(cpu_state)
return cpu_state
def get_adapter_state_dict(model: nn.Module, is_master: bool) -> dict[str, Tensor]:
"""Get adapter weights with clean keys for PEFT compatibility."""
lora_state = {}
named_params = {_strip_pytorch_wrapper_prefix(key): value for key, value in model.named_parameters()}
for key, value in model.state_dict().items():
param = named_params.get(key)
if param is None or not param.requires_grad:
continue
if isinstance(value, DTensor):
value = value.full_tensor()
if is_master:
clean_key = next(iter(get_fqns(model, key)))
clean_key = clean_key.replace(".base_layer.", ".")
# Add PEFT-expected prefix
peft_key = f"base_model.model.{clean_key}"
# Add .weight suffix for LoRA parameters if missing
if ("lora_A" in peft_key or "lora_B" in peft_key) and not peft_key.endswith(".weight"):
peft_key = f"{peft_key}.weight"
lora_state[peft_key] = value.to("cpu", non_blocking=False)
torch.distributed.barrier()
if is_master and len(lora_state) == 0:
raise ValueError("The LoRA state dict is empty. Something went wrong.")
return lora_state
-8
View File
@@ -10,14 +10,6 @@ class IncrementalTokenizationError(ValueError):
pass
def common_prefix_len(a: list[int], b: list[int]) -> int:
max_len = min(len(a), len(b))
for idx in range(max_len):
if a[idx] != b[idx]:
return idx
return max_len
def normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
if messages is None:
return []
+6 -4
View File
@@ -407,8 +407,9 @@ async def update_weights(
weight update, then resumes. This ensures all DP workers are idle and can
participate in the collective weight transfer.
Note: The server-side /update_weights endpoint automatically resets the prefix cache
to invalidate any cached KV states computed with the old weights.
Note: the prefix cache is intentionally not reset on weight update. The orchestrator
salts the prefix cache per weight version (``cache_salt`` in the sampling request, see
``orchestrator/envs.py``), so KV computed under old weights is never reused.
"""
logger = get_logger()
@@ -470,8 +471,9 @@ LORA_LOAD_TOTAL_TIMEOUT_S = 120.0
async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lora_path: Path) -> None:
"""Make a HTTP post request to the vLLM server to load a LoRA adapter.
Uses our wrapper endpoint that also resets the prefix cache to invalidate
KV states computed with old weights.
Uses our wrapper around vLLM's /v1/load_lora_adapter. The prefix cache is not reset
here; the orchestrator salts it per weight version (see ``orchestrator/envs.py``) so
KV computed under old weights is never reused.
Retries with exponential backoff if the adapter files are not found,
which can happen due to NFS propagation delays.
-28
View File
@@ -155,34 +155,6 @@ def gather_for_cp_wo_grad(t: torch.Tensor, cp_world_size: int, cp_group: dist.Pr
return torch.cat(empty_like_t, dim=1)
def get_padding_logit_from_prev_cp_rank(
logits: torch.Tensor, cp_rank: int, cp_world_size: int, cp_group: dist.ProcessGroup
) -> torch.Tensor | None:
"""
Get the padding logit from the previous context parallel rank.
Args:
logits: The logits tensor.
cp_rank: The rank of the current process.
cp_world_size: The number of processes in the context parallel group.
cp_group: The context parallel group.
Returns:
The padding logit from the previous context parallel rank.
"""
last_logit = logits[:, -1, :].unsqueeze(1)
all_rank_last_logits = [
torch.zeros(1, 1, logits.shape[2], dtype=logits.dtype, device=logits.device) for _ in range(cp_world_size)
]
dist.all_gather(all_rank_last_logits, last_logit, group=cp_group)
prev_cp_rank = cp_rank - 1
if prev_cp_rank >= 0:
return all_rank_last_logits[prev_cp_rank]
else:
return None
def setup_cp_params(
input_ids: torch.Tensor,
position_ids: torch.Tensor,
+1 -1
View File
@@ -43,7 +43,7 @@ class Heartbeat:
Non-blocking guarantee: This method never blocks the training loop. The HTTP
request runs in a daemon thread, so even if the server is slow/unresponsive
(up to the 2s timeout), training continues uninterrupted. The lock is held only
(up to the 1s timeout), training continues uninterrupted. The lock is held only
briefly (microseconds) to check/set flags atomically.
"""
with self._lock:
-57
View File
@@ -1,57 +0,0 @@
import hashlib
import torch
from torch.distributed.tensor import DTensor
from torch.optim.optimizer import Optimizer
TENSOR_SIG_SAMPLE_SIZE = 1000
def get_tensor_signature(a: torch.Tensor | torch.nn.Parameter) -> str:
while isinstance(a, torch.nn.Parameter):
a = a.data
if isinstance(a, DTensor):
a = a.to_local()
if a.device == torch.device("meta"):
return f"{a.dtype}{a.shape}<meta>"
if a.numel() < TENSOR_SIG_SAMPLE_SIZE:
b = a.as_strided(size=(a.numel(),), stride=(1,))
else:
step_size = a.numel() // TENSOR_SIG_SAMPLE_SIZE
b = a.as_strided(size=(TENSOR_SIG_SAMPLE_SIZE,), stride=(step_size,))
element_str = "".join([f"{x:.3e}" for x in b])
element_hash = hashlib.md5(element_str.encode("utf-8")).hexdigest()
return f"{a.dtype}{a.shape}{a.stride()}<{element_hash}>"
def get_signature(state_dict, compress: bool = True) -> str:
if compress:
return hashlib.md5(str(state_dict).encode("utf-8")).hexdigest()
else:
return "\n".join(f"{name}: {sig}" for name, sig in state_dict.items())
def get_optimizer_signature(optimizer: Optimizer, compress: bool = True) -> str:
def unwrap_tensor(state_dict: dict) -> dict:
new_dict = {}
for key, value in state_dict.items():
if isinstance(value, dict):
new_dict[key] = unwrap_tensor(value)
elif isinstance(value, torch.Tensor):
new_dict[key] = get_tensor_signature(value)
else:
new_dict[key] = str(value)
return new_dict
state_dict_sig = unwrap_tensor(optimizer.state_dict())
return get_signature(state_dict_sig, compress)
def get_module_signature(module: torch.nn.Module, compress: bool = True) -> str:
param_sig = {name: get_tensor_signature(param) for name, param in module.named_parameters()}
buffer_sig = {name: get_tensor_signature(buffer) for name, buffer in module.named_buffers()}
state_dict_sig = {**param_sig, **buffer_sig}
return get_signature(state_dict_sig, compress)
-45
View File
@@ -39,11 +39,6 @@ def import_object(dotted_path: str) -> Any:
return getattr(module, name)
def capitalize(s: str) -> str:
"""Capitalize the first letter of a string."""
return s[0].upper() + s[1:]
def clean_exit(func: Callable) -> Callable:
"""
A decorator that ensures the a torch.distributed process group is properly
@@ -113,26 +108,6 @@ def to_col_format(list_of_dicts: list[dict[str, Any]]) -> dict[str, list[Any]]:
return dict(dict_of_lists)
def to_row_format(dict_of_lists: dict[str, list[Any]]) -> list[dict[str, Any]]:
"""
Turns a dict of lists to a list of dicts.
Example:
```python
dict_of_lists = {"a": [1, 3], "b": [2, 4]} # Column format
to_row_format(dict_of_lists)
```
Returns:
```python
[{"a": 1, "b": 2}, {"a": 3, "b": 4}] # Row format
```
"""
return [dict(zip(dict_of_lists.keys(), values)) for values in zip(*dict_of_lists.values())]
def format_time(time_s: float) -> str:
"""
Format a time in seconds to a human-readable format:
@@ -188,15 +163,6 @@ def get_free_port() -> int:
return port
def get_cuda_visible_devices() -> list[int]:
"""Returns the list of availble CUDA devices, taking into account the CUDA_VISIBLE_DEVICES environment variable."""
cuda_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
if cuda_visible is None:
# Default to all devices if the environment variable is not set
return list(range(torch.cuda.device_count()))
return list(sorted([int(device) for device in cuda_visible.split(",")]))
def get_latest_ckpt_step(weights_dir: Path) -> int | None:
step_dirs = list(weights_dir.glob("step_*"))
if len(step_dirs) == 0:
@@ -208,17 +174,6 @@ def get_latest_ckpt_step(weights_dir: Path) -> int | None:
return None
def mean(values: list[float] | list[int]) -> float:
"""Compute the mean of a list of values."""
return sum(values) / len(values) if values else 0.0
def mean_normalize(values: list[float] | list[int]) -> list[float]:
"""Mean-Normalize a list of values to 0-1."""
sum_values = sum(values)
return [value / sum_values if sum_values > 0 else 0.0 for value in values]
@contextmanager
def default_dtype(dtype):
prev = torch.get_default_dtype()
-1
View File
@@ -92,7 +92,6 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
dp_world_size=1,
seq_len=4,
pad_to_multiple_of=1,
tokenizer=None,
config=FileSystemTransportConfig(),
bin_cost=build_bin_cost(None),
start_step=0,