Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87766fda3c | ||
|
|
73c4736352 |
+62
-216
@@ -1,13 +1,9 @@
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
@@ -35,11 +31,10 @@ from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
cleanup_processes,
|
||||
cleanup_threads,
|
||||
get_physical_gpu_ids,
|
||||
monitor_process,
|
||||
ProcessGroup,
|
||||
partition_gpus,
|
||||
set_proc_title,
|
||||
torchrun_cmd,
|
||||
)
|
||||
|
||||
RL_CONFIG = "rl.json"
|
||||
@@ -141,25 +136,9 @@ def rl_local(config: RLConfig):
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Derive launcher-local GPU IDs from deployment config
|
||||
gpu_offset = 0
|
||||
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
|
||||
infer_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
|
||||
gpu_offset += num_infer_gpus
|
||||
trainer_local_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
|
||||
|
||||
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
|
||||
physical_gpu_ids = get_physical_gpu_ids()
|
||||
if total_requested_gpus > len(physical_gpu_ids):
|
||||
raise ValueError(
|
||||
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
|
||||
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
|
||||
)
|
||||
physical_gpu_mapping = {local_id: physical_gpu_ids[local_id] for local_id in range(total_requested_gpus)}
|
||||
logger.info(f"Using local->physical GPU mapping: {physical_gpu_mapping}")
|
||||
|
||||
infer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in infer_local_gpu_ids]
|
||||
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
|
||||
infer_gpu_ids, trainer_gpu_ids = partition_gpus(num_infer_gpus, config.deployment.num_train_gpus)
|
||||
logger.info(f"Using local->physical GPU mapping: {dict(enumerate(infer_gpu_ids + trainer_gpu_ids))}")
|
||||
|
||||
start_command = sys.argv
|
||||
logger.debug(f"RL start command: {' '.join(start_command)}")
|
||||
@@ -185,53 +164,22 @@ def rl_local(config: RLConfig):
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
|
||||
# Start processes
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
error_queue: list[Exception] = []
|
||||
stop_events: dict[str, Event] = {}
|
||||
|
||||
def sigterm_handler(signum, frame):
|
||||
logger.warning("Received SIGTERM, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
|
||||
try:
|
||||
# Optionally, start inference process
|
||||
with ProcessGroup() as processes:
|
||||
if config.inference:
|
||||
inference_cmd = ["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()]
|
||||
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
|
||||
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
|
||||
# If we don't log stdout, the server hangs
|
||||
with open(log_dir / "inference.log", "w") as log_file:
|
||||
inference_process = Popen(
|
||||
inference_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(inference_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["inference"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(inference_process, stop_event, error_queue, "inference"),
|
||||
daemon=True,
|
||||
processes.start(
|
||||
"inference",
|
||||
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_INFERENCE_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.inference.env_vars,
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
|
||||
},
|
||||
log_path=log_dir / "inference.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
else:
|
||||
logger.warning(
|
||||
"No [inference] block configured - the policy inference server will not be started here. "
|
||||
@@ -259,167 +207,65 @@ def rl_local(config: RLConfig):
|
||||
# orchestrator start in parallel.
|
||||
for split, source in env_servers(config):
|
||||
name = source.resolved_name
|
||||
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
|
||||
logger.info(f"Starting {name} server")
|
||||
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
|
||||
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
|
||||
env_server_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(env_server_log, "w") as log_file:
|
||||
env_server_process = Popen(
|
||||
env_server_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(env_server_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events[f"env/{split}/{name}"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(env_server_process, stop_event, error_queue, f"{split} env server {name}"),
|
||||
daemon=True,
|
||||
processes.start(
|
||||
f"{split} env server {name}",
|
||||
["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars, **config.orchestrator.env_vars},
|
||||
log_path=log_dir / ENVS_DIR / split / f"{name}.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
|
||||
logger.info("Starting orchestrator")
|
||||
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
|
||||
with open(log_dir / "orchestrator.log", "w") as log_file:
|
||||
orchestrator_process = Popen(
|
||||
orchestrator_cmd,
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "orchestrator",
|
||||
},
|
||||
)
|
||||
processes.append(orchestrator_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["orchestrator"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
|
||||
daemon=True,
|
||||
processes.start(
|
||||
"orchestrator",
|
||||
["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "orchestrator",
|
||||
},
|
||||
log_path=log_dir / "orchestrator.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Start training process
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
trainer_cmd = [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
# Pipe all logs to file, and only master rank logs to stdout
|
||||
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
|
||||
f"--local-ranks-filter={','.join(map(str, config.trainer.log.ranks_filter))}",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={len(trainer_gpu_ids)}",
|
||||
"-m",
|
||||
"prime_rl.trainer.rl.train",
|
||||
"@",
|
||||
(config_dir / TRAINER_CONFIG).as_posix(),
|
||||
]
|
||||
logger.info(f"Starting trainer on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
|
||||
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
|
||||
with open(log_dir / "trainer.log", "w") as log_file:
|
||||
trainer_process = Popen(
|
||||
trainer_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.trainer.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "trainer",
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(trainer_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events["trainer"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
|
||||
processes.start(
|
||||
"trainer",
|
||||
torchrun_cmd(
|
||||
"prime_rl.trainer.rl.train",
|
||||
config_dir / TRAINER_CONFIG,
|
||||
len(trainer_gpu_ids),
|
||||
log_dir,
|
||||
config.trainer.log.ranks_filter,
|
||||
),
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**DEFAULT_TRAINER_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
"WANDB_PROGRAM": "uv run rl",
|
||||
"WANDB_ARGS": json.dumps(start_command),
|
||||
**config.env_vars,
|
||||
**config.trainer.env_vars,
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "trainer",
|
||||
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
|
||||
},
|
||||
log_path=log_dir / "trainer.log",
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Trainer and orchestrator completion is the successful stop condition.
|
||||
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
|
||||
while not all(event.is_set() for event in completion_events):
|
||||
if error_queue:
|
||||
error = error_queue[0]
|
||||
logger.error(f"Error: {error}")
|
||||
logger.error("Terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
# Small delay to avoid busy waiting
|
||||
time.sleep(1)
|
||||
|
||||
# Check if any critical process failed
|
||||
if orchestrator_process.returncode != 0:
|
||||
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
if trainer_process.returncode != 0:
|
||||
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
processes.wait("trainer", "orchestrator")
|
||||
logger.success("Training finished!")
|
||||
|
||||
# Cleanup threads and processes
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.warning("Received interrupt signal, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Error occurred: {e}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
raise
|
||||
|
||||
|
||||
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
|
||||
+25
-101
@@ -1,12 +1,9 @@
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig, PrimeEvalMonitorConfig, TrainMonitorsConfig
|
||||
@@ -34,11 +31,10 @@ from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
DEFAULT_TRAINER_ENV_VARS,
|
||||
cleanup_processes,
|
||||
cleanup_threads,
|
||||
get_physical_gpu_ids,
|
||||
monitor_process,
|
||||
ProcessGroup,
|
||||
partition_gpus,
|
||||
set_proc_title,
|
||||
torchrun_cmd,
|
||||
)
|
||||
|
||||
SFT_CONFIG = "sft.json"
|
||||
@@ -333,21 +329,14 @@ def sft_local(config: SFTConfig):
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
|
||||
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
|
||||
# Partition GPUs (inference first, then the trainer) only when the launcher must split
|
||||
# them between processes; plain SFT leaves them to torchrun.
|
||||
infer_gpu_ids: list[int] = []
|
||||
trainer_gpu_ids: list[int] = []
|
||||
if config.inference is not None:
|
||||
num_infer_gpus = config.deployment.num_infer_gpus
|
||||
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
|
||||
physical_gpu_ids = get_physical_gpu_ids()
|
||||
if total_requested_gpus > len(physical_gpu_ids):
|
||||
raise ValueError(
|
||||
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
|
||||
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
|
||||
)
|
||||
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
|
||||
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
|
||||
infer_gpu_ids, trainer_gpu_ids = partition_gpus(
|
||||
config.deployment.num_infer_gpus, config.deployment.num_train_gpus
|
||||
)
|
||||
|
||||
# Trainer and online-eval log to a single shared W&B run whose id ($WANDB_RUN_ID)
|
||||
# equals $PRL_RUN_ID, one label per process.
|
||||
@@ -364,37 +353,11 @@ def sft_local(config: SFTConfig):
|
||||
"WANDB_ARGS": json.dumps(sys.argv),
|
||||
}
|
||||
|
||||
processes: list[Popen] = []
|
||||
monitor_threads: list[Thread] = []
|
||||
error_queue: list[Exception] = []
|
||||
stop_events: dict[str, Event] = {}
|
||||
|
||||
def sigterm_handler(signum, frame):
|
||||
logger.warning("Received SIGTERM, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
|
||||
def start_process(name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> Popen:
|
||||
logger.debug(f"{name.capitalize()} command: {' '.join(cmd)}")
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(log_path, "w") as log_file:
|
||||
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
|
||||
processes.append(process)
|
||||
stop_event = Event()
|
||||
stop_events[name] = stop_event
|
||||
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, error_queue, name), daemon=True)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
return process
|
||||
|
||||
try:
|
||||
with ProcessGroup() as processes:
|
||||
# Optionally, start the inference server for online evals
|
||||
if config.inference is not None:
|
||||
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
|
||||
start_process(
|
||||
processes.start(
|
||||
"inference",
|
||||
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
|
||||
env={
|
||||
@@ -413,7 +376,7 @@ def sft_local(config: SFTConfig):
|
||||
for source in eval_env_servers(config):
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting {name} server")
|
||||
start_process(
|
||||
processes.start(
|
||||
f"env/eval/{name}",
|
||||
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
|
||||
@@ -422,7 +385,7 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
if config.eval is not None:
|
||||
logger.info("Starting online evals")
|
||||
start_process(
|
||||
processes.start(
|
||||
"online-eval",
|
||||
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
|
||||
env={
|
||||
@@ -439,23 +402,6 @@ def sft_local(config: SFTConfig):
|
||||
log_path=log_dir / "eval.log",
|
||||
)
|
||||
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
trainer_cmd = [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
|
||||
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={config.deployment.num_train_gpus}",
|
||||
"-m",
|
||||
"prime_rl.trainer.sft.train",
|
||||
"@",
|
||||
config_path.as_posix(),
|
||||
]
|
||||
gpus_suffix = f" on GPU(s) {' '.join(map(str, trainer_gpu_ids))}" if trainer_gpu_ids else ""
|
||||
logger.info(f"Starting SFT trainer with {config.deployment.num_train_gpus} GPU(s){gpus_suffix}")
|
||||
trainer_env = {
|
||||
@@ -470,48 +416,26 @@ def sft_local(config: SFTConfig):
|
||||
trainer_env["WANDB_SHARED_LABEL"] = "trainer"
|
||||
if trainer_gpu_ids:
|
||||
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
|
||||
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
|
||||
processes.start(
|
||||
"trainer",
|
||||
torchrun_cmd(
|
||||
"prime_rl.trainer.sft.train",
|
||||
config_path,
|
||||
config.deployment.num_train_gpus,
|
||||
log_dir,
|
||||
config.log.ranks_filter,
|
||||
),
|
||||
env=trainer_env,
|
||||
log_path=log_dir / "trainer.log",
|
||||
)
|
||||
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Wait for the trainer (and the online-eval process, which drains its final evals
|
||||
# after the trainer's last checkpoint) while surfacing any process failure.
|
||||
terminal_events = [stop_events["trainer"]]
|
||||
if "online-eval" in stop_events:
|
||||
terminal_events.append(stop_events["online-eval"])
|
||||
while True:
|
||||
pending = [event for event in terminal_events if not event.is_set()]
|
||||
if error_queue:
|
||||
logger.error(f"Error: {error_queue[0]}")
|
||||
logger.error("Terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
if not pending:
|
||||
break
|
||||
pending[0].wait(timeout=1)
|
||||
|
||||
if trainer_process.returncode != 0:
|
||||
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
processes.wait("trainer", *(["online-eval"] if config.eval is not None else []))
|
||||
logger.success("SFT training finished!")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.warning("Received interrupt signal, terminating all processes...")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
logger.error(f"Error occurred: {e}")
|
||||
cleanup_threads(monitor_threads)
|
||||
cleanup_processes(processes)
|
||||
raise
|
||||
|
||||
|
||||
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from transformers import AutoConfig
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
|
||||
from prime_rl.orchestrator.batch import build_bin_cost, prepare_batch
|
||||
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
max_num = -1
|
||||
for key in state_dict:
|
||||
if not key.startswith(layer_prefix):
|
||||
continue
|
||||
layer_num_str = key[len(layer_prefix) :].split(".")[0]
|
||||
if layer_num_str.isdigit():
|
||||
max_num = max(max_num, int(layer_num_str))
|
||||
return max_num + 1
|
||||
@@ -11,7 +11,6 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
from vllm.distributed.utils import StatelessProcessGroup
|
||||
|
||||
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
from prime_rl.trainer.models import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.utils import get_world
|
||||
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
|
||||
@@ -21,6 +20,18 @@ from prime_rl.utils.vlm import get_layer_prefix
|
||||
from prime_rl.utils.weights import resolve_wire_dtype
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
max_num = -1
|
||||
for key in state_dict:
|
||||
if not key.startswith(layer_prefix):
|
||||
continue
|
||||
layer_num_str = key[len(layer_prefix) :].split(".")[0]
|
||||
if layer_num_str.isdigit():
|
||||
max_num = max(max_num, int(layer_num_str))
|
||||
return max_num + 1
|
||||
|
||||
|
||||
def broadcast_integer(integer: int, communicator: PyNcclCommunicator) -> None:
|
||||
"""Broadcast an integer to a process group using NCCL communicator."""
|
||||
integer_tensor = torch.tensor([integer], dtype=torch.long).cuda()
|
||||
|
||||
@@ -2,6 +2,9 @@ import contextlib
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
@@ -44,6 +47,41 @@ def get_physical_gpu_ids() -> list[int]:
|
||||
return [int(token.strip()) for token in raw_visible.split(",") if token.strip()]
|
||||
|
||||
|
||||
def partition_gpus(num_infer: int, num_train: int) -> tuple[list[int], list[int]]:
|
||||
"""Split the launcher's physical GPUs into inference GPUs followed by trainer GPUs."""
|
||||
physical_gpu_ids = get_physical_gpu_ids()
|
||||
if num_infer + num_train > len(physical_gpu_ids):
|
||||
raise ValueError(
|
||||
f"Requested {num_infer + num_train} GPUs via deployment settings, but only "
|
||||
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
|
||||
)
|
||||
return physical_gpu_ids[:num_infer], physical_gpu_ids[num_infer : num_infer + num_train]
|
||||
|
||||
|
||||
def torchrun_cmd(
|
||||
module: str, config_path: Path, nproc_per_node: int, log_dir: Path, ranks_filter: list[int]
|
||||
) -> list[str]:
|
||||
"""Single-node torchrun command for a trainer module."""
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
return [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
f"--rdzv-endpoint=localhost:{get_free_port()}",
|
||||
f"--rdzv-id={uuid.uuid4().hex}",
|
||||
# Pipe all logs to file, and only master rank logs to stdout
|
||||
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
|
||||
f"--local-ranks-filter={','.join(map(str, ranks_filter))}",
|
||||
"--redirect=3",
|
||||
"--tee=3",
|
||||
f"--nproc-per-node={nproc_per_node}",
|
||||
"-m",
|
||||
module,
|
||||
"@",
|
||||
config_path.as_posix(),
|
||||
]
|
||||
|
||||
|
||||
def set_proc_title(name: str) -> None:
|
||||
"""Set the process title for visibility in tools like ``ps`` and ``htop``.
|
||||
|
||||
@@ -103,3 +141,65 @@ def monitor_process(process: Popen, stop_event: Event, error_queue: list, proces
|
||||
err_msg += f"\n{process.stderr.read().decode('utf-8')}"
|
||||
error_queue.append(RuntimeError(err_msg))
|
||||
stop_event.set()
|
||||
|
||||
|
||||
class ProcessGroup:
|
||||
"""Launcher subprocesses, each logging to its own file and watched by a monitor thread.
|
||||
|
||||
As a context manager, SIGTERM, Ctrl-C, errors and normal exit all terminate every
|
||||
started process."""
|
||||
|
||||
def __init__(self):
|
||||
self.processes: list[Popen] = []
|
||||
self.monitor_threads: list[Thread] = []
|
||||
self.error_queue: list[Exception] = []
|
||||
self.stop_events: dict[str, Event] = {}
|
||||
|
||||
def __enter__(self) -> "ProcessGroup":
|
||||
signal.signal(signal.SIGTERM, self._sigterm_handler)
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb) -> None:
|
||||
if exc_type is KeyboardInterrupt:
|
||||
get_logger().warning("Received interrupt signal, terminating all processes...")
|
||||
elif isinstance(exc, Exception):
|
||||
get_logger().error(f"Error occurred: {exc}")
|
||||
self.cleanup()
|
||||
if exc_type is KeyboardInterrupt:
|
||||
sys.exit(1)
|
||||
|
||||
def _sigterm_handler(self, signum, frame):
|
||||
get_logger().warning("Received SIGTERM, terminating all processes...")
|
||||
# Clean up here too: a SIGTERM during __exit__'s cleanup would otherwise leave orphans.
|
||||
self.cleanup()
|
||||
sys.exit(1)
|
||||
|
||||
def cleanup(self) -> None:
|
||||
cleanup_threads(self.monitor_threads)
|
||||
cleanup_processes(self.processes)
|
||||
|
||||
def start(self, name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> None:
|
||||
get_logger().debug(f"{name[:1].upper() + name[1:]} command: {' '.join(cmd)}")
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# If we don't log stdout, the inference server hangs
|
||||
with open(log_path, "w") as log_file:
|
||||
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
|
||||
self.processes.append(process)
|
||||
stop_event = Event()
|
||||
self.stop_events[name] = stop_event
|
||||
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, self.error_queue, name), daemon=True)
|
||||
monitor_thread.start()
|
||||
self.monitor_threads.append(monitor_thread)
|
||||
|
||||
def wait(self, *names: str) -> None:
|
||||
"""Block until the named processes exit; exit with code 1 as soon as any started process fails."""
|
||||
events = [self.stop_events[name] for name in names]
|
||||
while True:
|
||||
pending = [event for event in events if not event.is_set()]
|
||||
if self.error_queue:
|
||||
get_logger().error(f"Error: {self.error_queue[0]}")
|
||||
get_logger().error("Terminating all processes...")
|
||||
sys.exit(1)
|
||||
if not pending:
|
||||
return
|
||||
pending[0].wait(timeout=1)
|
||||
|
||||
@@ -3,7 +3,13 @@ from types import SimpleNamespace
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from prime_rl.trainer.batch import _is_multimodal_sample, build_bin_cost, pad_micro_batch, prepare_batch, prepare_sample
|
||||
from prime_rl.orchestrator.batch import (
|
||||
_is_multimodal_sample,
|
||||
build_bin_cost,
|
||||
pad_micro_batch,
|
||||
prepare_batch,
|
||||
prepare_sample,
|
||||
)
|
||||
from prime_rl.transports.batch.types import MicroBatch, MMImageRef, MMRefs, RoutedExperts, TrainingSample
|
||||
|
||||
|
||||
|
||||
@@ -8,13 +8,14 @@ from torch import nn
|
||||
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.trainer.model import load_dcp_from_hf
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM, eager_reference
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM
|
||||
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
|
||||
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
|
||||
from prime_rl.trainer.models.layers import norms
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
from tests.unit.train.models import deepseek_v4_eager_reference as eager_reference
|
||||
|
||||
# Every layer is built through `DeepseekV4Attention.__init__`, which refuses to construct without
|
||||
# the kernel it would dispatch to, so the whole file needs tilelang even though nothing here calls it.
|
||||
|
||||
@@ -8,20 +8,21 @@ import torch
|
||||
from torch import nn
|
||||
from torch.utils._python_dispatch import TorchDispatchMode
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, eager_reference
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config
|
||||
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
|
||||
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
|
||||
from prime_rl.trainer.models.deepseek_v4.eager_reference import (
|
||||
apply_rotary_pos_emb_interleaved,
|
||||
dense_mask_from_indices,
|
||||
eager_attention_with_sinks,
|
||||
)
|
||||
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection, DeepseekV4UnweightedRMSNorm
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT, dsv4_mhc
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_rope import dsv4_q_norm_rope, dsv4_rope
|
||||
from prime_rl.utils.cp import CPContext
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
from tests.unit.train.models import deepseek_v4_eager_reference as eager_reference
|
||||
from tests.unit.train.models.deepseek_v4_eager_reference import (
|
||||
apply_rotary_pos_emb_interleaved,
|
||||
dense_mask_from_indices,
|
||||
eager_attention_with_sinks,
|
||||
)
|
||||
|
||||
try:
|
||||
import tilelang
|
||||
|
||||
Reference in New Issue
Block a user