Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9b2fb9afbe | ||
|
|
be9f9f8d83 | ||
|
|
51fcbae998 | ||
|
|
74a13f0ee2 | ||
|
|
051c8bac23 | ||
|
|
a7db21723e | ||
|
|
00a4752a49 |
@@ -103,3 +103,4 @@ 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)
|
||||
@@ -288,6 +288,18 @@ class EnvConfig(BaseConfig):
|
||||
),
|
||||
] = {}
|
||||
|
||||
@property
|
||||
def resolved_name(self) -> str:
|
||||
return self.name or self.id.split("@")[0]
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env_name(self):
|
||||
if self.resolved_name == "all":
|
||||
raise ValueError(
|
||||
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class EvalEnvConfig(EnvConfig):
|
||||
"""Configures an environment for evaluation."""
|
||||
@@ -382,6 +394,14 @@ class EvalConfig(BaseConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_env_names(self):
|
||||
env_names = [env.resolved_name for env in self.env]
|
||||
duplicates = [n for n in env_names if env_names.count(n) > 1]
|
||||
if duplicates:
|
||||
raise ValueError(f"Duplicate eval environment names: {set(duplicates)}. Each env must have a unique name.")
|
||||
return self
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
"""Configures checkpointing the orchestrator."""
|
||||
@@ -893,6 +913,14 @@ class OrchestratorConfig(BaseConfig):
|
||||
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_env_names(self):
|
||||
env_names = [env.resolved_name for env in self.env]
|
||||
duplicates = [n for n in env_names if env_names.count(n) > 1]
|
||||
if duplicates:
|
||||
raise ValueError(f"Duplicate environment names: {set(duplicates)}. Each env must have a unique name.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env_ratios(self):
|
||||
if self.buffer.env_ratios is not None:
|
||||
|
||||
@@ -75,6 +75,13 @@ class SharedWandbConfig(BaseConfig):
|
||||
class SharedCheckpointConfig(BaseConfig):
|
||||
"""Configures shared checkpoint configs."""
|
||||
|
||||
output_dir: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer output_dir.",
|
||||
),
|
||||
] = None
|
||||
|
||||
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
|
||||
|
||||
resume_step: Annotated[
|
||||
@@ -152,7 +159,13 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
type: Literal["multi_node"] = "multi_node"
|
||||
|
||||
num_train_nodes: Annotated[int, Field(description="Number of training nodes.")]
|
||||
num_infer_nodes: Annotated[int, Field(description="Number of inference nodes.")]
|
||||
num_infer_nodes: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=0,
|
||||
description="Number of inference nodes. Set to 0 to skip inference and orchestrator (requires fake data).",
|
||||
),
|
||||
]
|
||||
num_teacher_nodes: Annotated[int | None, Field(description="Number of teacher inference nodes.")] = None
|
||||
|
||||
nodes_per_fsdp_group: Annotated[
|
||||
@@ -291,8 +304,18 @@ class RLConfig(BaseConfig):
|
||||
if self.deployment.type == "multi_node":
|
||||
if self.slurm is None:
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
if not self.inference:
|
||||
raise ValueError("Must configure inference when using multi-node deployment.")
|
||||
if self.deployment.num_infer_nodes > 0 and not self.inference:
|
||||
raise ValueError("Must configure inference when using multi-node deployment with inference nodes.")
|
||||
if self.deployment.num_infer_nodes == 0 and self.inference:
|
||||
raise ValueError(
|
||||
"Cannot configure inference with num_infer_nodes = 0. "
|
||||
"Either set num_infer_nodes > 0 or remove the inference config."
|
||||
)
|
||||
if self.deployment.num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
|
||||
raise ValueError(
|
||||
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
|
||||
"since no orchestrator or inference server will be running."
|
||||
)
|
||||
return self
|
||||
|
||||
# TODO: fix this
|
||||
@@ -363,6 +386,10 @@ class RLConfig(BaseConfig):
|
||||
if self.orchestrator.ckpt is None:
|
||||
self.orchestrator.ckpt = OrchestratorCheckpointConfig()
|
||||
|
||||
# If specified, override checkpoint output directory
|
||||
if self.ckpt.output_dir is not None:
|
||||
self.trainer.ckpt.output_dir = self.ckpt.output_dir
|
||||
|
||||
# If specified, use the same ckpt interval
|
||||
if self.ckpt.interval is not None:
|
||||
self.trainer.ckpt.interval = self.ckpt.interval
|
||||
|
||||
@@ -457,6 +457,13 @@ class WeightCheckpointConfig(BaseConfig):
|
||||
class CheckpointConfig(BaseConfig):
|
||||
"""Configures checkpointing the full model, optimizer and training state for resuming training."""
|
||||
|
||||
output_dir: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer output_dir. Useful for writing large checkpoints to a separate storage volume.",
|
||||
),
|
||||
] = None
|
||||
|
||||
interval: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
|
||||
@@ -388,8 +388,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
)
|
||||
else:
|
||||
assert config.inference is not None
|
||||
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
config_dir=config_dir, # TODO: should prob have each subconfig path separately
|
||||
@@ -399,9 +397,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
num_infer_nodes=config.deployment.num_infer_nodes,
|
||||
num_teacher_nodes=config.deployment.num_teacher_nodes,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
inference_tp=config.inference.parallel.tp,
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port,
|
||||
inference_tp=config.inference.parallel.tp if config.inference else 1,
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
)
|
||||
|
||||
@@ -431,12 +429,11 @@ def rl_slurm(config: RLConfig):
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
slurm_log_dir = config.output_dir / "slurm"
|
||||
log_message = (
|
||||
f"Logs:\n"
|
||||
f" Trainer: tail -F {slurm_log_dir}/latest_train_node_rank_0.log\n"
|
||||
f" Orchestrator: tail -F {slurm_log_dir}/latest_orchestrator.log\n"
|
||||
f" Inference: tail -F {slurm_log_dir}/latest_infer_node_rank_0.log"
|
||||
)
|
||||
log_lines = [f" Trainer: tail -F {slurm_log_dir}/latest_train_node_rank_0.log"]
|
||||
if config.deployment.num_infer_nodes > 0:
|
||||
log_lines.append(f" Orchestrator: tail -F {slurm_log_dir}/latest_orchestrator.log")
|
||||
log_lines.append(f" Inference: tail -F {slurm_log_dir}/latest_infer_node_rank_0.log")
|
||||
log_message = "Logs:\n" + "\n".join(log_lines)
|
||||
|
||||
script_path = config.output_dir / RL_SBATCH
|
||||
write_slurm_script(config, config_dir, script_path)
|
||||
@@ -458,8 +455,11 @@ def rl_slurm(config: RLConfig):
|
||||
def rl(config: RLConfig):
|
||||
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
|
||||
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
|
||||
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
|
||||
ckpt_output_dir = config.ckpt.output_dir if config.ckpt else None
|
||||
validate_output_dir(config.output_dir, resuming=resuming, clean=clean, ckpt_output_dir=ckpt_output_dir)
|
||||
config.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
if ckpt_output_dir is not None:
|
||||
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if config.slurm is not None:
|
||||
rl_slurm(config)
|
||||
|
||||
@@ -9,6 +9,45 @@ def transformers_v5_compat():
|
||||
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
|
||||
Qwen3VLMoeTextConfig.tie_word_embeddings = False
|
||||
|
||||
_patch_qwen35_lora()
|
||||
|
||||
|
||||
def _patch_qwen35_lora():
|
||||
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
|
||||
|
||||
Qwen3.5's GDN layers use create_qkvz_proj with 4 output_sizes (q, k, v, z)
|
||||
but packed_modules_mapping only lists 2 entries, causing an IndexError
|
||||
during LoRA initialization.
|
||||
|
||||
Also generalizes MergedColumnParallelLinearWithLoRA.can_replace_layer
|
||||
to accept any number of packed modules (not just 2).
|
||||
|
||||
Upstream: https://github.com/vllm-project/vllm/issues/36372
|
||||
"""
|
||||
from vllm.lora.layers.column_parallel_linear import MergedColumnParallelLinearWithLoRA
|
||||
from vllm.model_executor.models.qwen3_5 import (
|
||||
Qwen3_5ForCausalLMBase,
|
||||
Qwen3_5ForConditionalGeneration,
|
||||
)
|
||||
|
||||
qkvz_fix = ["in_proj_q", "in_proj_k", "in_proj_v", "in_proj_z"]
|
||||
|
||||
Qwen3_5ForCausalLMBase.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
|
||||
Qwen3_5ForConditionalGeneration.packed_modules_mapping["in_proj_qkvz"] = qkvz_fix
|
||||
|
||||
from vllm.lora.layers.utils import _not_fully_sharded_can_replace
|
||||
|
||||
@classmethod
|
||||
@_not_fully_sharded_can_replace
|
||||
def can_replace_layer(cls, source_layer, lora_config, packed_modules_list, model_config=None):
|
||||
from vllm.model_executor.layers.linear import MergedColumnParallelLinear
|
||||
|
||||
return type(source_layer) is MergedColumnParallelLinear and len(packed_modules_list) == len(
|
||||
source_layer.output_sizes
|
||||
)
|
||||
|
||||
MergedColumnParallelLinearWithLoRA.can_replace_layer = can_replace_layer
|
||||
|
||||
|
||||
# Monkeypatch PrometheusStatLogger to avoid NotImplementedError for LoRA in DP mode
|
||||
def monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode():
|
||||
|
||||
@@ -594,6 +594,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
await val_task
|
||||
val_outputs = val_task.result()
|
||||
|
||||
step_time = time.perf_counter() - step_start_time
|
||||
|
||||
# Gather metrics in dataframes
|
||||
results_df = pd.DataFrame(
|
||||
{
|
||||
@@ -601,7 +603,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"task": [rollout["task"] for rollout in train_rollouts],
|
||||
"reward": [rollout["reward"] for rollout in train_rollouts],
|
||||
"is_truncated": [rollout["is_truncated"] for rollout in train_rollouts],
|
||||
"error": [rollout["error"] for rollout in train_rollouts],
|
||||
"stop_condition": [rollout.get("stop_condition") for rollout in train_rollouts],
|
||||
"seq_len": [get_seq_len(rollout) for rollout in train_rollouts],
|
||||
"prefill_len": rollout_prefill_lens,
|
||||
@@ -613,7 +614,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
}
|
||||
)
|
||||
|
||||
# Gather individual reward function metrics
|
||||
# Separate DataFrame for env reward function metrics to avoid column name collisions
|
||||
metrics_df = pd.DataFrame([rollout["metrics"] for rollout in train_rollouts])
|
||||
|
||||
val_results_df = (
|
||||
@@ -635,14 +636,17 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
progress.total_problems += num_unique_examples
|
||||
throughput = num_tokens / generate_completions_time
|
||||
|
||||
# Compute solve all and none tensors
|
||||
problem_indices = results_df.index // config.rollouts_per_example
|
||||
reward_sum_per_problem = results_df.groupby(problem_indices).reward.sum()
|
||||
solve_all = (reward_sum_per_problem == config.rollouts_per_example).mean()
|
||||
solve_none = (reward_sum_per_problem == 0).mean()
|
||||
effective_batch_size = 1 - solve_none - solve_all
|
||||
def compute_solve_rates(df):
|
||||
"""Compute solve_none, solve_all, effective_batch_size for a set of rollouts."""
|
||||
reward_per_problem = df.groupby("example_id").reward.sum()
|
||||
solve_none = (reward_per_problem == 0).mean()
|
||||
solve_all = (reward_per_problem == config.rollouts_per_example).mean()
|
||||
return solve_none, solve_all, 1 - solve_none - solve_all
|
||||
|
||||
step_time = time.perf_counter() - step_start_time
|
||||
# Group by example_id to average across rollouts within each problem
|
||||
by_example = results_df.groupby("example_id")
|
||||
|
||||
solve_none, solve_all, effective_batch_size = compute_solve_rates(results_df)
|
||||
to_log = {
|
||||
# Progress metrics
|
||||
"progress/tokens": num_tokens,
|
||||
@@ -655,65 +659,49 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"progress/total_problems": progress.total_problems,
|
||||
"progress/ckpt_step": ckpt_step, # Shared W&B axis
|
||||
# Sequence length metrics
|
||||
"seq_len/mean": results_df.groupby("example_id").seq_len.mean().mean(),
|
||||
"seq_len/max": results_df.groupby("example_id").seq_len.mean().max(),
|
||||
"seq_len/min": results_df.groupby("example_id").seq_len.mean().min(),
|
||||
"prefill_len/mean": results_df.groupby("example_id").prefill_len.mean().mean(),
|
||||
"prefill_len/max": results_df.groupby("example_id").prefill_len.mean().max(),
|
||||
"prefill_len/min": results_df.groupby("example_id").prefill_len.mean().min(),
|
||||
"decode_len/mean": results_df.groupby("example_id").decode_len.mean().mean(),
|
||||
"decode_len/max": results_df.groupby("example_id").decode_len.mean().max(),
|
||||
"decode_len/min": results_df.groupby("example_id").decode_len.mean().min(),
|
||||
"is_truncated/mean": results_df.groupby("example_id").is_truncated.mean().mean(),
|
||||
"is_truncated/max": results_df.groupby("example_id").is_truncated.mean().max(),
|
||||
"is_truncated/min": results_df.groupby("example_id").is_truncated.mean().min(),
|
||||
"stop_condition/generation_truncated": (
|
||||
"seq_len/all/mean": by_example.seq_len.mean().mean(),
|
||||
"seq_len/all/max": by_example.seq_len.mean().max(),
|
||||
"seq_len/all/min": by_example.seq_len.mean().min(),
|
||||
"prefill_len/all/mean": by_example.prefill_len.mean().mean(),
|
||||
"prefill_len/all/max": by_example.prefill_len.mean().max(),
|
||||
"prefill_len/all/min": by_example.prefill_len.mean().min(),
|
||||
"decode_len/all/mean": by_example.decode_len.mean().mean(),
|
||||
"decode_len/all/max": by_example.decode_len.mean().max(),
|
||||
"decode_len/all/min": by_example.decode_len.mean().min(),
|
||||
"is_truncated/all/mean": by_example.is_truncated.mean().mean(),
|
||||
"is_truncated/all/max": by_example.is_truncated.mean().max(),
|
||||
"is_truncated/all/min": by_example.is_truncated.mean().min(),
|
||||
"stop_condition/all/generation_truncated": (
|
||||
results_df.is_truncated & (results_df.stop_condition != "prompt_too_long")
|
||||
).mean(),
|
||||
# Log rate of each stop condition (e.g. max_turns, prompt_too_long, has_error)
|
||||
**{
|
||||
f"stop_condition/{sc}": rate
|
||||
f"stop_condition/all/{sc}": rate
|
||||
for sc, rate in results_df.stop_condition.dropna().value_counts(normalize=True).items()
|
||||
},
|
||||
# Seqs per rollout metrics
|
||||
"samples_per_rollout/mean": results_df.groupby("example_id").samples_per_rollout.mean().mean(),
|
||||
"samples_per_rollout/max": results_df.groupby("example_id").samples_per_rollout.mean().max(),
|
||||
"samples_per_rollout/min": results_df.groupby("example_id").samples_per_rollout.mean().min(),
|
||||
# Turn metrics
|
||||
"num_turns/mean": results_df.groupby("example_id").num_turns.mean().mean(),
|
||||
"num_turns/max": results_df.groupby("example_id").num_turns.mean().max(),
|
||||
"num_turns/min": results_df.groupby("example_id").num_turns.mean().min(),
|
||||
# Verifier timing metrics
|
||||
"generation_ms/mean": results_df.groupby("example_id").generation_ms.mean().mean(),
|
||||
"generation_ms/max": results_df.groupby("example_id").generation_ms.mean().max(),
|
||||
"generation_ms/min": results_df.groupby("example_id").generation_ms.mean().min(),
|
||||
"scoring_ms/mean": results_df.groupby("example_id").scoring_ms.mean().mean(),
|
||||
"scoring_ms/max": results_df.groupby("example_id").scoring_ms.mean().max(),
|
||||
"scoring_ms/min": results_df.groupby("example_id").scoring_ms.mean().min(),
|
||||
"samples_per_rollout/all/mean": by_example.samples_per_rollout.mean().mean(),
|
||||
"samples_per_rollout/all/max": by_example.samples_per_rollout.mean().max(),
|
||||
"samples_per_rollout/all/min": by_example.samples_per_rollout.mean().min(),
|
||||
"num_turns/all/mean": by_example.num_turns.mean().mean(),
|
||||
"num_turns/all/max": by_example.num_turns.mean().max(),
|
||||
"num_turns/all/min": by_example.num_turns.mean().min(),
|
||||
"generation_ms/all/mean": by_example.generation_ms.mean().mean(),
|
||||
"generation_ms/all/max": by_example.generation_ms.mean().max(),
|
||||
"generation_ms/all/min": by_example.generation_ms.mean().min(),
|
||||
"scoring_ms/all/mean": by_example.scoring_ms.mean().mean(),
|
||||
"scoring_ms/all/max": by_example.scoring_ms.mean().max(),
|
||||
"scoring_ms/all/min": by_example.scoring_ms.mean().min(),
|
||||
# Performance metrics
|
||||
"perf/throughput": throughput,
|
||||
# Train reward
|
||||
"reward/mean": results_df.reward.mean(),
|
||||
"reward/std": results_df.reward.std(),
|
||||
"reward/min": results_df.reward.min(),
|
||||
"reward/max": results_df.reward.max(),
|
||||
"reward/median": results_df.reward.median(),
|
||||
"reward/all/mean": by_example.reward.mean().mean(),
|
||||
"reward/all/max": by_example.reward.mean().max(),
|
||||
"reward/all/min": by_example.reward.mean().min(),
|
||||
"sampling/temperature": temperature,
|
||||
# Batch metrics
|
||||
"batch/solve_none": solve_none,
|
||||
"batch/solve_all": solve_all,
|
||||
"batch/effective_batch_size": effective_batch_size,
|
||||
# Error metrics
|
||||
"error/mean": (~results_df.error.isna()).mean(),
|
||||
**{
|
||||
f"error/{error}": error_rate
|
||||
for error, error_rate in results_df.error.dropna()
|
||||
.apply(lambda e: e.get("error") if isinstance(e, dict) else e)
|
||||
.value_counts(normalize=True)
|
||||
.items()
|
||||
},
|
||||
# Env metrics
|
||||
**{f"metrics/{metric}": metrics_df[metric].mean() for metric in metrics_df.columns},
|
||||
# Solve / batch metrics
|
||||
"solve_none/all": solve_none,
|
||||
"solve_all/all": solve_all,
|
||||
"effective_batch_size/all": effective_batch_size,
|
||||
**{f"batch/{env}": r for env, r in results_df.task.value_counts(normalize=True).items()},
|
||||
# Time metrics
|
||||
"time/step": step_time,
|
||||
"time/generate_completions": generate_completions_time,
|
||||
@@ -732,32 +720,51 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"step": progress.step,
|
||||
}
|
||||
|
||||
# If more than one env, add per-env metrics
|
||||
if results_df.task.nunique() > 1:
|
||||
per_env_reward = results_df.groupby("task").reward.mean().to_dict()
|
||||
to_log.update({f"reward/{env}": reward for env, reward in per_env_reward.items()})
|
||||
# Per-env metrics
|
||||
per_env_columns = [
|
||||
"seq_len",
|
||||
"prefill_len",
|
||||
"decode_len",
|
||||
"is_truncated",
|
||||
"samples_per_rollout",
|
||||
"num_turns",
|
||||
"generation_ms",
|
||||
"scoring_ms",
|
||||
]
|
||||
|
||||
per_env_ratio = results_df.task.value_counts(normalize=True).to_dict()
|
||||
to_log.update({f"batch/{env}": ratio for env, ratio in per_env_ratio.items()})
|
||||
for env, env_df in results_df.groupby("task"):
|
||||
env_by_example = env_df.groupby("example_id")
|
||||
for col in per_env_columns:
|
||||
to_log[f"{col}/{env}/mean"] = env_by_example[col].mean().mean()
|
||||
to_log[f"{col}/{env}/max"] = env_by_example[col].mean().max()
|
||||
to_log[f"{col}/{env}/min"] = env_by_example[col].mean().min()
|
||||
to_log[f"reward/{env}/mean"] = env_by_example.reward.mean().mean()
|
||||
to_log[f"reward/{env}/max"] = env_by_example.reward.mean().max()
|
||||
to_log[f"reward/{env}/min"] = env_by_example.reward.mean().min()
|
||||
solve_none, solve_all, effective_batch_size = compute_solve_rates(env_df)
|
||||
to_log[f"solve_none/{env}"] = solve_none
|
||||
to_log[f"solve_all/{env}"] = solve_all
|
||||
to_log[f"effective_batch_size/{env}"] = effective_batch_size
|
||||
to_log[f"stop_condition/{env}/generation_truncated"] = (
|
||||
env_df.is_truncated & (env_df.stop_condition != "prompt_too_long")
|
||||
).mean()
|
||||
for sc, rate in env_df.stop_condition.dropna().value_counts(normalize=True).items():
|
||||
to_log[f"stop_condition/{env}/{sc}"] = rate
|
||||
env_metrics_df = metrics_df.loc[env_df.index]
|
||||
for metric in metrics_df.columns:
|
||||
to_log[f"metrics/{env}/{metric}"] = env_metrics_df.groupby(env_df["example_id"])[metric].mean().mean()
|
||||
|
||||
# Optionally, add val metrics
|
||||
if val_results_df is not None:
|
||||
to_log.update(
|
||||
{
|
||||
"val_reward/mean": val_results_df.reward.mean(),
|
||||
"val_reward/std": val_results_df.reward.std(),
|
||||
"val_reward/min": val_results_df.reward.min(),
|
||||
"val_reward/max": val_results_df.reward.max(),
|
||||
"val_reward/median": val_results_df.reward.median(),
|
||||
}
|
||||
)
|
||||
|
||||
if val_results_df.task.nunique() > 1:
|
||||
per_env_reward = val_results_df.groupby("task").reward.mean().to_dict()
|
||||
to_log.update({f"val_reward/{env}": reward for env, reward in per_env_reward.items()})
|
||||
|
||||
per_env_ratio = val_results_df.task.value_counts(normalize=True).to_dict()
|
||||
to_log.update({f"val_batch/{env}": ratio for env, ratio in per_env_ratio.items()})
|
||||
val_by_example = val_results_df.groupby("example_id")
|
||||
to_log["val/reward/all/mean"] = val_by_example.reward.mean().mean()
|
||||
to_log["val/reward/all/max"] = val_by_example.reward.mean().max()
|
||||
to_log["val/reward/all/min"] = val_by_example.reward.mean().min()
|
||||
for env, env_df in val_results_df.groupby("task"):
|
||||
env_by_example = env_df.groupby("example_id")
|
||||
to_log[f"val/reward/{env}/mean"] = env_by_example.reward.mean().mean()
|
||||
to_log[f"val/reward/{env}/max"] = env_by_example.reward.mean().max()
|
||||
to_log[f"val/reward/{env}/min"] = env_by_example.reward.mean().min()
|
||||
|
||||
# Log metrics to monitor(s)
|
||||
monitor.log(to_log, step=progress.step)
|
||||
|
||||
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from typing import NamedTuple, cast
|
||||
|
||||
@@ -30,6 +30,7 @@ class InflightRolloutInfo(NamedTuple):
|
||||
|
||||
off_policy_steps: int
|
||||
client_config: vf.ClientConfig
|
||||
task: str
|
||||
group_id: int | None = None
|
||||
|
||||
|
||||
@@ -110,7 +111,8 @@ class Scheduler:
|
||||
self.update_weights_time, self.wait_for_ckpt_time = 0, 0
|
||||
self.update_policy_task: asyncio.Task | None = None
|
||||
self.cancelled_rollouts_count = 0
|
||||
self.empty_rollouts_count = 0
|
||||
self.empty_rollouts_by_task: dict[str, int] = defaultdict(int)
|
||||
self.errored_rollouts_by_task: dict[str, int] = defaultdict(int)
|
||||
self.last_batch_generation_time = 0.0
|
||||
|
||||
@property
|
||||
@@ -202,7 +204,7 @@ class Scheduler:
|
||||
)
|
||||
)
|
||||
self.inflight_requests[run_rollout_task] = InflightRolloutInfo(
|
||||
off_policy_steps=0, client_config=client_config, group_id=group_id
|
||||
off_policy_steps=0, client_config=client_config, task=group.example["task"], group_id=group_id
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -370,7 +372,30 @@ class Scheduler:
|
||||
group = self.groups.get(group_id)
|
||||
if group is None:
|
||||
continue
|
||||
group.completed_rollouts.append(finished_task.result())
|
||||
rollout = finished_task.result()
|
||||
|
||||
task = rollout_info.task
|
||||
should_reschedule = False
|
||||
if len(rollout["trajectory"]) == 0:
|
||||
self.empty_rollouts_by_task[task] += 1
|
||||
should_reschedule = True
|
||||
self.logger.warning(
|
||||
f"Empty trajectory in group {group_id} ({task}), re-scheduling "
|
||||
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete)"
|
||||
)
|
||||
if rollout["error"] is not None:
|
||||
self.errored_rollouts_by_task[task] += 1
|
||||
should_reschedule = True
|
||||
self.logger.warning(
|
||||
f"Rollout error in group {group_id} ({task}), re-scheduling "
|
||||
f"({len(group.completed_rollouts)}/{self.rollouts_per_example} complete): "
|
||||
f"{rollout['error']}"
|
||||
)
|
||||
if should_reschedule:
|
||||
group.rollouts_to_schedule += 1
|
||||
continue
|
||||
|
||||
group.completed_rollouts.append(rollout)
|
||||
if len(group.completed_rollouts) < self.rollouts_per_example:
|
||||
continue
|
||||
completed_rollouts = self.groups.pop(group_id).completed_rollouts
|
||||
@@ -388,14 +413,6 @@ class Scheduler:
|
||||
self.buffer.update(completed_rollouts)
|
||||
accepted_rollouts = self.buffer.sample_rollouts(n=self.rollouts_per_example)
|
||||
|
||||
empty_count = sum(1 for r in accepted_rollouts if len(r["trajectory"]) == 0)
|
||||
if empty_count > 0:
|
||||
self.logger.warning(
|
||||
f"Filtered {empty_count}/{len(accepted_rollouts)} rollouts with empty trajectories"
|
||||
)
|
||||
accepted_rollouts = [r for r in accepted_rollouts if len(r["trajectory"]) > 0]
|
||||
self.empty_rollouts_count += empty_count
|
||||
|
||||
batch_rollouts.extend(accepted_rollouts)
|
||||
progress_increment = self.get_batch_progress_increment(accepted_rollouts)
|
||||
batch_progress += progress_increment
|
||||
@@ -443,17 +460,30 @@ class Scheduler:
|
||||
metrics = {
|
||||
"time/wait_for_ckpt": self.wait_for_ckpt_time,
|
||||
"time/update_weights": self.update_weights_time,
|
||||
"batch/async_level": self.async_level,
|
||||
"batch/inflight_rollouts": self.inflight_rollout_count,
|
||||
"batch/inflight_samples": self.inflight_sample_count,
|
||||
"batch/off_policy_level/max": self.max_off_policy_level,
|
||||
"batch/off_policy_level/mean": self.mean_off_policy_level,
|
||||
"batch/off_policy_level/min": self.min_off_policy_level,
|
||||
"batch/cancelled_rollouts": self.cancelled_rollouts_count,
|
||||
"batch/empty_rollouts": self.empty_rollouts_count,
|
||||
"scheduler/async_level": self.async_level,
|
||||
"scheduler/inflight_rollouts": self.inflight_rollout_count,
|
||||
"scheduler/inflight_samples": self.inflight_sample_count,
|
||||
"scheduler/cancelled_rollouts": self.cancelled_rollouts_count,
|
||||
"empty_rollouts/all": sum(self.empty_rollouts_by_task.values()),
|
||||
"errored_rollouts/all": sum(self.errored_rollouts_by_task.values()),
|
||||
"off_policy_level/all/max": self.max_off_policy_level,
|
||||
"off_policy_level/all/mean": self.mean_off_policy_level,
|
||||
"off_policy_level/all/min": self.min_off_policy_level,
|
||||
}
|
||||
for task, count in self.empty_rollouts_by_task.items():
|
||||
metrics[f"empty_rollouts/{task}"] = count
|
||||
for task, count in self.errored_rollouts_by_task.items():
|
||||
metrics[f"errored_rollouts/{task}"] = count
|
||||
by_task: dict[str, list[int]] = {}
|
||||
for info in self.inflight_requests.values():
|
||||
by_task.setdefault(info.task, []).append(info.off_policy_steps)
|
||||
for task, steps in by_task.items():
|
||||
metrics[f"off_policy_level/{task}/max"] = max(steps)
|
||||
metrics[f"off_policy_level/{task}/mean"] = sum(steps) / len(steps)
|
||||
metrics[f"off_policy_level/{task}/min"] = min(steps)
|
||||
self.cancelled_rollouts_count = 0
|
||||
self.empty_rollouts_count = 0
|
||||
self.empty_rollouts_by_task.clear()
|
||||
self.errored_rollouts_by_task.clear()
|
||||
|
||||
# Add inference pool metrics (e.g. elastic pool server counts)
|
||||
metrics.update(self.inference_pool.get_metrics())
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
export NUM_TRAIN_NODES={{ num_train_nodes }}
|
||||
export NUM_INFER_NODES={{ num_infer_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
export INFERENCE_TP={{ inference_tp }}
|
||||
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
|
||||
export INFERENCE_DATA_PARALLEL_RPC_PORT={{ inference_data_parallel_rpc_port }}
|
||||
@@ -35,6 +36,7 @@ export USE_DISTRIBUTED_EP=0
|
||||
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ] && [ "$NUM_INFER_NODES" -gt 1 ]; then
|
||||
USE_DISTRIBUTED_EP=1
|
||||
fi
|
||||
{%- endif %}
|
||||
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
@@ -57,11 +59,13 @@ export OMP_NUM_THREADS=1
|
||||
|
||||
# Networking
|
||||
HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
|
||||
TRAIN_HOSTS=( ${HOSTNAMES[@]:$NUM_INFER_NODES:$SLURM_JOB_NUM_NODES} )
|
||||
export INFER_HEAD_HOST="${INFER_HOSTS[0]}"
|
||||
export HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
|
||||
export INFER_HEAD_HOST="${INFER_HOSTS[0]}"
|
||||
|
||||
INFER_URLS=""
|
||||
if [ "$USE_DISTRIBUTED_EP" -eq 1 ]; then
|
||||
INFER_URLS="http://${INFER_HEAD_HOST}:8000/v1"
|
||||
@@ -75,11 +79,13 @@ else
|
||||
done
|
||||
fi
|
||||
export INFER_URLS
|
||||
echo "HOSTNAMES=${HOSTNAMES[*]}"
|
||||
echo "TRAIN_HOSTS=${TRAIN_HOSTS[*]}"
|
||||
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
|
||||
echo "INFER_URLS=${INFER_URLS}"
|
||||
echo "USE_DISTRIBUTED_EP=${USE_DISTRIBUTED_EP}"
|
||||
{%- endif %}
|
||||
|
||||
echo "HOSTNAMES=${HOSTNAMES[*]}"
|
||||
echo "TRAIN_HOSTS=${TRAIN_HOSTS[*]}"
|
||||
|
||||
export MASTER_ADDR="${HOSTNAMES[$NUM_INFER_NODES]}"
|
||||
export MASTER_PORT=29500
|
||||
@@ -113,6 +119,7 @@ srun bash -c '
|
||||
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
|
||||
export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
|
||||
INFER_NODE_RANK=$SLURM_PROCID
|
||||
@@ -151,6 +158,9 @@ else
|
||||
{% 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 %}
|
||||
TRAIN_NODE_RANK=$SLURM_PROCID
|
||||
{%- endif %}
|
||||
|
||||
export HF_HUB_OFFLINE=1
|
||||
|
||||
@@ -172,5 +182,5 @@ else
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.toml \
|
||||
2>&1 | tee -a $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_train_node_rank_${TRAIN_NODE_RANK}.log
|
||||
fi
|
||||
{% if num_infer_nodes > 0 %} fi{% endif %}
|
||||
'
|
||||
|
||||
@@ -443,10 +443,11 @@ def setup_ckpt_managers(
|
||||
) -> tuple[CheckpointManager | None, WeightCheckpointManager | None]:
|
||||
if ckpt_config is None:
|
||||
return None, None
|
||||
ckpt_manager = CheckpointManager(output_dir, ckpt_config)
|
||||
ckpt_output_dir = ckpt_config.output_dir or output_dir
|
||||
ckpt_manager = CheckpointManager(ckpt_output_dir, ckpt_config)
|
||||
if ckpt_config.weights:
|
||||
weight_ckpt_manager = WeightCheckpointManager(
|
||||
output_dir,
|
||||
ckpt_output_dir,
|
||||
ckpt_config.weights,
|
||||
lora_config=lora_config,
|
||||
keep_last=ckpt_config.keep_last,
|
||||
|
||||
@@ -44,6 +44,7 @@ from prime_rl.trainer.utils import (
|
||||
MemoryProfiler,
|
||||
Tensors,
|
||||
export_benchmark_json,
|
||||
get_zero_gradient_ratio,
|
||||
get_ckpt_disk_metrics,
|
||||
setup_torch_distributed,
|
||||
print_benchmark,
|
||||
@@ -166,9 +167,13 @@ def train(config: TrainerConfig):
|
||||
|
||||
logger.info(f"Using `{config.scheduler.type}` scheduler ({config.scheduler})")
|
||||
|
||||
# Set up weight broadcast
|
||||
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
weight_broadcast = setup_weight_broadcast(config.output_dir, config.weight_broadcast, config.model.lora)
|
||||
# Set up weight broadcast (skip when using fake data since there's no inference server)
|
||||
if config.data.fake:
|
||||
weight_broadcast = None
|
||||
logger.info("Skipping weight broadcast setup (fake data mode)")
|
||||
else:
|
||||
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
weight_broadcast = setup_weight_broadcast(config.output_dir, config.weight_broadcast, config.model.lora)
|
||||
|
||||
if parallel_dims.cp_enabled:
|
||||
substitute_hf_flash_attn(parallel_dims.world_mesh["cp"].get_group(), heads_k_stride=1)
|
||||
@@ -217,21 +222,24 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Broadcast weights at every step, (except step 0, because no need to broadcast the base model)
|
||||
# Also, with NCCL broadcast, we do not broadcast weights the last async level step as the orchestrator is already finished and will not initialize the receive on the inference; for filesystem broadcast, we do "broadcast" until the final step to allow to resume from the broadcast directory
|
||||
last_async_level_steps = config.max_steps and progress.step >= config.max_steps - config.max_async_level
|
||||
if progress.step > 0 and (not last_async_level_steps or config.weight_broadcast.type == "filesystem"):
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
|
||||
ckpt_interval = config.ckpt and config.ckpt.interval
|
||||
interval_to_keep = ckpt_interval if config.weight_broadcast.type == "filesystem" else None
|
||||
if config.weight_broadcast.type == "filesystem":
|
||||
weight_broadcast.maybe_clean(config.max_async_level, interval_to_keep)
|
||||
else:
|
||||
if weight_broadcast is None:
|
||||
broadcast_weights_time = 0
|
||||
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
|
||||
for idx in multi_run_manager.used_idxs:
|
||||
multi_run_manager.ready_to_update[idx] = False
|
||||
else:
|
||||
last_async_level_steps = config.max_steps and progress.step >= config.max_steps - config.max_async_level
|
||||
if progress.step > 0 and (not last_async_level_steps or config.weight_broadcast.type == "filesystem"):
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
|
||||
ckpt_interval = config.ckpt and config.ckpt.interval
|
||||
interval_to_keep = ckpt_interval if config.weight_broadcast.type == "filesystem" else None
|
||||
if config.weight_broadcast.type == "filesystem":
|
||||
weight_broadcast.maybe_clean(config.max_async_level, interval_to_keep)
|
||||
else:
|
||||
broadcast_weights_time = 0
|
||||
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
|
||||
for idx in multi_run_manager.used_idxs:
|
||||
multi_run_manager.ready_to_update[idx] = False
|
||||
|
||||
if (
|
||||
ckpt_manager is not None
|
||||
@@ -460,6 +468,7 @@ def train(config: TrainerConfig):
|
||||
)
|
||||
if grad_norm.device.type == "cpu":
|
||||
grad_norm = grad_norm.to(torch.device("cuda"))
|
||||
zero_grad_ratio = get_zero_gradient_ratio(model.parameters(), parallel_dims.dp_replicate)
|
||||
|
||||
# Update the model parameters
|
||||
optimizer.step()
|
||||
@@ -516,6 +525,7 @@ def train(config: TrainerConfig):
|
||||
optim_metrics = {
|
||||
"optim/lr": current_lr,
|
||||
"optim/grad_norm": grad_norm.item(),
|
||||
"optim/zero_grad_ratio": zero_grad_ratio,
|
||||
"step": progress.step,
|
||||
}
|
||||
monitor.log(optim_metrics, step=progress.step)
|
||||
@@ -559,6 +569,7 @@ def train(config: TrainerConfig):
|
||||
mfu=mfu,
|
||||
entropy=tensor_stats.get("entropy/mean", 0.0),
|
||||
mismatch_kl=tensor_stats.get("mismatch_kl/mean", 0.0),
|
||||
zero_grad_ratio=zero_grad_ratio,
|
||||
)
|
||||
# Update run/LoRA metrics
|
||||
multi_run_manager = get_multi_run_manager()
|
||||
|
||||
@@ -33,6 +33,7 @@ from prime_rl.trainer.sft.data import load_sft_dataset, setup_dataloader, setup_
|
||||
from prime_rl.trainer.utils import (
|
||||
MemoryProfiler,
|
||||
export_benchmark_json,
|
||||
get_zero_gradient_ratio,
|
||||
get_ckpt_disk_metrics,
|
||||
print_sample,
|
||||
setup_torch_distributed,
|
||||
@@ -340,6 +341,7 @@ def train(config: SFTConfig):
|
||||
)
|
||||
if grad_norm.device.type == "cpu":
|
||||
grad_norm = grad_norm.to(torch.device("cuda"))
|
||||
zero_grad_ratio = get_zero_gradient_ratio(model.parameters(), parallel_dims.dp_replicate)
|
||||
|
||||
logger.debug("Optimizer step")
|
||||
optimizer.step()
|
||||
@@ -408,6 +410,7 @@ def train(config: SFTConfig):
|
||||
optim_metrics = {
|
||||
"optim/lr": current_lr,
|
||||
"optim/grad_norm": grad_norm.item(),
|
||||
"optim/zero_grad_ratio": zero_grad_ratio,
|
||||
"step": progress.step,
|
||||
}
|
||||
monitor.log(optim_metrics, step=progress.step)
|
||||
|
||||
@@ -3,6 +3,7 @@ import pickle
|
||||
import shutil
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -14,7 +15,8 @@ from rich import print as rich_print
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from rich.text import Text
|
||||
from torch import Tensor
|
||||
from torch import Tensor, nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.trainer.world import get_world
|
||||
@@ -25,6 +27,62 @@ from prime_rl.utils.utils import format_num, format_time, get_step_path
|
||||
DEFAULT_TIMEOUT = timedelta(seconds=600)
|
||||
|
||||
|
||||
def _to_local_tensor(tensor: Tensor | DTensor) -> Tensor:
|
||||
if isinstance(tensor, DTensor):
|
||||
return tensor.to_local()
|
||||
return tensor
|
||||
|
||||
|
||||
def count_zero_gradient_elements(parameters: Iterable[nn.Parameter]) -> tuple[Tensor, Tensor]:
|
||||
"""Count zero-gradient parameter elements on the local distributed shards.
|
||||
|
||||
Parameters that require gradients but did not receive one in the current step
|
||||
are counted as fully zero. This makes inactive MoE experts visible in the
|
||||
metric instead of silently dropping them from the count.
|
||||
"""
|
||||
|
||||
device = torch.device("cuda", torch.cuda.current_device()) if torch.cuda.is_available() else torch.device("cpu")
|
||||
num_zeros = torch.zeros((), dtype=torch.long, device=device)
|
||||
num_tracked = torch.zeros((), dtype=torch.long, device=device)
|
||||
|
||||
for param in parameters:
|
||||
if not param.requires_grad:
|
||||
continue
|
||||
|
||||
local_param = _to_local_tensor(param.detach())
|
||||
if local_param.numel() == 0:
|
||||
continue
|
||||
|
||||
if local_param.device != num_zeros.device:
|
||||
num_zeros = num_zeros.to(local_param.device)
|
||||
num_tracked = num_tracked.to(local_param.device)
|
||||
|
||||
local_numel = torch.tensor(local_param.numel(), dtype=torch.long, device=local_param.device)
|
||||
num_tracked += local_numel
|
||||
|
||||
if param.grad is None:
|
||||
num_zeros += local_numel
|
||||
continue
|
||||
|
||||
local_grad = _to_local_tensor(param.grad.detach())
|
||||
if local_grad.numel() != local_param.numel():
|
||||
raise ValueError("Local gradient shape does not match the local parameter shape")
|
||||
|
||||
num_zeros += local_numel - torch.count_nonzero(local_grad)
|
||||
|
||||
return num_zeros, num_tracked
|
||||
|
||||
|
||||
def get_zero_gradient_ratio(parameters: Iterable[nn.Parameter], dp_replicate: int = 1) -> float:
|
||||
num_zero_grad, num_grad_elements = count_zero_gradient_elements(parameters)
|
||||
dist.all_reduce(num_zero_grad, op=dist.ReduceOp.SUM)
|
||||
dist.all_reduce(num_grad_elements, op=dist.ReduceOp.SUM)
|
||||
if dp_replicate > 1:
|
||||
num_zero_grad = torch.div(num_zero_grad, dp_replicate, rounding_mode="floor")
|
||||
num_grad_elements = torch.div(num_grad_elements, dp_replicate, rounding_mode="floor")
|
||||
return (num_zero_grad.float() / num_grad_elements.clamp_min(1).float()).item()
|
||||
|
||||
|
||||
def get_ckpt_disk_metrics(output_dir: Path) -> dict[str, float]:
|
||||
"""
|
||||
Disk usage metrics for the checkpoint directory (<output_dir>/checkpoints).
|
||||
|
||||
@@ -115,6 +115,11 @@ class MetricsServer(HealthServer):
|
||||
"trainer_mismatch_kl", "KL divergence between trainer and inference model", registry=self._registry
|
||||
)
|
||||
self._kl_ent_ratio = Gauge("trainer_kl_ent_ratio", "Ratio of mismatch KL to entropy", registry=self._registry)
|
||||
self._zero_grad_ratio = Gauge(
|
||||
"trainer_zero_grad_ratio",
|
||||
"Fraction of tracked parameter elements with zero gradient",
|
||||
registry=self._registry,
|
||||
)
|
||||
# Aggregate run metrics
|
||||
self._runs_discovered = Gauge(
|
||||
"trainer_runs_discovered", "Number of run folders discovered", registry=self._registry
|
||||
@@ -196,6 +201,7 @@ class MetricsServer(HealthServer):
|
||||
mfu: float = 0.0,
|
||||
entropy: float = 0.0,
|
||||
mismatch_kl: float = 0.0,
|
||||
zero_grad_ratio: float = 0.0,
|
||||
) -> None:
|
||||
"""Update metrics after a training step."""
|
||||
self._step.set(step)
|
||||
@@ -207,6 +213,7 @@ class MetricsServer(HealthServer):
|
||||
self._mfu.set(mfu)
|
||||
self._entropy.set(entropy)
|
||||
self._mismatch_kl.set(mismatch_kl)
|
||||
self._zero_grad_ratio.set(zero_grad_ratio)
|
||||
if entropy > 0:
|
||||
self._kl_ent_ratio.set(mismatch_kl / entropy)
|
||||
self._last_step_ts.set(time.time())
|
||||
|
||||
@@ -69,29 +69,37 @@ def has_checkpoints(output_dir: Path) -> bool:
|
||||
return ckpt_dir.exists() and any(ckpt_dir.iterdir())
|
||||
|
||||
|
||||
def validate_output_dir(output_dir: Path, *, resuming: bool, clean: bool) -> None:
|
||||
def validate_output_dir(output_dir: Path, *, resuming: bool, clean: bool, ckpt_output_dir: Path | None = None) -> None:
|
||||
"""Validate the output directory before training starts.
|
||||
|
||||
Raises if the directory contains checkpoints from a previous run, unless
|
||||
explicitly resuming or opting into cleaning. Other artifacts (logs,
|
||||
rollouts, configs) are fine and don't trigger the error.
|
||||
|
||||
When ckpt_output_dir is set, checkpoints live there instead of under
|
||||
output_dir, so the guard and clean logic check both locations.
|
||||
"""
|
||||
if not output_dir.exists():
|
||||
return
|
||||
dirs_to_check = [output_dir]
|
||||
if ckpt_output_dir is not None and ckpt_output_dir != output_dir:
|
||||
dirs_to_check.append(ckpt_output_dir)
|
||||
|
||||
if resuming:
|
||||
return
|
||||
if clean:
|
||||
logger = get_logger()
|
||||
logger.warning(f"Cleaning existing output directory: {output_dir}")
|
||||
shutil.rmtree(output_dir)
|
||||
for d in dirs_to_check:
|
||||
if d.exists():
|
||||
logger.warning(f"Cleaning existing directory: {d}")
|
||||
shutil.rmtree(d)
|
||||
return
|
||||
if has_checkpoints(output_dir):
|
||||
raise FileExistsError(
|
||||
f"Output directory '{output_dir}' already contains checkpoints from a previous run. "
|
||||
f"To resume the latest step of the previous run, set ckpt.resume_step=-1 or --ckpt.resume-step -1 via CLI. "
|
||||
f"To delete the existing directory and start fresh, set clean_output_dir=true or --clean-output-dir via CLI. "
|
||||
f"Otherwise use a unique output_dir for this experiment."
|
||||
)
|
||||
for d in dirs_to_check:
|
||||
if has_checkpoints(d):
|
||||
raise FileExistsError(
|
||||
f"Directory '{d}' already contains checkpoints from a previous run. "
|
||||
f"To resume the latest step of the previous run, set ckpt.resume_step=-1 or --ckpt.resume-step -1 via CLI. "
|
||||
f"To delete the existing directory and start fresh, set clean_output_dir=true or --clean-output-dir via CLI. "
|
||||
f"Otherwise use a unique output_dir for this experiment."
|
||||
)
|
||||
|
||||
|
||||
def sync_wait_for_path(path: Path, interval: int = 1, log_interval: int = 10) -> None:
|
||||
|
||||
@@ -18,8 +18,8 @@ def test_update_off_policy_does_not_increment_interleaved_on_policy_tasks():
|
||||
interleaved_task = None
|
||||
|
||||
scheduler.inflight_requests = {
|
||||
stale_task: InflightRolloutInfo(off_policy_steps=1, client_config=client, group_id=1),
|
||||
survivor_task: InflightRolloutInfo(off_policy_steps=0, client_config=client, group_id=2),
|
||||
stale_task: InflightRolloutInfo(off_policy_steps=1, client_config=client, task="test", group_id=1),
|
||||
survivor_task: InflightRolloutInfo(off_policy_steps=0, client_config=client, task="test", group_id=2),
|
||||
}
|
||||
|
||||
async def drop_group(group_id: int) -> int:
|
||||
@@ -38,6 +38,7 @@ def test_update_off_policy_does_not_increment_interleaved_on_policy_tasks():
|
||||
scheduler.inflight_requests[interleaved_task] = InflightRolloutInfo(
|
||||
off_policy_steps=0,
|
||||
client_config=client,
|
||||
task="test",
|
||||
group_id=3,
|
||||
)
|
||||
return len(tasks_to_remove)
|
||||
|
||||
Reference in New Issue
Block a user