Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1bbbf9231 | ||
|
|
f399e2664c | ||
|
|
0f236d322c | ||
|
|
f7192e15f3 | ||
|
|
bd110a10e9 | ||
|
|
d1c36af4b3 | ||
|
|
eba667d9c0 | ||
|
|
7e06730200 | ||
|
|
6c55a9aab2 |
+6
-1
@@ -2,6 +2,9 @@
|
||||
|
||||
Documenting changes which affect configuration usage patterns (added/moved/removed/renamed fields, notable logic changes).
|
||||
|
||||
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping_alpha` is set. Existing configs must delete this field. (2026-03-19)
|
||||
- **`orchestrator.advantage.length_shaping_alpha`**: Added Group Relative Reward Rescaling coefficient to the default advantage config. When set, applies length-based GR3 shaping during advantage computation and requires `orchestrator.buffer.online_difficulty_filtering = true` (default: `None`) (2026-03-18)
|
||||
- **`prime_monitor.log_extras.sample_ratio`**: Added ratio-based rollout sampling (0.0–1.0, default: None). When set, caps the number of rollouts logged per step to `len(rollouts) * sample_ratio`. `None` preserves current behavior (log all rollouts). Interacts with existing `interval` gate which still runs first. (2026-03-12)
|
||||
- **`client.connect_timeout`**: Added configurable TCP connect timeout for inference API requests (default: 30.0s). Previously hardcoded to 5.0s. Helps with vLLM or cluster flakiness (2026-03-11)
|
||||
- **`model.fused_lm_head_token_chunk_size`**: Added as the fused LM-head chunking field for the token-chunked implementation. Unlike the removed `model.fused_lm_head_chunk_size`, this chunks over flattened sequence tokens rather than vocabulary rows. `model.fused_lm_head_chunk_size` is no longer accepted; switch configs to `model.fused_lm_head_token_chunk_size` explicitly. (2026-03-09)
|
||||
- **`slurm.pre_run_command`**: Added optional shell command to run on the head node before starting the job. Useful for cleanup routines (e.g. killing stale processes, removing lock files). For all-nodes execution, wrap with `srun` in the command string (default: None) (2026-03-08)
|
||||
@@ -104,4 +107,6 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`inference.output_dir`**: Added directory for SLURM logs and generated scripts (default: `"outputs"`) (2026-02-26)
|
||||
- **`inference.dry_run`**: Added flag (default: `False`). When set, validates config, writes resolved config to `output_dir/configs/`, and exits without starting inference or submitting SLURM jobs (2026-02-26)
|
||||
- **`trainer.loss` (default loss)**: Made IPO (DPPO-Binary TV variant ([arxiv](https://arxiv.org/pdf/2602.04879)) + Kimi-K2.5 KL ([Kimi-K2.5](https://arxiv.org/pdf/2602.02276))) the default loss. Removed `ratio_type`, `token_mask_low`, `token_mask_high`, `sequence_clip_high`, `geo_mask_low`, `geo_mask_high`, `sequence_mask_low`, `sequence_mask_high`. Added `ipo_mask_low` (default: 0.2) and `ipo_mask_high` (default: 0.2) for token-level probability-difference masking. Changed `kl_tau` default from `0.0` to `1e-3`. (2026-03-02)
|
||||
- **Metrics logging overhaul**: All orchestrator metrics now follow a `{metric}/{scope}/{stat}` naming convention where scope is `all` (global) or an env name. Per-env breakdowns are always logged (previously only when >1 env). Key renames: `reward/mean` → `reward/all/mean`, `batch/solve_none` → `solve_none/all`, `val_reward/` → `val/reward/`, `metrics/{name}` → `metrics/{env}/{name}`, `stop_condition/{sc}` → `stop_condition/all/{sc}`, `error/mean` → `error/all/mean`. New per-env metrics: `solve_none/{env}`, `solve_all/{env}`, `effective_batch_size/{env}`, `stop_condition/{env}/generation_truncated`, `stop_condition/{env}/{sc}`, `error/{env}/mean`, plus per-env breakdowns for `seq_len`, `prefill_len`, `decode_len`, `is_truncated`, `samples_per_rollout`, `num_turns`, `generation_ms`, `scoring_ms`. Removed: `reward/std`, `reward/median`, per-error-type breakdown (`error/{error_type}`). Env name `"all"` is reserved and rejected at config validation. Env name validation now strips `@version` suffixes to match runtime behavior (e.g. `math@1.0` and `math@2.0` correctly detected as duplicates). Solve stats now use `example_id` grouping instead of index arithmetic (pre-existing bug fix). (2026-03-08)
|
||||
- **Metrics logging overhaul**: All orchestrator metrics now follow a `{metric}/{scope}/{stat}` naming convention where scope is `all` (global) or an env name. Per-env breakdowns are always logged (previously only when >1 env). Key renames: `reward/mean` → `reward/all/mean`, `batch/solve_none` → `solve_none/all`, `val_reward/` → `val/reward/`, `metrics/{name}` → `metrics/{env}/{name}`, `stop_condition/{sc}` → `stop_condition/all/{sc}`, `error/mean` → `error/all/mean`. New per-env metrics: `solve_none/{env}`, `solve_all/{env}`, `effective_batch_size/{env}`, `stop_condition/{env}/generation_truncated`, `stop_condition/{env}/{sc}`, `error/{env}/mean`, plus per-env breakdowns for `seq_len`, `prefill_len`, `decode_len`, `is_truncated`, `samples_per_rollout`, `num_turns`, `generation_ms`, `scoring_ms`. Removed: `reward/std`, `reward/median`, per-error-type breakdown (`error/{error_type}`). Env name `"all"` is reserved and rejected at config validation. Env name validation now strips `@version` suffixes to match runtime behavior (e.g. `math@1.0` and `math@2.0` correctly detected as duplicates). Solve stats now use `example_id` grouping instead of index arithmetic (pre-existing bug fix). (2026-03-08)
|
||||
- **`wandb.shared`** (experimental): Added shared W&B mode that logs trainer and orchestrator metrics to a single W&B run instead of two separate runs. Uses `wandb.Settings(mode="shared")` (requires wandb SDK >= 0.19.9). Enabled by default on the RL entrypoint. Disable with `--wandb.shared False`. Run ID is communicated via `WANDB_SHARED_RUN_ID` env var; process role via `WANDB_SHARED_LABEL`. Non-primary processes retry `wandb.init` up to 30 times waiting for the primary to create the run. Works with multi-node SLURM. (2026-03-18)
|
||||
- **`wandb.id`**: Removed from `WandbConfig`. Run IDs are now managed internally via env vars for shared mode. (2026-03-18)
|
||||
|
||||
+1
-1
@@ -102,7 +102,7 @@ override-dependencies = [
|
||||
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cu128" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "45fae8d" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "de2ed50" }
|
||||
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 = "5c1c72b" }
|
||||
|
||||
@@ -551,7 +551,10 @@ class DefaultAdvantageConfig(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["default"] = "default"
|
||||
length_weighted_mean: bool = False
|
||||
length_shaping_alpha: Annotated[
|
||||
float | None,
|
||||
Field(description="Penalty coefficient for Group Relative Reward Rescaling (GR³). Recommended value: 0.33"),
|
||||
] = None
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseModel):
|
||||
@@ -945,6 +948,13 @@ class OrchestratorConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_length_shaping_requires_online_difficulty_filtering(self):
|
||||
if isinstance(self.advantage, DefaultAdvantageConfig) and self.advantage.length_shaping_alpha is not None:
|
||||
if not self.buffer.online_difficulty_filtering:
|
||||
raise ValueError("Group Relative Reward (GR³) scaling requires online difficulty filtering")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench:
|
||||
|
||||
@@ -71,6 +71,20 @@ class SharedWandbConfig(BaseConfig):
|
||||
|
||||
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
|
||||
|
||||
shared: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Use shared W&B mode to log trainer and orchestrator metrics to a single run. "
|
||||
"Requires wandb SDK >= 0.19.9. Incompatible with offline mode.",
|
||||
),
|
||||
] = True
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_shared_not_offline(self):
|
||||
if self.shared and self.offline:
|
||||
raise ValueError("W&B shared mode requires server connectivity and is incompatible with offline mode")
|
||||
return self
|
||||
|
||||
|
||||
class SharedCheckpointConfig(BaseConfig):
|
||||
"""Configures shared checkpoint configs."""
|
||||
@@ -426,12 +440,15 @@ class RLConfig(BaseConfig):
|
||||
self.trainer.wandb.project = self.wandb.project
|
||||
self.orchestrator.wandb.project = self.wandb.project
|
||||
|
||||
# If specified, automatically use shared W&B name for orchestrator and trainer with suffixes
|
||||
if self.wandb.name:
|
||||
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
|
||||
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
|
||||
if self.wandb.shared:
|
||||
if self.wandb.name:
|
||||
self.trainer.wandb.name = self.wandb.name
|
||||
self.orchestrator.wandb.name = self.wandb.name
|
||||
else:
|
||||
if self.wandb.name:
|
||||
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
|
||||
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
|
||||
|
||||
# If specified, automatically use shared W&B offline mode for orchestrator and trainer
|
||||
if self.wandb.offline:
|
||||
self.trainer.wandb.offline = self.wandb.offline
|
||||
self.orchestrator.wandb.offline = self.wandb.offline
|
||||
|
||||
@@ -269,6 +269,18 @@ class LogExtrasConfig(BaseConfig):
|
||||
),
|
||||
] = 10
|
||||
|
||||
sample_ratio: Annotated[
|
||||
float | None,
|
||||
Field(
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Fraction of rollouts to log per step (0.0–1.0). "
|
||||
"When set, the effective sample cap is len(rollouts) * sample_ratio. "
|
||||
"1.0 = all rollouts, 0.5 = half, 0.0 = none. "
|
||||
"None (default) = log all rollouts (current behavior).",
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class WandbConfig(BaseConfig):
|
||||
"""Configures logging to Weights and Biases."""
|
||||
@@ -285,14 +297,6 @@ class WandbConfig(BaseConfig):
|
||||
|
||||
offline: Annotated[bool, Field(description="Whether to run W&B in offline mode.")] = False
|
||||
|
||||
# Individual configs (can only be specified on trainer or orchestrator)
|
||||
id: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The W&B run ID to log to. If None, a random ID will be generated. If you want to resume a run, you can set the ID to the run ID you want to resume.",
|
||||
),
|
||||
] = None
|
||||
|
||||
|
||||
class WandbWithExtrasConfig(WandbConfig):
|
||||
"""Configures logging to Weights and Biases with extras."""
|
||||
|
||||
@@ -474,6 +474,13 @@ class CheckpointConfig(BaseConfig):
|
||||
|
||||
weights: WeightCheckpointConfig | None = WeightCheckpointConfig()
|
||||
|
||||
weights_only: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="When true, only save weight checkpoints (no optimizer/scheduler state). Much faster and smaller than full checkpoints, but cannot resume training.",
|
||||
),
|
||||
] = False
|
||||
|
||||
resume_step: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
|
||||
@@ -132,6 +132,12 @@ def rl_local(config: RLConfig):
|
||||
logger.info("Starting RL run")
|
||||
logger.debug(f"RL start command: {' '.join(start_command)}")
|
||||
|
||||
# Build shared W&B env vars for subprocesses
|
||||
wandb_shared_env: dict[str, str] = {}
|
||||
if config.wandb and config.wandb.shared:
|
||||
wandb_shared_env["WANDB_SHARED_MODE"] = "1"
|
||||
wandb_shared_env["WANDB_SHARED_RUN_ID"] = uuid.uuid4().hex
|
||||
|
||||
# Check for existing processes on GPUs
|
||||
all_gpu_ids = list(set(infer_gpu_ids + trainer_gpu_ids + teacher_gpu_ids))
|
||||
check_gpus_available(all_gpu_ids)
|
||||
@@ -254,6 +260,8 @@ def rl_local(config: RLConfig):
|
||||
stderr=log_file,
|
||||
env={
|
||||
**os.environ,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "orchestrator",
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
@@ -300,6 +308,8 @@ def rl_local(config: RLConfig):
|
||||
trainer_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "trainer",
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
|
||||
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
@@ -401,6 +411,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
wandb_shared=config.wandb is not None and config.wandb.shared,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -33,16 +33,21 @@ Expected signature:
|
||||
"""
|
||||
|
||||
|
||||
def default_advantage_fn(inputs: AdvantageInputs, length_weighted_mean: bool = False) -> AdvantageOutputs:
|
||||
def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_shaping_alpha: float | None = None,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage: reward minus per-problem baseline."""
|
||||
if length_weighted_mean:
|
||||
baseline = (inputs.rewards * inputs.completion_lengths).sum(
|
||||
dim=1, keepdim=True
|
||||
) / inputs.completion_lengths.sum(dim=1, keepdim=True)
|
||||
else:
|
||||
baseline = inputs.rewards.mean(dim=1, keepdim=True)
|
||||
rewards = inputs.rewards
|
||||
|
||||
return AdvantageOutputs(advantages=inputs.rewards - baseline)
|
||||
if length_shaping_alpha is not None:
|
||||
completion_lengths = inputs.completion_lengths.to(dtype=rewards.dtype)
|
||||
lengths_normalized = completion_lengths / completion_lengths.mean(dim=1, keepdim=True)
|
||||
length_shaping = (1 + length_shaping_alpha * lengths_normalized) ** -1
|
||||
rewards = rewards * length_shaping
|
||||
baseline = rewards.mean(dim=1, keepdim=True)
|
||||
|
||||
return AdvantageOutputs(advantages=rewards - baseline)
|
||||
|
||||
|
||||
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
@@ -57,7 +62,10 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
return advantage_fn
|
||||
|
||||
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
|
||||
return default_advantage_fn(inputs, length_weighted_mean=config.length_weighted_mean)
|
||||
return default_advantage_fn(
|
||||
inputs,
|
||||
length_shaping_alpha=config.length_shaping_alpha,
|
||||
)
|
||||
|
||||
return advantage_fn
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import atexit
|
||||
import gc
|
||||
import multiprocessing as mp
|
||||
import random
|
||||
@@ -139,11 +140,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
config.model.name, trust_remote_code=config.model.trust_remote_code, use_fast=True
|
||||
)
|
||||
|
||||
# Build rollout filters
|
||||
rollout_filters = setup_filters(config.filters, vocab_size=tokenizer.vocab_size)
|
||||
if rollout_filters:
|
||||
logger.info(f"Initialized {len(rollout_filters)} rollout filter(s): {[f.name for f in rollout_filters]}")
|
||||
|
||||
# Setup monitor
|
||||
logger.info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
|
||||
monitor = setup_monitor(
|
||||
@@ -160,6 +156,11 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info("Initializing heartbeat")
|
||||
heart = Heartbeat(config.heartbeat.url)
|
||||
|
||||
# Build rollout filters
|
||||
rollout_filters = setup_filters(config.filters, vocab_size=tokenizer.vocab_size)
|
||||
if rollout_filters:
|
||||
logger.info(f"Initialized {len(rollout_filters)} rollout filter(s): {[f.name for f in rollout_filters]}")
|
||||
|
||||
# Load environment and extract dataset
|
||||
logger.info(
|
||||
f"Loading {len(config.env)} training environment(s) ({', '.join(env.name or env.id for env in config.env)})"
|
||||
@@ -193,6 +194,17 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
train_env_addresses = []
|
||||
env_processes: list[mp.Process] = []
|
||||
|
||||
def _cleanup_env_processes():
|
||||
for proc in env_processes:
|
||||
proc.terminate()
|
||||
proc.join(timeout=5)
|
||||
if proc.is_alive():
|
||||
proc.kill()
|
||||
proc.join(timeout=5)
|
||||
|
||||
atexit.register(_cleanup_env_processes)
|
||||
|
||||
for env_id, env, env_name in zip(env_ids, config.env, train_env_names):
|
||||
if env.address is None:
|
||||
address, process = spawn_env_server(
|
||||
@@ -782,9 +794,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
step=progress.step,
|
||||
)
|
||||
|
||||
# Flush all accumulated metrics for this step
|
||||
monitor.flush(step=progress.step)
|
||||
|
||||
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Reward: {results_df.reward.mean():.4f} |{f' Val. Reward: {val_results_df.reward.mean():.4f} |' if val_results_df is not None else ''} Throughput: {throughput:.1f} tokens/s | Seq. Length: {results_df.groupby('example_id').seq_len.mean().mean():.1f} tokens/sample | Async Level: {scheduler.async_level} | Max. Off-Policy Level: {scheduler.max_off_policy_level}"
|
||||
logger.success(step_message)
|
||||
|
||||
@@ -850,13 +859,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Cancel event loop lag monitor task
|
||||
event_loop_lag_monitor_task.cancel()
|
||||
|
||||
# Shutdown env processes
|
||||
for process in env_processes:
|
||||
process.terminate()
|
||||
process.join(timeout=5)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
process.join(timeout=5)
|
||||
# Shutdown env processes (also registered as atexit handler for crash safety)
|
||||
atexit.unregister(_cleanup_env_processes)
|
||||
_cleanup_env_processes()
|
||||
|
||||
logger.success("Orchestrator finished.")
|
||||
|
||||
|
||||
@@ -57,6 +57,11 @@ export CUDA_DEVICE_ORDER=PCI_BUS_ID
|
||||
export PYTHONUNBUFFERED=1
|
||||
export OMP_NUM_THREADS=1
|
||||
|
||||
{% if wandb_shared -%}
|
||||
export WANDB_SHARED_MODE=1
|
||||
export WANDB_SHARED_RUN_ID=$(python3 -c "import uuid; print(uuid.uuid4().hex)")
|
||||
{%- endif %}
|
||||
|
||||
# Networking
|
||||
HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
TRAIN_HOSTS=( ${HOSTNAMES[@]:$NUM_INFER_NODES:$SLURM_JOB_NUM_NODES} )
|
||||
@@ -155,7 +160,7 @@ else
|
||||
ORCHESTRATOR_ARGS="@ $CONFIG_DIR/orchestrator.toml"
|
||||
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --client.base-url $INFER_URLS"
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
{% endif %}{% if wandb_shared %}WANDB_SHARED_LABEL=orchestrator {% endif %}uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $OUTPUT_DIR/slurm/latest_orchestrator.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_orchestrator.log &
|
||||
fi
|
||||
{%- else %}
|
||||
@@ -169,7 +174,7 @@ else
|
||||
|
||||
echo $HOSTNAMES_STR | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
|
||||
|
||||
uv run torchrun \
|
||||
{% if wandb_shared %}WANDB_SHARED_LABEL=trainer {% endif %}uv run torchrun \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
|
||||
@@ -22,7 +22,7 @@ from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from transformers.utils.import_utils import is_flash_attn_3_available
|
||||
|
||||
from prime_rl.configs.trainer import ActivationCheckpointConfig, CompileConfig, ModelConfig, TokenizerConfig
|
||||
from prime_rl.trainer.lora import apply_lora_to_model, strip_lora_from_state_dict
|
||||
from prime_rl.trainer.lora import apply_lora_to_model, freeze_all_except_lora_and_specified, strip_lora_from_state_dict
|
||||
from prime_rl.trainer.models import (
|
||||
AutoModelForCausalLMPrimeRL,
|
||||
PreTrainedModelPrimeRL,
|
||||
@@ -758,6 +758,10 @@ def setup_model(
|
||||
|
||||
if parallel_dims.ep_enabled:
|
||||
apply_ep(model, parallel_dims)
|
||||
# EP replaces params with DTensors that default to requires_grad=True,
|
||||
# re-freeze base params that LoRA froze earlier.
|
||||
if config.lora is not None:
|
||||
freeze_all_except_lora_and_specified(model, config.lora)
|
||||
|
||||
# the right order is AC -> Compile -> FSDP
|
||||
if config.ac is not None:
|
||||
|
||||
@@ -3,6 +3,7 @@ import math
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
|
||||
from prime_rl.trainer.models.layers.lora.base import MultiLoRAModule, get_lora_num_tokens, get_multilora_scaling
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts
|
||||
@@ -285,6 +286,16 @@ class MultiLoRAGroupedExperts(MultiLoRAModule):
|
||||
detached_w3_lora_a = self.w3_lora_A[idx].detach()
|
||||
detached_w3_lora_b = self.w3_lora_B[idx].detach()
|
||||
|
||||
# With EP, LoRA weights are DTensors sharded across expert-parallel ranks.
|
||||
# Gather them before per-expert indexing.
|
||||
if isinstance(detached_w1_lora_a, DTensor):
|
||||
detached_w1_lora_a = detached_w1_lora_a.full_tensor()
|
||||
detached_w1_lora_b = detached_w1_lora_b.full_tensor()
|
||||
detached_w2_lora_a = detached_w2_lora_a.full_tensor()
|
||||
detached_w2_lora_b = detached_w2_lora_b.full_tensor()
|
||||
detached_w3_lora_a = detached_w3_lora_a.full_tensor()
|
||||
detached_w3_lora_b = detached_w3_lora_b.full_tensor()
|
||||
|
||||
# The clone is necessary to avoid views that cause giant memory spikes
|
||||
# TODO: There's probably a better way to do this
|
||||
for expert_id in range(self.num_experts):
|
||||
@@ -320,6 +331,39 @@ class MultiLoRAGroupedExperts(MultiLoRAModule):
|
||||
base_w2 = self.base_layer.w2 # [num_experts, dim, hidden_dim]
|
||||
base_w3 = self.base_layer.w3 # [num_experts, hidden_dim, dim]
|
||||
|
||||
# EP handling: mirror the @expert_parallel decorator — convert DTensors
|
||||
# to local shards and permute tokens by local expert with alignment padding.
|
||||
permuted_indices = None
|
||||
if isinstance(base_w1, DTensor):
|
||||
from torchtitan.distributed.expert_parallel import TOKEN_GROUP_ALIGN_SIZE_M
|
||||
from torchtitan.experiments.kernels.moe.indices import generate_permute_indices
|
||||
|
||||
base_w1 = base_w1.to_local()
|
||||
base_w2 = base_w2.to_local()
|
||||
base_w3 = base_w3.to_local()
|
||||
w1_lora_a = w1_lora_a.to_local()
|
||||
w1_lora_b = w1_lora_b.to_local()
|
||||
w2_lora_a = w2_lora_a.to_local()
|
||||
w2_lora_b = w2_lora_b.to_local()
|
||||
w3_lora_a = w3_lora_a.to_local()
|
||||
w3_lora_b = w3_lora_b.to_local()
|
||||
|
||||
experts_per_ep_rank = base_w1.shape[0]
|
||||
num_ep_ranks = num_tokens_per_expert.shape[0] // experts_per_ep_rank
|
||||
|
||||
with torch.no_grad():
|
||||
permuted_indices, num_tokens_per_expert, _ = generate_permute_indices(
|
||||
num_tokens_per_expert,
|
||||
experts_per_ep_rank,
|
||||
num_ep_ranks,
|
||||
x.shape[0] + experts_per_ep_rank * TOKEN_GROUP_ALIGN_SIZE_M,
|
||||
TOKEN_GROUP_ALIGN_SIZE_M,
|
||||
)
|
||||
|
||||
x = torch.vstack((x, x.new_zeros((x.shape[-1]))))
|
||||
input_shape = x.shape
|
||||
x = x[permuted_indices, :]
|
||||
|
||||
# Compute offsets for grouped_mm
|
||||
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
|
||||
|
||||
@@ -345,10 +389,9 @@ class MultiLoRAGroupedExperts(MultiLoRAModule):
|
||||
w2_lora_out = _run_lora_grouped_mm(lora_h, w2_lora_a, w2_lora_b, offsets)
|
||||
out = h2_base + scaling * w2_lora_out.bfloat16()
|
||||
|
||||
return out.type_as(x)
|
||||
out = out.type_as(x)
|
||||
else:
|
||||
# For-loop fallback for older GPUs
|
||||
return self._forward_for_loop(
|
||||
out = self._forward_for_loop(
|
||||
x,
|
||||
num_tokens_per_expert,
|
||||
w1_lora_a,
|
||||
@@ -363,6 +406,19 @@ class MultiLoRAGroupedExperts(MultiLoRAModule):
|
||||
scaling,
|
||||
)
|
||||
|
||||
# EP handling: unpermute output back to dispatched token order
|
||||
if permuted_indices is not None:
|
||||
# For-loop may produce fewer rows than permuted input (no padding rows),
|
||||
# pad to match before unpermuting
|
||||
if out.shape[0] < len(permuted_indices):
|
||||
num_padding = len(permuted_indices) - out.shape[0]
|
||||
out = torch.vstack((out, out.new_zeros((num_padding, out.shape[-1]))))
|
||||
out_unpermuted = out.new_zeros(input_shape)
|
||||
out_unpermuted[permuted_indices, :] = out
|
||||
out = out_unpermuted[:-1]
|
||||
|
||||
return out
|
||||
|
||||
def _forward_for_loop(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
|
||||
@@ -16,7 +16,7 @@ from prime_rl.trainer.ckpt import setup_ckpt_managers
|
||||
from prime_rl.trainer.multi_ckpt import setup_multi_checkpoint_manager
|
||||
from prime_rl.trainer.optim import setup_optimizer, setup_multi_optimizer
|
||||
from prime_rl.trainer.scheduler import setup_scheduler, setup_multi_scheduler
|
||||
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
|
||||
from prime_rl.utils.cp import (
|
||||
setup_cp_params,
|
||||
@@ -247,21 +247,23 @@ def train(config: TrainerConfig):
|
||||
and not (is_first_step or is_last_step)
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
# Single-run: Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
# Single-run: Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
# Maybe clean up old checkpoints
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Save weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
|
||||
# Maybe clean up old weight checkpoint
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
elif config.max_concurrent_runs > 1:
|
||||
# Multi-run: Save per-run checkpoints (each run has its own interval from orchestrator config)
|
||||
@@ -302,10 +304,7 @@ def train(config: TrainerConfig):
|
||||
seq_len = micro_batches[0]["input_ids"].shape[1]
|
||||
|
||||
# Normalize by the local number of unmasked tokens in the batch (per-batch length normalization)
|
||||
if isinstance(config.loss, DefaultLossConfig):
|
||||
loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
|
||||
else:
|
||||
loss_scale = batch_size
|
||||
loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
|
||||
loss_scale = max(loss_scale, 1)
|
||||
|
||||
logger.debug(f"Starting forward and backward pass ({batch_size=})")
|
||||
@@ -614,8 +613,9 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Write final checkpoint (only for single-run mode; multi-run checkpoints are managed by MultiCheckpointManager)
|
||||
if config.max_concurrent_runs == 1 and ckpt_manager is not None:
|
||||
logger.info("Writing final checkpoint")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
if not (config.ckpt and config.ckpt.weights_only):
|
||||
logger.info("Writing final checkpoint")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
if config.max_concurrent_runs == 1 and weight_ckpt_manager is not None:
|
||||
|
||||
@@ -173,6 +173,7 @@ def train(config: SFTConfig):
|
||||
cp_enabled = parallel_dims.cp_enabled
|
||||
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank() if cp_enabled else 0
|
||||
cp_group = parallel_dims.world_mesh["cp"].get_group() if cp_enabled else None
|
||||
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
|
||||
cp_size = parallel_dims.cp
|
||||
|
||||
ce_loss = None
|
||||
@@ -186,7 +187,8 @@ def train(config: SFTConfig):
|
||||
case _:
|
||||
raise ValueError(f"Invalid loss implementation: {config.loss_impl}")
|
||||
|
||||
def compute_loss(micro_batch: dict) -> torch.Tensor:
|
||||
def compute_loss(micro_batch: dict) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Forward pass returning (loss_sum, token_count) over unmasked tokens."""
|
||||
input_ids = micro_batch["input_ids"].to("cuda")
|
||||
position_ids = micro_batch["position_ids"].to("cuda")
|
||||
target_ids = micro_batch["target_ids"].to("cuda")
|
||||
@@ -197,69 +199,48 @@ def train(config: SFTConfig):
|
||||
target_ids = shard_for_cp(target_ids, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
loss_mask = shard_for_cp(loss_mask, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
|
||||
token_count = loss_mask.sum(dtype=torch.int64)
|
||||
|
||||
with maybe_activation_offloading(config.model.ac_offloading):
|
||||
if config.loss_impl == "liger_fused":
|
||||
masked_target_ids = target_ids.clone()
|
||||
masked_target_ids[~loss_mask] = FusedCrossEntropyOutputLinear.IGNORE_INDEX
|
||||
out = forward(model, input_ids, position_ids, labels=masked_target_ids)
|
||||
loss = out["loss"]
|
||||
loss_sum = out["loss"] * token_count
|
||||
else:
|
||||
out = forward(model, input_ids, position_ids)
|
||||
logits = out["logits"]
|
||||
B, L, V = logits.shape
|
||||
loss = ce_loss(logits.view(-1, V), target_ids.view(-1)).view(B, L)
|
||||
loss = loss[loss_mask].mean()
|
||||
token_loss = ce_loss(logits.view(-1, V), target_ids.view(-1)).view(B, L)
|
||||
loss_sum = token_loss[loss_mask].sum()
|
||||
del logits
|
||||
|
||||
del out
|
||||
return loss
|
||||
return loss_sum, token_count
|
||||
|
||||
maybe_record_function = nullcontext
|
||||
|
||||
def run_forward_loop(data_iter, num_steps=None, *, backward=True):
|
||||
total_loss = torch.tensor(0.0, device="cuda")
|
||||
def run_eval_loop(data_iter):
|
||||
"""Validation forward loop. Returns token-weighted global mean loss."""
|
||||
total_loss_sum = torch.tensor(0.0, device="cuda")
|
||||
total_token_count = torch.tensor(0, dtype=torch.int64, device="cuda")
|
||||
nan_count = torch.tensor(0, device="cuda")
|
||||
valid_steps = torch.tensor(0, device="cuda")
|
||||
max_vio_total = torch.tensor(0.0, device="cuda")
|
||||
divisor = num_steps or 1
|
||||
|
||||
ctx = nullcontext() if backward else torch.no_grad()
|
||||
with ctx:
|
||||
for step, micro_batch in enumerate(data_iter):
|
||||
if backward and config.log.log_data:
|
||||
input_ids_log = micro_batch["input_ids"].flatten().tolist()
|
||||
loss_mask_log = micro_batch["loss_mask"].flatten().tolist()
|
||||
print_sample(input_ids_log, loss_mask_log, tokenizer)
|
||||
|
||||
with maybe_record_function("forward"):
|
||||
loss = compute_loss(micro_batch)
|
||||
|
||||
if not torch.isnan(loss.detach()):
|
||||
total_loss += loss.detach()
|
||||
valid_steps += 1
|
||||
with torch.no_grad():
|
||||
for micro_batch in data_iter:
|
||||
loss_sum, token_count = compute_loss(micro_batch)
|
||||
if not torch.isnan(loss_sum.detach()):
|
||||
total_loss_sum += loss_sum.detach()
|
||||
total_token_count += token_count
|
||||
else:
|
||||
nan_count += 1
|
||||
|
||||
if backward:
|
||||
with maybe_record_function("backward"):
|
||||
(loss / divisor).backward()
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
max_vio = get_load_balance_stats(model)["max_vio"]
|
||||
if max_vio is not None:
|
||||
max_vio = max_vio.mean()
|
||||
dist.all_reduce(max_vio, op=dist.ReduceOp.MAX)
|
||||
max_vio_total += max_vio / divisor
|
||||
|
||||
if num_steps is not None and step + 1 >= num_steps:
|
||||
break
|
||||
|
||||
dist.all_reduce(total_loss, op=dist.ReduceOp.SUM)
|
||||
dist.all_reduce(valid_steps, op=dist.ReduceOp.SUM)
|
||||
dist.all_reduce(total_loss_sum, op=dist.ReduceOp.SUM, group=dp_cp_group)
|
||||
dist.all_reduce(total_token_count, op=dist.ReduceOp.SUM, group=dp_cp_group)
|
||||
dist.all_reduce(nan_count, op=dist.ReduceOp.SUM)
|
||||
|
||||
mean_loss = (total_loss / valid_steps).item() if valid_steps.item() > 0 else float("nan")
|
||||
return mean_loss, nan_count.item(), max_vio_total
|
||||
mean_loss = (total_loss_sum / total_token_count).item() if total_token_count.item() > 0 else float("nan")
|
||||
return mean_loss, nan_count.item()
|
||||
|
||||
def run_validation(step: int) -> None:
|
||||
val_dataset = setup_dataset(
|
||||
@@ -268,7 +249,7 @@ def train(config: SFTConfig):
|
||||
val_dataloader = setup_dataloader(val_dataset, config.val.data)
|
||||
|
||||
# No train/eval switch: no dropout in these models, and toggling would trigger torch.compile recompilation
|
||||
mean_loss, nan_count, _ = run_forward_loop(val_dataloader, backward=False)
|
||||
mean_loss, nan_count = run_eval_loop(val_dataloader)
|
||||
if nan_count > 0:
|
||||
logger.warning(f"Validation at step {step}: {nan_count} batches had NaN loss")
|
||||
if mean_loss != mean_loss:
|
||||
@@ -295,20 +276,23 @@ def train(config: SFTConfig):
|
||||
and not (is_first_step or is_last_step)
|
||||
and progress.step % config.ckpt.interval == 0
|
||||
):
|
||||
# Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
|
||||
save_ckpt_time = 0
|
||||
|
||||
if not config.ckpt.weights_only:
|
||||
# Save full checkpoint
|
||||
logger.info(f"Saving checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
|
||||
# Maybe clean up old checkpoints
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Save weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_ckpt_start_time = time.perf_counter()
|
||||
weight_ckpt_manager.save(progress.step, model, tokenizer)
|
||||
# Maybe clean up old weight checkpoint
|
||||
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
|
||||
weight_ckpt_manager.maybe_clean()
|
||||
else:
|
||||
save_ckpt_time = 0
|
||||
@@ -324,9 +308,56 @@ def train(config: SFTConfig):
|
||||
step_start_time = time.perf_counter()
|
||||
forward_backward_start_time = time.perf_counter()
|
||||
|
||||
batch_loss, nan_loss_count, batch_max_vio = run_forward_loop(dataiter, grad_accum_steps, backward=True)
|
||||
step_loss_sum = torch.tensor(0.0, device="cuda")
|
||||
step_local_token_count = torch.tensor(0, dtype=torch.int64, device="cuda")
|
||||
nan_loss_count = torch.tensor(0, device="cuda")
|
||||
batch_max_vio = torch.tensor(0.0, device="cuda")
|
||||
for micro_step in range(grad_accum_steps):
|
||||
micro_batch = next(dataiter)
|
||||
|
||||
if config.log.log_data:
|
||||
print_sample(
|
||||
micro_batch["input_ids"].flatten().tolist(), micro_batch["loss_mask"].flatten().tolist(), tokenizer
|
||||
)
|
||||
|
||||
with maybe_record_function("forward"):
|
||||
local_loss_sum, local_token_count = compute_loss(micro_batch)
|
||||
|
||||
step_local_token_count += local_token_count
|
||||
|
||||
if torch.isnan(local_loss_sum.detach()):
|
||||
nan_loss_count += 1
|
||||
logger.warning("Local loss is nan, excluding this micro step from backward")
|
||||
scaled_loss = torch.nan_to_num(local_loss_sum, nan=0.0) / grad_accum_steps
|
||||
else:
|
||||
step_loss_sum += local_loss_sum.detach()
|
||||
scaled_loss = local_loss_sum / grad_accum_steps
|
||||
|
||||
with maybe_record_function("backward"):
|
||||
scaled_loss.backward()
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
max_vio = get_load_balance_stats(model)["max_vio"]
|
||||
if max_vio is not None:
|
||||
max_vio = max_vio.mean()
|
||||
dist.all_reduce(max_vio, op=dist.ReduceOp.MAX)
|
||||
batch_max_vio += max_vio / grad_accum_steps
|
||||
|
||||
forward_backward_time = time.perf_counter() - forward_backward_start_time
|
||||
|
||||
# All-reduce token counts and rescale gradients to get a global token-weighted mean.
|
||||
# FSDP already divided grads by fsdp_gradient_divide_factor, so we undo that and
|
||||
# divide by the true global token count instead.
|
||||
global_step_token_count = step_local_token_count.clone()
|
||||
dist.all_reduce(global_step_token_count, op=dist.ReduceOp.SUM, group=dp_cp_group)
|
||||
global_token_count_val = global_step_token_count.item()
|
||||
|
||||
if global_token_count_val > 0:
|
||||
grad_scale = parallel_dims.fsdp_gradient_divide_factor * grad_accum_steps / global_token_count_val
|
||||
for param in model.parameters():
|
||||
if param.grad is not None:
|
||||
param.grad.mul_(grad_scale)
|
||||
|
||||
# Run validation after forward-backward (so torch.compile sees training graph first) but before
|
||||
# optimizer step (so eval_on_start evaluates untrained weights)
|
||||
if config.val is not None and (
|
||||
@@ -335,6 +366,15 @@ def train(config: SFTConfig):
|
||||
):
|
||||
run_validation(progress.step)
|
||||
|
||||
# Compute the global mean loss for logging.
|
||||
dist.all_reduce(step_loss_sum, op=dist.ReduceOp.SUM, group=dp_cp_group)
|
||||
dist.all_reduce(nan_loss_count, op=dist.ReduceOp.SUM)
|
||||
if global_token_count_val > 0:
|
||||
batch_loss = (step_loss_sum / global_token_count_val).item()
|
||||
else:
|
||||
batch_loss = 0.0
|
||||
nan_loss_count = nan_loss_count.item()
|
||||
|
||||
logger.debug(f"Clipping gradients with max norm {config.optim.max_norm}")
|
||||
grad_norm = clip_grad_norm_(
|
||||
model.parameters(), max_norm=config.optim.max_norm, ep_enabled=parallel_dims.ep_enabled
|
||||
@@ -457,8 +497,9 @@ def train(config: SFTConfig):
|
||||
|
||||
# Write final checkpoint
|
||||
if ckpt_manager is not None:
|
||||
logger.info("Writing final checkpoint")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
if not (config.ckpt and config.ckpt.weights_only):
|
||||
logger.info("Writing final checkpoint")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
# Write final weight checkpoint
|
||||
|
||||
@@ -12,7 +12,7 @@ class Monitor(ABC):
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -31,10 +31,6 @@ class Monitor(ABC):
|
||||
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
|
||||
pass
|
||||
|
||||
def flush(self, step: int) -> None:
|
||||
"""Commit all accumulated metrics for the given step."""
|
||||
pass
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close any resources held by the monitor. Override in subclasses that need cleanup."""
|
||||
pass
|
||||
@@ -46,7 +42,7 @@ class NoOpMonitor(Monitor):
|
||||
def __init__(self):
|
||||
self.history: list[dict[str, Any]] = []
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
self.history.append(metrics)
|
||||
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
|
||||
@@ -19,7 +19,7 @@ class MultiMonitor(Monitor):
|
||||
return []
|
||||
return self.monitors[0].history
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
monitor.log(metrics, step=step)
|
||||
@@ -54,13 +54,6 @@ class MultiMonitor(Monitor):
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to log distributions to {monitor.__class__.__name__}: {e}")
|
||||
|
||||
def flush(self, step: int) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
monitor.flush(step=step)
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to flush {monitor.__class__.__name__}: {e}")
|
||||
|
||||
def close(self) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
|
||||
@@ -2,6 +2,7 @@ import asyncio
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
@@ -117,7 +118,7 @@ class PrimeMonitor(Monitor):
|
||||
if config.log_extras.distributions:
|
||||
self.last_log_distributions_step = -1
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
self.history.append(metrics)
|
||||
if not self.is_master:
|
||||
return
|
||||
@@ -143,14 +144,22 @@ class PrimeMonitor(Monitor):
|
||||
or not self.config.log_extras.samples
|
||||
or step % self.config.log_extras.interval != 0
|
||||
):
|
||||
# Do not log samples if not enabled or not log interval step
|
||||
return
|
||||
|
||||
ratio = self.config.log_extras.sample_ratio
|
||||
if ratio is not None:
|
||||
if ratio <= 0.0:
|
||||
return
|
||||
if ratio < 1.0:
|
||||
max_samples = max(1, int(len(rollouts) * ratio))
|
||||
if len(rollouts) > max_samples:
|
||||
rollouts = random.sample(rollouts, max_samples)
|
||||
|
||||
assert self.last_log_samples_step <= step, "Step must be greater than last logged step"
|
||||
assert step not in self._pending_sample_steps, f"Step {step} upload already in progress"
|
||||
assert self.logger is not None, "Logger is required for sample logging"
|
||||
|
||||
self.logger.info(f"Logging samples to Prime Intellect API at step {step}")
|
||||
self.logger.info(f"Logging {len(rollouts)} samples to Prime Intellect API at step {step}")
|
||||
start_time = time.perf_counter()
|
||||
|
||||
parquet_bytes = self._rollouts_to_parquet_bytes(rollouts, step)
|
||||
|
||||
@@ -9,6 +9,7 @@ import pandas as pd
|
||||
import verifiers as vf
|
||||
import wandb
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from wandb.errors import CommError
|
||||
|
||||
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
@@ -34,6 +35,7 @@ class WandbMonitor(Monitor):
|
||||
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
|
||||
self.enabled = self.config is not None
|
||||
self.is_master = rank == 0
|
||||
|
||||
if not self.enabled or not self.is_master:
|
||||
if not self.is_master:
|
||||
self.logger.warning(f"Skipping {self.__class__.__name__} initialization from non-master rank ({rank})")
|
||||
@@ -42,15 +44,52 @@ class WandbMonitor(Monitor):
|
||||
assert config is not None
|
||||
self.logger.info(f"Initializing {self.__class__.__name__} ({config})")
|
||||
self._maybe_overwrite_wandb_command()
|
||||
self.wandb = wandb.init(
|
||||
project=config.project,
|
||||
name=config.name,
|
||||
id=config.id,
|
||||
dir=output_dir,
|
||||
resume="allow",
|
||||
config=run_config.model_dump() if run_config else None,
|
||||
mode="offline" if config.offline else None,
|
||||
)
|
||||
|
||||
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1"
|
||||
if shared_mode:
|
||||
run_id = os.environ.get("WANDB_SHARED_RUN_ID")
|
||||
label = os.environ.get("WANDB_SHARED_LABEL")
|
||||
primary = label == "orchestrator"
|
||||
settings = wandb.Settings(
|
||||
mode="shared",
|
||||
x_label=label,
|
||||
x_primary=primary,
|
||||
x_update_finish_state=primary,
|
||||
)
|
||||
self.logger.info(
|
||||
f"Using shared W&B mode ({label=}, {primary=}). "
|
||||
"This is an experimental feature. Disable with --wandb.shared False"
|
||||
)
|
||||
else:
|
||||
run_id = None
|
||||
primary = False
|
||||
settings = wandb.Settings(
|
||||
mode="offline" if config.offline else "online",
|
||||
)
|
||||
|
||||
def init_wandb(max_retries: int):
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
return wandb.init(
|
||||
id=run_id,
|
||||
project=config.project,
|
||||
name=config.name,
|
||||
dir=output_dir,
|
||||
config=run_config.model_dump() if run_config else None,
|
||||
settings=settings,
|
||||
)
|
||||
except CommError:
|
||||
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})"
|
||||
)
|
||||
time.sleep(10)
|
||||
|
||||
max_retries = 1 if not shared_mode or primary else 30
|
||||
self.wandb = init_wandb(max_retries)
|
||||
|
||||
wandb.define_metric("*", step_metric="step")
|
||||
|
||||
# Optionally, initialize sample logging attributes
|
||||
if config is not None and isinstance(config, WandbWithExtrasConfig) and config.log_extras:
|
||||
@@ -71,13 +110,13 @@ class WandbMonitor(Monitor):
|
||||
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
|
||||
sys.argv = json.loads(wandb_args)
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
self.history.append(metrics)
|
||||
if not self.is_master:
|
||||
return
|
||||
if not self.enabled:
|
||||
return
|
||||
wandb.log(metrics, step=step)
|
||||
wandb.log({**metrics, "step": step})
|
||||
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
"""Logs rollouts to W&B table."""
|
||||
@@ -122,7 +161,7 @@ class WandbMonitor(Monitor):
|
||||
self.samples_table.add_data(*sample.values())
|
||||
self.samples.append(sample)
|
||||
|
||||
wandb.log({"samples": self.samples_table}, step=step)
|
||||
wandb.log({"samples": self.samples_table, "step": step})
|
||||
self.last_log_samples_step = step
|
||||
self.logger.debug(f"Logged samples at step {step} to W&B table in {time.perf_counter() - start_time:.2f}s")
|
||||
|
||||
@@ -147,11 +186,6 @@ class WandbMonitor(Monitor):
|
||||
"""Log distributions (no-op for W&B)."""
|
||||
pass
|
||||
|
||||
def flush(self, step: int) -> None:
|
||||
if not self.is_master or not self.enabled:
|
||||
return
|
||||
wandb.log({}, step=step, commit=True)
|
||||
|
||||
def save_final_summary(self, filename: str = "final_summary.json") -> None:
|
||||
"""Save final summary to W&B table."""
|
||||
if not self.is_master or not self.enabled:
|
||||
|
||||
@@ -15,24 +15,24 @@ def test_default_advantage_fn_simple_mean():
|
||||
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]]),
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_weighted_mean=False)
|
||||
result = default_advantage_fn(inputs)
|
||||
|
||||
assert result.advantages.shape == (2, 3)
|
||||
# Check that mean is subtracted per row
|
||||
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
|
||||
|
||||
|
||||
def test_default_advantage_fn_length_weighted():
|
||||
def test_default_advantage_fn_gr3_length_shaping():
|
||||
inputs = AdvantageInputs(
|
||||
rewards=torch.tensor([[1.0, 0.5, 0.8]]),
|
||||
completion_lengths=torch.tensor([[10, 20, 10]]),
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_weighted_mean=True)
|
||||
|
||||
# Length-weighted mean: (1.0*10 + 0.5*20 + 0.8*10) / (10+20+10) = 28/40 = 0.7
|
||||
expected_baseline = 0.7
|
||||
expected = torch.tensor([[1.0 - expected_baseline, 0.5 - expected_baseline, 0.8 - expected_baseline]])
|
||||
result = default_advantage_fn(inputs, length_shaping_alpha=0.33)
|
||||
|
||||
expected = torch.tensor([[0.20915856, -0.25799648, 0.04883792]])
|
||||
assert torch.allclose(result.advantages, expected, atol=1e-6)
|
||||
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(1), atol=1e-6)
|
||||
|
||||
|
||||
def test_compute_advantages_with_config():
|
||||
|
||||
@@ -2593,7 +2593,7 @@ requires-dist = [
|
||||
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
|
||||
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=5c1c72b" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=45fae8d" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=de2ed50" },
|
||||
{ name = "vllm", specifier = ">=0.17.0" },
|
||||
{ name = "wandb", specifier = ">=0.24.2" },
|
||||
{ name = "wiki-search", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
|
||||
@@ -3840,8 +3840,8 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "verifiers"
|
||||
version = "0.1.11.dev1"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=45fae8d#45fae8dd7b44043672cc27ee75c0a2741f2d1b97" }
|
||||
version = "0.1.11"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=de2ed50#de2ed50f015ed1af0990b218de1df0853d9b3973" }
|
||||
dependencies = [
|
||||
{ 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')" },
|
||||
|
||||
Reference in New Issue
Block a user