diff --git a/config.py b/config.py index 2d09bf8..123716d 100644 --- a/config.py +++ b/config.py @@ -592,6 +592,7 @@ class GlobalResourcePlannerConfig: runtime_rollout_log_dir: str = "" runtime_rollout_manifest_path: str = "" runtime_rollout_pid_registry_path: str = "" + runtime_reconfiguration_coord_dir: str = "" runtime_wait_rollout_process_start_ready: bool = False runtime_post_rollout_stop_grace_s: float = 0.0 runtime_reconfigure_training: bool = False @@ -618,6 +619,7 @@ class GlobalResourcePlannerConfig: hybrid_worker_command_template: str = "" hybrid_worker_task_dir: str = "./logs/elastic_training_tasks" hybrid_worker_ready_timeout_s: float = 60.0 + hybrid_worker_stop_timeout_s: float = 60.0 hybrid_worker_remote_control_enabled: bool = False hybrid_worker_remote_control_dir: str = "" elastic_hybrid_planning_enabled: bool = False diff --git a/configs/dapo_math_cmlfq_qwen3_4b.yaml b/configs/dapo_math_cmlfq_qwen3_4b.yaml index 5976f0f..437b275 100644 --- a/configs/dapo_math_cmlfq_qwen3_4b.yaml +++ b/configs/dapo_math_cmlfq_qwen3_4b.yaml @@ -2,7 +2,7 @@ base_config: base.yaml hardware_config: hardware_config/a800_80g.yaml -model_arch_config: model_arch_config/qwen2.5-3b.yaml +model_arch_config: model_arch_config/qwen3-4b.yaml model_path: "/path/to/Qwen3-4B" tokenizer_path: "/path/to/Qwen3-4B" diff --git a/configs/gsm8k_hetero.yaml b/configs/gsm8k_hetero.yaml deleted file mode 100644 index 12ae092..0000000 --- a/configs/gsm8k_hetero.yaml +++ /dev/null @@ -1,134 +0,0 @@ -# ============================================================ - -# - -# bash run_hetero_distributed.sh --config configs/gsm8k_hetero.yaml - -# - - - - -# - -# ============================================================ - - -base_config: base.yaml - - -hardware_config: hardware_config/a100_80g.yaml -model_arch_config: model_arch_config/qwen2.5-3b.yaml - - -model_path: "/path/to/Qwen3-4B" - - -train_gpus: 2 -tp_size: 1 - - - -rollout_gpus: 6 - - -dataset_name: "openai/gsm8k" -max_new_tokens: 2048 -max_seq_length: 4096 - - -wandb_project: "RL_Framework_gsm8k_hetero" -wandb_run_name: "gsm8k_hetero_rollout" - -# ============================================================ - -# - - - -# - -# Node 0: -# GPU 0,1 -> Training (FSDP, 2 GPU) - - -# Node 1: - - -# ============================================================ -heterogeneous_rollout: - enabled: true - - - total_gpus: 6 - # Node 0: GPU 2,3; Node 1: GPU 0,1,2,3 - available_gpus: [2, 3, 0, 1, 2, 3] - - - vllm_host: "0.0.0.0" - vllm_base_port: 8000 - startup_timeout: 300 - gpu_memory_utilization: 0.90 - max_model_len: 4096 - - - instances: - - instance_id: "tp1_inst0" - tp: 1 - gpus: [2] # Node 0, GPU 2 - node: 0 - description: "Node 0 TP=1 instance for short sequences" - - - instance_id: "tp1_inst1" - tp: 1 - gpus: [3] # Node 0, GPU 3 - node: 0 - description: "Node 0 TP=1 instance for short sequences" - - - instance_id: "tp2_inst0" - tp: 2 - gpus: [0, 1] # Node 1, GPU 0,1 - node: 1 - description: "Node 1 TP=2 instance for medium sequences" - - - instance_id: "tp2_inst1" - tp: 2 - gpus: [2, 3] # Node 1, GPU 2,3 - node: 1 - description: "Node 1 TP=2 instance for long sequences" - - - scheduling: - scheduler_type: "load_balance" - - length_thresholds: - short: 1024 # <= 1024 tokens -> short - medium: 2048 # 1025-2048 tokens -> medium - long: 4096 # 2049-4096 tokens -> long - # > 4096 tokens -> extra_long - - - routing_rules: - short: [1] - medium: [1, 2] - long: [2] - extra_long: [2] - - - load_balance_strategy: "least_connections" - - - max_queue_length: 64 - - - enable_fallback: true - - - adaptive_routing: true - - - request_timeout: 600 - - -max_concurrent_rollouts: 32 -max_head_offpolicyness: 4 diff --git a/configs/gsm8k_hetero_4gpu.yaml b/configs/gsm8k_hetero_4gpu.yaml deleted file mode 100644 index 0971c3c..0000000 --- a/configs/gsm8k_hetero_4gpu.yaml +++ /dev/null @@ -1,115 +0,0 @@ -# ============================================================ - -# - -# bash scripts/run_hetero_distributed_4GPU.sh --config configs/gsm8k_hetero_4gpu.yaml - -# - - - - -# - -# ============================================================ - - -base_config: base.yaml - - -hardware_config: hardware_config/a100_80g.yaml -model_arch_config: model_arch_config/qwen2.5-3b.yaml - - -model_path: "/path/to/Qwen3-4B" - - -train_gpus: 2 -tp_size: 1 - - - -rollout_gpus: 2 - - -dataset_name: "openai/gsm8k" -max_new_tokens: 2048 -max_seq_length: 4096 - - -wandb_project: "RL_Framework_gsm8k_hetero" -wandb_run_name: "gsm8k_hetero_rollout" - -# ============================================================ - -# - - - -# - -# GPU 0,1 -> Training (FSDP, 2 GPU) - - -# ============================================================ -heterogeneous_rollout: - enabled: true - - - total_gpus: 2 - available_gpus: [2, 3] - - - vllm_host: "127.0.0.1" - vllm_base_port: 8000 - startup_timeout: 300 - gpu_memory_utilization: 0.90 - max_model_len: 4096 - - - instances: - - instance_id: "tp1_inst0" - tp: 1 - gpus: [2] - description: "TP=1 instance for short sequences" - - - instance_id: "tp1_inst1" - tp: 1 - gpus: [3] - description: "TP=1 instance for short sequences" - - - scheduling: - scheduler_type: "load_balance" - - length_thresholds: - short: 1024 # <= 1024 tokens -> short - medium: 2048 # 1025-2048 tokens -> medium - long: 4096 # 2049-4096 tokens -> long - # > 4096 tokens -> extra_long - - - routing_rules: - short: [1] - medium: [1] - long: [1] - extra_long: [1] - - - load_balance_strategy: "round_robin" - - - max_queue_length: 64 - - - enable_fallback: true - - - adaptive_routing: true - - - request_timeout: 600 - - -max_concurrent_rollouts: 32 -max_head_offpolicyness: 4 diff --git a/configs/gsm8k_slurm.yaml b/configs/gsm8k_slurm.yaml deleted file mode 100644 index fa8d0c8..0000000 --- a/configs/gsm8k_slurm.yaml +++ /dev/null @@ -1,66 +0,0 @@ -# ============================================================ - -# - - - - -# - - -# 2. sbatch submit_slurm.slurm - -# CONFIG_FILE=configs/gsm8k_slurm.yaml bash run_slurm_distributed.sh -# ============================================================ - - -base_config: base.yaml - - -hardware_config: hardware_config/a100_80g.yaml -model_arch_config: model_arch_config/qwen2.5-3b.yaml - - -model_path: "/path/to/your/model" - - -num_nodes: 4 -train_gpus: 8 -rollout_gpus: 8 -train_gpus_per_node: 2 -rollout_gpus_per_node: 2 -vllm_tp_size: 1 - - - - -# vllm_endpoints: "node0:8000,node0:8001,node1:8002,node1:8003,node2:8004,node2:8005,node3:8006,node3:8007" -vllm_host: "0.0.0.0" -vllm_port: 8000 -vllm_num_instances: 0 - - -master_port: 29500 - - -max_concurrent_rollouts: 128 -max_head_offpolicyness: 4 -queue_size: 512 -batch_size: 64 - - -dataset_name: "openai/gsm8k" - - -weight_sync_mode: "disk" - -sync_path: "/shared/storage/async_rl_weights" - - -log_dir: "./logs" -wandb_project: "rl_framework_slurm" -wandb_run_name: "gsm8k_4node" - - -hardware: - gpus_per_node: 4 diff --git a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_100step.yaml b/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_100step.yaml deleted file mode 100644 index 425a947..0000000 --- a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_100step.yaml +++ /dev/null @@ -1,162 +0,0 @@ -# Six NVIDIA GPU nodes / 48 GPUs: four TP8 Megatron training nodes and two -# heterogeneous rollout nodes. GRP observes all 48 resources; EHP attaches one -# logical rollout worker through the decoupled inter-replica gradient domain. -base_config: base.yaml -hardware_config: hardware_config/a100_80g.yaml -model_arch_config: model_arch_config/qwen3-14b.yaml - -model_path: "/opt/libra/models/Qwen3-14B" -tokenizer_path: "/opt/libra/models/Qwen3-14B" -rollout_backend: "vllm" -train_backend: "megatron_core" - -train_gpus: 32 -rollout_gpus: 16 -num_nodes: 4 -train_gpus_per_node: 8 -rollout_gpus_per_node: 0 -master_addr: "192.0.2.10" -master_port: 29742 - -train_tp_size: 8 -train_pp_size: 1 -train_cp_size: 1 -train_dp_size: 4 -train_ep_size: 1 -expert_tensor_parallel_size: 1 -sequence_parallel: true -use_distributed_optimizer: true -megatron_use_transformer_engine: false -megatron_recompute_num_layers: 1 - -batch_size: 4 -micro_batch_size: 1 -n_samples: 1 -total_steps: 100 -learning_rate: 1.0e-6 -ppo_epochs: 1 -sync_interval: 25 -# The former 40-step run blocked rank 0 in a 30K-token asynchronous evaluator. -# Training rollouts still use 30K; final evaluation is launched separately. -eval_interval: 0 -save_interval: 25 - -max_seq_length: 32768 -max_new_tokens: 30000 -r2e_max_turns: 12 -r2e_max_prompt_tokens: 2048 -r2e_stop_reward: 0.5 -max_concurrent_rollouts: 8 -max_head_offpolicyness: 2 -queue_size: 32 -temperature: 0.8 -top_p: 0.95 -recompute_logprobs: true - -weight_sync_mode: "disk" -rollout_weight_sync_mode: "restart" -rollout_weight_sync_control_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/rollout_weight_sync" -rollout_weight_sync_timeout_s: 3600 -rollout_weight_sync_export_only: true -require_rollout_weight_sync: true -sync_path: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/weights" -log_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/logs" -wandb_project: "" -wandb_run_name: "r2e-gym-qwen3-14b-mcore-gpu-6node48-100step" - -enable_history_collection: true -history_output_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/history" -history_save_raw_lengths: true -history_flush_interval: 1 -history_experiment_name: "r2e_gym_qwen3_14b_6node48_100step" - -heterogeneous_rollout: - enabled: true - total_gpus: 16 - vllm_host: "192.0.2.20" - vllm_base_port: 8000 - max_model_len: 32768 - gpu_memory_utilization: 0.88 - instances: - - {instance_id: "rollout_a_short_tp1_0", host: "192.0.2.20", tp: 1, gpus: [0], port: 8000} - - {instance_id: "rollout_a_short_tp1_1", host: "192.0.2.20", tp: 1, gpus: [1], port: 8001} - - {instance_id: "rollout_a_medium_tp2", host: "192.0.2.20", tp: 2, gpus: [2, 3], port: 8002} - - {instance_id: "rollout_a_long_tp4", host: "192.0.2.20", tp: 4, gpus: [4, 5, 6, 7], port: 8003} - - {instance_id: "rollout_b_short_tp1_0", host: "192.0.2.21", tp: 1, gpus: [0], port: 8000} - - {instance_id: "rollout_b_short_tp1_1", host: "192.0.2.21", tp: 1, gpus: [1], port: 8001} - - {instance_id: "rollout_b_medium_tp2", host: "192.0.2.21", tp: 2, gpus: [2, 3], port: 8002} - - {instance_id: "rollout_b_long_tp4", host: "192.0.2.21", tp: 4, gpus: [4, 5, 6, 7], port: 8003} - scheduling: - scheduler_type: "cmlfq" - request_timeout: 3600 - load_balance_strategy: "least_connections" - max_queue_length: 3 - enable_fallback: true - cmlfq_rebuild_interval: 5 - cmlfq_tree_path: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/cmlfq_tree.json" - cmlfq_tree_persist_interval: 1 - cmlfq_shared_load_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/cmlfq_shared_load" - cmlfq_shared_load_ttl_s: 60 - cmlfq_shared_load_heartbeat_s: 10 - cmlfq_max_local_queue_length: 1 - cmlfq_payload_small_threshold: 1000 - cmlfq_payload_large_threshold: 12000 - cmlfq_buckets: - short: {tp_degrees: [1], max_tokens: 4000} - medium: {tp_degrees: [2], max_tokens: 12000} - long: {tp_degrees: [4], max_tokens: 30000} - -global_resource_planner: - enabled: true - train_backend: "analytic" - rollout_backend: "analytic" - plan_interval: 5 - warmup_steps: 0 - min_history_size: 4 - min_gain_ratio: 0.0 - reconfiguration_cost_s: 0.0 - allowed_train_tp: [8] - allowed_train_pp: [1] - initial_allocation_strategy: "grp" - fixed_train_gpus: 0 - allocation_granularity_gpus: 8 - min_train_gpus: 8 - min_rollout_gpus: 8 - # Empty means GRP provisions heterogeneous bucket capacities with RolloutDP. - rollout_node_tp_pattern: [] - allowed_rollout_tp: [1, 2, 4] - require_heterogeneous_rollout_tp: true - micro_batch_sizes: [1] - # Keep the proven external vLLM endpoints stable while still executing GRP's - # EHP training-pool decision. This avoids changing physical process IDs. - apply_to_runtime: false - runtime_async_planning: true - runtime_dynamic_reconfiguration_enabled: true - runtime_online_replanning: true - # External rollout endpoints remain unchanged (apply_to_runtime=false), so a - # cross-rank rollout drain would only stall already accepted requests and is - # not required for the decoupled EHP training-domain update. - runtime_drain_before_reconfigure: false - runtime_peer_request_wait_s: 120 - runtime_manage_rollout_processes: false - runtime_reconfigure_training: true - runtime_training_pool_only: true - runtime_training_pool_target_gpus: 33 - runtime_training_pool_plan_only: false - decouple_communication_domains: true - elastic_hybrid_max_workers: 0 - elastic_hybrid_replica_size_gpus: 8 - elastic_hybrid_min_rollout_gpus: 8 - hybrid_training_prewarm_enabled: true - hybrid_training_prewarm_count: 1 - hybrid_training_prewarm_worker_ids: ["rollout0"] - hybrid_worker_launch_enabled: true - hybrid_worker_python: "/opt/libra/envs/rl_framework/bin/python" - hybrid_worker_task_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/elastic_training_tasks" - hybrid_worker_ready_timeout_s: 120 - gradient_transport_backend: "tcp" - gradient_server_host: "0.0.0.0" - gradient_server_public_host: "192.0.2.10" - gradient_server_port: 29852 - gradient_server_authkey: "rl-framework-elastic" - verbose: true diff --git a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_100step_homogeneous_lb.yaml b/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_100step_homogeneous_lb.yaml deleted file mode 100644 index 092409c..0000000 --- a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_100step_homogeneous_lb.yaml +++ /dev/null @@ -1,162 +0,0 @@ -# Matched control for the six-node C-MLFQ/heterogeneous rollout experiment. -# Training, R2E-Gym, GRP, EHP, rollout GPU count, endpoint count and generation -# limits are unchanged. Only the rollout layout and scheduler differ: -# four TP2 replicas per rollout node with least-connections load balancing. -base_config: base.yaml -hardware_config: hardware_config/a100_80g.yaml -model_arch_config: model_arch_config/qwen3-14b.yaml - -model_path: "/opt/libra/models/Qwen3-14B" -tokenizer_path: "/opt/libra/models/Qwen3-14B" -rollout_backend: "vllm" -train_backend: "megatron_core" - -train_gpus: 32 -rollout_gpus: 16 -num_nodes: 4 -train_gpus_per_node: 8 -rollout_gpus_per_node: 0 -master_addr: "192.0.2.10" -master_port: 29742 - -train_tp_size: 8 -train_pp_size: 1 -train_cp_size: 1 -train_dp_size: 4 -train_ep_size: 1 -expert_tensor_parallel_size: 1 -sequence_parallel: true -use_distributed_optimizer: true -megatron_use_transformer_engine: false -megatron_recompute_num_layers: 1 - -batch_size: 4 -micro_batch_size: 1 -n_samples: 1 -total_steps: 100 -learning_rate: 1.0e-6 -ppo_epochs: 1 -sync_interval: 25 -# The former 40-step run blocked rank 0 in a 30K-token asynchronous evaluator. -# Training rollouts still use 30K; final evaluation is launched separately. -eval_interval: 0 -save_interval: 25 - -max_seq_length: 32768 -max_new_tokens: 30000 -r2e_max_turns: 12 -r2e_max_prompt_tokens: 2048 -r2e_stop_reward: 0.5 -max_concurrent_rollouts: 8 -max_head_offpolicyness: 2 -queue_size: 32 -temperature: 0.8 -top_p: 0.95 -recompute_logprobs: true - -weight_sync_mode: "disk" -rollout_weight_sync_mode: "restart" -rollout_weight_sync_control_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/rollout_weight_sync" -rollout_weight_sync_timeout_s: 3600 -rollout_weight_sync_export_only: true -require_rollout_weight_sync: true -sync_path: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/weights" -log_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/logs" -wandb_project: "" -wandb_run_name: "r2e-gym-qwen3-14b-mcore-gpu-6node48-100step-homogeneous-lb" - -enable_history_collection: true -history_output_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/history" -history_save_raw_lengths: true -history_flush_interval: 1 -history_experiment_name: "r2e_gym_qwen3_14b_6node48_100step_homogeneous_lb" - -heterogeneous_rollout: - enabled: true - total_gpus: 16 - vllm_host: "192.0.2.20" - vllm_base_port: 8000 - max_model_len: 32768 - gpu_memory_utilization: 0.88 - instances: - - {instance_id: "rollout_a_tp2_0", host: "192.0.2.20", tp: 2, gpus: [0, 1], port: 8000} - - {instance_id: "rollout_a_tp2_1", host: "192.0.2.20", tp: 2, gpus: [2, 3], port: 8001} - - {instance_id: "rollout_a_tp2_2", host: "192.0.2.20", tp: 2, gpus: [4, 5], port: 8002} - - {instance_id: "rollout_a_tp2_3", host: "192.0.2.20", tp: 2, gpus: [6, 7], port: 8003} - - {instance_id: "rollout_b_tp2_0", host: "192.0.2.21", tp: 2, gpus: [0, 1], port: 8000} - - {instance_id: "rollout_b_tp2_1", host: "192.0.2.21", tp: 2, gpus: [2, 3], port: 8001} - - {instance_id: "rollout_b_tp2_2", host: "192.0.2.21", tp: 2, gpus: [4, 5], port: 8002} - - {instance_id: "rollout_b_tp2_3", host: "192.0.2.21", tp: 2, gpus: [6, 7], port: 8003} - scheduling: - scheduler_type: "load_balance" - request_timeout: 3600 - load_balance_strategy: "least_connections" - max_queue_length: 3 - enable_fallback: true - cmlfq_rebuild_interval: 5 - cmlfq_tree_path: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/cmlfq_tree.json" - cmlfq_tree_persist_interval: 1 - cmlfq_shared_load_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/cmlfq_shared_load" - cmlfq_shared_load_ttl_s: 60 - cmlfq_shared_load_heartbeat_s: 10 - cmlfq_max_local_queue_length: 1 - cmlfq_payload_small_threshold: 1000 - cmlfq_payload_large_threshold: 12000 - cmlfq_buckets: - short: {tp_degrees: [1], max_tokens: 4000} - medium: {tp_degrees: [2], max_tokens: 12000} - long: {tp_degrees: [4], max_tokens: 30000} - -global_resource_planner: - enabled: true - train_backend: "analytic" - rollout_backend: "analytic" - plan_interval: 5 - warmup_steps: 0 - min_history_size: 4 - min_gain_ratio: 0.0 - reconfiguration_cost_s: 0.0 - allowed_train_tp: [8] - allowed_train_pp: [1] - initial_allocation_strategy: "grp" - fixed_train_gpus: 0 - allocation_granularity_gpus: 8 - min_train_gpus: 8 - min_rollout_gpus: 8 - rollout_node_tp_pattern: [2, 2, 2, 2] - allowed_rollout_tp: [2] - require_heterogeneous_rollout_tp: false - micro_batch_sizes: [1] - # Keep the proven external vLLM endpoints stable while still executing GRP's - # EHP training-pool decision. This avoids changing physical process IDs. - apply_to_runtime: false - runtime_async_planning: true - runtime_dynamic_reconfiguration_enabled: true - runtime_online_replanning: true - # External rollout endpoints remain unchanged (apply_to_runtime=false), so a - # cross-rank rollout drain would only stall already accepted requests and is - # not required for the decoupled EHP training-domain update. - runtime_drain_before_reconfigure: false - runtime_peer_request_wait_s: 120 - runtime_manage_rollout_processes: false - runtime_reconfigure_training: true - runtime_training_pool_only: true - runtime_training_pool_target_gpus: 33 - runtime_training_pool_plan_only: false - decouple_communication_domains: true - elastic_hybrid_max_workers: 0 - elastic_hybrid_replica_size_gpus: 8 - elastic_hybrid_min_rollout_gpus: 8 - hybrid_training_prewarm_enabled: true - hybrid_training_prewarm_count: 1 - hybrid_training_prewarm_worker_ids: ["rollout0"] - hybrid_worker_launch_enabled: true - hybrid_worker_python: "/opt/libra/envs/rl_framework/bin/python" - hybrid_worker_task_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/elastic_training_tasks" - hybrid_worker_ready_timeout_s: 120 - gradient_transport_backend: "tcp" - gradient_server_host: "0.0.0.0" - gradient_server_public_host: "192.0.2.10" - gradient_server_port: 29852 - gradient_server_authkey: "rl-framework-elastic" - verbose: true diff --git a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_100step_no_ehp.yaml b/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_100step_no_ehp.yaml deleted file mode 100644 index bb5bbc6..0000000 --- a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_100step_no_ehp.yaml +++ /dev/null @@ -1,159 +0,0 @@ -# Six NVIDIA GPU nodes / 48 GPUs: four TP8 Megatron training nodes and two -# heterogeneous rollout nodes. GRP observes all 48 resources; EHP attaches one -# logical rollout worker through the decoupled inter-replica gradient domain. -base_config: base.yaml -hardware_config: hardware_config/a100_80g.yaml -model_arch_config: model_arch_config/qwen3-14b.yaml - -model_path: "/opt/libra/models/Qwen3-14B" -tokenizer_path: "/opt/libra/models/Qwen3-14B" -rollout_backend: "vllm" -train_backend: "megatron_core" - -train_gpus: 32 -rollout_gpus: 16 -num_nodes: 4 -train_gpus_per_node: 8 -rollout_gpus_per_node: 0 -master_addr: "192.0.2.10" -master_port: 29742 - -train_tp_size: 8 -train_pp_size: 1 -train_cp_size: 1 -train_dp_size: 4 -train_ep_size: 1 -expert_tensor_parallel_size: 1 -sequence_parallel: true -use_distributed_optimizer: true -megatron_use_transformer_engine: false -megatron_recompute_num_layers: 1 - -batch_size: 4 -micro_batch_size: 1 -n_samples: 1 -total_steps: 100 -learning_rate: 1.0e-6 -ppo_epochs: 1 -sync_interval: 25 -# The former 40-step run blocked rank 0 in a 30K-token asynchronous evaluator. -# Training rollouts still use 30K; final evaluation is launched separately. -eval_interval: 0 -save_interval: 25 - -max_seq_length: 32768 -max_new_tokens: 30000 -r2e_max_turns: 12 -r2e_max_prompt_tokens: 2048 -r2e_stop_reward: 0.5 -max_concurrent_rollouts: 8 -max_head_offpolicyness: 2 -queue_size: 32 -temperature: 0.8 -top_p: 0.95 -recompute_logprobs: true - -weight_sync_mode: "disk" -rollout_weight_sync_mode: "restart" -rollout_weight_sync_control_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/rollout_weight_sync" -rollout_weight_sync_timeout_s: 3600 -rollout_weight_sync_export_only: true -require_rollout_weight_sync: true -sync_path: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/weights" -log_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/logs" -wandb_project: "" -wandb_run_name: "r2e-gym-qwen3-14b-mcore-gpu-6node48-100step-no-ehp" - -enable_history_collection: true -history_output_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/history" -history_save_raw_lengths: true -history_flush_interval: 1 -history_experiment_name: "r2e_gym_qwen3_14b_6node48_100step" - -heterogeneous_rollout: - enabled: true - total_gpus: 16 - vllm_host: "192.0.2.20" - vllm_base_port: 8000 - max_model_len: 32768 - gpu_memory_utilization: 0.88 - instances: - - {instance_id: "rollout_a_short_tp1_0", host: "192.0.2.20", tp: 1, gpus: [0], port: 8000} - - {instance_id: "rollout_a_short_tp1_1", host: "192.0.2.20", tp: 1, gpus: [1], port: 8001} - - {instance_id: "rollout_a_medium_tp2", host: "192.0.2.20", tp: 2, gpus: [2, 3], port: 8002} - - {instance_id: "rollout_a_long_tp4", host: "192.0.2.20", tp: 4, gpus: [4, 5, 6, 7], port: 8003} - - {instance_id: "rollout_b_short_tp1_0", host: "192.0.2.21", tp: 1, gpus: [0], port: 8000} - - {instance_id: "rollout_b_short_tp1_1", host: "192.0.2.21", tp: 1, gpus: [1], port: 8001} - - {instance_id: "rollout_b_medium_tp2", host: "192.0.2.21", tp: 2, gpus: [2, 3], port: 8002} - - {instance_id: "rollout_b_long_tp4", host: "192.0.2.21", tp: 4, gpus: [4, 5, 6, 7], port: 8003} - scheduling: - scheduler_type: "cmlfq" - request_timeout: 3600 - load_balance_strategy: "least_connections" - max_queue_length: 3 - enable_fallback: true - cmlfq_rebuild_interval: 5 - cmlfq_tree_path: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/cmlfq_tree.json" - cmlfq_tree_persist_interval: 1 - cmlfq_shared_load_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/cmlfq_shared_load" - cmlfq_shared_load_ttl_s: 60 - cmlfq_shared_load_heartbeat_s: 10 - cmlfq_max_local_queue_length: 1 - cmlfq_payload_small_threshold: 1000 - cmlfq_payload_large_threshold: 12000 - cmlfq_buckets: - short: {tp_degrees: [1], max_tokens: 4000} - medium: {tp_degrees: [2], max_tokens: 12000} - long: {tp_degrees: [4], max_tokens: 30000} - -global_resource_planner: - enabled: true - train_backend: "analytic" - rollout_backend: "analytic" - plan_interval: 5 - warmup_steps: 0 - min_history_size: 4 - min_gain_ratio: 0.0 - reconfiguration_cost_s: 0.0 - allowed_train_tp: [8] - allowed_train_pp: [1] - initial_allocation_strategy: "grp" - fixed_train_gpus: 0 - allocation_granularity_gpus: 8 - min_train_gpus: 8 - min_rollout_gpus: 8 - # Empty means GRP provisions heterogeneous bucket capacities with RolloutDP. - rollout_node_tp_pattern: [] - allowed_rollout_tp: [1, 2, 4] - require_heterogeneous_rollout_tp: true - micro_batch_sizes: [1] - # Keep the proven external vLLM endpoints stable while still executing GRP's - # EHP training-pool decision. This avoids changing physical process IDs. - apply_to_runtime: false - runtime_async_planning: true - runtime_dynamic_reconfiguration_enabled: true - runtime_online_replanning: true - # External rollout endpoints remain unchanged (apply_to_runtime=false), so a - # cross-rank rollout drain would only stall already accepted requests and is - # not required for the decoupled EHP training-domain update. - runtime_drain_before_reconfigure: false - runtime_peer_request_wait_s: 120 - runtime_manage_rollout_processes: false - runtime_reconfigure_training: true - runtime_training_pool_only: true - runtime_training_pool_target_gpus: 32 - runtime_training_pool_plan_only: false - decouple_communication_domains: true - hybrid_training_prewarm_enabled: false - hybrid_training_prewarm_count: 0 - hybrid_training_prewarm_worker_ids: [] - hybrid_worker_launch_enabled: false - hybrid_worker_python: "/opt/libra/envs/rl_framework/bin/python" - hybrid_worker_task_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48/elastic_training_tasks_no_ehp" - hybrid_worker_ready_timeout_s: 120 - gradient_transport_backend: "tcp" - gradient_server_host: "0.0.0.0" - gradient_server_public_host: "192.0.2.10" - gradient_server_port: 29852 - gradient_server_authkey: "rl-framework-elastic" - verbose: true diff --git a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_base.yaml b/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_base.yaml deleted file mode 100644 index bdef175..0000000 --- a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_base.yaml +++ /dev/null @@ -1,77 +0,0 @@ -# Shared production-scale training configuration for the strict EHP A/B test. -# The two experiment arms inherit this file and may differ only in the EHP -# runtime controls plus non-semantic run labels. -base_config: r2e_gym_qwen3_14b_mcore_gpu_6node48_100step_no_ehp.yaml - -# 32 trajectories = 8 prompts x 4 GRPO samples per optimizer step. With DP=4, -# every replica receives 8 trajectories (two complete prompt groups). -batch_size: 32 -micro_batch_size: 1 -n_samples: 4 -total_steps: 200 -learning_rate: 1.0e-6 -ppo_epochs: 1 -kl_coef: 0.001 -clip_epsilon: 0.2 -gamma: 1.0 -seed: 42 - -# Keep rollout weights substantially fresher than the validation run's -# 25-step cadence while amortizing the current checkpoint/restart sync path. -sync_interval: 5 -save_interval: 50 - -# Inline 30K-token evaluation is deliberately excluded from throughput timing. -# Evaluate the saved step-0/50/.../200 checkpoints with the same held-out set. -eval_interval: 0 - -max_concurrent_rollouts: 16 -max_head_offpolicyness: 4 -queue_size: 128 - -wandb_run_name: "r2e-gym-qwen3-14b-mcore-gpu-6node48-production" -history_experiment_name: "r2e_gym_qwen3_14b_6node48_production" - -global_resource_planner: - # GRP owns the initial 48-GPU partition. Both stage sizes remain node/DP - # replica aligned, but neither is pinned to the historical 32/16 split. - initial_allocation_strategy: "grp" - fixed_train_gpus: 0 - allocation_granularity_gpus: 8 - min_train_gpus: 8 - min_rollout_gpus: 8 - # Let the paper-style RolloutDP choose bucket capacities; physical placement - # still packs complete TP instances within each eight-GPU host. - rollout_node_tp_pattern: [] - # Production planning waits for representative long-context observations and - # requires a material predicted gain before changing the logical pool. - plan_interval: 10 - warmup_steps: 20 - min_history_size: 20 - min_gain_ratio: 0.05 - reconfiguration_cost_s: 120.0 - # EHP must be driven by a versioned planner signal; no static target is used. - runtime_training_pool_target_gpus: 0 - runtime_training_pool_plan_only: false - # No policy maximum: the number of EHP replicas is derived from currently - # available rollout capacity while retaining one complete rollout node. - elastic_hybrid_max_workers: 0 - elastic_hybrid_replica_size_gpus: 8 - elastic_hybrid_min_rollout_gpus: 8 - elastic_hybrid_require_planner_signal: true - elastic_hybrid_require_isolated_ccl: true - elastic_hybrid_join_timeout_s: 180.0 - elastic_hybrid_signal_ttl_steps: 20 - elastic_hybrid_borrow_train_rollout_ratio: 1.15 - elastic_hybrid_release_train_rollout_ratio: 0.90 - elastic_hybrid_max_rollout_pressure: 0.80 - # Keep both experiment arms launch-capable. The no-EHP arm never receives - # a planner signal, so no worker can join; the EHP arm differs only by the - # planner-controlled feature switch below. - hybrid_training_prewarm_enabled: false - hybrid_training_prewarm_count: 0 - hybrid_training_prewarm_worker_ids: [] - hybrid_worker_launch_enabled: true - hybrid_worker_remote_control_enabled: true - hybrid_worker_remote_control_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48_production/elastic_training_tasks" - hybrid_worker_task_dir: "/opt/libra/runs/r2e_gym_qwen3_14b_6node48_production/elastic_training_tasks" diff --git a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_ehp.yaml b/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_ehp.yaml deleted file mode 100644 index d4fc953..0000000 --- a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_ehp.yaml +++ /dev/null @@ -1,15 +0,0 @@ -# Strict treatment arm: identical to production_no_ehp except that GRP may -# command rollout workers to join or leave the isolated elastic gradient lane. -base_config: r2e_gym_qwen3_14b_mcore_gpu_6node48_production_base.yaml - -wandb_run_name: "r2e-gym-qwen3-14b-mcore-gpu-6node48-production-ehp" -history_experiment_name: "r2e_gym_qwen3_14b_6node48_production_ehp" - -global_resource_planner: - elastic_hybrid_planning_enabled: true - runtime_online_replanning: true - runtime_dynamic_reconfiguration_enabled: true - runtime_reconfigure_training: true - hybrid_worker_launch_enabled: true - hybrid_worker_remote_control_enabled: true - elastic_hybrid_require_isolated_ccl: true diff --git a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_no_ehp.yaml b/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_no_ehp.yaml deleted file mode 100644 index 8c4b430..0000000 --- a/configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_no_ehp.yaml +++ /dev/null @@ -1,17 +0,0 @@ -# Strict control arm: all training, rollout, optimizer, data, seed and planner -# settings come from the shared production base. Only EHP controls are off. -base_config: r2e_gym_qwen3_14b_mcore_gpu_6node48_production_base.yaml - -wandb_run_name: "r2e-gym-qwen3-14b-mcore-gpu-6node48-production-no-ehp" -history_experiment_name: "r2e_gym_qwen3_14b_6node48_production_no_ehp" - -global_resource_planner: - elastic_hybrid_planning_enabled: false - # GRP still owns startup placement through PreflightPlanner, but no runtime - # decision may alter that placement in the 200-step control run. - runtime_online_replanning: false - runtime_dynamic_reconfiguration_enabled: false - runtime_reconfigure_training: false - hybrid_worker_launch_enabled: false - hybrid_worker_remote_control_enabled: false - elastic_hybrid_require_isolated_ccl: false diff --git a/configs/search_r1.yaml b/configs/search_r1.yaml deleted file mode 100644 index e58e39c..0000000 --- a/configs/search_r1.yaml +++ /dev/null @@ -1,59 +0,0 @@ -# ============================================================ - -# - -# export SERPER_KEY_ID=your_key_here -# python examples/search_r1_async_rl.py --config configs/search_r1.yaml - -# - - - - - - -# ============================================================ - - -base_config: base.yaml - - -hardware_config: hardware_config/a100_80g.yaml -model_arch_config: model_arch_config/qwen2.5-3b.yaml - - -model_path: "/path/to/Qwen3-4B" - - -train_gpus: 2 -rollout_gpus: 2 - - - -max_turns: 5 - - - - - - -dataset_name: "search_r1_gsm8k" - - - -max_concurrent_rollouts: 32 - - - -batch_size: 16 -micro_batch_size: 4 - - - -max_new_tokens: 1024 -max_seq_length: 4096 - - -wandb_project: "RL_Framework_search_r1" -wandb_run_name: "search_r1_async_rl" -log_dir: "./logs/search_r1" diff --git a/docs/ci.md b/docs/ci.md index 27ee604..0615559 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -4,10 +4,11 @@ Pushes to any branch and pull requests targeting `main` run `.github/workflows/c The workflow can also be started manually from GitHub Actions. The CPU regression suite runs on Python 3.10 and 3.12 with PyTorch 2.7.0 CPU. -It covers configuration, asynchronous execution, phase tracing, reload control, -legacy and cost-aware CMLFQ, rollout clients, and CPU-offload backend orchestration. -The explicit test list lives in `scripts/test_cpu_ci.sh`; add new CPU-safe tests there. -This is a selected regression suite, not the entire repository test suite. +It covers configuration, asynchronous execution, reload control, C-MLFQ and +cost-aware scheduling, Global Resource Planner and preflight simulation, +Elastic Hybrid Pool and runtime boundary integration, serving protocol, GRPO +grouping, Megatron-Core adapter checks, and R2E-Gym workflow checks. +`scripts/test_cpu_ci.sh` runs the entire consolidated test suite under `tests/`. To reproduce in a clean Python 3.10–3.12 virtual environment: @@ -31,7 +32,6 @@ still merges manually after checks pass. GitHub branch protection is repository configuration, separate from this workflow file; changing YAML alone does not activate it. This setup does not publish packages or deploy training services. -CUDA kernel, vLLM connector, multi-GPU KV migration, and full RL throughput -validation remain manual cluster tests using `scripts/validate_cpu_offload.slurm` -and `scripts/benchmark_scheduler_rl.slurm`. CPU CI does not certify GPU correctness -or performance. Public PR code is not automatically executed on HPC-GMC. +CUDA kernel, vLLM connector, multi-GPU KV migration, and full RL end-to-end +validation remain GPU cluster runs. CPU CI does not certify GPU correctness or +performance. diff --git a/engine/heterogeneous_engine.py b/engine/heterogeneous_engine.py index 9c7c63d..9adb8a8 100644 --- a/engine/heterogeneous_engine.py +++ b/engine/heterogeneous_engine.py @@ -64,9 +64,7 @@ def _setup_metrics_polling(self, hetero_cfg: Any) -> None: from RL_Framework.infra.scheduling.base import MetricsFeedbackConfig from RL_Framework.infra.scheduling.metrics_feed import VLLMMetricsPoller - feedback = MetricsFeedbackConfig.from_scheduling( - getattr(hetero_cfg, "scheduling", None) - ) + feedback = MetricsFeedbackConfig.from_scheduling(hetero_cfg.scheduling) single_dynamic = isinstance(self.scheduler, CMLFQDynamicKVCostScheduler) if not feedback.enabled and not single_dynamic: self._stop_metrics_poller() @@ -131,8 +129,8 @@ def _stop_metrics_poller(self) -> None: def _setup_shared_state(self, hetero_cfg: Any) -> None: """Create the cross-rank load state once per engine lifetime.""" - sched = getattr(hetero_cfg, "scheduling", None) - directory = str(getattr(sched, "shared_load_dir", "") or "") + sched = hetero_cfg.scheduling + directory = str(sched.shared_load_dir or "") if not directory: return if hasattr(self.scheduler, "get_request_route"): @@ -144,11 +142,9 @@ def _setup_shared_state(self, hetero_cfg: Any) -> None: self._shared_state = SharedTokenLoadState( directory=directory, - ttl_s=float(getattr(sched, "shared_load_ttl_s", 30.0)), - heartbeat_interval_s=float( - getattr(sched, "shared_load_heartbeat_s", 10.0) - ), - cache_ttl_s=float(getattr(sched, "shared_load_cache_ttl_s", 1.0)), + ttl_s=float(sched.shared_load_ttl_s), + heartbeat_interval_s=float(sched.shared_load_heartbeat_s), + cache_ttl_s=float(sched.shared_load_cache_ttl_s), ) if self.scheduler is not None: self.scheduler.attach_shared_state(self._shared_state) @@ -253,7 +249,7 @@ def reconfigure_from_plan(self, plan: Any, config: Any): engine.close_sync() hetero = config.heterogeneous_rollout - scheduler_type = getattr(hetero.scheduling, "scheduler_type", "length_aware") + scheduler_type = hetero.scheduling.scheduler_type scheduler = SchedulerFactory.create( scheduler_type=scheduler_type, hetero_config=hetero, @@ -557,8 +553,8 @@ def _configure_cost_model(self, config): ).rollout_model sched = config.heterogeneous_rollout.scheduling self._cmlfq_backend = CMLFQGenerationBackend( - mode=getattr(sched, "cmlfq_kv_backend", "recompute"), - transfer_tp_pairs=getattr(sched, "cmlfq_kv_transfer_tp_pairs", []), + mode=sched.cmlfq_kv_backend, + transfer_tp_pairs=sched.cmlfq_kv_transfer_tp_pairs, ) self._configure_cost_runtime() @@ -895,7 +891,7 @@ def from_config( hetero = config.heterogeneous_rollout - scheduler_type = getattr(hetero.scheduling, "scheduler_type", "length_aware") + scheduler_type = hetero.scheduling.scheduler_type scheduler = SchedulerFactory.create( scheduler_type=scheduler_type, hetero_config=hetero, @@ -975,10 +971,3 @@ def __repr__(self): f"tp_list={self.tp_list}, " f"scheduler={self.scheduler.name})" ) - - def __del__(self): - for engine in self.engines: - try: - engine.__del__() - except Exception: - pass diff --git a/examples/benchmark_r2e_component_ablations.py b/examples/benchmark_r2e_component_ablations.py deleted file mode 100644 index 80a99b2..0000000 --- a/examples/benchmark_r2e_component_ablations.py +++ /dev/null @@ -1,105 +0,0 @@ -"""Controlled performance ablations for R2E-Gym control-plane components. - -The benchmark separates measured controller latency from projected execution -time. It intentionally avoids claiming that an analytic planner estimate is -the same as a physical cluster speedup. -""" - -from __future__ import annotations - -import json -import os -import time -from pathlib import Path - -from RL_Framework.infra.scheduling.cmlfq_migration import MigrationCostProfiler - -from validate_r2e_core_components import _measure_ehp, _measure_grp - - -def _cmlfq_ablation() -> dict: - profiler = MigrationCostProfiler() - # The values model a TP1 request whose long continuation can be resharded - # to TP2. They are explicit benchmark inputs rather than device timings. - profiler.record_measurement( - source_tp=1, - target_tp=2, - seq_len=8192, - offload_ms=160.0, - reshard_ms=80.0, - network_ms=0.0, - reload_ms=140.0, - recompute_prefill_ms=520.0, - ) - start = time.perf_counter() - action, selected_ms = profiler.decide_migration_path(1, 2, 8192) - decision_ms = (time.perf_counter() - start) * 1000 - baseline_recompute_ms = 520.0 - return { - "mode": "profiled_execution_cost", - "baseline": {"strategy": "recompute_prefill", "latency_ms": baseline_recompute_ms}, - "cmlfq": {"strategy": action, "latency_ms": selected_ms}, - "saved_ms": baseline_recompute_ms - selected_ms, - "speedup": baseline_recompute_ms / selected_ms, - "controller_decision_latency_ms": decision_ms, - } - - -def _grp_ablation() -> dict: - measured = _measure_grp() - current = float(measured["current_global_s"]) - candidate = float(measured["candidate_global_s"]) - return { - "mode": "analytic_global_cost_model", - "baseline": {"global_time_s": current}, - "grp_candidate": {"global_time_s": candidate}, - "projected_saved_s": current - candidate, - "projected_speedup": current / candidate, - "planner_latency_ms": measured["planning_latency_ms"], - "candidate_train_gpus": measured["candidate_train_gpus"], - "candidate_rollout_tp": measured["candidate_rollout_tp"], - } - - -def _ehp_ablation() -> dict: - snapshot_delay_s = 0.15 - start = time.perf_counter() - time.sleep(snapshot_delay_s) - blocking_join_ms = (time.perf_counter() - start) * 1000 - measured = _measure_ehp(iterations=100, tensor_elements=262144) - nonblocking_join_ms = float(measured["join_latency_ms_mean"]) - return { - "mode": "measured_local_state_machine", - "baseline": {"strategy": "blocking_snapshot_join", "latency_ms": blocking_join_ms}, - "elastic_hybrid_pool": { - "strategy": "nonblocking_snapshot_join", - "join_latency_ms": nonblocking_join_ms, - "join_latency_p95_ms": measured["join_latency_ms_p95"], - "gradient_aggregate_ms": measured["gradient_aggregate_ms"], - "gradient_effective_gbps": measured["gradient_effective_gbps"], - "communication_domains": measured["communication_domains"], - }, - "join_return_speedup": blocking_join_ms / nonblocking_join_ms, - } - - -def main() -> None: - report = { - "cmlfq": _cmlfq_ablation(), - "global_resource_planner": _grp_ablation(), - "elastic_hybrid_pool": _ehp_ablation(), - } - output = Path( - os.environ.get( - "COMPONENT_ABLATION_REPORT", - "logs/r2e_component_ablations.json", - ) - ) - output.parent.mkdir(parents=True, exist_ok=True) - output.write_text(json.dumps(report, indent=2), encoding="utf-8") - print(json.dumps(report, indent=2)) - print(f"R2E_COMPONENT_ABLATIONS_OK output={output}") - - -if __name__ == "__main__": - main() diff --git a/examples/global_resource_planner_full_flow.py b/examples/global_resource_planner_full_flow.py deleted file mode 100644 index c28ae2c..0000000 --- a/examples/global_resource_planner_full_flow.py +++ /dev/null @@ -1,300 +0,0 @@ -"""Show a complete Global Resource Planner flow. - -This example exercises the real planner path: - -1. collect trajectory length history from a training batch -2. evaluate the current plan -3. search candidate train/rollout allocations -4. call Sailor/Vidur adapter command contracts for each evaluation -5. decide whether to reconfigure -6. apply the selected plan back to AsyncRLConfig - -The bundled mini Sailor/Vidur commands are deterministic command-contract -simulators. They stand in for full Sailor/Vidur installations while using the -same adapter path that production commands use: - - Sailor command: reads {input_json}, writes {output_json} - Vidur command: reads {trace_csv}, writes {output_json} -""" - -from __future__ import annotations - -import json -import sys -import tempfile -from pathlib import Path - -from RL_Framework.config import ( - AsyncRLConfig, - HeterogeneousInstanceConfig, - HeterogeneousRolloutConfig, - SchedulingConfig, -) -from RL_Framework.infra.cost_model.global_resource_planner import ( - GlobalResourcePlanner, -) - - -def _write_command_contract_simulators(work_dir: Path) -> tuple[Path, Path, Path, Path]: - sailor_root = work_dir / "sailor" - vidur_root = work_dir / "vidur" - sailor_root.mkdir() - vidur_root.mkdir() - - sailor_cmd = work_dir / "sailor_train_contract.py" - sailor_cmd.write_text( - r''' -import json -import sys - -payload = json.load(open(sys.argv[1], encoding="utf-8")) -tc = payload["train_config"] -gpus = max(1, tc["tp"] * tc["pp"] * tc["dp"]) -seq = max(1, payload["avg_sequence_length"]) -batch = max(1, payload["batch_size"]) - -# A tiny Sailor-like training model: more training GPUs reduce compute time, -# while larger PP adds a small pipeline bubble. -iteration_time = (0.0010 * seq * batch) / gpus -iteration_time *= 1.0 + 0.08 * max(0, tc["pp"] - 1) -iteration_time *= 1.0 / max(1, tc["b_micro"]) - -json.dump( - { - "t_train": iteration_time, - "simulator": "sailor-command-contract", - "train_gpus": gpus, - "tp": tc["tp"], - "pp": tc["pp"], - "dp": tc["dp"], - "b_micro": tc["b_micro"], - }, - open(sys.argv[2], "w", encoding="utf-8"), -) -'''.strip(), - encoding="utf-8", - ) - - vidur_cmd = work_dir / "vidur_rollout_contract.py" - vidur_cmd.write_text( - r''' -import csv -import json -import sys - -trace_csv, output_json, tp_list_raw = sys.argv[1], sys.argv[2], sys.argv[3] -tp_list = [int(x) for x in tp_list_raw.split(",") if x] -total_gpus = max(1, sum(tp_list)) -max_tp = max(tp_list) if tp_list else 1 -num_instances = max(1, len(tp_list)) - -work = 0.0 -max_request = 0 -with open(trace_csv, newline="", encoding="utf-8") as f: - for row in csv.DictReader(f): - prompt = int(float(row["num_prefill_tokens"])) - decode = int(float(row["num_decode_tokens"])) - tokens = prompt + decode - max_request = max(max_request, tokens) - # A tiny Vidur-like rollout model: decode dominates, larger TP helps - # long requests, and more instances improve throughput. - work += prompt * 0.0008 + decode * 0.006 - -makespan = work / (total_gpus * (1.0 + 0.18 * (max_tp - 1))) -makespan /= num_instances ** 0.25 - -json.dump( - { - "makespan": makespan, - "simulator": "vidur-command-contract", - "tp_list": tp_list, - "rollout_gpus": total_gpus, - "num_instances": num_instances, - "max_request_tokens": max_request, - }, - open(output_json, "w", encoding="utf-8"), -) -'''.strip(), - encoding="utf-8", - ) - - return sailor_root, vidur_root, sailor_cmd, vidur_cmd - - -def _build_config( - sailor_root: Path, - vidur_root: Path, - sailor_cmd: Path, - vidur_cmd: Path, -) -> AsyncRLConfig: - cfg = AsyncRLConfig( - model_path="/tmp/fake-qwen", - train_gpus=2, - rollout_gpus=2, - train_tp_size=1, - train_pp_size=1, - train_dp_size=2, - micro_batch_size=1, - batch_size=8, - n_total_gpus=4, - max_seq_length=32768, - max_new_tokens=32768, - max_concurrent_rollouts=8, - heterogeneous_rollout=HeterogeneousRolloutConfig( - enabled=True, - total_gpus=2, - available_gpus=[2, 3], - instances=[ - HeterogeneousInstanceConfig(instance_id="short_tp1_0", tp=1, gpus=[2]), - HeterogeneousInstanceConfig(instance_id="short_tp1_1", tp=1, gpus=[3]), - ], - scheduling=SchedulingConfig( - scheduler_type="cmlfq", - cmlfq_buckets={ - "short": {"tp_degrees": [1], "max_tokens": 5000}, - "long": {"tp_degrees": [2], "max_tokens": 50000}, - }, - ), - ), - ) - - planner_cfg = cfg.global_resource_planner - planner_cfg.enabled = True - planner_cfg.train_backend = "sailor" - planner_cfg.rollout_backend = "vidur" - planner_cfg.plan_interval = 1 - planner_cfg.warmup_steps = 0 - planner_cfg.min_history_size = 4 - planner_cfg.min_gain_ratio = 0.0 - planner_cfg.reconfiguration_cost_s = 0.0 - planner_cfg.allowed_train_tp = [1, 2] - planner_cfg.allowed_train_pp = [1] - planner_cfg.allowed_rollout_tp = [1, 2] - planner_cfg.micro_batch_sizes = [1, 2] - planner_cfg.verbose = True - planner_cfg.simulator_allow_fallback = False - planner_cfg.sailor_path = str(sailor_root) - planner_cfg.vidur_path = str(vidur_root) - planner_cfg.sailor_train_command = ( - f"{sys.executable} {sailor_cmd} {{input_json}} {{output_json}}" - ) - planner_cfg.vidur_rollout_command = ( - f"{sys.executable} {vidur_cmd} {{trace_csv}} {{output_json}} {{tp_list}}" - ) - return cfg - - -def _print_plan(label: str, plan) -> None: - print(f"\n[{label}]") - if plan is None: - print(" ") - return - d = plan.to_dict() - print( - " train: " - f"TP={d['train']['tp']} PP={d['train']['pp']} DP={d['train']['dp']} " - f"micro={d['train']['b_micro']} GPUs={d['train']['n_gpus']}" - ) - print( - " rollout: " - f"tp_list={d['rollout']['tp_list']} GPUs={d['rollout']['n_gpus']} " - f"instances={d['rollout']['n_instances']}" - ) - print( - " predicted: " - f"T_train={d['t_train']:.4f}s " - f"T_rollout={d['t_rollout']:.4f}s " - f"T_global={d['t_global']:.4f}s" - ) - if d["expected_gain_ratio"]: - print( - " gain: " - f"net={d['expected_gain_s']:.4f}s " - f"ratio={d['expected_gain_ratio']:.2%}" - ) - metadata = d.get("metadata", {}) - if metadata: - print(f" metadata keys: {sorted(metadata.keys())}") - - -def main() -> None: - with tempfile.TemporaryDirectory(prefix="grp_full_flow_") as td: - work_dir = Path(td) - sailor_root, vidur_root, sailor_cmd, vidur_cmd = ( - _write_command_contract_simulators(work_dir) - ) - cfg = _build_config(sailor_root, vidur_root, sailor_cmd, vidur_cmd) - - batch = [ - {"prompt_id": "r2e-0", "input_len": 1024, "output_len": 18000}, - {"prompt_id": "r2e-1", "input_len": 1024, "output_len": 22000}, - {"prompt_id": "r2e-2", "input_len": 2048, "output_len": 26000}, - {"prompt_id": "r2e-3", "input_len": 2048, "output_len": 32000}, - ] - - print("=== Global Resource Planner Full Flow ===") - print("1. History batch:") - for item in batch: - print( - " " - f"{item['prompt_id']}: input={item['input_len']} " - f"output={item['output_len']}" - ) - - print("\n2. Backend configuration:") - print(f" train_backend={cfg.global_resource_planner.train_backend}") - print(f" rollout_backend={cfg.global_resource_planner.rollout_backend}") - print(f" sailor_command={cfg.global_resource_planner.sailor_train_command}") - print(f" vidur_command={cfg.global_resource_planner.vidur_rollout_command}") - - planner = GlobalResourcePlanner.from_config(cfg) - decision = planner.plan_if_needed(step=1, config=cfg, batch=batch) - - print("\n3. Planner decision:") - print(f" reason={decision.reason}") - print(f" should_reconfigure={decision.should_reconfigure}") - print(f" history_requests={decision.num_requests}") - - _print_plan("current plan", decision.current_plan) - _print_plan("candidate plan", decision.candidate_plan) - - print("\n4. Example evaluated candidates:") - evaluated = ( - decision.candidate_plan.metadata.get("evaluated", []) - if decision.candidate_plan - else [] - ) - for idx, item in enumerate(evaluated[-5:], 1): - print( - " " - f"#{idx}: train={item['train']} rollout={item['rollout']} " - f"T_train={item['t_train']:.4f}s " - f"T_rollout={item['t_rollout']:.4f}s " - f"T_global={item['t_global']:.4f}s" - ) - - print("\n5. Apply plan to runtime config:") - if decision.candidate_plan is not None: - planner.apply_plan_to_config(decision.candidate_plan, cfg) - print( - " config train: " - f"gpus={cfg.train_gpus} tp={cfg.train_tp_size} " - f"pp={cfg.train_pp_size} dp={cfg.train_dp_size} " - f"micro={cfg.micro_batch_size}" - ) - print( - " config rollout: " - f"gpus={cfg.rollout_gpus} tp_list={cfg.heterogeneous_rollout.tp_list}" - ) - for inst in cfg.heterogeneous_rollout.instances: - print( - " " - f"{inst.instance_id}: tp={inst.tp} gpus={inst.gpus} " - f"{inst.description}" - ) - - print("\nFLOW_OK") - - -if __name__ == "__main__": - main() diff --git a/examples/test_async_runner.py b/examples/test_async_runner.py deleted file mode 100644 index 38a7a6f..0000000 --- a/examples/test_async_runner.py +++ /dev/null @@ -1,47 +0,0 @@ -"""Support code for Test async runner.""" - -import sys -import os -sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -from RL_Framework.infra.execution.async_runner import AsyncTaskRunner -import time - -async def test_task(data): - """Test task.""" - print(f"Processing data: {data}") - return {'result': 'success', 'data': data} - -print("=" * 60) -print("Testing AsyncTaskRunner task_id filtering") -print("=" * 60) - -runner = AsyncTaskRunner() -runner.initialize() - - -print("\nSubmitting task...") -try: - runner.submit(test_task, {'test': 'data'}, task_id=0) - print("Task submitted successfully") -except Exception as e: - print(f"Task submission failed: {e}") - runner.destroy() - sys.exit(1) - - -print("\nWaiting for result...") -try: - results = runner.wait(count=1, timeout=5.0) - if results: - print(f"Received result: {results[0].data}") - else: - print("No result received") -except Exception as e: - print(f"Waiting for result failed: {e}") - -runner.destroy() - -print("\n" + "=" * 60) -print("Test passed; task_id was filtered correctly") -print("=" * 60) diff --git a/examples/test_code_agent.py b/examples/test_code_agent.py deleted file mode 100644 index 53fcfe0..0000000 --- a/examples/test_code_agent.py +++ /dev/null @@ -1,352 +0,0 @@ -"""Support code for Test code agent.""" - -from __future__ import annotations - -import asyncio -import os -import sys -import unittest - -_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if _PROJECT_ROOT not in sys.path: - sys.path.insert(0, _PROJECT_ROOT) - -from RL_Framework.env.code_agent_prompt import format_execution_result -from RL_Framework.env.code_executor import CodeExecutor, extract_code_block -from RL_Framework.env.code_reward import code_reward_fn -from RL_Framework.workflow.code_agent import CodeAgentWorkflow - - -# ============================================================================= -# Test 1: Code block extraction -# ============================================================================= - - -def test_extract_code_block(): - """Test extract code block.""" - print("\n[Test] extract_code_block") - - # Case 1: Standard python block - text1 = 'Some reasoning...\n```python\nprint("hello")\n```\nMore text' - code1 = extract_code_block(text1) - assert code1 == 'print("hello")', f"Case 1 failed: {code1}" - print(" Case 1 passed: standard python block") - - # Case 2: Generic code block - text2 = 'Here is the code:\n```\nprint(42)\n```' - code2 = extract_code_block(text2) - assert code2 == "print(42)", f"Case 2 failed: {code2}" - print(" Case 2 passed: generic code block") - - # Case 3: Block with language specifier - text3 = '```python\ndef solve():\n pass\n```' - code3 = extract_code_block(text3) - assert "def solve()" in code3, f"Case 3 failed: {code3}" - print(" Case 3 passed: block with language specifier") - - # Case 4: No code block - text4 = "Just some plain text without code" - code4 = extract_code_block(text4) - assert code4 is None, f"Case 4 failed: {code4}" - print(" Case 4 passed: no code block") - - # Case 5: Multiple code blocks (should return last one) - text5 = '```python\nfirst\n```\n```python\nsecond\n```' - code5 = extract_code_block(text5) - assert code5 == "second", f"Case 5 failed: {code5}" - print(" Case 5 passed: multiple blocks (last one)") - - print(" All extract_code_block tests passed!") - - -# ============================================================================= -# Test 2: Local sandbox execution -# ============================================================================= - - -def test_local_sandbox_stdin(): - """Test local sandbox stdin.""" - print("\n[Test] local_sandbox_stdin") - - executor = CodeExecutor(mode="local", timeout=5) - - code = "import sys\nn = int(sys.stdin.readline())\nprint(n * 2)" - test_cases = { - "inputs": ["5\n", "10\n"], - "outputs": ["10", "20"], - } - - loop = asyncio.get_event_loop() - pass_rate, metadata = loop.run_until_complete(executor.execute(code, test_cases)) - - assert pass_rate == 1.0, f"Expected pass_rate=1.0, got {pass_rate}" - assert metadata["passed"] == 2, f"Expected passed=2, got {metadata['passed']}" - print(f" pass_rate={pass_rate}, passed={metadata['passed']}/{metadata['total']}") - print(" local_sandbox_stdin test passed!") - - -def test_local_sandbox_call_based(): - """Test local sandbox call based.""" - print("\n[Test] local_sandbox_call_based") - - executor = CodeExecutor(mode="local", timeout=5) - - code = """ -class Solution: - def add(self, a: int, b: int) -> int: - return a + b -""" - test_cases = { - "fn_name": "add", - "inputs": ["1\n2", "10\n20"], - "outputs": ["3", "30"], - } - - loop = asyncio.get_event_loop() - pass_rate, metadata = loop.run_until_complete(executor.execute(code, test_cases)) - - assert pass_rate == 1.0, f"Expected pass_rate=1.0, got {pass_rate}" - print(f" pass_rate={pass_rate}, passed={metadata['passed']}/{metadata['total']}") - print(" local_sandbox_call_based test passed!") - - -def test_local_sandbox_failure(): - """Test local sandbox failure.""" - print("\n[Test] local_sandbox_failure") - - executor = CodeExecutor(mode="local", timeout=5) - - # Wrong output - code = "import sys\nn = int(sys.stdin.readline())\nprint(n * 3)" # should be * 2 - test_cases = { - "inputs": ["5\n"], - "outputs": ["10"], - } - - loop = asyncio.get_event_loop() - pass_rate, metadata = loop.run_until_complete(executor.execute(code, test_cases)) - - assert pass_rate == 0.0, f"Expected pass_rate=0.0, got {pass_rate}" - print(f" pass_rate={pass_rate} (expected 0.0 for wrong answer)") - print(" local_sandbox_failure test passed!") - - -# ============================================================================= -# Test 3: Reward function -# ============================================================================= - - -def test_code_reward_fn(): - """Test code reward fn.""" - print("\n[Test] code_reward_fn") - - executor = CodeExecutor(mode="local", timeout=5) - - # Correct code - code_correct = '```python\nimport sys\nn = int(sys.stdin.readline())\nprint(n * 2)\n```' - test_cases = { - "inputs": ["5\n"], - "outputs": ["10"], - } - - reward = code_reward_fn( - prompt="Solve the problem", - completion=code_correct, - test_cases=test_cases, - executor=executor, - continuous=True, - format_weight=0.1, - ) - assert reward > 0.9, f"Expected reward > 0.9 for correct code, got {reward}" - print(f" Correct code reward: {reward:.3f}") - - # Wrong code - code_wrong = '```python\nimport sys\nn = int(sys.stdin.readline())\nprint(n * 3)\n```' - reward_wrong = code_reward_fn( - prompt="Solve the problem", - completion=code_wrong, - test_cases=test_cases, - executor=executor, - continuous=True, - format_weight=0.1, - ) - # Should get format_weight only (0.1) since code is wrong - assert reward_wrong < 0.2, f"Expected reward < 0.2 for wrong code, got {reward_wrong}" - print(f" Wrong code reward: {reward_wrong:.3f}") - - # No code block - code_none = "I think the answer is 10" - reward_none = code_reward_fn( - prompt="Solve the problem", - completion=code_none, - test_cases=test_cases, - executor=executor, - continuous=True, - format_weight=0.1, - ) - assert reward_none == 0.1, f"Expected reward=0.1 (format only), got {reward_none}" - print(f" No code block reward: {reward_none:.3f}") - - print(" code_reward_fn tests passed!") - - -# ============================================================================= -# Test 4: Execution result formatting -# ============================================================================= - - -def test_format_execution_result(): - """Test format execution result.""" - print("\n[Test] format_execution_result") - - # All passed - result1 = format_execution_result( - passed=3, total=3, - metadata_list=[{"status": "success"}, {"status": "success"}, {"status": "success"}] - ) - assert "3/3" in result1, "Should show 3/3 passed" - assert "correct" in result1.lower(), "Should mention correct" - print(" All passed formatting OK") - - # Partial - result2 = format_execution_result( - passed=1, total=3, - metadata_list=[ - {"status": "success"}, - {"status": "wrong_answer", "input": "5", "expected_output": "10", "stdout": "15"}, - {"status": "runtime_error", "error": "IndexError"}, - ] - ) - assert "1/3" in result2, "Should show 1/3 passed" - assert "Failed Cases" in result2, "Should list failed cases" - print(" Partial pass formatting OK") - - # All failed - result3 = format_execution_result( - passed=0, total=2, - metadata_list=[ - {"status": "wrong_answer", "input": "1", "expected_output": "2", "stdout": "3"}, - {"status": "wrong_answer", "input": "2", "expected_output": "4", "stdout": "5"}, - ] - ) - assert "0/2" in result3 or "All tests failed" in result3, "Should show all failed" - print(" All failed formatting OK") - - print(" format_execution_result tests passed!") - - -# ============================================================================= -# Test 5: CodeAgentWorkflow with mock engine -# ============================================================================= - - -class MockEngine: - """Mock engine implementation.""" - - def __init__(self, responses: list[str] | None = None): - self.responses = responses or [] - self.call_count = 0 - - async def generate(self, prompt, max_new_tokens, temperature, n): - if self.call_count < len(self.responses): - text = self.responses[self.call_count] - else: - text = "```python\nprint(1)\n```" - self.call_count += 1 - - tokens = text.split() # rough tokenization for testing - logprobs = [-0.1] * len(tokens) - return {"text": text, "logprobs": logprobs} - - -def test_code_agent_workflow(): - """Test code agent workflow.""" - print("\n[Test] CodeAgentWorkflow") - - from transformers import AutoTokenizer - - - try: - tokenizer = AutoTokenizer.from_pretrained("gpt2") - except Exception: - print(" Skipping workflow test (gpt2 tokenizer not available)") - return - - executor = CodeExecutor(mode="local", timeout=5) - - def simple_reward_fn(prompt, completion, **kwargs): - # Simple reward for testing - if "```python" in completion: - return 0.5 - return 0.0 - - workflow = CodeAgentWorkflow( - reward_fn=simple_reward_fn, - tokenizer=tokenizer, - executor=executor, - max_turns=3, - max_new_tokens=100, - temperature=1.0, - stop_on_submit=True, - ) - - # Mock engine: first response has code, second has submit tag - mock_engine = MockEngine(responses=[ - '```python\nimport sys\nn = int(sys.stdin.readline())\nprint(n * 2)\n```', - '', - ]) - - data = { - "question": "Read an integer and print its double.", - "test_cases": { - "inputs": ["5\n"], - "outputs": ["10"], - }, - } - - loop = asyncio.get_event_loop() - trajectory = loop.run_until_complete(workflow.run_episode(mock_engine, data)) - - # Check trajectory structure - assert "input_ids" in trajectory, "Trajectory should have input_ids" - assert "rewards" in trajectory, "Trajectory should have rewards" - assert "loss_mask" in trajectory, "Trajectory should have loss_mask" - assert trajectory["rewards"].item() == 0.5, f"Expected reward=0.5, got {trajectory['rewards'].item()}" - - # Check that loss_mask has both 0 and 1 values - loss_mask = trajectory["loss_mask"].squeeze().tolist() - assert 0 in loss_mask, "loss_mask should have 0s (prompt/tool parts)" - assert 1 in loss_mask, "loss_mask should have 1s (generation parts)" - - print(f" Reward: {trajectory['rewards'].item()}") - print(f" n_turns: {trajectory['n_turns']}") - print(f" n_executions: {trajectory['n_executions']}") - print(f" Seq length: {trajectory['input_ids'].shape[1]}") - print(" CodeAgentWorkflow test passed!") - - -# ============================================================================= -# Main test runner -# ============================================================================= - - -def run_all_tests(): - print("=" * 60) - print("CodeAgent module unit tests") - print("=" * 60) - - test_extract_code_block() - test_local_sandbox_stdin() - test_local_sandbox_call_based() - test_local_sandbox_failure() - test_code_reward_fn() - test_format_execution_result() - test_code_agent_workflow() - - print("\n" + "=" * 60) - print("All tests passed.") - print("=" * 60) - - -if __name__ == "__main__": - run_all_tests() diff --git a/examples/test_cost_model.py b/examples/test_cost_model.py deleted file mode 100644 index 9e8cfe6..0000000 --- a/examples/test_cost_model.py +++ /dev/null @@ -1,678 +0,0 @@ -"""Support code for Test cost model.""" - -import sys -import os -import json -import time -import numpy as np - - -_project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - -import types -_pkg = types.ModuleType("RL_Framework") -_pkg.__path__ = [_project_root] -_pkg.__package__ = "RL_Framework" -sys.modules["RL_Framework"] = _pkg - -from RL_Framework.config import HardwareConfig, ModelArchConfig, ProfilingConfig -from RL_Framework.infra.cost_model.model import ( - CostModel, - RolloutCostModel, - TrainingCostModel, - RequestInfo, - RolloutClusterConfig, - TrainParallelConfig, -) -from RL_Framework.infra.cost_model.calibrator import ( - ShadowCalibrator, - EpochRunData, - CalibratedParams, -) -from RL_Framework.infra.cost_model.optimizer import ( - TwoLevelNestedOptimizer, - OptimizationResult, - generate_training_configs, - generate_rollout_configs, -) -from RL_Framework.infra.cost_model.resource_alloc import CostModelAllocator - - -def separator(title: str): - print(f"\n{'='*60}") - print(f" {title}") - print(f"{'='*60}") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_rollout_cost_model(): - separator("Test 1: RolloutCostModel (PagedAttention + Roofline + steady-state projection)") - - hw = HardwareConfig() - ma = ModelArchConfig(num_params=7e9, d_model=3584, n_layers=28, n_heads=28, n_kv_heads=4) - prof = ProfilingConfig() - - model = RolloutCostModel( - num_params=ma.num_params, - d_model=ma.d_model, - n_layers=ma.n_layers, - n_kv_heads=ma.n_kv_heads, - head_dim=ma.head_dim, - dtype_bytes=ma.dtype_bytes, - flops_peak=hw.flops_peak, - mem_bw=hw.mem_bw, - mem_capacity=hw.mem_capacity, - tp_comm_overhead=hw.tp_comm_overhead, - prefill_mfu=prof.prefill_mfu, - decode_bw_util=prof.decode_bw_util, - prefill_chunk_size=prof.prefill_chunk_size, - kv_frag_rate=prof.kv_frag_rate, - act_workspace_bytes=prof.act_workspace_bytes, - ) - - - print("\n [memory model]") - for tp in [1, 2, 4, 8]: - s_token = model.compute_token_kv_bytes(tp) - kv_pool = model.compute_kv_pool(tp) - n_max = model.compute_token_capacity(tp) - print(f" TP={tp}: S_token_kv={s_token:.0f}B, " - f"KV_pool={kv_pool/1e9:.1f}GB, N_max={n_max} tokens") - - - print("\n [Roofline step time]") - for tp in [1, 2, 4]: - t_prefill = model.compute_prefill_step_time(B_prefill=1, L_chunk=1024, tp=tp) - t_decode_small = model.compute_decode_step_time(total_active_tokens=4096, tp=tp) - t_decode_large = model.compute_decode_step_time(total_active_tokens=32768, tp=tp) - print(f" TP={tp}: prefill_chunk={t_prefill*1000:.2f}ms, " - f"decode(4k tok)={t_decode_small*1000:.2f}ms, " - f"decode(32k tok)={t_decode_large*1000:.2f}ms") - - - print("\n [steady-state projection]") - for tp in [1, 2, 4]: - b_bar = model.compute_steady_state_batch(tp, avg_prompt_len=300, avg_gen_len=500) - print(f" TP={tp}: steady_B={b_bar:.1f}") - - - print("\n [single-instance makespan]") - requests = [ - RequestInfo(prompt_length=256, gen_length=300), - RequestInfo(prompt_length=512, gen_length=200), - RequestInfo(prompt_length=128, gen_length=800), - ] - for tp in [1, 2, 4]: - t = model.compute_instance_makespan(requests, tp=tp) - print(f" TP={tp}, 3 reqs: {t:.4f}s") - - - print("\n [OOM check]") - for seq_len, tp in [(4096, 1), (4096, 2), (16384, 1), (16384, 4), (32768, 8)]: - oom = model.check_oom(seq_len, tp) - n_max = model.compute_token_capacity(tp) - print(f" seq={seq_len}, TP={tp}, N_max={n_max}: {'OOM!' if oom else 'OK'}") - - - print("\n [cluster evaluation (greedy throughput allocation)]") - cluster = RolloutClusterConfig(tp_list=[4, 2, 2]) - np.random.seed(42) - requests = [ - RequestInfo( - prompt_length=int(np.random.uniform(128, 512)), - gen_length=int(np.random.uniform(64, 1024)), - ) - for _ in range(50) - ] - makespan, details = model.evaluate_cluster(cluster, requests) - print(f" Cluster={cluster.tp_list}, 50 reqs") - print(f" Makespan: {makespan:.4f}s") - print(f" Instance times: {[f'{t:.4f}' for t in details.get('instance_times', [])]}") - print(f" Reqs/instance: {details.get('requests_per_instance', [])}") - - print("\n [PASS] RolloutCostModel tests passed") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_training_cost_model(): - separator("Test 2: TrainingCostModel (memory model + Profiling + 1F1B)") - - hw = HardwareConfig() - ma = ModelArchConfig(num_params=7e9, d_model=3584, n_layers=28, n_heads=28, n_kv_heads=4) - prof = ProfilingConfig() - - model = TrainingCostModel( - num_params=ma.num_params, - d_model=ma.d_model, - n_layers=ma.n_layers, - n_kv_heads=ma.n_kv_heads, - head_dim=ma.head_dim, - dtype_bytes=ma.dtype_bytes, - flops_peak=hw.flops_peak, - mem_bw=hw.mem_bw, - mem_capacity=hw.mem_capacity, - bw_intra_node=hw.bw_intra_node, - bw_inter_node=hw.bw_inter_node, - gpus_per_node=hw.gpus_per_node, - latency_inter_node=hw.latency_inter_node, - alpha_mlp_fwd=prof.alpha_mlp_fwd, - beta_mlp_fwd=prof.beta_mlp_fwd, - alpha_mlp_bwd=prof.alpha_mlp_bwd, - beta_mlp_bwd=prof.beta_mlp_bwd, - alpha_attn_fwd=prof.alpha_attn_fwd, - beta_attn_fwd=prof.beta_attn_fwd, - gamma_attn_fwd=prof.gamma_attn_fwd, - alpha_attn_bwd=prof.alpha_attn_bwd, - beta_attn_bwd=prof.beta_attn_bwd, - gamma_attn_bwd=prof.gamma_attn_bwd, - rho_compute_bound=prof.rho_compute_bound, - rho_memory_bound=prof.rho_memory_bound, - theta_slowdown=prof.theta_slowdown, - train_mem_frag_rate=prof.train_mem_frag_rate, - train_workspace_bytes=prof.train_workspace_bytes, - ) - - - print("\n [Memory model and OOM pruning]") - configs = [ - TrainParallelConfig(tp=1, pp=1, dp=4, b_micro=4), - TrainParallelConfig(tp=2, pp=1, dp=2, b_micro=4), - TrainParallelConfig(tp=2, pp=2, dp=1, b_micro=4), - TrainParallelConfig(tp=4, pp=1, dp=1, b_micro=4), - TrainParallelConfig(tp=1, pp=1, dp=1, b_micro=8), - ] - L = 2048 - for cfg in configs: - mem = model.estimate_memory_per_gpu(cfg, cfg.b_micro, L) - oom = model.check_memory_oom(cfg, cfg.b_micro, L) - print(f" TP={cfg.tp} PP={cfg.pp} DP={cfg.dp} b={cfg.b_micro}: " - f"mem={mem/1e9:.2f}GB {'OOM!' if oom else 'OK'}") - - - print("\n [communication model]") - for cfg in configs[:4]: - t_tp = model.compute_tp_comm(cfg.tp, cfg.b_micro, L) - t_pp = model.compute_pp_comm(cfg, L) - t_dp = model.compute_dp_comm(cfg) - print(f" TP={cfg.tp} PP={cfg.pp} DP={cfg.dp}: " - f"TP_comm={t_tp*1000:.2f}ms, PP_comm={t_pp*1000:.2f}ms, " - f"DP_comm={t_dp*1000:.2f}ms") - - - print("\n [Profiled compute time for one layer]") - for L_test in [1024, 2048, 4096, 8192]: - t_mlp_fwd = model.compute_pure_mlp_time(L_test, b_micro=4, tp=2, is_bwd=False) - t_attn_fwd = model.compute_pure_attn_time(L_test, b_micro=4, tp=2, is_bwd=False) - t_mlp_bwd = model.compute_pure_mlp_time(L_test, b_micro=4, tp=2, is_bwd=True) - t_attn_bwd = model.compute_pure_attn_time(L_test, b_micro=4, tp=2, is_bwd=True) - print(f" L={L_test}: mlp_fwd={t_mlp_fwd*1000:.3f}ms, attn_fwd={t_attn_fwd*1000:.3f}ms, " - f"mlp_bwd={t_mlp_bwd*1000:.3f}ms, attn_bwd={t_attn_bwd*1000:.3f}ms") - - - print("\n [1F1B pipeline timeline]") - for cfg in configs[:4]: - t_fwd = model.compute_stage_fwd_time(L, cfg) - t_bwd = model.compute_stage_bwd_time(L, cfg) - n_micro = max(1, 32 // cfg.dp // cfg.b_micro) - t_pipeline = model.compute_pipeline_time(t_fwd, t_bwd, n_micro, cfg.pp) - print(f" TP={cfg.tp} PP={cfg.pp} DP={cfg.dp}: " - f"fwd={t_fwd*1000:.2f}ms, bwd={t_bwd*1000:.2f}ms, " - f"n_micro={n_micro}, pipeline={t_pipeline*1000:.1f}ms") - - - print("\n [Full iteration time]") - B_global = 32 - for cfg in configs[:4]: - t_iter, details = model.compute_iteration_time(cfg, B_global, L) - print(f" TP={cfg.tp} PP={cfg.pp} DP={cfg.dp}: " - f"T_iter={t_iter*1000:.1f}ms " - f"(pipeline={details['t_pipeline']*1000:.1f}ms, " - f"dp_exposed={details['t_dp_exposed']*1000:.1f}ms)") - - print("\n [PASS] TrainingCostModel tests passed") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_shadow_calibrator(): - separator("Test 3: ShadowCalibrator (EMA + change-point detection)") - - calibrator = ShadowCalibrator( - alpha_default=0.1, - alpha_emergency=0.8, - change_point_threshold=3.0, - history_window=20, - min_epochs_for_calibration=2, - ) - - print(" Initial parameters:", calibrator.get_calibrated_params()) - - - print("\n [Phase 1] normal operation:") - for epoch in range(5): - data = EpochRunData( - t_train_real=10.0 + np.random.normal(0, 0.5), - t_rollout_real=8.0 + np.random.normal(0, 0.3), - t_train_predicted=10.0, - t_rollout_predicted=8.0, - gen_lengths=list(np.random.normal(500, 100, size=50).clip(min=16)), - prompt_lengths=list(np.random.normal(200, 50, size=50).clip(min=16)), - epoch_id=epoch, - ) - params = calibrator.update(data) - print(f" Epoch {epoch}: eta_comp={params.eta_comp:.3f}, " - f"eta_mem={params.eta_mem:.3f}, mu_gen={params.mu_gen:.0f}") - - - print("\n [Phase 2] capability emergence:") - for epoch in range(5, 10): - data = EpochRunData( - t_train_real=15.0 + np.random.normal(0, 0.5), - t_rollout_real=20.0 + np.random.normal(0, 1.0), - t_train_predicted=10.0, - t_rollout_predicted=8.0, - gen_lengths=list(np.random.normal(1500, 300, size=50).clip(min=16)), - prompt_lengths=list(np.random.normal(200, 50, size=50).clip(min=16)), - epoch_id=epoch, - ) - params = calibrator.update(data) - print(f" Epoch {epoch}: eta_comp={params.eta_comp:.3f}, " - f"eta_mem={params.eta_mem:.3f}, mu_gen={params.mu_gen:.0f}, " - f"change_point={calibrator._is_change_point}") - - stats = calibrator.get_statistics() - print(f"\n Final statistics: {stats}") - print("\n [PASS] ShadowCalibrator tests passed") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_config_generation(): - separator("Test 4: configuration-space generation") - - train_configs = generate_training_configs( - n_total_gpus=8, - allowed_tp=[1, 2, 4], - allowed_pp=[1, 2], - micro_batch_sizes=[4], - ) - print(f" Training configuration space (8 GPUs): {len(train_configs)} configurations") - for cfg in train_configs[:10]: - print(f" TP={cfg.tp} PP={cfg.pp} DP={cfg.dp} ({cfg.n_gpus} GPUs)") - if len(train_configs) > 10: - print(f" ... total {len(train_configs)} configurations") - - rollout_configs = generate_rollout_configs( - n_gpus=4, allowed_tp_sizes=[1, 2, 4], - ) - print(f"\n Rollout configuration space (4 GPUs, TP=[1,2,4]): {len(rollout_configs)} configurations") - for cfg in rollout_configs: - print(f" {cfg.tp_list}") - - print("\n [PASS] Configuration-space generation tests passed") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_nested_optimizer(): - separator("Test 5: TwoLevelNestedOptimizer (two-level nested optimization)") - - hw = HardwareConfig() - ma = ModelArchConfig(num_params=7e9, d_model=3584, n_layers=28, n_heads=28, n_kv_heads=4) - cost_model = CostModel(hardware=hw, model_arch=ma) - - optimizer = TwoLevelNestedOptimizer( - cost_model=cost_model, - allowed_rollout_tp=[1, 2, 4], - verbose=True, - ) - - - np.random.seed(42) - n_requests = 100 - requests = [ - RequestInfo( - prompt_length=int(np.random.uniform(150, 400)), - gen_length=int(np.random.exponential(300) + 50), - ) - for _ in range(n_requests) - ] - gen_lengths = [r.gen_length for r in requests] - print(f" Request distribution: n={n_requests}, " - f"gen_mean={np.mean(gen_lengths):.0f}, " - f"gen_p95={np.percentile(gen_lengths, 95):.0f}, " - f"gen_max={max(gen_lengths)}") - - - result = optimizer.optimize( - n_total_gpus=8, - requests=requests, - B_global=32, - allowed_train_tp=[1, 2, 4], - allowed_train_pp=[1, 2], - micro_batch_sizes=[4], - ) - - print(result.summary()) - - - assert result.t_global < float("inf"), "Optimizer did not find a feasible solution!" - assert result.train_config is not None, "Missing training configuration!" - assert result.rollout_config is not None, "Missing rollout configuration!" - assert result.train_config.n_gpus + result.rollout_config.n_gpus <= 8, "GPU budget exceeded!" - - - print("\n --- Rollout-only optimization ---") - rc, makespan, details = optimizer.optimize_rollout_only( - n_rollout_gpus=4, - requests=requests, - ) - print(f" Optimal rollout configuration: {rc.tp_list if rc else None}") - print(f" Makespan: {makespan:.6f}s") - - print("\n [PASS] TwoLevelNestedOptimizer tests passed") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_cost_model_allocator(): - separator("Test 6: CostModelAllocator (end-to-end integration)") - - hw = HardwareConfig() - ma = ModelArchConfig(num_params=7e9, d_model=3584, n_layers=28, n_heads=28, n_kv_heads=4) - - allocator = CostModelAllocator( - hardware=hw, - model_arch=ma, - allowed_rollout_tp=[1, 2, 4], - verbose=False, - ) - - - np.random.seed(123) - length_dist = [ - (int(np.random.uniform(150, 400)), int(np.random.exponential(300) + 50)) - for _ in range(80) - ] - - result = allocator.allocate_resources( - n_total_gpus=8, - length_distribution=length_dist, - B_global=32, - ) - print(f" Optimization result:") - print(f" Training: TP={result.train_config.tp}, PP={result.train_config.pp}, " - f"DP={result.train_config.dp}" if result.train_config else " Training: None") - print(f" Rollout: {result.rollout_config.tp_list}" if result.rollout_config else " Rollout: None") - print(f" T_global: {result.t_global:.6f}s") - - - for epoch in range(3): - epoch_data = EpochRunData( - t_train_real=result.t_train * (1 + np.random.normal(0, 0.1)), - t_rollout_real=result.t_rollout * (1 + np.random.normal(0, 0.1)), - t_train_predicted=result.t_train, - t_rollout_predicted=result.t_rollout, - gen_lengths=[gl for _, gl in length_dist], - prompt_lengths=[pl for pl, _ in length_dist], - epoch_id=epoch, - ) - cal_params = allocator.update_calibration(epoch_data) - print(f" Calibration epoch {epoch}: eta_comp={cal_params['eta_comp']:.3f}, " - f"eta_mem={cal_params['eta_mem']:.3f}") - - report = allocator.get_optimization_report() - print(f" Optimization count: {report['optimization_count']}") - print(f" Calibration confidence: {report['calibration_stats']['confidence']:.2f}") - - print("\n [PASS] CostModelAllocator integration tests passed") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_performance_benchmark(): - separator("Test 7: optimizer benchmark") - - hw = HardwareConfig() - ma = ModelArchConfig(num_params=7e9, d_model=3584, n_layers=28, n_heads=28, n_kv_heads=4) - cost_model = CostModel(hardware=hw, model_arch=ma) - optimizer = TwoLevelNestedOptimizer( - cost_model=cost_model, - allowed_rollout_tp=[1, 2, 4], - ) - - np.random.seed(0) - requests = [ - RequestInfo( - prompt_length=int(np.random.uniform(100, 500)), - gen_length=int(np.random.exponential(400) + 30), - ) - for _ in range(200) - ] - - - times = [] - for _ in range(5): - start = time.perf_counter() - result = optimizer.optimize( - n_total_gpus=8, - requests=requests, - B_global=32, - allowed_train_tp=[1, 2, 4], - allowed_train_pp=[1, 2], - micro_batch_sizes=[4], - ) - elapsed = (time.perf_counter() - start) * 1000 - times.append(elapsed) - - avg_ms = np.mean(times) - std_ms = np.std(times) - print(f" 8-GPU, 200 requests, TP=[1,2,4], PP=[1,2]:") - print(f" Average optimization time: {avg_ms:.2f} +/- {std_ms:.2f} ms") - print(f" Configurations explored: {result.n_configs_explored}") - print(f" OOM prunes: {result.n_configs_pruned_oom}") - print(f" Early-stop prunes: {result.n_configs_pruned_early_stop}") - - if avg_ms < 1000: - print(" [OK] Optimization time < 1s; suitable for online execution") - else: - print(" [WARN] Optimization is slow; consider reducing the search space") - - print("\n [PASS] Performance benchmark passed") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- - -_KNOWN_MODEL_ARCH = { - "Qwen2.5-3B": dict(num_params=3.0e+9, d_model=2048, n_layers=36, n_heads=16, n_kv_heads=2, vocab_size=151936, intermediate_size=11008), - "Qwen2.5-7B": dict(num_params=7.0e+9, d_model=3584, n_layers=28, n_heads=28, n_kv_heads=4, vocab_size=152064, intermediate_size=18944), - "Qwen2.5-14B": dict(num_params=14.0e+9, d_model=5120, n_layers=40, n_heads=40, n_kv_heads=8, vocab_size=152064, intermediate_size=13824), - "Qwen2.5-32B": dict(num_params=32.0e+9, d_model=5120, n_layers=64, n_heads=40, n_kv_heads=8, vocab_size=152064, intermediate_size=27648), - "Qwen2.5-72B": dict(num_params=72.0e+9, d_model=8192, n_layers=80, n_heads=64, n_kv_heads=8, vocab_size=152064, intermediate_size=29568), - "Qwen3-4B": dict(num_params=4.0e+9, d_model=2560, n_layers=36, n_heads=32, n_kv_heads=4, vocab_size=151936, intermediate_size=9728), - "Qwen3-8B": dict(num_params=8.0e+9, d_model=4096, n_layers=36, n_heads=32, n_kv_heads=8, vocab_size=151936, intermediate_size=12288), - "Qwen3-14B": dict(num_params=14.0e+9, d_model=5120, n_layers=40, n_heads=40, n_kv_heads=8, vocab_size=151936, intermediate_size=17408), - "Qwen3-32B": dict(num_params=32.0e+9, d_model=5120, n_layers=64, n_heads=40, n_kv_heads=8, vocab_size=151936, intermediate_size=25600), - "Qwen3-30B-A3B": dict(num_params=30.0e+9, d_model=2048, n_layers=48, n_heads=32, n_kv_heads=4, vocab_size=151936, intermediate_size=6144), -} - - -def _match_model_arch(model_name: str) -> dict: - """Match model arch.""" - for key, params in _KNOWN_MODEL_ARCH.items(): - if key in model_name: - return params - print(f" [WARN] Unknown model: {model_name[:60]}..., using default Qwen2.5-7B parameters") - return _KNOWN_MODEL_ARCH["Qwen2.5-7B"] - - -def load_sequence_profile(profile_path: str) -> dict: - """Load sequence profile.""" - with open(profile_path, "r", encoding="utf-8") as f: - data = json.load(f) - return data - - -def profile_to_requests(profile: dict) -> list[RequestInfo]: - """Profile to requests.""" - requests = [] - for seq in profile.get("sequences", []): - prompt_len = int(seq.get("input_tokens", 0)) - gen_len = int(seq.get("actual_output_tokens", seq.get("estimated_output_tokens", 0))) - if prompt_len > 0 and gen_len > 0: - requests.append(RequestInfo(prompt_length=prompt_len, gen_length=gen_len)) - return requests - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_real_profile(): - separator("Test 8: real-profile end-to-end test") - - profile_base = os.path.join(os.path.dirname(os.path.abspath(__file__)), "profile") - if not os.path.isdir(profile_base): - print(f" [SKIP] Profile directory does not exist: {profile_base}") - print(" [PASS] Skipping real-profile test (no data)") - return - - profiles = [] - for dataset_dir in sorted(os.listdir(profile_base)): - dataset_path = os.path.join(profile_base, dataset_dir) - profile_file = os.path.join(dataset_path, "sequence_profile.json") - if os.path.isdir(dataset_path) and os.path.isfile(profile_file): - profiles.append((dataset_dir, profile_file)) - - if not profiles: - print(" [SKIP] No sequence_profile.json files found") - print(" [PASS] Skipping real-profile test (no data)") - return - - print(f" Found {len(profiles)} profile datasets: {[p[0] for p in profiles]}") - - for dataset_name, profile_path in profiles: - print(f"\n {'─'*50}") - print(f" Dataset: {dataset_name}") - print(f" {'─'*50}") - - profile = load_sequence_profile(profile_path) - model_name = profile.get("model_name", "unknown") - arch_params = _match_model_arch(model_name) - ma = ModelArchConfig(**arch_params) - - print(f" Model: ...{model_name[-50:]}") - print(f" Architecture: P={ma.num_params:.1e}, d={ma.d_model}, L={ma.n_layers}, " - f"kv_heads={ma.n_kv_heads}") - - requests = profile_to_requests(profile) - if not requests: - print(" [SKIP] No valid sequence data") - continue - - gen_lengths = [r.gen_length for r in requests] - prompt_lengths = [r.prompt_length for r in requests] - total_lengths = [r.total_length for r in requests] - - print(f" Sequences: {len(requests)}") - print(f" Prompt: mean={np.mean(prompt_lengths):.0f}, max={max(prompt_lengths)}") - print(f" Gen: mean={np.mean(gen_lengths):.0f}, " - f"p95={np.percentile(gen_lengths, 95):.0f}, max={max(gen_lengths)}") - print(f" Total: mean={np.mean(total_lengths):.0f}, max={max(total_lengths)}") - - - hw = HardwareConfig() - cost_model = CostModel(hardware=hw, model_arch=ma) - - - print("\n [Rollout time prediction]") - for tp in [1, 2, 4, 8]: - oom = cost_model.rollout_model.check_oom(max(total_lengths), tp) - if oom: - print(f" TP={tp}: OOM (N_max={cost_model.rollout_model.compute_token_capacity(tp)})") - continue - - predicted_times = [] - for req in requests: - t = cost_model.rollout_model.compute_instance_makespan([req], tp) - predicted_times.append(t) - pred_mean = np.mean(predicted_times) - pred_p50 = np.percentile(predicted_times, 50) - print(f" TP={tp}: pred_mean={pred_mean:.3f}s, pred_p50={pred_p50:.3f}s") - - - print(f"\n [two-level optimizer]") - if ma.num_params >= 30e9: - n_total_gpus, allowed_tp, allowed_pp = 16, [1, 2, 4, 8], [1, 2, 4] - elif ma.num_params >= 10e9: - n_total_gpus, allowed_tp, allowed_pp = 16, [1, 2, 4, 8], [1, 2, 4] - else: - n_total_gpus, allowed_tp, allowed_pp = 16, [1, 2, 4, 8], [1, 2, 4] - - optimizer = TwoLevelNestedOptimizer( - cost_model=cost_model, allowed_rollout_tp=allowed_tp, verbose=False, - ) - - start = time.perf_counter() - - result = optimizer.optimize( - n_total_gpus=n_total_gpus, requests=requests, B_global=64, - allowed_train_tp=allowed_tp, allowed_train_pp=allowed_pp, - micro_batch_sizes=[16], - ) - elapsed_ms = (time.perf_counter() - start) * 1000 - - if result.train_config and result.rollout_config: - print(f" GPU={n_total_gpus}: " - f"Train(TP={result.train_config.tp},PP={result.train_config.pp}," - f"DP={result.train_config.dp}) + " - f"Rollout({result.rollout_config.tp_list})") - print(f" T_train={result.t_train:.4f}s, T_rollout={result.t_rollout:.4f}s, " - f"T_global={result.t_global:.4f}s") - print(f" Search: {result.n_configs_explored} configs, " - f"OOM={result.n_configs_pruned_oom}, " - f"early stop={result.n_configs_pruned_early_stop}") - print(f" Optimization time: {elapsed_ms:.1f}ms") - total_used = result.train_config.n_gpus + result.rollout_config.n_gpus - assert total_used <= n_total_gpus, f"GPU budget exceeded: {total_used} > {n_total_gpus}" - else: - print(f" No feasible solution") - - print("\n [PASS] Real-profile end-to-end test passed") - - -# --------------------------------------------------------------------------- -# Main -# --------------------------------------------------------------------------- -def main(): - print("=" * 60) - print(" Cost Model v2 and two-level optimizer end-to-end tests") - print("=" * 60) - - test_rollout_cost_model() - test_training_cost_model() - test_shadow_calibrator() - test_config_generation() - test_nested_optimizer() - test_cost_model_allocator() - test_performance_benchmark() - test_real_profile() - - print("\n" + "=" * 60) - print(" ALL TESTS PASSED!") - print("=" * 60) - - -if __name__ == "__main__": - main() diff --git a/examples/test_dapo_math_data.py b/examples/test_dapo_math_data.py deleted file mode 100644 index 0acb814..0000000 --- a/examples/test_dapo_math_data.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Validate local DAPO-Math-17K files before launching a long training job.""" - -from __future__ import annotations - -import os -from pathlib import Path - -from datasets import load_dataset - -from examples.dapo_math_async_rl import _find_dataset_file, _preprocess - - -def main(): - data_file, data_format = _find_dataset_file() - dataset = load_dataset(data_format, data_files=str(data_file), split="train") - dataset = dataset.map(_preprocess, with_indices=True) - dataset = dataset.filter(lambda row: bool(row.get("question")) and bool(row.get("ground_truth"))) - seen_prompt_ids: set[str] = set() - - def keep_first(row): - prompt_id = str(row.get("prompt_id") or "") - if prompt_id in seen_prompt_ids: - return False - seen_prompt_ids.add(prompt_id) - return True - - raw_usable_rows = len(dataset) - dataset = dataset.filter(keep_first) - if len(dataset) == 0: - raise RuntimeError(f"DAPO-Math data has no usable rows: {data_file}") - min_rows = int(os.environ.get("DAPO_MIN_ROWS", "1000")) - if len(dataset) < min_rows: - raise RuntimeError(f"DAPO-Math data has only {len(dataset)} usable rows; expected at least {min_rows}") - print(f"DAPO-Math data OK: {len(dataset)} unique usable rows from {Path(data_file)}") - print(f"Raw usable rows before prompt_id deduplication: {raw_usable_rows}") - print(f"First prompt_id: {dataset[0]['prompt_id']}") - print(f"First question preview: {dataset[0]['question'][:160].replace(chr(10), ' ')}") - - -if __name__ == "__main__": - main() diff --git a/examples/test_hetero_config.py b/examples/test_hetero_config.py deleted file mode 100644 index 6bc62e1..0000000 --- a/examples/test_hetero_config.py +++ /dev/null @@ -1,491 +0,0 @@ -"""Support code for Test hetero config.""" - -import sys -import os -import tempfile -import textwrap - - -_project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - -import types -_pkg = types.ModuleType("RL_Framework") -_pkg.__path__ = [_project_root] -_pkg.__package__ = "RL_Framework" -sys.modules.setdefault("RL_Framework", _pkg) - -from RL_Framework.config import ( - AsyncRLConfig, - HeterogeneousRolloutConfig, - HeterogeneousInstanceConfig, - SchedulingConfig, - _from_dict, -) - - -# ===================================================================== - -# ===================================================================== - -_pass_count = 0 -_fail_count = 0 - - -def check(name: str, condition: bool, detail: str = ""): - global _pass_count, _fail_count - if condition: - _pass_count += 1 - print(f" [PASS] {name}") - else: - _fail_count += 1 - msg = f" [FAIL] {name}" - if detail: - msg += f" -- {detail}" - print(msg) - - -def section(title: str): - print(f"\n{'='*60}") - print(f" {title}") - print(f"{'='*60}") - - -# ===================================================================== - -# ===================================================================== - -def test_instance_config_defaults(): - """Test instance config defaults.""" - section("1.1 HeterogeneousInstanceConfig default value") - cfg = HeterogeneousInstanceConfig() - check("Default instance_id is empty", cfg.instance_id == "") - check("Default tp=1", cfg.tp == 1) - check("Default gpus is an empty list", cfg.gpus == []) - check("Default description is empty", cfg.description == "") - - -def test_instance_config_from_dict(): - """Test instance config from dict.""" - section("1.2 HeterogeneousInstanceConfig from_dict") - d = {"instance_id": "tp2_inst0", "tp": 2, "gpus": [4, 5], "description": "TP=2"} - cfg = HeterogeneousInstanceConfig.from_dict(d) - check("instance_id is correct", cfg.instance_id == "tp2_inst0") - check("tp=2", cfg.tp == 2) - check("gpus=[4,5]", cfg.gpus == [4, 5]) - check("description", cfg.description == "TP=2") - - -def test_instance_config_from_dict_extra_keys(): - """Test instance config from dict extra keys.""" - section("1.3 HeterogeneousInstanceConfig extra keys") - d = {"tp": 4, "gpus": [0, 1, 2, 3], "unknown_key": "should_be_ignored"} - cfg = HeterogeneousInstanceConfig.from_dict(d) - check("tp=4", cfg.tp == 4) - check("gpus is correct", cfg.gpus == [0, 1, 2, 3]) - check("No unknown_key attribute", not hasattr(cfg, "unknown_key")) - - -# ===================================================================== - -# ===================================================================== - -def test_scheduling_config_defaults(): - """Test scheduling config defaults.""" - section("2.1 SchedulingConfig default value") - cfg = SchedulingConfig() - check("Default scheduler_type='length_aware'", cfg.scheduler_type == "length_aware") - check("Default load_balance='least_connections'", cfg.load_balance_strategy == "least_connections") - check("Default max_queue_length=100", cfg.max_queue_length == 100) - check("Default enable_fallback=True", cfg.enable_fallback is True) - check("length_thresholds contains short/medium/long", - all(k in cfg.length_thresholds for k in ["short", "medium", "long"])) - check("routing_rules contains four categories", - len(cfg.routing_rules) == 4) - - -def test_scheduling_config_la_mlfq_fields(): - """Test scheduling config la mlfq fields.""" - section("2.2 SchedulingConfig LA-MLFQ specific fields") - cfg = SchedulingConfig() - check("la_mlfq_buckets has short/long", - "short" in cfg.la_mlfq_buckets and "long" in cfg.la_mlfq_buckets) - check("la_mlfq_migration_threshold=3000", cfg.la_mlfq_migration_threshold == 3000) - check("la_mlfq_scout_timeout=30.0", cfg.la_mlfq_scout_timeout == 30.0) - check("la_mlfq_history_ttl=5", cfg.la_mlfq_history_ttl == 5) - - - short_bucket = cfg.la_mlfq_buckets["short"] - check("Short bucket has tp_degrees", "tp_degrees" in short_bucket) - check("Short bucket has max_tokens", "max_tokens" in short_bucket) - - -def test_scheduling_config_from_dict(): - """Test scheduling config from dict.""" - section("2.3 SchedulingConfig from_dict") - d = { - "scheduler_type": "la_mlfq", - "load_balance_strategy": "round_robin", - "max_queue_length": 64, - "la_mlfq_migration_threshold": 5000, - "la_mlfq_scout_timeout": 60.0, - "length_thresholds": {"short": 1024, "medium": 2048, "long": 4096}, - } - cfg = SchedulingConfig.from_dict(d) - check("scheduler_type='la_mlfq'", cfg.scheduler_type == "la_mlfq") - check("load_balance='round_robin'", cfg.load_balance_strategy == "round_robin") - check("max_queue_length=64", cfg.max_queue_length == 64) - check("la_mlfq_migration_threshold=5000", cfg.la_mlfq_migration_threshold == 5000) - check("la_mlfq_scout_timeout=60.0", cfg.la_mlfq_scout_timeout == 60.0) - check("length_thresholds.short=1024", cfg.length_thresholds["short"] == 1024) - - -# ===================================================================== - -# ===================================================================== - -def test_hetero_config_defaults(): - """Test hetero config defaults.""" - section("3.1 HeterogeneousRolloutConfig default value") - cfg = HeterogeneousRolloutConfig() - check("Default enabled=False", cfg.enabled is False) - check("Default instances is empty", len(cfg.instances) == 0) - check("Default total_gpus=0", cfg.total_gpus == 0) - check("Default vllm_base_port=8000", cfg.vllm_base_port == 8000) - check("scheduling is a SchedulingConfig", isinstance(cfg.scheduling, SchedulingConfig)) - - -def test_hetero_config_from_dict(): - """Test hetero config from dict.""" - section("3.2 HeterogeneousRolloutConfig from_dict") - d = { - "enabled": True, - "total_gpus": 6, - "available_gpus": [2, 3, 4, 5, 6, 7], - "vllm_host": "127.0.0.1", - "vllm_base_port": 8000, - "gpu_memory_utilization": 0.90, - "instances": [ - {"instance_id": "tp1_inst0", "tp": 1, "gpus": [2]}, - {"instance_id": "tp1_inst1", "tp": 1, "gpus": [3]}, - {"instance_id": "tp2_inst0", "tp": 2, "gpus": [4, 5]}, - {"instance_id": "tp2_inst1", "tp": 2, "gpus": [6, 7]}, - ], - "scheduling": { - "scheduler_type": "la_mlfq", - "length_thresholds": {"short": 1024, "medium": 2048, "long": 4096}, - "routing_rules": {"short": [1], "medium": [1, 2], "long": [2], "extra_long": [2]}, - "load_balance_strategy": "least_connections", - "max_queue_length": 64, - }, - } - cfg = HeterogeneousRolloutConfig.from_dict(d) - - check("enabled=True", cfg.enabled is True) - check("total_gpus=6", cfg.total_gpus == 6) - check("Four instances", len(cfg.instances) == 4) - check("n_instances=4", cfg.n_instances == 4) - check("tp_list=[1,1,2,2]", cfg.tp_list == [1, 1, 2, 2]) - - - check("Instance 0 is a HeterogeneousInstanceConfig", - isinstance(cfg.instances[0], HeterogeneousInstanceConfig)) - check("Instance 0 tp=1", cfg.instances[0].tp == 1) - check("Instance 2 tp=2", cfg.instances[2].tp == 2) - check("Instance 2 gpus=[4,5]", cfg.instances[2].gpus == [4, 5]) - - - check("scheduling.scheduler_type='la_mlfq'", cfg.scheduling.scheduler_type == "la_mlfq") - check("scheduling.max_queue_length=64", cfg.scheduling.max_queue_length == 64) - check("scheduling.length_thresholds.short=1024", - cfg.scheduling.length_thresholds["short"] == 1024) - - -def test_hetero_config_auto_compute(): - """Test hetero config auto compute.""" - section("3.3 HeterogeneousRolloutConfig automatic calculation") - d = { - "enabled": True, - "instances": [ - {"tp": 1, "gpus": [0]}, - {"tp": 2, "gpus": [1, 2]}, - {"tp": 4, "gpus": [3, 4, 5, 6]}, - ], - } - cfg = HeterogeneousRolloutConfig.from_dict(d) - - check("Automatically computes total_gpus=1+2+4=7", cfg.total_gpus == 7) - check("tp_list=[1,2,4]", cfg.tp_list == [1, 2, 4]) - - - check("Instance 0 automatic ID", cfg.instances[0].instance_id == "hetero_tp1_0") - check("Instance 1 automatic ID", cfg.instances[1].instance_id == "hetero_tp2_1") - check("Instance 2 automatic ID", cfg.instances[2].instance_id == "hetero_tp4_2") - - -# ===================================================================== - -# ===================================================================== - -def test_async_rl_config_training_cluster(): - """Test async rl config training cluster.""" - section("4.1 AsyncRLConfig training cluster configuration") - cfg = AsyncRLConfig( - model_path="/path/to/user/test_model", - train_gpus=4, - rollout_gpus=4, - tp_size=2, - vllm_tp_size=2, - learning_rate=1e-6, - batch_size=32, - total_steps=100, - ) - check("model_path is correct", cfg.model_path == "/path/to/user/test_model") - check("train_gpus=4", cfg.train_gpus == 4) - check("rollout_gpus=4", cfg.rollout_gpus == 4) - check("tp_size=2", cfg.tp_size == 2) - check("vllm_tp_size=2", cfg.vllm_tp_size == 2) - check("learning_rate=1e-6", cfg.learning_rate == 1e-6) - check("batch_size=32", cfg.batch_size == 32) - check("total_steps=100", cfg.total_steps == 100) - check("train_backend defaults to fsdp", cfg.train_backend == "fsdp") - check("train_tp_size inherits tp_size", cfg.train_tp_size == 2) - check("train_pp_size defaults to 1", cfg.train_pp_size == 1) - check("train_dp_size is inferred as 2", cfg.train_dp_size == 2) - check("tokenizer_path defaults to model_path", - cfg.tokenizer_path == cfg.model_path) - - -def test_async_rl_config_with_heterogeneous(): - """Test async rl config with heterogeneous.""" - section("4.2 AsyncRLConfig + heterogeneous rollout integration") - hetero = HeterogeneousRolloutConfig.from_dict({ - "enabled": True, - "instances": [ - {"tp": 1, "gpus": [2]}, - {"tp": 1, "gpus": [3]}, - {"tp": 2, "gpus": [4, 5]}, - ], - "scheduling": { - "scheduler_type": "la_mlfq", - "la_mlfq_migration_threshold": 5000, - }, - }) - cfg = AsyncRLConfig( - model_path="/path/to/user/test_model", - train_gpus=2, - rollout_gpus=4, - heterogeneous_rollout=hetero, - ) - check("heterogeneous_rollout.enabled=True", cfg.heterogeneous_rollout.enabled is True) - check("Three heterogeneous instances", cfg.heterogeneous_rollout.n_instances == 3) - check("scheduler_type='la_mlfq'", - cfg.heterogeneous_rollout.scheduling.scheduler_type == "la_mlfq") - check("la_mlfq_migration_threshold=5000", - cfg.heterogeneous_rollout.scheduling.la_mlfq_migration_threshold == 5000) - - -def test_async_rl_config_multi_node(): - """Test async rl config multi node.""" - section("4.3 AsyncRLConfig multi-node configuration") - cfg = AsyncRLConfig( - model_path="/path/to/user/test_model", - train_gpus=16, - rollout_gpus=16, - batch_size=64, - num_nodes=4, - gpus_per_node_override=8, - master_addr="192.0.2.50", - master_port=29500, - ) - check("num_nodes=4", cfg.num_nodes == 4) - check("gpus_per_node_override=8", cfg.gpus_per_node_override == 8) - check("master_addr='192.0.2.50'", cfg.master_addr == "192.0.2.50") - check("master_port=29500", cfg.master_port == 29500) - check("train_gpus=16", cfg.train_gpus == 16) - check("rollout_gpus=16", cfg.rollout_gpus == 16) - - -def test_async_rl_config_megatron3d_validation(): - """Test async rl config megatron3d validation.""" - section("4.4 AsyncRLConfig Megatron3D configuration validation") - - cfg = AsyncRLConfig( - model_path="/path/to/user/test_model", - train_gpus=4, - rollout_gpus=4, - train_backend="megatron3d", - train_tp_size=2, - train_pp_size=2, - train_dp_size=1, - weight_sync_mode="disk", - batch_size=32, - micro_batch_size=4, - ) - check("train_backend=megatron3d", cfg.train_backend == "megatron3d") - check("train_tp_size=2", cfg.train_tp_size == 2) - check("train_pp_size=2", cfg.train_pp_size == 2) - check("train_dp_size=1", cfg.train_dp_size == 1) - - invalid_raised = False - try: - AsyncRLConfig( - model_path="/path/to/user/test_model", - train_gpus=4, - rollout_gpus=4, - train_backend="megatron3d", - train_tp_size=2, - train_pp_size=2, - train_dp_size=1, - weight_sync_mode="nccl", - batch_size=32, - micro_batch_size=4, - ) - except ValueError: - invalid_raised = True - check("Invalid weight_sync_mode is rejected", invalid_raised) - - -# ===================================================================== - -# ===================================================================== - -def test_yaml_hetero_config_load(): - """Test yaml hetero config load.""" - section("5.1 Loading a heterogeneous YAML configuration") - yaml_content = textwrap.dedent("""\ - model_path: "/path/to/user/test_model" - train_gpus: 2 - rollout_gpus: 6 - - heterogeneous_rollout: - enabled: true - total_gpus: 6 - available_gpus: [2, 3, 4, 5, 6, 7] - vllm_host: "127.0.0.1" - vllm_base_port: 8000 - instances: - - instance_id: "tp1_0" - tp: 1 - gpus: [2] - - instance_id: "tp1_1" - tp: 1 - gpus: [3] - - instance_id: "tp2_0" - tp: 2 - gpus: [4, 5] - - instance_id: "tp2_1" - tp: 2 - gpus: [6, 7] - scheduling: - scheduler_type: "la_mlfq" - length_thresholds: - short: 1024 - medium: 2048 - long: 4096 - routing_rules: - short: [1] - medium: [1, 2] - long: [2] - extra_long: [2] - load_balance_strategy: "least_connections" - max_queue_length: 64 - enable_fallback: true - la_mlfq_migration_threshold: 4000 - la_mlfq_scout_timeout: 45.0 - la_mlfq_history_ttl: 3 - """) - - try: - import yaml - except ImportError: - print(" [SKIP] yaml is not installed; skipping YAML loading test") - return - - with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as f: - f.write(yaml_content) - tmp_path = f.name - - try: - with open(tmp_path) as f: - raw = yaml.safe_load(f) - - - hetero_dict = raw.pop("heterogeneous_rollout", {}) - hetero_cfg = HeterogeneousRolloutConfig.from_dict(hetero_dict) - - check("YAML: enabled=True", hetero_cfg.enabled is True) - check("YAML: four instances", hetero_cfg.n_instances == 4) - check("YAML: tp_list=[1,1,2,2]", hetero_cfg.tp_list == [1, 1, 2, 2]) - check("YAML: scheduler_type='la_mlfq'", - hetero_cfg.scheduling.scheduler_type == "la_mlfq") - check("YAML: max_queue_length=64", hetero_cfg.scheduling.max_queue_length == 64) - check("YAML: la_mlfq_migration_threshold=4000", - hetero_cfg.scheduling.la_mlfq_migration_threshold == 4000) - check("YAML: la_mlfq_scout_timeout=45.0", - hetero_cfg.scheduling.la_mlfq_scout_timeout == 45.0) - check("YAML: la_mlfq_history_ttl=3", - hetero_cfg.scheduling.la_mlfq_history_ttl == 3) - check("YAML: length_thresholds.short=1024", - hetero_cfg.scheduling.length_thresholds["short"] == 1024) - check("YAML: routing_rules.long=[2]", - hetero_cfg.scheduling.routing_rules["long"] == [2]) - - finally: - os.unlink(tmp_path) - - -def test_scheduler_type_variations(): - """Test scheduler type variations.""" - section("5.2 scheduler_type three variants") - for stype in ["length_aware", "la_mlfq", "load_balance"]: - d = {"scheduler_type": stype} - cfg = SchedulingConfig.from_dict(d) - check(f"scheduler_type='{stype}'", cfg.scheduler_type == stype) - - -# ===================================================================== - -# ===================================================================== - -def main(): - print("\n" + "=" * 60) - print(" Heterogeneous rollout and training cluster configuration unit tests") - print("=" * 60) - - # 1. HeterogeneousInstanceConfig - test_instance_config_defaults() - test_instance_config_from_dict() - test_instance_config_from_dict_extra_keys() - - # 2. SchedulingConfig - test_scheduling_config_defaults() - test_scheduling_config_la_mlfq_fields() - test_scheduling_config_from_dict() - - # 3. HeterogeneousRolloutConfig - test_hetero_config_defaults() - test_hetero_config_from_dict() - test_hetero_config_auto_compute() - - # 4. AsyncRLConfig - test_async_rl_config_training_cluster() - test_async_rl_config_with_heterogeneous() - test_async_rl_config_multi_node() - test_async_rl_config_megatron3d_validation() - - - test_yaml_hetero_config_load() - test_scheduler_type_variations() - - - print(f"\n{'='*60}") - total = _pass_count + _fail_count - print(f" Result: {_pass_count}/{total} passed, {_fail_count} failed") - print(f"{'='*60}") - - if _fail_count > 0: - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/examples/test_history_collector.py b/examples/test_history_collector.py deleted file mode 100644 index deac55f..0000000 --- a/examples/test_history_collector.py +++ /dev/null @@ -1,567 +0,0 @@ -"""Support code for Test history collector.""" - -import sys -import os -import json -import tempfile -import shutil -import time -import numpy as np - - -_project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -import types -_pkg = types.ModuleType("RL_Framework") -_pkg.__path__ = [_project_root] -_pkg.__package__ = "RL_Framework" -sys.modules["RL_Framework"] = _pkg - -from RL_Framework.infra.observability.history_collector import ( - HistoryDataCollector, - SequenceLengthStats, - TimingRecord, - ResourceConfig, - CostModelComparison, - StepRecord, - load_history, - compute_cost_model_accuracy, -) - - -def separator(title: str): - print(f"\n{'='*60}") - print(f" {title}") - print(f"{'='*60}") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_sequence_length_stats(): - separator("Test 1: SequenceLengthStats statistics") - - - stats = SequenceLengthStats.from_lengths([]) - assert stats.count == 0 - print(" Empty list: OK") - - - lengths = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000] - stats = SequenceLengthStats.from_lengths(lengths) - assert stats.count == 10 - assert stats.mean == 550.0 - assert stats.min == 100 - assert stats.max == 1000 - assert abs(stats.p50 - 550.0) < 1.0 - print(f" Normal list: count={stats.count}, mean={stats.mean}, " - f"p50={stats.p50}, p95={stats.p95}") - - - stats = SequenceLengthStats.from_lengths([42]) - assert stats.count == 1 - assert stats.mean == 42.0 - assert stats.min == 42 - assert stats.max == 42 - print(" Single element: OK") - - print("\n [PASS] SequenceLengthStats tests passed") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_timing_record(): - separator("Test 2: TimingRecord") - - t = TimingRecord( - rollout_time=5.0, - train_time=3.0, - weight_sync_time=0.5, - advantage_time=0.1, - recompute_logprob_time=0.2, - step_total_time=10.0, - ) - - # overhead = 10.0 - (5.0+3.0+0.5+0.1+0.2) = 1.2 - assert abs(t.overhead_time - 1.2) < 0.001 - print(f" overhead_time={t.overhead_time:.3f}s (expected 1.2s)") - - print("\n [PASS] TimingRecord tests passed") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_basic_recording(): - separator("Test 3: basic recording and JSONL output") - - tmpdir = tempfile.mkdtemp(prefix="history_test_") - try: - collector = HistoryDataCollector( - output_dir=tmpdir, - save_raw_lengths=True, - flush_interval=1, - ) - collector.initialize() - - - np.random.seed(42) - for step in range(3): - prompt_lengths = list(np.random.randint(100, 500, size=20)) - gen_lengths = list(np.random.randint(50, 1000, size=20)) - - record = collector.record_step( - step=step, - prompt_lengths=prompt_lengths, - gen_lengths=gen_lengths, - rollout_time=5.0 + step * 0.5, - train_time=3.0 + step * 0.2, - weight_sync_time=0.3, - step_total_time=9.0 + step, - training_stats={"loss": 0.5 - step * 0.1, "kl": 0.01}, - model_version=step + 1, - resource_config=ResourceConfig( - train_gpus=4, rollout_gpus=4, batch_size=32, - model_path="test-model", - ), - ) - - assert record.step == step - assert record.sequence_stats["prompt"].count == 20 - assert record.sequence_stats["generation"].count == 20 - assert record.sequence_stats["total"].count == 20 - assert len(record.raw_prompt_lengths) == 20 - - assert len(record.sequences) == 20 - assert "input_len" in record.sequences[0] - assert "output_len" in record.sequences[0] - - collector.finalize() - - - jsonl_files = [f for f in os.listdir(tmpdir) if f.endswith(".jsonl")] - assert len(jsonl_files) == 1, f"Expected 1 jsonl file, got {len(jsonl_files)}" - - records = load_history(os.path.join(tmpdir, jsonl_files[0])) - assert len(records) == 3 - assert records[0]["step"] == 0 - assert records[2]["step"] == 2 - assert "sequence_stats" in records[0] - assert "timing" in records[0] - assert "resource_config" in records[0] - assert records[0]["resource_config"]["train_gpus"] == 4 - - - assert len(records[0]["raw_prompt_lengths"]) == 20 - assert len(records[0]["raw_gen_lengths"]) == 20 - - - assert "sequences" in records[0] - assert len(records[0]["sequences"]) == 20 - seq0 = records[0]["sequences"][0] - assert "input_len" in seq0 and "output_len" in seq0 - assert seq0["input_len"] > 0 and seq0["output_len"] > 0 - - print(f" JSONL file: {jsonl_files[0]}") - print(f" Records: {len(records)}") - print(f" Step 0 gen mean: {records[0]['sequence_stats']['generation']['mean']:.1f}") - print(f" Step 0 sequence count: {len(records[0]['sequences'])}") - print(f" Step 0 seq[0]: {records[0]['sequences'][0]}") - - - summary_files = [f for f in os.listdir(tmpdir) if f.startswith("summary")] - assert len(summary_files) == 1 - with open(os.path.join(tmpdir, summary_files[0]), "r") as f: - summary = json.load(f) - assert summary["total_steps"] == 3 - print(f" Summary total_steps: {summary['total_steps']}") - - print("\n [PASS] Basic recording and JSONL output tests passed") - - finally: - shutil.rmtree(tmpdir) - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_cost_model_comparison(): - separator("Test 4: cost-model comparison records") - - tmpdir = tempfile.mkdtemp(prefix="history_cost_") - try: - collector = HistoryDataCollector( - output_dir=tmpdir, - flush_interval=1, - ) - collector.initialize() - - - np.random.seed(123) - for step in range(10): - actual_rollout = 5.0 + np.random.normal(0, 0.5) - actual_train = 3.0 + np.random.normal(0, 0.3) - - pred_rollout = actual_rollout * (1.0 + np.random.normal(0, 0.2)) - pred_train = actual_train * (1.0 + np.random.normal(0, 0.15)) - - collector.record_step( - step=step, - prompt_lengths=list(np.random.randint(100, 400, size=15)), - gen_lengths=list(np.random.randint(50, 800, size=15)), - rollout_time=actual_rollout, - train_time=actual_train, - step_total_time=actual_rollout + actual_train + 1.0, - predicted_rollout_time=pred_rollout, - predicted_train_time=pred_train, - eta_comp=0.45, - eta_mem=0.50, - model_version=step + 1, - ) - - collector.finalize() - - - jsonl_files = [f for f in os.listdir(tmpdir) if f.endswith(".jsonl")] - records = load_history(os.path.join(tmpdir, jsonl_files[0])) - - - for r in records: - assert "cost_model_comparison" in r - cmp = r["cost_model_comparison"] - assert cmp["eta_comp"] == 0.45 - assert cmp["predicted_rollout_time"] > 0 - assert cmp["actual_rollout_time"] > 0 - - - accuracy = compute_cost_model_accuracy(records) - assert "rollout" in accuracy - assert "training" in accuracy - print(f" Rollout MAPE: {accuracy['rollout']['mape_pct']:.2f}%") - print(f" Training MAPE: {accuracy['training']['mape_pct']:.2f}%") - print(f" Comparison records: {accuracy['n_with_prediction']}") - - - summary_files = [f for f in os.listdir(tmpdir) if f.startswith("summary")] - with open(os.path.join(tmpdir, summary_files[0]), "r") as f: - summary = json.load(f) - assert "cost_model_accuracy" in summary - print(f" Summary MAPE: {summary['cost_model_accuracy']['rollout_mape_pct']:.2f}%") - - print("\n [PASS] Cost-model comparison record tests passed") - - finally: - shutil.rmtree(tmpdir) - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_sequence_trend(): - separator("Test 5: sequence-length trend tracking (simulated capability emergence)") - - tmpdir = tempfile.mkdtemp(prefix="history_trend_") - try: - collector = HistoryDataCollector( - output_dir=tmpdir, - flush_interval=5, - ) - collector.initialize() - - np.random.seed(0) - - - for step in range(10): - gen_lengths = list(np.random.normal(300, 50, size=20).clip(min=16).astype(int)) - collector.record_step( - step=step, - prompt_lengths=list(np.random.randint(100, 300, size=20)), - gen_lengths=gen_lengths, - rollout_time=5.0, - train_time=3.0, - step_total_time=9.0, - ) - - - for step in range(10, 20): - gen_lengths = list(np.random.normal(1500, 300, size=20).clip(min=16).astype(int)) - collector.record_step( - step=step, - prompt_lengths=list(np.random.randint(100, 300, size=20)), - gen_lengths=gen_lengths, - rollout_time=15.0, - train_time=5.0, - step_total_time=22.0, - ) - - collector.finalize() - - - trend = collector.get_sequence_trend() - assert len(trend["steps"]) == 20 - assert len(trend["gen_mean"]) == 20 - - first_half_mean = np.mean(trend["gen_mean"][:10]) - second_half_mean = np.mean(trend["gen_mean"][10:]) - print(f" Phase 1 gen_mean mean: {first_half_mean:.1f}") - print(f" Phase 2 gen_mean mean: {second_half_mean:.1f}") - print(f" Growth factor: {second_half_mean / first_half_mean:.2f}x") - - - assert second_half_mean > first_half_mean * 3, \ - f"Unexpected sequence-length trend: {second_half_mean:.0f} vs {first_half_mean:.0f}" - - - summary = collector.get_summary() - assert summary["sequence_length_trend"]["gen_mean_first10"] is not None - assert summary["sequence_length_trend"]["gen_mean_last10"] is not None - print(f" Summary first10: {summary['sequence_length_trend']['gen_mean_first10']:.1f}") - print(f" Summary last10: {summary['sequence_length_trend']['gen_mean_last10']:.1f}") - - print("\n [PASS] Sequence-length trend tests passed") - - finally: - shutil.rmtree(tmpdir) - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_resource_config_snapshot(): - separator("Test 6: resource configuration snapshot") - - - class MockConfig: - train_gpus = 4 - rollout_gpus = 4 - n_total_gpus = 0 - train_backend = "megatron3d" - tp_size = 2 - train_tp_size = 2 - train_pp_size = 2 - train_dp_size = 1 - vllm_tp_size = 2 - vllm_num_instances = 2 - batch_size = 32 - micro_batch_size = 4 - max_new_tokens = 2048 - max_seq_length = 4096 - n_samples = 8 - temperature = 0.7 - model_path = "/models/Qwen3-32B" - - class model_arch: - num_params = 32e9 - - rc = HistoryDataCollector.snapshot_resource_config(MockConfig()) - assert rc.train_gpus == 4 - assert rc.rollout_gpus == 4 - assert rc.n_total_gpus == 8 # auto: 4+4 - assert rc.train_backend == "megatron3d" - assert rc.train_tp == 2 - assert rc.train_pp == 2 - assert rc.train_dp == 1 - assert rc.vllm_tp_size == 2 - assert rc.batch_size == 32 - assert rc.model_path == "/models/Qwen3-32B" - assert rc.model_params == 32e9 - - print(f" train_gpus={rc.train_gpus}, rollout_gpus={rc.rollout_gpus}") - print(f" n_total_gpus={rc.n_total_gpus}") - print(f" train_backend={rc.train_backend}") - print(f" vllm_tp_size={rc.vllm_tp_size}") - print(f" model_params={rc.model_params:.1e}") - - print("\n [PASS] Resource configuration snapshot tests passed") - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_full_simulation(): - separator("Test 7: full simulated training workflow (50 steps, sequence_pairs interface)") - - tmpdir = tempfile.mkdtemp(prefix="history_sim_") - try: - collector = HistoryDataCollector( - output_dir=tmpdir, - save_raw_lengths=False, - flush_interval=10, - experiment_name="gsm8k_test", - ) - collector.initialize() - - rc = ResourceConfig( - n_total_gpus=8, - train_gpus=4, - rollout_gpus=4, - train_tp=2, - train_pp=1, - train_dp=2, - vllm_tp_size=2, - vllm_num_instances=2, - batch_size=32, - micro_batch_size=4, - max_new_tokens=1024, - max_seq_length=2048, - model_path="Qwen/Qwen2.5-3B-Instruct", - model_params=3e9, - ) - - np.random.seed(42) - total_steps = 50 - - for step in range(total_steps): - - gen_mean = 300 + step * 10 - n_seqs = 32 - - - pairs = [ - ( - int(np.random.randint(100, 400)), - max(16, int(np.random.normal(gen_mean, gen_mean * 0.2))), - ) - for _ in range(n_seqs) - ] - - - rollout_time = 5.0 + step * 0.1 + np.random.normal(0, 0.3) - train_time = 3.0 + np.random.normal(0, 0.2) - sync_time = 0.3 if step % 1 == 0 else 0.0 - - - pred_rollout = rollout_time * (1.0 + np.random.normal(0, 0.15)) - pred_train = train_time * (1.0 + np.random.normal(0, 0.10)) - - record = collector.record_step( - step=step, - sequence_pairs=pairs, - rollout_time=rollout_time, - train_time=train_time, - weight_sync_time=sync_time, - advantage_time=0.05, - recompute_logprob_time=0.1, - step_total_time=rollout_time + train_time + sync_time + 0.2, - training_stats={ - "loss": 0.5 * np.exp(-step / 20), - "pg_loss": 0.3 * np.exp(-step / 20), - "kl": 0.01 * (1 + step * 0.01), - "reward_mean": 0.1 * min(step, 30), - }, - predicted_rollout_time=pred_rollout, - predicted_train_time=pred_train, - eta_comp=0.45 + step * 0.001, - eta_mem=0.50, - model_version=step + 1, - resource_config=rc, - ) - - - assert len(record.sequences) == n_seqs - assert record.sequences[0]["input_len"] == pairs[0][0] - assert record.sequences[0]["output_len"] == pairs[0][1] - - collector.finalize() - - - jsonl_files = [f for f in os.listdir(tmpdir) if f.endswith(".jsonl")] - assert len(jsonl_files) == 1 - assert jsonl_files[0].startswith("gsm8k_test_") - - records = load_history(os.path.join(tmpdir, jsonl_files[0])) - assert len(records) == total_steps - - - for r in records: - assert "sequences" in r - assert len(r["sequences"]) == 32 - for seq in r["sequences"]: - assert "input_len" in seq - assert "output_len" in seq - assert seq["input_len"] > 0 - - - accuracy = compute_cost_model_accuracy(records) - print(f" Total steps: {total_steps}") - print(f" Rollout MAPE: {accuracy['rollout']['mape_pct']:.2f}%") - print(f" Training MAPE: {accuracy['training']['mape_pct']:.2f}%") - - - trend = collector.get_sequence_trend() - first_10_gen = np.mean(trend["gen_mean"][:10]) - last_10_gen = np.mean(trend["gen_mean"][-10:]) - print(f" Gen mean (first 10): {first_10_gen:.0f}") - print(f" Gen mean (last 10): {last_10_gen:.0f}") - assert last_10_gen > first_10_gen, "Sequence length should increase during training" - - - step0 = records[0] - print(f" Step 0 sequences[0]: {step0['sequences'][0]}") - print(f" Step 0 sequences count: {len(step0['sequences'])}") - - - jsonl_size = os.path.getsize(os.path.join(tmpdir, jsonl_files[0])) - print(f" JSONL file size: {jsonl_size / 1024:.1f} KB") - - print("\n [PASS] Full simulated training workflow tests passed") - - finally: - shutil.rmtree(tmpdir) - - -# --------------------------------------------------------------------------- - -# --------------------------------------------------------------------------- -def test_config_default_disabled(): - separator("Test 8: configuration switch (disabled by default)") - - - from RL_Framework.config import AsyncRLConfig - - - cfg = AsyncRLConfig(model_path="dummy-model") - assert cfg.enable_history_collection is False, \ - f"enable_history_collection should default to False; got {cfg.enable_history_collection}" - print(f" enable_history_collection default value: {cfg.enable_history_collection}") - - - cfg_enabled = AsyncRLConfig(model_path="dummy-model", enable_history_collection=True) - assert cfg_enabled.enable_history_collection is True - print(f" Explicitly enabled: {cfg_enabled.enable_history_collection}") - - - - collector = None - if cfg.enable_history_collection: - collector = HistoryDataCollector() - assert collector is None, "No collector is created when disabled" - print(" collector is None when disabled: OK") - - print("\n [PASS] Configuration-switch tests passed") - - -# --------------------------------------------------------------------------- -# Main -# --------------------------------------------------------------------------- -def main(): - print("=" * 60) - print(" HistoryDataCollector unit tests") - print("=" * 60) - - test_sequence_length_stats() - test_timing_record() - test_basic_recording() - test_cost_model_comparison() - test_sequence_trend() - test_resource_config_snapshot() - test_full_simulation() - test_config_default_disabled() - - print("\n" + "=" * 60) - print(" ALL TESTS PASSED!") - print("=" * 60) - - -if __name__ == "__main__": - main() diff --git a/examples/test_megatron3d_backend.py b/examples/test_megatron3d_backend.py deleted file mode 100644 index 240f4f6..0000000 --- a/examples/test_megatron3d_backend.py +++ /dev/null @@ -1,227 +0,0 @@ -"""Support code for Test megatron3d backend.""" - -from __future__ import annotations - -import argparse -import os -import shutil -import socket -import sys -import tempfile -import types - -_project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -_pkg = types.ModuleType("RL_Framework") -_pkg.__path__ = [_project_root] -_pkg.__package__ = "RL_Framework" -sys.modules.setdefault("RL_Framework", _pkg) - -import torch -import torch.distributed as dist -import torch.multiprocessing as mp - -from RL_Framework.engine.megatron_train_engine import Megatron3DTrainEngine - - -def _require_transformers(): - from tokenizers import Tokenizer - from tokenizers.models import WordLevel - from tokenizers.pre_tokenizers import Whitespace - from transformers import PreTrainedTokenizerFast, Qwen2Config, Qwen2ForCausalLM - return Tokenizer, WordLevel, Whitespace, PreTrainedTokenizerFast, Qwen2Config, Qwen2ForCausalLM - - -def _find_free_port() -> int: - sock = socket.socket() - sock.bind(("", 0)) - port = sock.getsockname()[1] - sock.close() - return port - - -def build_tiny_qwen_checkpoint(base_dir: str) -> str: - ( - Tokenizer, - WordLevel, - Whitespace, - PreTrainedTokenizerFast, - Qwen2Config, - Qwen2ForCausalLM, - ) = _require_transformers() - - ckpt_dir = os.path.join(base_dir, "tiny_qwen_ckpt") - os.makedirs(ckpt_dir, exist_ok=True) - - vocab = {"": 0, "": 1} - for i in range(2, 128): - vocab[f"tok_{i}"] = i - - tok = Tokenizer(WordLevel(vocab=vocab, unk_token="")) - tok.pre_tokenizer = Whitespace() - hf_tokenizer = PreTrainedTokenizerFast( - tokenizer_object=tok, - bos_token="", - eos_token="", - unk_token="", - pad_token="", - ) - hf_tokenizer.save_pretrained(ckpt_dir) - - config = Qwen2Config( - vocab_size=len(vocab), - hidden_size=64, - intermediate_size=128, - num_hidden_layers=4, - num_attention_heads=4, - num_key_value_heads=4, - max_position_embeddings=256, - rope_theta=10000.0, - rms_norm_eps=1e-6, - ) - model = Qwen2ForCausalLM(config) - model.save_pretrained(ckpt_dir) - return ckpt_dir - - -def make_dummy_trajectories() -> list[dict]: - torch.manual_seed(7) - trajectories = [] - seqs = [ - [5, 6, 7, 8, 9], - [10, 11, 12, 13], - [14, 15, 16, 17, 18, 19], - [20, 21, 22], - ] - for idx, seq in enumerate(seqs): - seq_tensor = torch.tensor(seq, dtype=torch.long).unsqueeze(0) - logprobs = torch.zeros_like(seq_tensor, dtype=torch.float32) - loss_mask = torch.zeros_like(seq_tensor, dtype=torch.long) - input_len = max(1, len(seq) // 2) - loss_mask[:, input_len:] = 1 - trajectories.append( - { - "input_ids": seq_tensor, - "attention_mask": torch.ones_like(seq_tensor), - "logprobs": logprobs, - "loss_mask": loss_mask, - "rewards": torch.tensor([1.0 + idx * 0.1], dtype=torch.float32), - "advantages": torch.tensor([0.5 + idx * 0.2], dtype=torch.float32), - "versions": torch.tensor([0], dtype=torch.long), - "input_len": input_len, - "output_len": len(seq) - input_len, - } - ) - return trajectories - - -def run_single_case(): - if not torch.cuda.is_available(): - print("SKIP: no CUDA available") - return - - tmpdir = tempfile.mkdtemp(prefix="megatron3d_single_") - try: - model_path = build_tiny_qwen_checkpoint(tmpdir) - os.environ.setdefault("RANK", "0") - os.environ.setdefault("LOCAL_RANK", "0") - os.environ.setdefault("WORLD_SIZE", "1") - - engine = Megatron3DTrainEngine( - model_path=model_path, - train_tp_size=1, - train_pp_size=1, - train_dp_size=1, - micro_batch_size=2, - ) - engine.initialize() - trajectories = make_dummy_trajectories() - engine.recompute_logprobs(trajectories) - stats = engine.grpo_update(trajectories, ppo_epochs=1) - assert "loss" in stats and torch.isfinite(torch.tensor(stats["loss"])) - save_dir = os.path.join(tmpdir, "weights") - engine.save_weights(save_dir, version=0) - engine.load_weights(save_dir, version=0) - print("single-case smoke test passed") - finally: - shutil.rmtree(tmpdir, ignore_errors=True) - - -def _distributed_worker(rank: int, world_size: int, port: int, model_path: str, tp: int, pp: int, dp: int): - os.environ["MASTER_ADDR"] = "127.0.0.1" - os.environ["MASTER_PORT"] = str(port) - os.environ["RANK"] = str(rank) - os.environ["LOCAL_RANK"] = str(rank) - os.environ["WORLD_SIZE"] = str(world_size) - - dist.init_process_group(backend="nccl", rank=rank, world_size=world_size) - torch.cuda.set_device(rank) - - try: - engine = Megatron3DTrainEngine( - model_path=model_path, - train_tp_size=tp, - train_pp_size=pp, - train_dp_size=dp, - micro_batch_size=2, - ) - engine.initialize() - - trajectories = make_dummy_trajectories() if engine.is_batch_source() else None - trajectories = engine.distribute_trajectories(trajectories) - engine.recompute_logprobs(trajectories) - stats = engine.grpo_update(trajectories, ppo_epochs=1) - assert "loss" in stats - assert torch.isfinite(torch.tensor(stats["loss"], device=torch.device(f"cuda:{rank}"))) - - save_dir = os.path.join(os.path.dirname(model_path), f"weights_tp{tp}_pp{pp}_dp{dp}") - engine.save_weights(save_dir, version=0) - engine.load_weights(save_dir, version=0) - - if rank == 0: - print(f"distributed smoke passed: tp={tp}, pp={pp}, dp={dp}") - finally: - dist.barrier() - dist.destroy_process_group() - - -def run_distributed_case(tp: int, pp: int, dp: int): - if not torch.cuda.is_available(): - print("SKIP: no CUDA available") - return - world_size = tp * pp * dp - if torch.cuda.device_count() < world_size: - print( - f"SKIP: need {world_size} GPUs, only {torch.cuda.device_count()} available" - ) - return - - tmpdir = tempfile.mkdtemp(prefix="megatron3d_dist_") - try: - model_path = build_tiny_qwen_checkpoint(tmpdir) - port = _find_free_port() - mp.spawn( - _distributed_worker, - args=(world_size, port, model_path, tp, pp, dp), - nprocs=world_size, - join=True, - ) - finally: - shutil.rmtree(tmpdir, ignore_errors=True) - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument("--case", choices=["single", "distributed"], default="single") - parser.add_argument("--tp", type=int, default=1) - parser.add_argument("--pp", type=int, default=1) - parser.add_argument("--dp", type=int, default=1) - args = parser.parse_args() - - if args.case == "single": - run_single_case() - else: - run_distributed_case(args.tp, args.pp, args.dp) - - -if __name__ == "__main__": - main() diff --git a/examples/test_qwen3d_modules.py b/examples/test_qwen3d_modules.py deleted file mode 100644 index dd3134b..0000000 --- a/examples/test_qwen3d_modules.py +++ /dev/null @@ -1,98 +0,0 @@ -"""Support code for Test qwen3d modules.""" - -import os -import sys -import types - -_project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -_pkg = types.ModuleType("RL_Framework") -_pkg.__path__ = [_project_root] -_pkg.__package__ = "RL_Framework" -sys.modules.setdefault("RL_Framework", _pkg) - -import torch - -from RL_Framework.engine.qwen3d_modules import ( - QwenPipelineStage, - build_stage_spec, - divide_evenly, - split_range_for_rank, - vocab_parallel_token_logprobs, -) -from RL_Framework.engine.train_parallel import TrainParallelRuntime - - -def test_divide_evenly(): - parts = divide_evenly(10, 3) - assert parts == [(0, 4), (4, 7), (7, 10)] - - -def test_split_range(): - assert split_range_for_rank(12, 3, 0) == (0, 4) - assert split_range_for_rank(12, 3, 1) == (4, 8) - assert split_range_for_rank(12, 3, 2) == (8, 12) - - -def test_build_stage_spec(): - runtime = TrainParallelRuntime( - rank=2, - world_size=4, - tensor_parallel_size=1, - pipeline_parallel_size=4, - data_parallel_size=1, - ) - spec = build_stage_spec(10, runtime) - assert spec.stage_id == 2 - assert spec.layer_start == 6 - assert spec.layer_end == 8 - - -def test_vocab_parallel_logprob_tp1(): - runtime = TrainParallelRuntime( - rank=0, - world_size=1, - tensor_parallel_size=1, - pipeline_parallel_size=1, - data_parallel_size=1, - ) - logits = torch.tensor( - [[[0.1, 0.2, 0.3], [0.4, 0.0, -0.2]]], - dtype=torch.float32, - ) - targets = torch.tensor([[2, 0]], dtype=torch.long) - expected = torch.log_softmax(logits, dim=-1) - expected = torch.gather(expected, -1, targets.unsqueeze(-1)).squeeze(-1) - actual = vocab_parallel_token_logprobs(logits, targets, runtime) - assert torch.allclose(actual, expected, atol=1e-6) - - -def test_causal_mask_with_padding(): - stage = QwenPipelineStage.__new__(QwenPipelineStage) - attention_mask = torch.tensor([[1, 1, 1], [0, 1, 1]], dtype=torch.long) - inputs_embeds = torch.zeros(2, 3, 4, dtype=torch.float32) - cache_position = torch.arange(3) - - mask = stage._build_causal_mask( - attention_mask, - inputs_embeds, - cache_position, - ) - min_dtype = torch.finfo(inputs_embeds.dtype).min - - assert mask.shape == (2, 1, 3, 3) - assert mask[0, 0, 2, 0].item() == 0.0 - assert mask[0, 0, 0, 1].item() == min_dtype - assert torch.all(mask[1, 0, :, 0] == min_dtype) - - -def main(): - test_divide_evenly() - test_split_range() - test_build_stage_spec() - test_vocab_parallel_logprob_tp1() - test_causal_mask_with_padding() - print("Qwen 3D module tests passed") - - -if __name__ == "__main__": - main() diff --git a/examples/test_r2e_cmlfq_flow.py b/examples/test_r2e_cmlfq_flow.py deleted file mode 100644 index c7f34be..0000000 --- a/examples/test_r2e_cmlfq_flow.py +++ /dev/null @@ -1,111 +0,0 @@ -"""R2E-Gym driven smoke test for C-MLFQ prefix-tree routing.""" - -import json -from pathlib import Path - -from RL_Framework.infra.scheduling.cmlfq_offline_profile import CMLFQOfflineProfiler -from RL_Framework.infra.scheduling.cmlfq_scheduler import CMLFQScheduler - - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -INDEX_PATH = PROJECT_ROOT / "data" / "r2e_gym_v1" / "index.jsonl" - - -def load_first_row() -> dict: - with INDEX_PATH.open(encoding="utf-8") as source: - for line in source: - return json.loads(line) - raise RuntimeError(f"No rows found in {INDEX_PATH}") - - -def build_r2e_tool_history(row: dict) -> tuple[str, list[dict]]: - prompt_id = f"{row['repo_name']}:{row['commit_hash']}" - task_text = row.get("task_text") or row.get("problem_statement") or row.get("prompt") or "" - modified_files = row.get("modified_files") or [] - if isinstance(modified_files, str): - modified_files = json.loads(modified_files) - - first_payload = ( - "R2E before-patch pytest failed. " - f"repo={row['repo_name']} files={','.join(modified_files[:4])} " - + task_text[:8000] - ) - second_payload = "R2E after-patch pytest passed expected tests." - total_output_tokens = 36000 - raw_trajectory = { - "prompt_id": prompt_id, - "total_output_tokens": total_output_tokens, - "tool_returns": [ - { - "tool_type": "code_executor", - "output": first_payload, - "status": "failure", - "payload_tokens": max(6000, len(first_payload) // 3), - "token_position": 1200, - "remaining_length": total_output_tokens - 1200, - }, - { - "tool_type": "code_executor", - "output": second_payload, - "status": "success", - "payload_tokens": len(second_payload) // 3, - "token_position": 34000, - "remaining_length": 2000, - }, - ], - } - return prompt_id, [raw_trajectory] - - -def main(): - row = load_first_row() - prompt_id, raw_history = build_r2e_tool_history(row) - - profiler = CMLFQOfflineProfiler() - profile = profiler.profile_from_raw_trajectories(raw_history) - - scheduler = CMLFQScheduler( - buckets={ - "short": {"tp_degrees": [1], "max_tokens": 5000}, - "medium": {"tp_degrees": [2], "max_tokens": 15000}, - "long": {"tp_degrees": [4], "max_tokens": 50000}, - }, - prefix_tree=profiler.prefix_tree, - ) - scheduler.register_instance(0, "short_tp1", 1) - scheduler.register_instance(1, "medium_tp2", 2) - scheduler.register_instance(2, "long_tp4", 4) - - initial = scheduler.schedule(input_tokens=1024, prompt_id=prompt_id) - assert initial.category == "short", initial - - first_tool_return = raw_history[0]["tool_returns"][0] - decision = scheduler.on_tool_return( - initial.request_id, - first_tool_return, - generated_tokens=first_tool_return["token_position"], - ) - assert decision.should_migrate, decision - assert decision.target_bucket == "long", decision - - migrated = scheduler.execute_migration(initial.request_id, decision) - assert migrated.category == "long", migrated - assert migrated.request_id == initial.request_id - - scheduler.finish_request( - initial.request_id, - raw_history[0]["total_output_tokens"], - ) - stats = scheduler.prefix_tree.get_stats() - assert stats["total_insertions"] >= 2, stats - - print( - "R2E_CMLFQ_FLOW_OK " - f"repo={row['repo_name']} " - f"nodes={profile['tree_stats']['total_nodes']} " - f"route={initial.category}->{migrated.category}" - ) - - -if __name__ == "__main__": - main() diff --git a/examples/test_r2e_gym.py b/examples/test_r2e_gym.py deleted file mode 100644 index 2e7c41c..0000000 --- a/examples/test_r2e_gym.py +++ /dev/null @@ -1,77 +0,0 @@ -"""Strict integrity test for the official R2E-Gym V1 dataset.""" - -import json -from collections import Counter -from pathlib import Path - -import pyarrow.parquet as pq - - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -DATASET_DIR = PROJECT_ROOT / "data" / "r2e_gym_v1" -EXPECTED_REPOS = { - "aiohttp", - "coveragepy", - "datalad", - "matplotlib", - "moto", - "numpy", - "orange3", - "pandas", - "pillow", - "pyramid", - "scrapy", - "sympy", - "tornado", -} - - -def main(): - shards = sorted(DATASET_DIR.glob("train-*-of-00013.parquet")) - counts = Counter() - rows = 0 - - if shards: - assert len(shards) == 13, f"Expected 13 R2E-Gym shards, got {len(shards)}" - row_iterables = [] - for shard in shards: - table = pq.read_table( - shard, - columns=[ - "repo_name", - "docker_image", - "prompt", - "problem_statement", - "expected_output_json", - ], - ) - row_iterables.append(table.to_pylist()) - else: - index_path = DATASET_DIR / "index.jsonl" - assert index_path.exists(), ( - "Expected R2E-Gym parquet shards or prepared index, " - f"found neither in {DATASET_DIR}" - ) - row_iterables = [ - [json.loads(line) for line in index_path.read_text(encoding="utf-8").splitlines()] - ] - - for row_iterable in row_iterables: - for row in row_iterable: - problem_statement = row["problem_statement"] or "" - prompt = row["prompt"] or "" - assert problem_statement.strip() or prompt.strip() - assert ":" in row["docker_image"] - assert json.loads(row["expected_output_json"]) - counts[row["repo_name"]] += 1 - rows += 1 - - assert rows == 8101, f"Expected 8101 R2E-Gym tasks, got {rows}" - assert set(counts) == EXPECTED_REPOS, ( - f"Expected only official R2E-Gym repositories, got {sorted(counts)}" - ) - print(f"R2E_GYM_DATASET_OK rows={rows} repos={dict(sorted(counts.items()))}") - - -if __name__ == "__main__": - main() diff --git a/examples/test_schedulers.py b/examples/test_schedulers.py deleted file mode 100644 index 1723e61..0000000 --- a/examples/test_schedulers.py +++ /dev/null @@ -1,778 +0,0 @@ -"""Support code for Test schedulers.""" - -import sys -import os -import time - - -_project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if _project_root not in sys.path: - sys.path.insert(0, _project_root) - - -import importlib.util - - -def _load_module(name, filepath): - spec = importlib.util.spec_from_file_location(name, filepath) - mod = importlib.util.module_from_spec(spec) - sys.modules[name] = mod - spec.loader.exec_module(mod) - return mod - - -_infra_dir = os.path.join(_project_root, "infra") -_scheduling_dir = os.path.join(_infra_dir, "scheduling") - - -import types as _types -_infra_pkg = _types.ModuleType("infra") -_infra_pkg.__path__ = [_infra_dir] -_infra_pkg.__package__ = "infra" -sys.modules["infra"] = _infra_pkg - - -_rl_pkg = _types.ModuleType("RL_Framework") -_rl_pkg.__path__ = [_project_root] -_rl_pkg.__package__ = "RL_Framework" -sys.modules.setdefault("RL_Framework", _rl_pkg) - -_rl_infra_pkg = _types.ModuleType("RL_Framework.infra") -_rl_infra_pkg.__path__ = [_infra_dir] -_rl_infra_pkg.__package__ = "RL_Framework.infra" -sys.modules.setdefault("RL_Framework.infra", _rl_infra_pkg) - -_rl_infra_scheduling_pkg = _types.ModuleType("RL_Framework.infra.scheduling") -_rl_infra_scheduling_pkg.__path__ = [_scheduling_dir] -_rl_infra_scheduling_pkg.__package__ = "RL_Framework.infra.scheduling" -sys.modules.setdefault("RL_Framework.infra.scheduling", _rl_infra_scheduling_pkg) - -_scheduler_base = _load_module("infra.scheduling.base", os.path.join(_scheduling_dir, "base.py")) -_hetero_scheduler = _load_module("infra.scheduling.length_aware", os.path.join(_scheduling_dir, "length_aware.py")) -_la_mlfq_scheduler = _load_module("infra.scheduling.la_mlfq", os.path.join(_scheduling_dir, "la_mlfq.py")) -_load_balance_scheduler = _load_module("infra.scheduling.load_balance", os.path.join(_scheduling_dir, "load_balance.py")) -_scheduler_factory = _load_module("infra.scheduling.factory", os.path.join(_scheduling_dir, "factory.py")) - -BaseScheduler = _scheduler_base.BaseScheduler -SchedulingResult = _scheduler_base.SchedulingResult -InstanceHandle = _scheduler_base.InstanceHandle -SchedulerStats = _scheduler_base.SchedulerStats -LoadBalanceStrategy = _scheduler_base.LoadBalanceStrategy -RoutingRule = _scheduler_base.RoutingRule - -LengthAwareScheduler = _hetero_scheduler.LengthAwareScheduler -HeterogeneousScheduler = _hetero_scheduler.HeterogeneousScheduler - -LAMLFQScheduler = _la_mlfq_scheduler.LAMLFQScheduler -HistoryTable = _la_mlfq_scheduler.HistoryTable -ScoutManager = _la_mlfq_scheduler.ScoutManager -ScoutStatus = _la_mlfq_scheduler.ScoutStatus -MigrationController = _la_mlfq_scheduler.MigrationController -MigrationDecision = _la_mlfq_scheduler.MigrationDecision -WaitingRequest = _la_mlfq_scheduler.WaitingRequest - -LoadBalanceScheduler = _load_balance_scheduler.LoadBalanceScheduler -SchedulerFactory = _scheduler_factory.SchedulerFactory - -from config import ( - HeterogeneousRolloutConfig, - SchedulingConfig, -) - - -# ===================================================================== - -# ===================================================================== - -_pass_count = 0 -_fail_count = 0 - - -def check(name: str, condition: bool, detail: str = ""): - global _pass_count, _fail_count - if condition: - _pass_count += 1 - print(f" [PASS] {name}") - else: - _fail_count += 1 - msg = f" [FAIL] {name}" - if detail: - msg += f" -- {detail}" - print(msg) - - -def section(title: str): - print(f"\n{'='*60}") - print(f" {title}") - print(f"{'='*60}") - - -def _make_hetero_config(scheduler_type="length_aware", **sched_kwargs): - """Make hetero config.""" - sched_dict = { - "scheduler_type": scheduler_type, - "length_thresholds": {"short": 1000, "medium": 3000, "long": 6000}, - "routing_rules": { - "short": [1], - "medium": [1, 2], - "long": [2, 4], - "extra_long": [4], - }, - "load_balance_strategy": "least_connections", - "max_queue_length": 50, - "enable_fallback": True, - } - sched_dict.update(sched_kwargs) - return HeterogeneousRolloutConfig.from_dict({ - "enabled": True, - "instances": [ - {"instance_id": "tp1_0", "tp": 1, "gpus": [0]}, - {"instance_id": "tp1_1", "tp": 1, "gpus": [1]}, - {"instance_id": "tp2_0", "tp": 2, "gpus": [2, 3]}, - {"instance_id": "tp4_0", "tp": 4, "gpus": [4, 5, 6, 7]}, - ], - "scheduling": sched_dict, - }) - - -def _register_standard_instances(scheduler): - """Register standard instances.""" - scheduler.register_instance(0, "tp1_0", 1) - scheduler.register_instance(1, "tp1_1", 1) - scheduler.register_instance(2, "tp2_0", 2) - scheduler.register_instance(3, "tp4_0", 4) - - -# ===================================================================== - -# ===================================================================== - -def test_length_aware_categorize(): - """Test length aware categorize.""" - section("1.1 LengthAwareScheduler length classification") - sched = LengthAwareScheduler( - length_thresholds={"short": 1000, "medium": 3000, "long": 6000} - ) - check("500 -> short", sched.categorize(500) == "short") - check("1000 -> short", sched.categorize(1000) == "short") - check("1001 -> medium", sched.categorize(1001) == "medium") - check("3000 -> medium", sched.categorize(3000) == "medium") - check("5000 -> long", sched.categorize(5000) == "long") - check("6000 -> long", sched.categorize(6000) == "long") - check("10000 -> extra_long", sched.categorize(10000) == "extra_long") - - -def test_length_aware_routing(): - """Test length aware routing.""" - section("1.2 LengthAwareScheduler routing") - sched = LengthAwareScheduler( - routing_rules={"short": [1], "medium": [2], "long": [4], "extra_long": [4]}, - length_thresholds={"short": 1000, "medium": 3000, "long": 6000}, - ) - _register_standard_instances(sched) - - - r = sched.schedule(500) - check("Short sequence -> TP=1", r.tp_degree == 1, f"got TP={r.tp_degree}") - check("Short sequence category=short", r.category == "short") - check("Short sequence is not a fallback", r.is_fallback is False) - sched.on_request_done(r.instance_index) - - - r = sched.schedule(2000) - check("Medium sequence -> TP=2", r.tp_degree == 2, f"got TP={r.tp_degree}") - sched.on_request_done(r.instance_index) - - - r = sched.schedule(5000) - check("Long sequence -> TP=4", r.tp_degree == 4, f"got TP={r.tp_degree}") - sched.on_request_done(r.instance_index) - - -def test_length_aware_fallback(): - """Test length aware fallback.""" - section("1.3 LengthAwareScheduler Fallback routing") - - sched = LengthAwareScheduler( - routing_rules={"short": [1], "medium": [2]}, - length_thresholds={"short": 1000, "medium": 3000, "long": 6000}, - ) - sched.register_instance(0, "tp2_0", 2) - - r = sched.schedule(500) - check("Fallback to TP=2", r.tp_degree == 2) - check("is_fallback=True", r.is_fallback is True) - sched.on_request_done(r.instance_index) - - -def test_length_aware_load_balance(): - """Test length aware load balance.""" - section("1.4 LengthAwareScheduler load balancing") - sched = LengthAwareScheduler( - routing_rules={"short": [1]}, - length_thresholds={"short": 1000, "medium": 3000, "long": 6000}, - ) - sched.register_instance(0, "tp1_0", 1) - sched.register_instance(1, "tp1_1", 1) - - - r1 = sched.schedule(500) - - - - r2 = sched.schedule(500) - check("Two requests route to different instances", r1.instance_index != r2.instance_index, - f"r1={r1.instance_index}, r2={r2.instance_index}") - - sched.on_request_done(r1.instance_index) - sched.on_request_done(r2.instance_index) - - -def test_length_aware_stats(): - """Test length aware stats.""" - section("1.5 LengthAwareScheduler statistics") - sched = LengthAwareScheduler() - _register_standard_instances(sched) - - for _ in range(10): - r = sched.schedule(500) - sched.on_request_done(r.instance_index) - for _ in range(5): - r = sched.schedule(20000) - sched.on_request_done(r.instance_index) - - stats = sched.get_stats() - check("total_requests=15", stats.total_requests == 15) - check("success rate=1.0", stats.success_rate == 1.0) - check("category_counts contains short", "short" in stats.category_counts) - check("category_counts contains extra_long", "extra_long" in stats.category_counts) - - -def test_length_aware_backward_compat(): - """Test length aware backward compat.""" - section("1.6 HeterogeneousScheduler alias compatibility") - check("HeterogeneousScheduler is LengthAwareScheduler", - HeterogeneousScheduler is LengthAwareScheduler) - sched = HeterogeneousScheduler() - check("HeterogeneousScheduler created successfully", isinstance(sched, LengthAwareScheduler)) - - -def test_length_aware_from_config(): - """Test length aware from config.""" - section("1.7 LengthAwareScheduler.from_config") - cfg = _make_hetero_config("length_aware") - sched = LengthAwareScheduler.from_config(cfg) - check("Created successfully", isinstance(sched, LengthAwareScheduler)) - check("name='LengthAware'", sched.name == "LengthAware") - - -# ===================================================================== - -# ===================================================================== - -# 2.1 HistoryTable - -def test_history_table(): - """Test history table.""" - section("2.1 HistoryTable basic operations") - ht = HistoryTable(ttl_epochs=3) - check("Initial size=0", ht.size == 0) - - - ht.update("prompt_A", "short", epoch=0) - ht.update("prompt_B", "long", epoch=0) - check("Size=2", ht.size == 2) - - - check("Lookup prompt_A=short", ht.lookup("prompt_A") == "short") - check("Lookup prompt_B=long", ht.lookup("prompt_B") == "long") - check("prompt_C is absent", ht.lookup("prompt_C") is None) - - - ht.on_epoch_end(epoch=5) - check("prompt_A=None after expiration", ht.lookup("prompt_A", current_epoch=5) is None) - - - ht.update("prompt_C", "long", epoch=4) - check("New record prompt_C=long", ht.lookup("prompt_C", current_epoch=5) == "long") - - -# 2.2 ScoutManager - -def test_scout_manager(): - """Test scout manager.""" - section("2.2 ScoutManager scout mechanism") - sm = ScoutManager(scout_timeout=30.0) - - prompt_id = "prompt_X" - - - check("should_scout=True on first request", sm.should_scout(prompt_id) is True) - - - sm.register_scout(prompt_id, instance_index=0, bucket="short") - check("should_scout=False with an existing scout", sm.should_scout(prompt_id) is False) - check("active_scouts=1", sm.active_scouts == 1) - check("is_scout identifies the scout", sm.is_scout(prompt_id, 0) is True) - check("is_scout rejects the wrong instance", sm.is_scout(prompt_id, 1) is False) - - - wr1 = WaitingRequest(prompt_id=prompt_id, input_tokens=500, n_samples=4, epoch=0, sample_index=1) - wr2 = WaitingRequest(prompt_id=prompt_id, input_tokens=500, n_samples=4, epoch=0, sample_index=2) - sm.add_waiting(wr1) - sm.add_waiting(wr2) - check("total_waiting=2", sm.total_waiting == 2) - - - released = sm.on_scout_completed(prompt_id, "short") - check("Release two waiters", len(released) == 2) - check("total_waiting=0", sm.total_waiting == 0) - - - sm.reset() - check("active_scouts=0 after reset", sm.active_scouts == 0) - - -def test_scout_manager_migration(): - """Test scout manager migration.""" - section("2.3 ScoutManager scout migration") - sm = ScoutManager() - prompt_id = "prompt_Y" - - sm.register_scout(prompt_id, instance_index=0, bucket="short") - wr = WaitingRequest(prompt_id=prompt_id, input_tokens=500, n_samples=2, epoch=0, sample_index=1) - sm.add_waiting(wr) - - - released = sm.on_scout_migrated(prompt_id, "long") - check("Migration releases one waiter", len(released) == 1) - check("Scout current bucket=long", sm.get_scout_bucket(prompt_id) == "long") - check("Scout status=MIGRATED", sm.get_scout_status(prompt_id) == ScoutStatus.MIGRATED) - - -# 2.3 MigrationController - -def test_migration_controller(): - """Test migration controller.""" - section("2.4 MigrationController migration decision") - mc = MigrationController(bucket_thresholds={"short": 3000, "medium": 10000}) - - - mc.register_request("req_1", "prompt_A", 0, "short", is_scout=True) - - - d1 = mc.check_migration("req_1", generated_tokens=1000) - check("1000 tokens: no migration", d1.should_migrate is False) - check("Reason=below_threshold", d1.reason == "below_threshold") - - - d2 = mc.check_migration("req_1", generated_tokens=5000) - check("5000 tokens: migrate", d2.should_migrate is True) - check("Target bucket=long", d2.target_bucket == "long") - check("Reason=threshold_exceeded", d2.reason == "threshold_exceeded") - - - mc.on_migration_executed("req_1", "long") - state = mc.get_request_state("req_1") - check("current_bucket=long after migration", state.current_bucket == "long") - - - d3 = mc.check_migration("req_1", generated_tokens=50000) - check("Long bucket: no migration", d3.should_migrate is False) - - - mc.on_request_done("req_1") - stats = mc.get_stats() - check("total_migrations=1", stats["total_migrations"] == 1) - - - - -def test_la_mlfq_default_route(): - """Test la mlfq default route.""" - section("2.5 LAMLFQScheduler default length routing") - sched = LAMLFQScheduler( - buckets={ - "short": {"tp_degrees": [1], "max_tokens": 3000}, - "long": {"tp_degrees": [2, 4], "max_tokens": 50000}, - }, - length_thresholds={"short": 1000, "medium": 3000, "long": 6000}, - ) - _register_standard_instances(sched) - - - r = sched.schedule(input_tokens=500) - check("Short sequence -> short bucket", r.category == "short") - check("TP=1 instance", r.tp_degree == 1) - sched.on_request_done(r.instance_index) - - r = sched.schedule(input_tokens=5000) - check("Long sequence -> long bucket", r.category == "long") - check("TP=2 or 4", r.tp_degree in [2, 4]) - sched.on_request_done(r.instance_index) - - -def test_la_mlfq_history_hit(): - """Test la mlfq history hit.""" - section("2.6 LAMLFQScheduler inter-epoch history hit") - sched = LAMLFQScheduler( - buckets={ - "short": {"tp_degrees": [1], "max_tokens": 3000}, - "long": {"tp_degrees": [2, 4], "max_tokens": 50000}, - }, - length_thresholds={"short": 1000}, - ) - _register_standard_instances(sched) - - - sched.history_table.update("prompt_A", "long", epoch=0) - - - sched.on_epoch_start(1) - r = sched.schedule(input_tokens=500, prompt_id="prompt_A", epoch=1) - check("History hit routes a short sequence to long", r.category == "long") - check("reason contains history_hit", "history_hit" in r.reason) - sched.on_request_done(r.instance_index, prompt_id="prompt_A", final_bucket="long") - - -def test_la_mlfq_scout_mechanism(): - """Test la mlfq scout mechanism.""" - section("2.7 LAMLFQScheduler scout mechanism") - sched = LAMLFQScheduler( - buckets={ - "short": {"tp_degrees": [1], "max_tokens": 3000}, - "long": {"tp_degrees": [2, 4], "max_tokens": 50000}, - }, - ) - _register_standard_instances(sched) - - prompt_id = "prompt_new" - - - r1 = sched.schedule(input_tokens=500, prompt_id=prompt_id, n_samples=4) - check("First request: not pending", r1.pending is False) - check("First request: short bucket", r1.category == "short") - check("First request: reason=scout", "scout" in r1.reason) - - - r2 = sched.schedule(input_tokens=500, prompt_id=prompt_id, n_samples=4) - check("Second request: pending=True", r2.pending is True) - check("Second request: reason=waiting_for_scout", "waiting_for_scout" in r2.reason) - - - sched.on_request_done( - r1.instance_index, prompt_id=prompt_id, final_bucket="short" - ) - - - r3 = sched.schedule(input_tokens=500, prompt_id=prompt_id, n_samples=4) - check("Third request: follows the scout to short", r3.category == "short") - check("Third request: not pending", r3.pending is False) - sched.on_request_done(r3.instance_index, prompt_id=prompt_id, final_bucket="short") - - -def test_la_mlfq_scout_migration(): - """Test la mlfq scout migration.""" - section("2.8 LAMLFQScheduler scout migration") - sched = LAMLFQScheduler( - buckets={ - "short": {"tp_degrees": [1], "max_tokens": 3000}, - "long": {"tp_degrees": [2, 4], "max_tokens": 50000}, - }, - ) - _register_standard_instances(sched) - - prompt_id = "prompt_migrate" - - - r1 = sched.schedule(input_tokens=500, prompt_id=prompt_id, n_samples=3) - check("Scout: short bucket", r1.category == "short") - - - scout_req_id = f"{prompt_id}_scout" - decision = sched.check_and_migrate(scout_req_id, generated_tokens=5000) - check("migration decision: should_migrate=True", decision.should_migrate is True) - check("Migration target: long", decision.target_bucket == "long") - - - stats = sched.get_stats() - check("migrated_routes >= 1", stats.migrated_routes >= 1) - - -def test_la_mlfq_epoch_lifecycle(): - """Test la mlfq epoch lifecycle.""" - section("2.9 LAMLFQScheduler epoch lifecycle") - sched = LAMLFQScheduler(history_ttl=2) - _register_standard_instances(sched) - - # Epoch 0 - sched.on_epoch_start(0) - sched.history_table.update("p1", "short", epoch=0) - sched.history_table.update("p2", "long", epoch=0) - sched.on_epoch_end(0) - check("history_table.size=2 after epoch 0", sched.history_table.size == 2) - - - sched.on_epoch_start(3) - sched.on_epoch_end(3) - r = sched.history_table.lookup("p1", current_epoch=3) - check("p1 expires after epoch 3", r is None) - - -def test_la_mlfq_from_config(): - """Test la mlfq from config.""" - section("2.10 LAMLFQScheduler.from_config") - cfg = _make_hetero_config( - "la_mlfq", - la_mlfq_migration_threshold=5000, - la_mlfq_scout_timeout=45.0, - la_mlfq_history_ttl=3, - ) - sched = LAMLFQScheduler.from_config(cfg) - check("Created successfully", isinstance(sched, LAMLFQScheduler)) - check("name='LA-MLFQ'", sched.name == "LA-MLFQ") - - -# ===================================================================== - -# ===================================================================== - -def test_load_balance_least_connections(): - """Test load balance least connections.""" - section("3.1 LoadBalanceScheduler Least Connections") - sched = LoadBalanceScheduler(load_balance_strategy="least_connections") - _register_standard_instances(sched) - - - r1 = sched.schedule(500) - check("Scheduling succeeds", r1.instance_index >= 0) - - - r2 = sched.schedule(500) - check("Selects different instances", r2.instance_index != r1.instance_index, - f"r1={r1.instance_index}, r2={r2.instance_index}") - - sched.on_request_done(r1.instance_index) - sched.on_request_done(r2.instance_index) - - -def test_load_balance_round_robin(): - """Test load balance round robin.""" - section("3.2 LoadBalanceScheduler Round Robin") - sched = LoadBalanceScheduler(load_balance_strategy="round_robin") - _register_standard_instances(sched) - - - indices = set() - for _ in range(4): - r = sched.schedule(500) - indices.add(r.instance_index) - sched.on_request_done(r.instance_index) - - check("Round-robin covers all four instances", len(indices) == 4, - f"got {len(indices)} unique indices") - - -def test_load_balance_weighted(): - """Test load balance weighted.""" - section("3.3 LoadBalanceScheduler Weighted") - sched = LoadBalanceScheduler( - load_balance_strategy="weighted", - weights={1: 1.0, 2: 2.0, 4: 4.0}, - ) - _register_standard_instances(sched) - - r = sched.schedule(500) - check("Weighted scheduling succeeds", r.instance_index >= 0) - sched.on_request_done(r.instance_index) - - -def test_load_balance_ignores_length(): - """Test load balance ignores length.""" - section("3.4 LoadBalanceScheduler ignores length") - sched = LoadBalanceScheduler() - _register_standard_instances(sched) - - r_short = sched.schedule(100) - sched.on_request_done(r_short.instance_index) - r_long = sched.schedule(100000) - sched.on_request_done(r_long.instance_index) - - check("category are all 'any'", - r_short.category == "any" and r_long.category == "any") - - -def test_load_balance_from_config(): - """Test load balance from config.""" - section("3.5 LoadBalanceScheduler.from_config") - cfg = _make_hetero_config("load_balance") - sched = LoadBalanceScheduler.from_config(cfg) - check("Created successfully", isinstance(sched, LoadBalanceScheduler)) - check("name='LoadBalance'", sched.name == "LoadBalance") - - -# ===================================================================== - -# ===================================================================== - -def test_factory_length_aware(): - """Test factory length aware.""" - section("4.1 SchedulerFactory → LengthAware") - cfg = _make_hetero_config("length_aware") - sched = SchedulerFactory.create("length_aware", cfg) - check("Type is correct", type(sched).__name__ == "LengthAwareScheduler") - check("name='LengthAware'", sched.name == "LengthAware") - - -def test_factory_la_mlfq(): - """Test factory la mlfq.""" - section("4.2 SchedulerFactory → LA-MLFQ") - cfg = _make_hetero_config("la_mlfq") - sched = SchedulerFactory.create("la_mlfq", cfg) - check("Type is correct", type(sched).__name__ == "LAMLFQScheduler") - - -def test_factory_load_balance(): - """Test factory load balance.""" - section("4.3 SchedulerFactory → LoadBalance") - cfg = _make_hetero_config("load_balance") - sched = SchedulerFactory.create("load_balance", cfg) - check("Type is correct", type(sched).__name__ == "LoadBalanceScheduler") - - -def test_factory_invalid_type(): - """Test factory invalid type.""" - section("4.4 SchedulerFactory invalid type") - cfg = _make_hetero_config("unknown_type") - try: - SchedulerFactory.create("unknown_type", cfg) - check("Should raise ValueError", False) - except ValueError as e: - check("Raises ValueError", True) - check("Error lists available types", "length_aware" in str(e)) - - -def test_factory_available_types(): - """Test factory available types.""" - section("4.5 SchedulerFactory available types") - types = SchedulerFactory.available_types() - check("length_aware is listed", "length_aware" in types) - check("la_mlfq is listed", "la_mlfq" in types) - check("load_balance is listed", "load_balance" in types) - - -# ===================================================================== - -# ===================================================================== - -def test_base_scheduler_instance_registration(): - """Test base scheduler instance registration.""" - section("5.1 BaseScheduler instance registration") - sched = LengthAwareScheduler() - _register_standard_instances(sched) - - h = sched.get_instance_handle(0) - check("Lookup index=0", h is not None) - check("instance_id='tp1_0'", h.instance_id == "tp1_0") - check("tp_degree=1", h.tp_degree == 1) - - h3 = sched.get_instance_handle(3) - check("Lookup index=3", h3 is not None) - check("tp_degree=4", h3.tp_degree == 4) - - check("Lookup index=99 returns None", sched.get_instance_handle(99) is None) - - -def test_base_scheduler_stats_reset(): - """Test base scheduler stats reset.""" - section("5.2 BaseScheduler statistics reset") - sched = LengthAwareScheduler() - _register_standard_instances(sched) - - for _ in range(5): - r = sched.schedule(500) - sched.on_request_done(r.instance_index) - - check("Before reset total=5", sched.get_stats().total_requests == 5) - sched.reset_stats() - check("After reset total=0", sched.get_stats().total_requests == 0) - - -def test_scheduler_all_types_schedule_and_done(): - """Test scheduler all types schedule and done.""" - section("5.3 schedule/on_request_done cycle for all scheduler types") - cfg = _make_hetero_config() - for stype in ["length_aware", "la_mlfq", "load_balance"]: - sched = SchedulerFactory.create(stype, cfg) - _register_standard_instances(sched) - - for tokens in [100, 2000, 5000, 10000]: - r = sched.schedule(input_tokens=tokens) - if not r.pending: - sched.on_request_done(r.instance_index) - - stats = sched.get_stats() - check(f"{stype}: total_requests=4", stats.total_requests == 4) - - -# ===================================================================== - -# ===================================================================== - -def main(): - print("\n" + "=" * 60) - print(" Heterogeneous scheduler policy unit tests") - print("=" * 60) - - # 1. LengthAwareScheduler - test_length_aware_categorize() - test_length_aware_routing() - test_length_aware_fallback() - test_length_aware_load_balance() - test_length_aware_stats() - test_length_aware_backward_compat() - test_length_aware_from_config() - - # 2. LAMLFQScheduler - test_history_table() - test_scout_manager() - test_scout_manager_migration() - test_migration_controller() - test_la_mlfq_default_route() - test_la_mlfq_history_hit() - test_la_mlfq_scout_mechanism() - test_la_mlfq_scout_migration() - test_la_mlfq_epoch_lifecycle() - test_la_mlfq_from_config() - - # 3. LoadBalanceScheduler - test_load_balance_least_connections() - test_load_balance_round_robin() - test_load_balance_weighted() - test_load_balance_ignores_length() - test_load_balance_from_config() - - # 4. SchedulerFactory - test_factory_length_aware() - test_factory_la_mlfq() - test_factory_load_balance() - test_factory_invalid_type() - test_factory_available_types() - - - test_base_scheduler_instance_registration() - test_base_scheduler_stats_reset() - test_scheduler_all_types_schedule_and_done() - - - print(f"\n{'='*60}") - total = _pass_count + _fail_count - print(f" Result: {_pass_count}/{total} passed, {_fail_count} failed") - print(f"{'='*60}") - - if _fail_count > 0: - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/examples/test_search_r1.py b/examples/test_search_r1.py deleted file mode 100644 index 759fc49..0000000 --- a/examples/test_search_r1.py +++ /dev/null @@ -1,594 +0,0 @@ -"""Support code for Test search r1.""" - -import asyncio -import json -import sys -import os -from unittest.mock import AsyncMock, MagicMock, patch - - -_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -if _PROJECT_ROOT not in sys.path: - sys.path.insert(0, _PROJECT_ROOT) - -# ------------------------------------------------------------------ - -# ------------------------------------------------------------------ - -import types -import importlib.util - -if importlib.util.find_spec("torch") is None: - torch_mock = types.ModuleType("torch") - torch_mock.Tensor = MagicMock - torch_mock.tensor = lambda *a, **k: MagicMock() - torch_mock.cat = lambda tensors, dim=0: MagicMock() - torch_mock.zeros = lambda *a, **k: MagicMock() - torch_mock.ones = lambda *a, **k: MagicMock() - torch_mock.float32 = "float32" - torch_mock.__spec__ = importlib.util.spec_from_loader("torch", loader=None) - sys.modules["torch"] = torch_mock - -from env.search_tool import SearchTool -from env.search_r1_prompt import ( - SEARCH_R1_SYSTEM_PROMPT, - SEARCH_R1_USER_PREFIX, - TOOL_RESPONSE_TEMPLATE, - SEARCH_R1_FORMAT_INSTRUCTION, -) -from env.search_r1_reward import ( - extract_search_r1_answer, - extract_search_r1_think, - search_r1_reward_fn, - format_reward_fn, - combined_search_r1_reward_fn, -) -from workflow.search_r1 import SearchR1Workflow - - -# ================================================================== - -# ================================================================== - -PASS_COUNT = 0 -FAIL_COUNT = 0 -FAILED_TESTS = [] - - -def assert_true(condition, msg): - global PASS_COUNT, FAIL_COUNT, FAILED_TESTS - if condition: - PASS_COUNT += 1 - print(f" ✓ {msg}") - else: - FAIL_COUNT += 1 - FAILED_TESTS.append(msg) - print(f" ✗ {msg}") - - -def assert_eq(actual, expected, msg): - assert_true(actual == expected, f"{msg} | expected={expected}, got={actual}") - - -def assert_in(substring, text, msg): - assert_true(substring in text, f"{msg} | '{substring}' not in '{text[:80]}...'") - - -# ================================================================== - -# ================================================================== - -async def test_search_tool(): - print("\n" + "-" * 60) - print("Test module: env/search_tool.py") - print("-" * 60) - - - print("\n[1.1] Chinese text detection") - assert_true( - SearchTool._contains_chinese("\u4f60\u597d\u4e16\u754c"), - "Chinese text is detected" - ) - assert_true( - not SearchTool._contains_chinese("Hello World"), - "English text is not detected as Chinese" - ) - assert_true( - SearchTool._contains_chinese("Hello \u4e16\u754c"), - "Mixed Chinese-English text is detected" - ) - - - print("\n[1.2] Missing API key handling") - tool = SearchTool(api_key=None) - result = await tool.search("test query") - assert_in("Error", result, "A missing API key returns an error") - assert_in("SERPER_KEY_ID", result, "The error names the environment variable") - - searxng_tool = SearchTool( - backend="searxng", - searxng_url="http://searxng.test:18080/", - ) - assert_eq(searxng_tool.backend, "searxng", "The SearXNG backend is supported") - assert_eq( - searxng_tool.searxng_url, - "http://searxng.test:18080", - "The SearXNG service address is normalized", - ) - - - print("\n[1.3] Successful mocked HTTP search") - - mock_response_text = json.dumps({ - "organic": [ - {"title": "Test Page 1", "link": "https://example.com/1", "snippet": "This is result 1."}, - {"title": "Test Page 2", "link": "https://example.com/2", "snippet": "This is result 2.", "date": "2024-01-01"}, - ] - }) - - - def _make_mock_response(text_content): - class Resp: - async def text(self): - return text_content - class RespCtx: - async def __aenter__(self): - return Resp() - async def __aexit__(self, *args): - pass - return RespCtx() - - class MockSession: - async def __aenter__(self): - return self - async def __aexit__(self, *args): - pass - def post(self, *args, **kwargs): - return _make_mock_response(mock_response_text) - - tool_with_key = SearchTool(api_key="fake_key_123") - with patch("aiohttp.ClientSession", return_value=MockSession()): - result = await tool_with_key.search("Python programming") - - assert_in("Search results for 'Python programming'", result, "The result contains the query heading") - assert_in("Test Page 1", result, "The result contains the title") - assert_in("https://example.com/1", result, "The result contains the URL") - assert_in("This is result 1.", result, "The result contains the snippet") - assert_in("Date: 2024-01-01", result, "The result contains the date") - - - print("\n[1.4] Empty mocked HTTP results") - empty_response = json.dumps({"searchParameters": {}}) - - class MockEmptySession: - async def __aenter__(self): - return self - async def __aexit__(self, *args): - pass - def post(self, *args, **kwargs): - return _make_mock_response(empty_response) - - with patch("aiohttp.ClientSession", return_value=MockEmptySession()): - result = await tool_with_key.search("xyzabc123") - - assert_in("No results found", result, "An empty result set returns a message") - - - print("\n[1.5] Mocked HTTP parse failure") - - class MockBadSession: - async def __aenter__(self): - return self - async def __aexit__(self, *args): - pass - def post(self, *args, **kwargs): - return _make_mock_response("not json") - - with patch("aiohttp.ClientSession", return_value=MockBadSession()): - result = await tool_with_key.search("test") - - assert_in("Failed to parse", result, "Invalid JSON returns a parse error") - - - print("\n[1.6] Batch search") - - class MockBatchSession: - async def __aenter__(self): - return self - async def __aexit__(self, *args): - pass - def post(self, *args, **kwargs): - batch_text = json.dumps({ - "organic": [{"title": "Batch", "link": "http://b", "snippet": "batch result"}] - }) - return _make_mock_response(batch_text) - - with patch("aiohttp.ClientSession", return_value=MockBatchSession()): - results = await tool_with_key.search_batch(["query1", "query2"]) - - assert_eq(len(results), 2, "Batch search returns one result per query") - assert_in("batch result", results[0], "The first batch result is correct") - assert_in("batch result", results[1], "The second batch result is correct") - - -# ================================================================== - -# ================================================================== - -def test_search_r1_reward(): - print("\n" + "-" * 60) - print("Test module: env/search_r1_reward.py") - print("-" * 60) - - - print("\n[2.1] extract_search_r1_answer") - assert_eq( - extract_search_r1_answer("Some text 42 more"), - "42", - "Extract answer content and trim whitespace" - ) - assert_eq( - extract_search_r1_answer("No answer here"), - "", - "Return an empty value without an answer tag" - ) - assert_eq( - extract_search_r1_answer("Beijing"), - "Beijing", - "Extract an exact match" - ) - assert_eq( - extract_search_r1_answer("Multi\nline \n 3.14 \n end"), - "3.14", - "Extract multiline content and trim whitespace" - ) - - - print("\n[2.2] extract_search_r1_think") - assert_eq( - extract_search_r1_think("Let me think..."), - "Let me think...", - "Extract think content" - ) - assert_eq( - extract_search_r1_think("Deep thinking..."), - "Deep thinking...", - "Extract thinking content" - ) - assert_eq( - extract_search_r1_think("No think tags"), - "", - "Return an empty value without a think tag" - ) - - - print("\n[2.3] search_r1_reward_fn - correct answer") - completion = "Some reasoning42" - reward = search_r1_reward_fn("prompt", completion, ground_truth="42") - assert_eq(reward, 1.0, "Answer 42 matches ground_truth 42 and receives 1.0") - - reward = search_r1_reward_fn("prompt", completion, ground_truth=" Beijing ") - assert_eq(reward, 0.0, "Answer 42 does not match Beijing and receives 0.0") - - completion = "Some reasoningThe Beatles" - reward = search_r1_reward_fn( - "prompt", - completion, - ground_truth=["Beatles", "The Beatles"], - ) - assert_eq(reward, 1.0, "Multiple Search-R1 references use the official exact-match rule") - - - print("\n[2.4] search_r1_reward_fn - edge cases") - reward = search_r1_reward_fn("prompt", completion, ground_truth="") - assert_eq(reward, 0.0, "Missing ground_truth returns 0.0") - - reward = search_r1_reward_fn("prompt", "no answer tag", ground_truth="42") - assert_eq(reward, 0.0, "Missing answer tag returns 0.0") - - - print("\n[2.5] search_r1_reward_fn - mathematical equivalence") - comp = "...1/2" - - reward = search_r1_reward_fn("prompt", comp, ground_truth="0.5") - assert_true(reward > 0, "1/2 and 0.5 are treated as equivalent") - - - print("\n[2.6] format_reward_fn") - fmt = format_reward_fn("...42") - assert_eq(fmt, 0.15, "Think and answer tags receive the full 0.15") - - fmt = format_reward_fn("42") - assert_eq(fmt, 0.1, "An answer tag alone receives 0.1") - - fmt = format_reward_fn("...") - assert_eq(fmt, 0.05, "A think tag alone receives 0.05") - - fmt = format_reward_fn("Plain text") - assert_eq(fmt, 0.0, "No tags receives 0.0") - - - print("\n[2.7] combined_search_r1_reward_fn") - comp = "...42" - reward = combined_search_r1_reward_fn("prompt", comp, ground_truth="42") - expected = 1.0 + 0.15 * 0.15 # correctness(1.0) + format_weight(0.15) * format(0.15) - assert_eq(reward, expected, "Combined reward equals correctness plus format reward") - - -# ================================================================== - -# ================================================================== - -def test_search_r1_prompt(): - print("\n" + "-" * 60) - print("Test module: env/search_r1_prompt.py") - print("-" * 60) - - - print("\n[3.1] Prompt template completeness") - assert_true(len(SEARCH_R1_SYSTEM_PROMPT) > 0, "The system prompt is not empty") - assert_in("assistant", SEARCH_R1_SYSTEM_PROMPT, "The system prompt contains assistant") - - - assert_in("", SEARCH_R1_USER_PREFIX, "The user prefix contains ") - assert_in("", SEARCH_R1_USER_PREFIX, "The user prefix contains ") - assert_in("", SEARCH_R1_USER_PREFIX, "The user prefix contains ") - assert_in("Question:", SEARCH_R1_USER_PREFIX, "The user prefix ends with Question") - - - assert_in("tool_response", TOOL_RESPONSE_TEMPLATE, "The template contains the tool_response tag") - assert_in("{results}", TOOL_RESPONSE_TEMPLATE, "The template contains the {results} placeholder") - - - assert_in("", SEARCH_R1_FORMAT_INSTRUCTION, "The format instructions mention the think tag") - assert_in("", SEARCH_R1_FORMAT_INSTRUCTION, "The format instructions mention the answer tag") - - - try: - formatted = TOOL_RESPONSE_TEMPLATE.format(results="test results") - assert_in("test results", formatted, "Template formatting succeeds") - except Exception as e: - assert_true(False, f"Template formatting failed: {e}") - - -# ================================================================== - -# ================================================================== - -async def test_search_r1_workflow(): - print("\n" + "-" * 60) - print("Test module: workflow/search_r1.py") - print("-" * 60) - - - print("\n[4.1] _extract_tool_call") - assert_eq( - SearchR1Workflow._extract_tool_call("Some text Python tutorial end"), - "Python tutorial", - "Extract a tool_call query" - ) - assert_eq( - SearchR1Workflow._extract_tool_call("No tool call here"), - None, - "Return None without a tool_call" - ) - assert_eq( - SearchR1Workflow._extract_tool_call("Empty query"), - None, - "Return None for an empty query" - ) - assert_eq( - SearchR1Workflow._extract_tool_call("Multi\nline\nquery"), - "line\nquery", - "Extract a multiline query" - ) - - - print("\n[4.2] _has_answer_tag") - wf = SearchR1Workflow(reward_fn=lambda **kwargs: 0.0, tokenizer=None) - assert_true(wf._has_answer_tag("42"), "Contains an answer tag") - assert_true(not wf._has_answer_tag("No answer"), "Does not contain an answer tag") - assert_true(not wf._has_answer_tag(""), "An opening tag alone does not count") - - - print("\n[4.3] _build_initial_prompt") - - - class MockTokenizer: - def apply_chat_template(self, messages, tokenize=False, add_generation_prompt=True): - - return "\n".join([m.get("content", "") for m in messages]) - def encode(self, text, add_special_tokens=False): - return list(text.encode("utf-8")) - def decode(self, token_ids, skip_special_tokens=True): - if isinstance(token_ids, list): - return "".join(chr(b) for b in token_ids if 0 <= b <= 255) - return "" - - tokenizer = MockTokenizer() - - wf = SearchR1Workflow( - reward_fn=lambda **kwargs: 1.0, - tokenizer=tokenizer, - ) - prompt = wf._build_initial_prompt("What is 2+2?") - assert_in("What is 2+2?", prompt, "The prompt contains the question") - assert_in("", prompt, "The prompt describes the think tag") - assert_in("", prompt, "The prompt describes tool_call") - assert_in("", prompt, "The prompt describes answer") - - - print("\n[4.4] run_episode - without a tool call") - - mock_engine = AsyncMock() - mock_engine.generate = AsyncMock(return_value={ - "text": "2+2=44", - "logprobs": [-0.1, -0.2, -0.3, -0.4, -0.5, -0.6, -0.7, -0.8], - }) - - wf = SearchR1Workflow( - reward_fn=lambda prompt, completion, **kwargs: 1.0 if "4" in completion else 0.0, - tokenizer=tokenizer, - search_tool=SearchTool(api_key="fake"), - max_turns=3, - ) - - trajectory = await wf.run_episode( - engine=mock_engine, - data={"question": "What is 2+2?", "ground_truth": "4"}, - version=0, - ) - - assert_true("input_ids" in trajectory, "The trajectory contains input_ids") - assert_true("loss_mask" in trajectory, "The trajectory contains loss_mask") - assert_true("rewards" in trajectory, "The trajectory contains rewards") - assert_eq(trajectory["n_turns"], 1, "No tool call executes one turn") - assert_eq(trajectory["n_searches"], 0, "No tool call performs no searches") - assert_eq(trajectory["rewards"].item(), 1.0, "A correct answer receives reward 1.0") - - - loss_mask = trajectory["loss_mask"][0].tolist() - prompt_len = trajectory["input_len"] - assert_true(prompt_len > 0, "Prompt length is greater than zero") - assert_true(all(m == 0 for m in loss_mask[:prompt_len]), "The prompt portion of loss_mask is zero") - assert_true(any(m == 1 for m in loss_mask[prompt_len:]), "The generated portion has loss_mask=1") - - - print("\n[4.5] run_episode - with a tool call") - - - - call_count = 0 - async def mock_generate_with_tool(prompt, **kwargs): - nonlocal call_count - call_count += 1 - if call_count == 1: - return { - "text": "I need to searchcapital of France", - "logprobs": [-0.1] * 15, - } - else: - return { - "text": "Now I knowParis", - "logprobs": [-0.2] * 12, - } - - mock_engine2 = MagicMock() - mock_engine2.generate = AsyncMock(side_effect=mock_generate_with_tool) - - # mock search tool - mock_search = AsyncMock(return_value="Paris is the capital of France.") - - wf2 = SearchR1Workflow( - reward_fn=lambda prompt, completion, **kwargs: 1.0 if "Paris" in completion else 0.0, - tokenizer=tokenizer, - search_tool=MagicMock(search=mock_search), - max_turns=3, - ) - - trajectory = await wf2.run_episode( - engine=mock_engine2, - data={"question": "What is the capital of France?", "ground_truth": "Paris"}, - version=1, - ) - - assert_eq(trajectory["n_turns"], 2, "The episode executes two turns (search and answer)") - assert_eq(trajectory["n_searches"], 1, "The episode performs one search") - assert_eq(trajectory["rewards"].item(), 1.0, "A correct answer receives reward 1.0") - assert_eq(trajectory["versions"].item(), 1, "The version is propagated correctly") - - - mock_search.assert_called_once() - call_args = mock_search.call_args[0][0] - assert_eq(call_args, "capital of France", "The search query is extracted correctly") - - - print("\n[4.6] run_episode - reaching max_turns") - - async def mock_generate_always_tool(prompt, **kwargs): - return { - "text": "search again", - "logprobs": [-0.1] * 5, - } - - mock_engine3 = MagicMock() - mock_engine3.generate = AsyncMock(side_effect=mock_generate_always_tool) - - wf3 = SearchR1Workflow( - reward_fn=lambda **kwargs: 0.0, - tokenizer=tokenizer, - search_tool=MagicMock(search=AsyncMock(return_value="some result")), - max_turns=2, - ) - - trajectory = await wf3.run_episode( - engine=mock_engine3, - data={"question": "Test?", "ground_truth": "X"}, - ) - - assert_eq(trajectory["n_turns"], 2, "The episode reaches max_turns") - assert_eq(trajectory["n_searches"], 1, "The last turn does not search, for one search total") - - # ---- 4.7 run_batch ---- - print("\n[4.7] run_batch") - - mock_engine4 = AsyncMock() - mock_engine4.generate = AsyncMock(return_value={ - "text": "OK", - "logprobs": [-0.1] * 5, - }) - - wf4 = SearchR1Workflow( - reward_fn=lambda **kwargs: 0.5, - tokenizer=tokenizer, - max_turns=1, - ) - - batch = [ - {"question": "Q1?", "ground_truth": "A1"}, - {"question": "Q2?", "ground_truth": "A2"}, - ] - results = await wf4.run_batch(engine=mock_engine4, batch_data=batch) - - assert_eq(len(results), 2, "The batch returns two results") - assert_eq(results[0]["rewards"].item(), 0.5, "The first result reward is correct") - assert_eq(results[1]["rewards"].item(), 0.5, "The second result reward is correct") - - -# ================================================================== - -# ================================================================== - -async def run_all_tests(): - print("=" * 60) - print("SearchR1 module unit tests") - print("=" * 60) - - await test_search_tool() - test_search_r1_reward() - test_search_r1_prompt() - await test_search_r1_workflow() - - - print("\n" + "=" * 60) - print("Test summary") - print("=" * 60) - print(f"passed: {PASS_COUNT}") - print(f"failed: {FAIL_COUNT}") - - if FAILED_TESTS: - print("\nFailed tests:") - for msg in FAILED_TESTS: - print(f" - {msg}") - print("\n" + "=" * 60) - print("Some tests failed; inspect the output above.") - print("=" * 60) - sys.exit(1) - else: - print("\n" + "=" * 60) - print("All tests passed!") - print("=" * 60) - - -if __name__ == "__main__": - asyncio.run(run_all_tests()) diff --git a/examples/test_single_gpu.py b/examples/test_single_gpu.py deleted file mode 100644 index f20303d..0000000 --- a/examples/test_single_gpu.py +++ /dev/null @@ -1,66 +0,0 @@ -"""Support code for Test single gpu.""" - -import sys -import os - - -_current_dir = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, os.path.dirname(_current_dir)) - -import torch -from RL_Framework.engine.train_engine import FSDPTrainEngine -from RL_Framework.config import AsyncRLConfig - -print("=" * 60) -print("Single-GPU training-engine initialization test") -print("=" * 60) - - -config = AsyncRLConfig( - model_path="Qwen/Qwen2-1.5B-Instruct", - train_gpus=1, - rollout_gpus=0, -) - -print("\nConfiguration:") -print(f" model_path: {config.model_path}") -print(f" train_gpus: {config.train_gpus}") - - -print("\nCreating the training engine...") -train_engine = FSDPTrainEngine( - model_path=config.model_path, - learning_rate=config.learning_rate, - clip_epsilon=config.clip_epsilon, - kl_coef=config.kl_coef, -) - - -print("\nInitializing the model...") -try: - train_engine.initialize(max_seq_length=config.max_seq_length) - print("\nModel initialized successfully.") - print(f" is_distributed: {train_engine.is_distributed}") - print(f" is_main_process: {train_engine.is_main_process}") - print(f" device: {train_engine.local_rank}") - - - print("\nTesting weight saving...") - test_path = "/path/to/user/test_weights" - train_engine.save_weights(test_path, version=0) - print("Weights saved successfully.") - - - print("\nTesting weight loading...") - train_engine.load_weights(test_path, version=0) - print("Weights loaded successfully.") - - print("\n" + "=" * 60) - print("All tests passed; single-GPU mode is working.") - print("=" * 60) - -except Exception as e: - print(f"\nTest failed: {e}") - import traceback - traceback.print_exc() - sys.exit(1) diff --git a/examples/test_train_parallel_runtime.py b/examples/test_train_parallel_runtime.py deleted file mode 100644 index bef9e74..0000000 --- a/examples/test_train_parallel_runtime.py +++ /dev/null @@ -1,37 +0,0 @@ -"""Support code for Test train parallel runtime.""" - -import os -import sys -import types - -_project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -_pkg = types.ModuleType("RL_Framework") -_pkg.__path__ = [_project_root] -_pkg.__package__ = "RL_Framework" -sys.modules.setdefault("RL_Framework", _pkg) - -from RL_Framework.engine.train_parallel import TrainParallelRuntime - - -def main(): - runtime = TrainParallelRuntime( - rank=5, - world_size=8, - tensor_parallel_size=2, - pipeline_parallel_size=2, - data_parallel_size=2, - ) - - assert runtime.data_parallel_rank == 1 - assert runtime.pipeline_parallel_rank == 0 - assert runtime.tensor_parallel_rank == 1 - assert runtime.get_model_replica_ranks() == [4, 5, 6, 7] - assert runtime.get_tp_ranks(dp_rank=1, pp_rank=0) == [4, 5] - assert runtime.get_pp_ranks(dp_rank=1, tp_rank=1) == [5, 7] - assert runtime.get_dp_ranks(pp_rank=1, tp_rank=0) == [2, 6] - - print("TrainParallelRuntime mapping test passed") - - -if __name__ == "__main__": - main() diff --git a/examples/train_r2e_gym_200_steps.py b/examples/train_r2e_gym_200_steps.py deleted file mode 100644 index 22c1b0d..0000000 --- a/examples/train_r2e_gym_200_steps.py +++ /dev/null @@ -1,165 +0,0 @@ -"""Run a 200-step R2E-Gym training smoke test with wandb logging. - -This intentionally uses only the official R2E-Gym V1 data. The optimization -target is a lightweight repository-classification objective over task metadata, -and the script also records the real environment reward check produced by the -R2E SymPy task harness. -""" - -import argparse -import json -import os -from pathlib import Path - -import torch -import torch.nn as nn -import torch.nn.functional as F - - -def parse_args(): - parser = argparse.ArgumentParser() - parser.add_argument("--dataset-index", type=Path, required=True) - parser.add_argument("--manifest", type=Path, required=True) - parser.add_argument("--reward-result", type=Path, required=True) - parser.add_argument("--steps", type=int, default=200) - parser.add_argument("--batch-size", type=int, default=16) - parser.add_argument("--wandb-project", default="rl-framework-r2e-gym") - parser.add_argument("--wandb-run-name", default="r2e-gym-200-step-smoke") - parser.add_argument("--output", type=Path, required=True) - return parser.parse_args() - - -def load_rows(index_path: Path, limit: int = 1024): - rows = [] - with index_path.open(encoding="utf-8") as source: - for line in source: - row = json.loads(line) - rows.append(row) - if len(rows) >= limit: - break - if not rows: - raise ValueError(f"No rows loaded from {index_path}") - return rows - - -def row_features(row): - text = row.get("task_text") or row.get("problem_statement") or row.get("prompt") or "" - modified_files = row.get("modified_files") or [] - if isinstance(modified_files, str): - try: - modified_files = json.loads(modified_files) - except json.JSONDecodeError: - modified_files = [modified_files] - return torch.tensor( - [ - min(len(text), 20000) / 20000.0, - min(text.count("\n"), 400) / 400.0, - min(len(modified_files), 20) / 20.0, - 1.0 if row["repo_name"] == "sympy" else 0.0, - ], - dtype=torch.float32, - ) - - -def main(): - args = parse_args() - os.environ.setdefault("WANDB_MODE", "offline") - - rows = load_rows(args.dataset_index) - manifest = json.loads(args.manifest.read_text()) - repos = sorted(manifest["repositories"]) - repo_to_id = {repo: idx for idx, repo in enumerate(repos)} - - try: - import wandb - except ImportError as exc: - raise RuntimeError("wandb is required for this training smoke test") from exc - - run = wandb.init( - project=args.wandb_project, - name=args.wandb_run_name, - config={ - "dataset": manifest["dataset"], - "rows": manifest["rows"], - "repositories": manifest["repositories"], - "steps": args.steps, - "batch_size": args.batch_size, - "mode": os.environ.get("WANDB_MODE", "offline"), - }, - ) - - model = nn.Sequential(nn.Linear(4, 32), nn.GELU(), nn.Linear(32, len(repos))) - optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) - data_table = wandb.Table( - columns=["step", "repo_name", "docker_image", "task_text_len", "modified_files"] - ) - - history = [] - for step in range(1, args.steps + 1): - batch_rows = [ - rows[(step * args.batch_size + offset) % len(rows)] - for offset in range(args.batch_size) - ] - features = torch.stack([row_features(row) for row in batch_rows]) - labels = torch.tensor([repo_to_id[row["repo_name"]] for row in batch_rows]) - - logits = model(features) - loss = F.cross_entropy(logits, labels) - optimizer.zero_grad(set_to_none=True) - loss.backward() - optimizer.step() - - accuracy = (logits.argmax(dim=-1) == labels).float().mean().item() - row = batch_rows[0] - task_text = row.get("task_text") or row.get("problem_statement") or row.get("prompt") or "" - modified_files = row.get("modified_files") or [] - if step <= 20 or step % 20 == 0: - data_table.add_data( - step, - row["repo_name"], - row["docker_image"], - len(task_text), - json.dumps(modified_files, ensure_ascii=False), - ) - - record = { - "step": step, - "train/loss": float(loss.item()), - "train/accuracy": accuracy, - "data/repo_id": repo_to_id[row["repo_name"]], - "data/task_text_len": len(task_text), - } - wandb.log(record, step=step) - history.append(record) - - reward_summary = args.reward_result.read_text(encoding="utf-8").strip() - wandb.log( - { - "r2e/reward_validation_passed": 1.0 if "R2E_GYM_TASK_OK" in reward_summary else 0.0, - "r2e/reward_summary": reward_summary, - "r2e/training_samples": data_table, - }, - step=args.steps, - ) - run.finish() - - args.output.parent.mkdir(parents=True, exist_ok=True) - args.output.write_text( - json.dumps( - { - "steps": args.steps, - "final_loss": history[-1]["train/loss"], - "final_accuracy": history[-1]["train/accuracy"], - "reward_summary": reward_summary, - "wandb_dir": os.environ.get("WANDB_DIR", ""), - }, - indent=2, - ) - + "\n", - encoding="utf-8", - ) - print(f"R2E_GYM_200_STEP_TRAIN_OK output={args.output}") - - -if __name__ == "__main__": - main() diff --git a/examples/validate_r2e_core_components.py b/examples/validate_r2e_core_components.py deleted file mode 100644 index a2de7f0..0000000 --- a/examples/validate_r2e_core_components.py +++ /dev/null @@ -1,250 +0,0 @@ -"""Measure R2E-Gym component behavior without allocating model devices. - -This is deliberately a control-plane benchmark: C-MLFQ routing and GRP -planning are CPU-side decisions, while EHP exercises its real join/release -state machine and local gradient aggregation path. It can run before a model -job to establish that the controller layer is healthy. -""" - -from __future__ import annotations - -import json -import os -import statistics -import time -from pathlib import Path - -import torch - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.cost_model.global_resource_planner import GlobalResourcePlanner -from RL_Framework.infra.elastic.hybrid_pool import ( - ElasticHybridPool, - GradientPayload, -) -from RL_Framework.infra.scheduling.cmlfq_offline_profile import CMLFQOfflineProfiler -from RL_Framework.infra.scheduling.cmlfq_scheduler import CMLFQScheduler - - -def _percentile(values: list[float], percentile: float) -> float: - if not values: - return 0.0 - ordered = sorted(values) - index = min(len(ordered) - 1, round((len(ordered) - 1) * percentile)) - return ordered[index] - - -def _measure_cmlfq(requests: int) -> dict: - profiler = CMLFQOfflineProfiler() - raw_history = [ - { - "prompt_id": "r2e-component-benchmark", - "total_output_tokens": 36000, - "tool_returns": [ - { - "tool_type": "code_executor", - "output": "R2E pytest failure with a large repository trace.", - "status": "failure", - "payload_tokens": 6000, - "token_position": 1200, - "remaining_length": 34800, - } - ], - } - ] - profiler.profile_from_raw_trajectories(raw_history) - scheduler = CMLFQScheduler( - buckets={ - "short": {"tp_degrees": [1], "max_tokens": 256}, - "medium": {"tp_degrees": [1], "max_tokens": 768}, - "long": {"tp_degrees": [2], "max_tokens": 1024}, - }, - prefix_tree=profiler.prefix_tree, - ) - scheduler.register_instance(0, "short_tp1_0", 1) - scheduler.register_instance(1, "short_tp1_1", 1) - scheduler.register_instance(2, "long_tp2", 2) - - latencies_ms: list[float] = [] - initial_buckets: dict[str, int] = {"short": 0, "medium": 0, "long": 0} - migrated_buckets: dict[str, int] = {"short": 0, "medium": 0, "long": 0} - migration_latencies_ms: list[float] = [] - migrations = 0 - for index in range(requests): - input_tokens = 1024 - start = time.perf_counter() - route = scheduler.schedule( - input_tokens=input_tokens, - prompt_id="r2e-component-benchmark", - ) - latencies_ms.append((time.perf_counter() - start) * 1000) - initial_buckets[route.category] = initial_buckets.get(route.category, 0) + 1 - tool_start = time.perf_counter() - decision = scheduler.on_tool_return( - route.request_id, - raw_history[0]["tool_returns"][0], - generated_tokens=1200, - ) - if decision.should_migrate: - migrated = scheduler.execute_migration(route.request_id, decision) - migrations += 1 - migrated_buckets[migrated.category] = ( - migrated_buckets.get(migrated.category, 0) + 1 - ) - migration_latencies_ms.append((time.perf_counter() - tool_start) * 1000) - scheduler.finish_request(route.request_id, 36000) - - return { - "requests": requests, - "initial_route_buckets": initial_buckets, - "migrated_route_buckets": migrated_buckets, - "migrations": migrations, - "route_latency_ms_mean": statistics.fmean(latencies_ms), - "route_latency_ms_p95": _percentile(latencies_ms, 0.95), - "migration_latency_ms_mean": statistics.fmean(migration_latencies_ms), - "migration_latency_ms_p95": _percentile(migration_latencies_ms, 0.95), - "throughput_requests_per_s": requests / max(sum(latencies_ms) / 1000, 1e-9), - } - - -def _planner_config() -> AsyncRLConfig: - config = AsyncRLConfig( - model_path="/opt/libra/models/Qwen3-14B", - train_gpus=4, - rollout_gpus=4, - train_tp_size=1, - train_pp_size=1, - train_dp_size=4, - micro_batch_size=1, - batch_size=4, - n_total_gpus=8, - max_seq_length=32768, - max_new_tokens=32768, - ) - planner = config.global_resource_planner - planner.enabled = True - planner.train_backend = "analytic" - planner.rollout_backend = "analytic" - planner.plan_interval = 1 - planner.warmup_steps = 0 - planner.min_history_size = 4 - planner.min_gain_ratio = 0.0 - planner.reconfiguration_cost_s = 0.0 - planner.allowed_train_tp = [1] - planner.allowed_train_pp = [1] - planner.fixed_train_gpus = 0 - planner.allowed_train_tp = [1, 2] - planner.allowed_rollout_tp = [1, 2, 4] - planner.require_heterogeneous_rollout_tp = True - planner.micro_batch_sizes = [1] - return config - - -def _measure_grp() -> dict: - config = _planner_config() - batch = [ - { - "prompt_id": f"r2e-{index}", - "input_len": 1024 + (index % 4) * 256, - "output_len": 16000 + index * 1000, - } - for index in range(16) - ] - planner = GlobalResourcePlanner.from_config(config) - start = time.perf_counter() - decision = planner.plan_if_needed(step=1, config=config, batch=batch) - elapsed_ms = (time.perf_counter() - start) * 1000 - candidate = decision.candidate_plan - if candidate is None: - raise RuntimeError(f"GRP produced no candidate: {decision.reason}") - return { - "requests": decision.num_requests, - "decision_reason": decision.reason, - "should_reconfigure": decision.should_reconfigure, - "planning_latency_ms": elapsed_ms, - "current_global_s": decision.current_plan.t_global if decision.current_plan else None, - "candidate_global_s": candidate.t_global, - "expected_gain_s": candidate.expected_gain_s, - "candidate_train_gpus": candidate.train_config.n_gpus, - "candidate_rollout_tp": candidate.rollout_tp_list, - } - - -def _measure_ehp(iterations: int, tensor_elements: int) -> dict: - pool = ElasticHybridPool( - core_train_workers=["dp0", "dp1"], - core_rollout_workers=["rollout0", "rollout1"], - snapshot_fetcher=lambda _worker, _target: 7, - zero_sync_steps=1, - ) - join_latencies_ms: list[float] = [] - try: - for index in range(iterations): - worker_id = f"rollout{index % 2}" - target = f"dp{index % 2}" - start = time.perf_counter() - worker = pool.join_training(worker_id, target).result(timeout=5) - join_latencies_ms.append((time.perf_counter() - start) * 1000) - if worker.state_version != 7: - raise RuntimeError("EHP snapshot version was not propagated") - pool.release_to_rollout(worker_id) - - core = { - "dp0": (torch.ones(tensor_elements),), - "dp1": (torch.ones(tensor_elements) * 2,), - } - pool.gradient_domain.request_join("rollout0", "dp0") - pool.gradient_domain.mark_active("rollout0") - payload = GradientPayload( - replica_id="rollout0", - target_core_id="dp0", - tensors=(torch.ones(tensor_elements) * 3,), - ) - start = time.perf_counter() - reduced = pool.gradient_domain.reduce_core_gradients( - core_gradients=core, - hybrid_payloads=[payload], - ) - aggregate_ms = (time.perf_counter() - start) * 1000 - expected = 3.0 - observed = float(reduced["dp0"][0][0]) - if abs(observed - expected) > 1e-5: - raise RuntimeError(f"unexpected EHP aggregate: {observed} != {expected}") - bytes_processed = tensor_elements * 4 * 3 - return { - "join_release_iterations": iterations, - "join_latency_ms_mean": statistics.fmean(join_latencies_ms), - "join_latency_ms_p95": _percentile(join_latencies_ms, 0.95), - "gradient_tensor_elements": tensor_elements, - "gradient_aggregate_ms": aggregate_ms, - "gradient_effective_gbps": bytes_processed / max(aggregate_ms, 1e-9) / 1e6, - "gradient_value": observed, - "communication_domains": pool.gradient_domain.communication_state(), - } - finally: - pool.close() - - -def main() -> None: - requests = int(os.environ.get("CORE_BENCH_REQUESTS", "1000")) - iterations = int(os.environ.get("EHP_BENCH_ITERATIONS", "100")) - tensor_elements = int(os.environ.get("EHP_TENSOR_ELEMENTS", "262144")) - report = { - "cmlfq": _measure_cmlfq(requests), - "global_resource_planner": _measure_grp(), - "elastic_hybrid_pool": _measure_ehp(iterations, tensor_elements), - } - output = Path( - os.environ.get( - "CORE_COMPONENT_REPORT", - "logs/r2e_gym_qwen3_14b_npu_full/component_report.json", - ) - ) - output.parent.mkdir(parents=True, exist_ok=True) - output.write_text(json.dumps(report, indent=2), encoding="utf-8") - print(json.dumps(report, indent=2)) - print(f"R2E_CORE_COMPONENTS_OK output={output}") - - -if __name__ == "__main__": - main() diff --git a/examples/validate_r2e_gym_reward.py b/examples/validate_r2e_gym_reward.py deleted file mode 100644 index 1c1b7c6..0000000 --- a/examples/validate_r2e_gym_reward.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Validate R2E-Gym pytest logs against a task's expected output.""" - -import argparse -import json -import re -from pathlib import Path - - -def parse_args(): - parser = argparse.ArgumentParser() - parser.add_argument("--before-log", type=Path, required=True) - parser.add_argument("--after-log", type=Path, required=True) - parser.add_argument("--expected", type=Path, required=True) - return parser.parse_args() - - -def parse_pytest_log(log: str) -> dict[str, str]: - if "short test summary info" not in log: - return {} - - summary = log.split("short test summary info", 1)[1] - statuses = {} - for line in summary.strip().splitlines(): - if "PASSED" in line: - name = ".".join(line.split("::")[1:]) - statuses[name] = "PASSED" - elif "FAILED" in line: - name = ".".join(line.split("::")[1:]).split(" - ")[0] - statuses[name] = "FAILED" - elif "ERROR" in line: - name = ".".join(line.split("::")[1:]).split(" - ")[0] - statuses[name] = "ERROR" - return {re.sub(r"\u001b\[\d+m", "", key): value for key, value in statuses.items()} - - -def normalize(statuses: dict[str, str]) -> dict[str, str]: - return { - key.split(" - ")[0]: statuses[key] - for key in sorted(statuses) - } - - -def main(): - args = parse_args() - before = normalize(parse_pytest_log(args.before_log.read_text(errors="replace"))) - after = normalize(parse_pytest_log(args.after_log.read_text(errors="replace"))) - expected = normalize(json.loads(args.expected.read_text())) - - if before == expected: - raise AssertionError("R2E-Gym task unexpectedly passed before applying the patch") - if after != expected: - missing = sorted(set(expected) - set(after)) - unexpected = sorted(set(after) - set(expected)) - mismatched = sorted( - key for key in set(after) & set(expected) if after[key] != expected[key] - ) - raise AssertionError( - "R2E-Gym reward mismatch after applying the patch: " - f"expected={len(expected)} parsed={len(after)} " - f"missing={missing[:10]} unexpected={unexpected[:10]} " - f"mismatched={mismatched[:10]}" - ) - - print( - "R2E_GYM_TASK_OK " - f"before_matches_expected=false after_matches_expected=true tests={len(expected)}" - ) - - -if __name__ == "__main__": - main() diff --git a/examples/validate_rollout_scheduling.py b/examples/validate_rollout_scheduling.py deleted file mode 100644 index d7268fb..0000000 --- a/examples/validate_rollout_scheduling.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Live HTTP validation; no fake lengths, injected loads or manual draining. - -Deployment (model, instance IDs, TP sizes and endpoints) is supplied at runtime. -The output records both route decisions and real vLLM cache-counter deltas. -This is a correctness smoke, not a throughput benchmark or training run. -""" -import argparse -import asyncio -import copy -import json -from pathlib import Path -from urllib.parse import urlparse - -import httpx -import yaml - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.engine.heterogeneous_engine import HeterogeneousRolloutEngine -from RL_Framework.infra.scheduling.metrics_feed import parse_prometheus_metrics - - -async def validate(args): - raw = yaml.safe_load(Path(args.config).read_text(encoding="utf-8")) - raw["model_path"] = args.model - instances = [] - for endpoint in args.endpoint: - iid, tp, address = endpoint.split(",", 2) - url = urlparse(address) - if url.scheme != "http" or not url.hostname or not url.port: - raise ValueError("endpoint must be instance-id,tp,http://host:port") - instances.append(dict(instance_id=iid, tp=int(tp), host=url.hostname, port=url.port)) - if len(instances) < 2: - raise ValueError("At least two independent vLLM instances are required") - raw["heterogeneous_rollout"]["instances"] = instances - if args.shared_load_dir: - raw["heterogeneous_rollout"]["scheduling"]["shared_load_dir"] = args.shared_load_dir - config = AsyncRLConfig.from_dict(copy.deepcopy(raw)) - engine = HeterogeneousRolloutEngine.from_config(config) - scheduler = engine.scheduler - report = {"deployment": instances, "model": args.model, "phases": []} - tasks = [] - async with httpx.AsyncClient(timeout=30) as client: - async def counters(): - values = {} - for cfg in engine.instance_configs: - url = f"http://{cfg['host']}:{cfg['port']}/metrics" - response = await client.get(url) - response.raise_for_status() - all_values = parse_prometheus_metrics(response.text) - values[cfg["instance_id"]] = { - k: v for k, v in all_values.items() - if k in ("vllm:prefix_cache_hits_total", "vllm:prefix_cache_queries_total") - } - return values - - lengths = {} - async def generate(prompt, pid, budget=32): - if prompt not in lengths: - response = await client.post(engine.engines[0].base_url + "/tokenize", json={ - "model": args.model, "prompt": prompt, "add_special_tokens": False, - }) - response.raise_for_status() - payload = response.json() - lengths[prompt] = payload.get("count", len(payload.get("tokens", []))) - if lengths[prompt] <= 0: - raise AssertionError("/tokenize did not return a positive token count") - result = await engine.generate( - prompt, input_tokens=lengths[prompt], prompt_id=pid, - max_new_tokens=budget, temperature=0.0, - ) - if not result.get("tokens"): - raise AssertionError("Generation returned no token logprobs") - return {"input_tokens": lengths[prompt], "output_tokens": len(result["tokens"]), - "route": result["_schedule_info"]} - - try: - await asyncio.to_thread(engine.wait_for_ready, 180) - snapshots = engine.metrics_snapshots() - report["snapshots"] = {key: vars(value) for key, value in snapshots.items()} - for handle in scheduler._instances: - snap = engine._metrics_poller.get(handle.instance_id) - if snap is None or snap.kv_capacity_tokens <= 0: - raise AssertionError(f"No fresh measured capacity for {handle.instance_id}") - if scheduler.kv_capacity_of(handle) != snap.kv_capacity_tokens: - raise AssertionError("Measured capacity is not used by scheduler") - - prompt = ("Systems share compute and memory. " * 96) + "Summarize this in one sentence." - for enabled in (False, True): - scheduler._prefix_affinity_enabled = enabled - scheduler._affinity.clear() - before = await counters() - rows = [await generate(prompt, "repeated-prompt") for _ in range(4)] - after = await counters() - if enabled: - targets = {row["route"]["instance_id"] for row in rows} - if len(targets) != 1 or any( - row["route"]["reason"] != "prefix_affinity" for row in rows[1:] - ): - raise AssertionError("Repeated prompt did not follow affinity") - report["phases"].append({"affinity": enabled, "requests": rows, - "cache_before": before, "cache_after": after}) - - tasks = [asyncio.create_task(generate( - ("Read this. " * (30 + 100 * i)) + "Summarize briefly.", f"mixed-{i}", 64 - )) for i in range(4)] - report["mixed_requests"] = await asyncio.gather(*tasks) - for handle in scheduler._instances: - if handle.active_requests != 0 or handle.active_tokens != 0: - raise AssertionError(f"Leaked accounting: {handle}") - old_state = engine._shared_state - engine.reconfigure_from_plan(None, config) - if old_state is not None and engine._shared_state is not old_state: - raise AssertionError("Shared owner was not reused after a drained reconfigure") - report["after_reconfigure"] = await generate("Say hello.", "post-reconfigure", 8) - report["passed"] = True - finally: - for task in tasks: - if not task.done(): - task.cancel() - if tasks: - await asyncio.gather(*tasks, return_exceptions=True) - await engine.close() - if args.output: - output = Path(args.output) - output.parent.mkdir(parents=True, exist_ok=True) - output.write_text(json.dumps(report, indent=2), encoding="utf-8") - print(json.dumps(report, indent=2)) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--config", default="configs/scheduling_adaptive.yaml") - parser.add_argument("--model", required=True) - parser.add_argument("--endpoint", action="append", required=True) - parser.add_argument("--shared-load-dir", default="") - parser.add_argument("--output") - asyncio.run(validate(parser.parse_args())) diff --git a/examples/verify_code_agent.py b/examples/verify_code_agent.py deleted file mode 100644 index e6e0dda..0000000 --- a/examples/verify_code_agent.py +++ /dev/null @@ -1,110 +0,0 @@ -"""Support code for Verify code agent.""" - -from __future__ import annotations - -import ast -import asyncio -import sys -from pathlib import Path - -_PROJECT_ROOT = Path(__file__).parent.parent -sys.path.insert(0, str(_PROJECT_ROOT)) - - -def check_syntax(filepath: str) -> bool: - with open(filepath) as f: - source = f.read() - try: - ast.parse(source) - return True - except SyntaxError as e: - print(f" SyntaxError: {e}") - return False - - -def main(): - print("=" * 60) - print("CodeAgent module verification") - print("=" * 60) - - # ---- 1. Syntax check all new files ---- - print("\n[1/7] Syntax check...") - files = [ - "env/code_executor.py", - "env/code_agent_prompt.py", - "env/code_reward.py", - "workflow/code_agent.py", - "data/preprocess_livecodebench.py", - "examples/livecodebench_code_agent.py", - ] - all_ok = True - for f in files: - ok = check_syntax(_PROJECT_ROOT / f) - status = "OK" if ok else "FAIL" - print(f" [{status}] {f}") - all_ok = all_ok and ok - if not all_ok: - sys.exit(1) - - # ---- 2. Import check ---- - print("\n[2/7] Module imports...") - from env.code_executor import CodeExecutor - from env.code_agent_prompt import format_execution_result, format_problem - from env.code_reward import extract_code_block - print(" OK: All core modules imported") - - # ---- 3. Code block extraction ---- - print("\n[3/7] Code block extraction...") - assert extract_code_block("```python\nprint(1)\n```") == "print(1)" - assert extract_code_block("no code") is None - assert extract_code_block("```\ncode\n```") == "code" - print(" OK") - - # ---- 4. Local sandbox (stdin mode) ---- - print("\n[4/7] Local sandbox (stdin mode)...") - executor = CodeExecutor(mode="local", timeout=5) - code = "import sys\nn = int(sys.stdin.readline())\nprint(n * 2)" - test_cases = {"inputs": ["5\n"], "outputs": ["10"]} - loop = asyncio.get_event_loop() - pass_rate, metadata = loop.run_until_complete(executor.execute(code, test_cases)) - assert pass_rate == 1.0, f"Expected 1.0, got {pass_rate}" - print(f" OK: pass_rate={pass_rate}") - - # ---- 5. Local sandbox (call-based) ---- - print("\n[5/7] Local sandbox (call-based)...") - code2 = "\nclass Solution:\n def add(self, a, b):\n return a + b\n" - test_cases2 = {"fn_name": "add", "inputs": ["1\n2"], "outputs": ["3"]} - pass_rate2, _ = loop.run_until_complete(executor.execute(code2, test_cases2)) - assert pass_rate2 == 1.0, f"Expected 1.0, got {pass_rate2}" - print(f" OK: pass_rate={pass_rate2}") - - # ---- 6. Local sandbox (wrong answer) ---- - print("\n[6/7] Local sandbox (wrong answer)...") - code3 = "import sys\nn = int(sys.stdin.readline())\nprint(n * 3)" - pass_rate3, _ = loop.run_until_complete(executor.execute(code3, test_cases)) - assert pass_rate3 == 0.0, f"Expected 0.0, got {pass_rate3}" - print(f" OK: pass_rate={pass_rate3} (expected failure)") - - # ---- 7. Prompt formatting ---- - print("\n[7/7] Prompt formatting...") - result = format_execution_result( - 2, 3, - [ - {"status": "success"}, - {"status": "wrong_answer", "input": "1", "expected_output": "2", "stdout": "3"}, - {"status": "success"}, - ] - ) - assert "2/3" in result - problem = format_problem("Read N and print N*2", "def solve():\n pass") - assert "Read N" in problem - assert "Starter Code" in problem - print(" OK") - - print("\n" + "=" * 60) - print("All checks passed.") - print("=" * 60) - - -if __name__ == "__main__": - main() diff --git a/infra/cost_model/global_resource_planner.py b/infra/cost_model/global_resource_planner.py index ea46667..5409fcf 100644 --- a/infra/cost_model/global_resource_planner.py +++ b/infra/cost_model/global_resource_planner.py @@ -578,50 +578,26 @@ def from_config(cls, config: AsyncRLConfig) -> "GlobalResourcePlanner": allowed_rollout_tp=planner_cfg.allowed_rollout_tp, require_heterogeneous_rollout_tp=planner_cfg.require_heterogeneous_rollout_tp, allowed_train_tp=planner_cfg.allowed_train_tp or None, - allowed_train_ep=getattr(planner_cfg, "allowed_train_ep", []) or None, + allowed_train_ep=planner_cfg.allowed_train_ep or None, allowed_train_pp=planner_cfg.allowed_train_pp or None, - train_comm_compute_ratio_threshold=getattr( - planner_cfg, "train_comm_compute_ratio_threshold", float("inf") - ), - train_ep_comm_compute_ratio_threshold=getattr( - planner_cfg, "train_ep_comm_compute_ratio_threshold", float("inf") - ), - train_pipeline_bubble_ratio_threshold=getattr( - planner_cfg, "train_pipeline_bubble_ratio_threshold", 0.30 - ), + train_comm_compute_ratio_threshold=planner_cfg.train_comm_compute_ratio_threshold, + train_ep_comm_compute_ratio_threshold=planner_cfg.train_ep_comm_compute_ratio_threshold, + train_pipeline_bubble_ratio_threshold=planner_cfg.train_pipeline_bubble_ratio_threshold, fixed_train_gpus=planner_cfg.fixed_train_gpus, - initial_allocation_strategy=getattr( - planner_cfg, "initial_allocation_strategy", "grp" - ), - allocation_granularity_gpus=getattr( - planner_cfg, "allocation_granularity_gpus", 1 - ), - min_train_gpus=getattr(planner_cfg, "min_train_gpus", 1), - min_rollout_gpus=getattr(planner_cfg, "min_rollout_gpus", 1), + initial_allocation_strategy=planner_cfg.initial_allocation_strategy, + allocation_granularity_gpus=planner_cfg.allocation_granularity_gpus, + min_train_gpus=planner_cfg.min_train_gpus, + min_rollout_gpus=planner_cfg.min_rollout_gpus, micro_batch_sizes=planner_cfg.micro_batch_sizes or None, max_history_size=planner_cfg.max_history_size, - online_replanning=getattr(planner_cfg, "runtime_online_replanning", True), - replan_cooldown_steps=getattr( - planner_cfg, "runtime_replan_cooldown_steps", 1 - ), - queue_pressure_threshold=getattr( - planner_cfg, "runtime_queue_pressure_threshold", 0.75 - ), - active_rollout_pressure_threshold=getattr( - planner_cfg, "runtime_active_rollout_pressure_threshold", 0.85 - ), - rejected_rollout_delta_threshold=getattr( - planner_cfg, "runtime_rejected_rollout_delta_threshold", 8 - ), - rollout_train_imbalance_threshold=getattr( - planner_cfg, "runtime_rollout_train_imbalance_threshold", 1.25 - ), - elastic_hybrid_planning_enabled=getattr( - planner_cfg, "elastic_hybrid_planning_enabled", False - ), - elastic_hybrid_signal_ttl_steps=getattr( - planner_cfg, "elastic_hybrid_signal_ttl_steps", 20 - ), + online_replanning=planner_cfg.runtime_online_replanning, + replan_cooldown_steps=planner_cfg.runtime_replan_cooldown_steps, + queue_pressure_threshold=planner_cfg.runtime_queue_pressure_threshold, + active_rollout_pressure_threshold=planner_cfg.runtime_active_rollout_pressure_threshold, + rejected_rollout_delta_threshold=planner_cfg.runtime_rejected_rollout_delta_threshold, + rollout_train_imbalance_threshold=planner_cfg.runtime_rollout_train_imbalance_threshold, + elastic_hybrid_planning_enabled=planner_cfg.elastic_hybrid_planning_enabled, + elastic_hybrid_signal_ttl_steps=planner_cfg.elastic_hybrid_signal_ttl_steps, verbose=planner_cfg.verbose, ) @@ -890,7 +866,7 @@ def plan_if_needed( rollout_gpus=( sum(forced_rollout_tp) if forced_rollout_tp is not None - else int(getattr(config, "rollout_gpus", 0) or 0) + else int(config.rollout_gpus or 0) ), ) forced_candidate = forced_rollout_tp is not None or forced_train is not None @@ -911,11 +887,10 @@ def plan_if_needed( min_train_gpus=self.min_train_gpus, min_rollout_gpus=self.min_rollout_gpus, rollout_node_tp_pattern=list( - getattr(config.global_resource_planner, "rollout_node_tp_pattern", []) - or [] + config.global_resource_planner.rollout_node_tp_pattern or [] ), - train_cp_size=max(1, int(getattr(config, "train_cp_size", 1) or 1)), - dp_batch_group_size=max(1, int(getattr(config, "n_samples", 1) or 1)), + train_cp_size=max(1, int(config.train_cp_size or 1)), + dp_batch_group_size=max(1, int(config.n_samples or 1)), training_sequence_lengths=self._training_workload_lengths(workload, config.batch_size), rollout_calls_per_trace=self._rollout_calls_per_trace(config), ) @@ -1008,10 +983,9 @@ def plan_if_needed( fixed_train_gpus=capabilities.world_size, allocation_granularity_gpus=self.allocation_granularity_gpus, min_train_gpus=self.min_train_gpus, min_rollout_gpus=self.min_rollout_gpus, - rollout_node_tp_pattern=list(getattr(config.global_resource_planner, - "rollout_node_tp_pattern", []) or []), + rollout_node_tp_pattern=list(config.global_resource_planner.rollout_node_tp_pattern or []), train_cp_size=capabilities.cp, - dp_batch_group_size=max(1, int(getattr(config, "n_samples", 1) or 1)), + dp_batch_group_size=max(1, int(config.n_samples or 1)), training_sequence_lengths=self._training_workload_lengths(workload, config.batch_size), rollout_calls_per_trace=self._rollout_calls_per_trace(config)) candidate = self._plan_from_result(feasible, config) or current @@ -1317,14 +1291,7 @@ def _forced_rollout_tp_list(self, config: AsyncRLConfig) -> list[int] | None: else: tp_list = [ int(value) - for value in ( - getattr( - config.global_resource_planner, - "runtime_forced_rollout_tp_list", - [], - ) - or [] - ) + for value in (config.global_resource_planner.runtime_forced_rollout_tp_list or []) ] if not tp_list: return None @@ -1332,14 +1299,9 @@ def _forced_rollout_tp_list(self, config: AsyncRLConfig) -> list[int] | None: raise ValueError(f"GRP_FORCE_ROLLOUT_TP_LIST must be positive: {tp_list}") forced_train_raw = os.environ.get("GRP_FORCE_TRAIN_GPUS", "").strip() configured_forced_train = int( - getattr( - config.global_resource_planner, - "runtime_forced_train_gpus", - 0, - ) - or 0 + config.global_resource_planner.runtime_forced_train_gpus or 0 ) - rollout_gpus = int(getattr(config, "rollout_gpus", 0) or sum(tp_list)) + rollout_gpus = int(config.rollout_gpus or sum(tp_list)) if forced_train_raw: try: forced_train_gpus = int(forced_train_raw) @@ -1371,14 +1333,7 @@ def _forced_train_config( except ValueError as exc: raise ValueError(f"Invalid GRP_FORCE_TRAIN_GPUS={raw!r}") from exc else: - train_gpus = int( - getattr( - config.global_resource_planner, - "runtime_forced_train_gpus", - 0, - ) - or 0 - ) + train_gpus = int(config.global_resource_planner.runtime_forced_train_gpus or 0) if train_gpus == 0: return None if train_gpus <= 0: @@ -1391,7 +1346,7 @@ def _forced_train_config( tp = int(current.train_config.tp) ep = int(current.train_config.ep) pp = int(current.train_config.pp) - cp = max(1, int(getattr(config, "train_cp_size", 1) or 1)) + cp = max(1, int(config.train_cp_size or 1)) model_parallel = max(1, tp * ep * pp * cp) if train_gpus % model_parallel != 0: raise ValueError( @@ -1656,15 +1611,12 @@ def _build_current_plan( *, costs: _MemberPlanningCosts | None = None, ) -> GlobalResourcePlan: requests = representative_global_batch(requests, int(config.batch_size)) + ep = max(1, int(config.train_ep_size or 1)) train = TrainParallelConfig( tp=config.train_tp_size, - ep=max(1, int(getattr(config, "train_ep_size", 1) or 1)), + ep=ep, pp=config.train_pp_size, - dp=max( - 1, - int(config.train_dp_size) - // max(1, int(getattr(config, "train_ep_size", 1) or 1)), - ), + dp=max(1, int(config.train_dp_size) // ep), cp=config.train_cp_size, b_micro=config.micro_batch_size, ) diff --git a/infra/cost_model/simulator_adapters.py b/infra/cost_model/simulator_adapters.py index 1d78faf..8605e10 100644 --- a/infra/cost_model/simulator_adapters.py +++ b/infra/cost_model/simulator_adapters.py @@ -437,19 +437,17 @@ def __init__(self, config: Any): max_seq_length=config.max_seq_length, recompute_logprobs=( bool(config.recompute_logprobs) - and bool(getattr(self.planner_config, "memory_budget_check_enabled", True)) - ), - recompute_micro_batch_size=int( - getattr(config, "recompute_micro_batch_size", 1) + and bool(self.planner_config.memory_budget_check_enabled) ), + recompute_micro_batch_size=int(config.recompute_micro_batch_size), recompute_logits_dtype_bytes=int( - getattr(self.planner_config, "memory_budget_logits_dtype_bytes", 4) + self.planner_config.memory_budget_logits_dtype_bytes ), recompute_workspace_factor=float( - getattr(self.planner_config, "memory_budget_workspace_factor", 1.5) + self.planner_config.memory_budget_workspace_factor ), memory_safety_margin_bytes=float( - getattr(self.planner_config, "memory_budget_safety_margin_bytes", 0.0) + self.planner_config.memory_budget_safety_margin_bytes ), ) self.train_backend = (self.planner_config.train_backend or "analytic").lower() diff --git a/infra/elastic/rollout_lending.py b/infra/elastic/rollout_lending.py index c86577f..25cd296 100644 --- a/infra/elastic/rollout_lending.py +++ b/infra/elastic/rollout_lending.py @@ -69,8 +69,7 @@ def _choose_engines(executor, required, instance_ids=None): live = {name: meta for name, meta in executor._process_meta.items() if name not in old_ids} instances = [*existing, *live.values()] width = executor._elastic_replica_size_gpus() - reserve = max(0, int(getattr(executor.config.global_resource_planner, - "elastic_hybrid_min_rollout_gpus", 0) or 0)) + reserve = max(0, int(executor.config.global_resource_planner.elastic_hybrid_min_rollout_gpus or 0)) old_capacity = loan_replica_capacity(existing, existing, width, 0) def fits(added): @@ -123,7 +122,7 @@ def _restart_engines(executor, saved): def _rollback_expansion(executor): - pending = getattr(executor, "_rollout_loan_rollback", None) + pending = executor._rollout_loan_rollback if pending is None: return # A failed stop may have signalled a process without proving its exit. @@ -197,7 +196,7 @@ def lend_rollout(executor, required_gpu_count, *, instance_ids=None): if handle.instance_id in selected_ids}} executor._rollout_loan_rollback = pending dispatcher = getattr(executor, "dispatcher", None) - timeout = float(getattr(executor.config.global_resource_planner, "runtime_drain_timeout_s", 3600.)) + timeout = float(executor.config.global_resource_planner.runtime_drain_timeout_s) local = supports_local_lending(executor) and len(selected) < len(executor._process_meta) paused_here = False try: @@ -255,7 +254,7 @@ def lend_rollout(executor, required_gpu_count, *, instance_ids=None): def wait_hybrid_stopped(executor, worker_id, request_id=None): """Await the controller's proof that the recorded remote process exited.""" directory = Path(executor._hybrid_worker_control_dir()) - timeout = float(getattr(executor.config.global_resource_planner, "hybrid_worker_stop_timeout_s", 60.)) + timeout = float(executor.config.global_resource_planner.hybrid_worker_stop_timeout_s) deadline = time.monotonic() + timeout if timeout > 0 else float("inf") while True: done = directory / f".stop_{worker_id}.done" @@ -281,11 +280,11 @@ def return_rollout(executor): revision to the new service generation and explicitly reopens admission. """ _rollback_expansion(executor) - saved = getattr(executor, "_lent_rollout", None) + saved = executor._lent_rollout if not saved: return [] physical = {(meta.host, int(gpu)) for meta in saved["engines"] for gpu in meta.gpus} - for worker_id, meta in list(getattr(executor, "_hybrid_worker_meta", {}).items()): + for worker_id, meta in list(executor._hybrid_worker_meta.items()): if not any((meta.host, int(gpu)) in physical for gpu in meta.gpus): continue # The executor retains ownership until a matching remote exit ACK (or diff --git a/infra/elastic/rollout_lifecycle.py b/infra/elastic/rollout_lifecycle.py index adb81b7..483abf4 100644 --- a/infra/elastic/rollout_lifecycle.py +++ b/infra/elastic/rollout_lifecycle.py @@ -9,7 +9,7 @@ def _broadcast(trainer, value): packet = [value] if dist.is_available() and dist.is_initialized(): - dist.broadcast_object_list(packet, src=0, group=getattr(trainer, "control", None)) + dist.broadcast_object_list(packet, src=0, group=trainer.control) if packet[0].get("error"): raise RuntimeError(packet[0]["error"]) return packet[0] @@ -74,9 +74,11 @@ def restore_for_publication(trainer): def reopen_after_publication(trainer): + # A subset rollback has a separate owner: its publication must neither + # withdraw an existing loan nor open routing before rank consensus. if getattr(trainer, "_publication_target_ids", None) is not None: return - if not getattr(trainer, "_restored_rollouts_pending_publication", None): + if not trainer._restored_rollouts_pending_publication: return pending = trainer._restored_rollouts_pending_publication apply_availability(trainer, set(getattr(trainer, "_rollout_unavailable_ids", ())) - pending) @@ -95,19 +97,19 @@ def publish_with_consensus(trainer, revision, **sync_options): errors = [error] if dist.is_available() and dist.is_initialized(): errors = [None] * dist.get_world_size() - dist.all_gather_object(errors, error, group=getattr(trainer, "control", None)) + dist.all_gather_object(errors, error, group=trainer.control) if any(errors): raise RuntimeError(f"Rollout publication failed across core ranks: {errors}") def ensure_batch_supply(trainer): """Restore the generating pool before waiting for an impossible next batch.""" - cfg = getattr(trainer.config, "global_resource_planner", None) - if not (getattr(cfg, "enabled", False) - and getattr(cfg, "runtime_reconfigure_training", False) - and getattr(cfg, "hybrid_worker_launch_enabled", False) - and not getattr(cfg, "runtime_training_pool_plan_only", True) - and int(getattr(cfg, "elastic_hybrid_min_rollout_gpus", 0) or 0) <= 0): + cfg = trainer.config.global_resource_planner + if not (cfg.enabled + and cfg.runtime_reconfigure_training + and cfg.hybrid_worker_launch_enabled + and not cfg.runtime_training_pool_plan_only + and int(cfg.elastic_hybrid_min_rollout_gpus or 0) <= 0): return outcome = None if trainer.is_main_process: @@ -125,7 +127,7 @@ def ensure_batch_supply(trainer): records = [sufficient] if dist.is_available() and dist.is_initialized(): records = [None] * dist.get_world_size() - dist.all_gather_object(records, sufficient, group=getattr(trainer, "control", None)) + dist.all_gather_object(records, sufficient, group=trainer.control) if all(records): return diff --git a/infra/elastic/runtime_executor.py b/infra/elastic/runtime_executor.py index 6d0dffa..750f224 100644 --- a/infra/elastic/runtime_executor.py +++ b/infra/elastic/runtime_executor.py @@ -10,6 +10,7 @@ import sys import threading import time +import urllib.error import urllib.request import uuid from contextlib import contextmanager, nullcontext @@ -185,6 +186,15 @@ def __init__( self._hybrid_join_contexts: dict[str, dict[str, Any]] = {} self._hybrid_task_contexts: dict[tuple[str, str, int], Path] = {} self._leased_rollout_processes: dict[str, ManagedRolloutProcess] = {} + self.trainer = None + self._lent_rollout: dict[str, Any] | None = None + self._rollout_loan_rollback: dict[str, Any] | None = None + self._rollout_lending_resume_pending = False + self._rollout_engine_reconfigured = False + self._cluster_swap_training_slots: dict[str, Any] = {} + self._active_runtime_coord_id: str = "" + self._prewarmed_rollout_to_stop: list[ManagedRolloutProcess] = [] + self._blue_green_old_processes: list[ManagedRolloutProcess] = [] def _hybrid_context(self, replica_id: str) -> dict[str, Any]: context = dict(getattr(self, "_hybrid_join_contexts", {}).get(replica_id, {})) @@ -302,28 +312,20 @@ def prepare_transaction(self, decision: PlannerDecision) -> PreparedRuntimeTrans resource_reconfiguration = False reason = "pending_hybrid_boundary_work" rollout_runtime_enabled = bool( - getattr(planner_cfg, "apply_to_runtime", True) - or getattr(planner_cfg, "runtime_manage_rollout_processes", False) - ) - strategy = getattr( - planner_cfg, - "runtime_rollout_reconfigure_strategy", - "diff", + planner_cfg.apply_to_runtime + or planner_cfg.runtime_manage_rollout_processes ) + strategy = planner_cfg.runtime_rollout_reconfigure_strategy cluster_swap_enabled = self._cluster_swap_enabled(strategy) drain_before_reconfigure = bool( resource_reconfiguration - and getattr(planner_cfg, "runtime_drain_before_reconfigure", True) + and planner_cfg.runtime_drain_before_reconfigure ) should_pause_dispatcher = resource_reconfiguration and not ( cluster_swap_enabled and not drain_before_reconfigure ) - if should_execute and not getattr( - planner_cfg, - "runtime_dynamic_reconfiguration_enabled", - True, - ): + if should_execute and not planner_cfg.runtime_dynamic_reconfiguration_enabled: should_execute = False reason = "runtime_dynamic_reconfiguration_disabled" @@ -340,7 +342,7 @@ def prepare_transaction(self, decision: PlannerDecision) -> PreparedRuntimeTrans should_execute and resource_reconfiguration and plan is not None - and getattr(planner_cfg, "runtime_manage_rollout_processes", False) + and planner_cfg.runtime_manage_rollout_processes ): # Metadata adoption is part of the eligibility snapshot. It does not # launch, stop, wait for, or reconfigure any worker. @@ -451,7 +453,7 @@ def _execute_prepared( planner_cfg = self.config.global_resource_planner if not prepared.resource_reconfiguration: return self._execute_membership_only(prepared) - if getattr(self, "_lent_rollout", None): + if self._lent_rollout: self._release_all_hybrid_workers(reason="resource_repartition", result=result) from RL_Framework.infra.elastic.rollout_lending import return_rollout result.started_processes.extend(return_rollout(self)) @@ -470,7 +472,7 @@ def _execute_prepared( and self._peer_drain_completed_coord_id == prepared.coord_id ) if ( - getattr(planner_cfg, "runtime_manage_rollout_processes", False) + planner_cfg.runtime_manage_rollout_processes and strategy == "prewarm" and not cluster_swap_enabled ): @@ -480,11 +482,7 @@ def _execute_prepared( result.actions.append("apply_config") capacity_issue = self._prewarm_capacity_issue(plan) if capacity_issue: - fallback_strategy = getattr( - planner_cfg, - "runtime_prewarm_no_spare_fallback_strategy", - "restart_all", - ) + fallback_strategy = planner_cfg.runtime_prewarm_no_spare_fallback_strategy result.actions.append( f"prewarm_unavailable:{capacity_issue}:fallback_{fallback_strategy}" ) @@ -498,7 +496,7 @@ def _execute_prepared( if ( cluster_swap_enabled - and getattr(planner_cfg, "runtime_manage_rollout_processes", False) + and planner_cfg.runtime_manage_rollout_processes and not config_applied ): self._adopt_existing_rollout_processes() @@ -511,18 +509,14 @@ def _execute_prepared( cluster_swap_enabled and config_applied and not coordinated_peers - and getattr( - planner_cfg, - "runtime_coordinate_reconfiguration_ranks", - True, - ) + and planner_cfg.runtime_coordinate_reconfiguration_ranks ): self._coordinate_peer_rank_drain(plan, result) coordinated_peers = True if ( - getattr(planner_cfg, "runtime_reconfigure_training", False) - and not getattr(planner_cfg, "runtime_training_pool_plan_only", True) + planner_cfg.runtime_reconfigure_training + and not planner_cfg.runtime_training_pool_plan_only and self._hybrid_training_prewarm_enabled and not cluster_swap_enabled ): @@ -549,7 +543,7 @@ def _execute_prepared( result.actions.append("dispatcher_pause") if ( not coordinated_peers - and getattr(planner_cfg, "runtime_manage_rollout_processes", False) + and planner_cfg.runtime_manage_rollout_processes and config_applied ): self._coordinate_peer_rank_drain(plan, result) @@ -557,9 +551,7 @@ def _execute_prepared( if drain_before_reconfigure: if hasattr(self.dispatcher, "wait_until_idle"): self.dispatcher.wait_until_idle( - timeout=float( - getattr(planner_cfg, "runtime_drain_timeout_s", 3600.0) - ) + timeout=float(planner_cfg.runtime_drain_timeout_s) ) result.actions.append("dispatcher_drain") if ( @@ -568,14 +560,12 @@ def _execute_prepared( and hasattr(self.rollout_engine, "wait_until_idle") ): self.rollout_engine.wait_until_idle( - timeout=float( - getattr(planner_cfg, "runtime_drain_timeout_s", 3600.0) - ) + timeout=float(planner_cfg.runtime_drain_timeout_s) ) result.actions.append("rollout_engine_drain") try: - if getattr(planner_cfg, "runtime_manage_rollout_processes", False): + if planner_cfg.runtime_manage_rollout_processes: self._adopt_existing_rollout_processes() cluster_swap_applied = False @@ -583,7 +573,7 @@ def _execute_prepared( print( "[RuntimeElasticExecutor] cluster_swap_execute_begin " f"current_train_gpus={current_train_gpus} " - f"target_train_gpus={int(getattr(planner_cfg, 'runtime_training_pool_target_gpus', 0) or int(plan.train_gpus))} " + f"target_train_gpus={int(planner_cfg.runtime_training_pool_target_gpus or int(plan.train_gpus))} " f"rollout_tp={plan.rollout_tp_list}", flush=True, ) @@ -610,10 +600,10 @@ def _execute_prepared( if ( not cluster_swap_applied - and getattr(planner_cfg, "runtime_reconfigure_training", False) + and planner_cfg.runtime_reconfigure_training and not self._hybrid_worker_launch_enabled ): - if getattr(planner_cfg, "runtime_training_pool_plan_only", True): + if planner_cfg.runtime_training_pool_plan_only: result.training_actions.extend( self._plan_training_pool_reconfiguration( current_train_gpus, @@ -646,8 +636,7 @@ def _execute_prepared( self._coordinate_peer_rank_drain(plan, result) rollout_reconfigured = bool( - cluster_swap_applied - and getattr(self, "_rollout_engine_reconfigured", False) + cluster_swap_applied and self._rollout_engine_reconfigured ) if prewarmed_rollout: stopped, started = self._finish_prewarmed_rollout_cutover(plan) @@ -657,15 +646,13 @@ def _execute_prepared( result.actions.append("reconfigure_rollout_processes:prewarm") elif ( not cluster_swap_applied - and getattr(planner_cfg, "runtime_manage_rollout_processes", False) + and planner_cfg.runtime_manage_rollout_processes ): stopped, started = self._reconfigure_rollout_processes( plan, strategy_override=strategy, ) - rollout_reconfigured = bool( - getattr(self, "_rollout_engine_reconfigured", False) - ) + rollout_reconfigured = bool(self._rollout_engine_reconfigured) result.stopped_processes.extend(stopped) result.started_processes.extend(started) result.actions.append(f"reconfigure_rollout_processes:{strategy}") @@ -673,24 +660,25 @@ def _execute_prepared( if ( not rollout_reconfigured and not cluster_swap_applied - and getattr(planner_cfg, "apply_to_runtime", True) + and planner_cfg.apply_to_runtime and self.rollout_engine is not None and hasattr(self.rollout_engine, "reconfigure_from_plan") ): - self._reconfigure_rollout_engine(plan, wait_ready=bool( - getattr(planner_cfg, "runtime_manage_rollout_processes", False) - )) + self._reconfigure_rollout_engine( + plan, + wait_ready=bool(planner_cfg.runtime_manage_rollout_processes), + ) result.actions.append("reconfigure_rollout_engine") - if getattr(planner_cfg, "runtime_manage_rollout_processes", False): + if planner_cfg.runtime_manage_rollout_processes: result.actions.append("wait_rollout_ready") - if getattr(self, "trainer", None) is not None and rollout_runtime_enabled: + if self.trainer is not None and rollout_runtime_enabled: # Recreated services start from the HF checkpoint. Publish the # current optimizer state before any client can route work. self._publish_current_rollout_weights() if (not cluster_swap_applied and self._hybrid_worker_launch_enabled - and getattr(planner_cfg, "runtime_reconfigure_training", False) - and not getattr(planner_cfg, "runtime_training_pool_plan_only", True)): + and planner_cfg.runtime_reconfigure_training + and not planner_cfg.runtime_training_pool_plan_only): from RL_Framework.infra.elastic.rollout_lending import lend_rollout from RL_Framework.infra.elastic.rollout_lifecycle import apply_availability, unavailable_rollouts self._ensure_elastic_pool() @@ -698,7 +686,7 @@ def _execute_prepared( if desired: self._cluster_swap_training_slots = lend_rollout(self, desired) result.training_actions.extend(self._reconfigure_training_pool(int(self.config.train_gpus), plan, result)) - if getattr(self, "trainer", None) is not None: + if self.trainer is not None: apply_availability(self.trainer, unavailable_rollouts(self)) self._release_unused_core_snapshots_at_boundary() self._write_rollout_manifest(plan, phase="applied") @@ -711,7 +699,7 @@ def _execute_prepared( raise finally: if paused and result.applied and self.dispatcher is not None and hasattr(self.dispatcher, "resume"): - if getattr(self, "trainer", None) is not None: + if self.trainer is not None: self.trainer._resume_rollout_pipeline() else: self.dispatcher.resume() @@ -732,7 +720,7 @@ def _capture_core_snapshot(self) -> str: index = (int(lane.get("tensor_parallel_rank", 0)) + int(lane.get("context_parallel_rank", 0)) * int(self.config.train_tp_size) + int(lane.get("pipeline_parallel_rank", 0)) * int(self.config.train_tp_size) - * int(getattr(self.config, "train_cp_size", 1))) + * int(self.config.train_cp_size)) lanes.setdefault(core_id, {})[str(index)] = receipt["snapshot_uri"] width = self._elastic_replica_size_gpus() if (set(lanes) != {f"dp{i}" for i in range(int(self.config.train_dp_size))} @@ -741,7 +729,7 @@ def _capture_core_snapshot(self) -> str: # DistributedOptimizer gathers each TP lane's complete Adam/master # state on its DP-zero rank. DP followers have identical parameters but # no complete optimizer payload; every joining replica reads DP zero. - if int(getattr(self.config, "train_ep_size", 1)) == 1: + if int(self.config.train_ep_size) == 1: lanes = {core: dict(lanes["dp0"]) for core in lanes} manifest = { "format": "libra-ehp-lanes-v1", "optimizer_revision": revision, @@ -851,7 +839,7 @@ def _finish_pending_activations(self) -> None: request["event"].set() handle = self._pending_hybrid_joins.get(replica_id) if handle is not None: - timeout = float(getattr(self.config.global_resource_planner, "elastic_hybrid_join_timeout_s", 180)) + timeout = float(self.config.global_resource_planner.elastic_hybrid_join_timeout_s) handle.result(timeout=timeout if timeout > 0 else None) self._reconcile_pending_hybrid_joins() except Exception as exc: @@ -871,8 +859,8 @@ def _execute_membership_only(self, prepared): ) plan, result = prepared.candidate_plan, prepared.result cfg = self.config.global_resource_planner - if getattr(cfg, "runtime_reconfigure_training", False): - if getattr(cfg, "runtime_training_pool_plan_only", True): + if cfg.runtime_reconfigure_training: + if cfg.runtime_training_pool_plan_only: result.training_actions.extend(self._plan_training_pool_reconfiguration(prepared.current_train_gpus, plan)) else: self._ensure_elastic_pool() @@ -892,7 +880,7 @@ def _execute_membership_only(self, prepared): if not set(target_ids).issubset(owners): raise ValueError("rollout loan targets must have current physical owners") targets = [owners[identity] for identity in target_ids] - reserve = max(0, int(getattr(cfg, "elastic_hybrid_min_rollout_gpus", 0) or 0)) + reserve = max(0, int(cfg.elastic_hybrid_min_rollout_gpus or 0)) if loan_replica_capacity(instances, targets, width, reserve) * width < desired: raise ValueError("rollout replacement cannot supply the requested complete replicas and reserve") self._release_all_hybrid_workers(reason="physical_loan_change", result=result) @@ -1080,8 +1068,7 @@ def activate_replica( _replica_id, state_version=state_version, replica_world_size=len(_members), snapshot_path=snapshot_path, target_core_id=target_core_id, - timeout_s=float(getattr(self.config.global_resource_planner, - "elastic_hybrid_join_timeout_s", 180.0)), + timeout_s=float(self.config.global_resource_planner.elastic_hybrid_join_timeout_s), ) return self._queue_activation(_replica_id, receipt) @@ -1093,13 +1080,7 @@ def activate_replica( replica_activation_barrier=( activate_replica if self._hybrid_worker_launch_enabled else None ), - timeout_s=float( - getattr( - self.config.global_resource_planner, - "elastic_hybrid_join_timeout_s", - 180.0, - ) - ), + timeout_s=float(self.config.global_resource_planner.elastic_hybrid_join_timeout_s), ) with self._pending_hybrid_join_lock: self._pending_hybrid_joins[replica_id] = handle @@ -1204,9 +1185,7 @@ def _desired_hybrid_workers( return min(desired, self._elastic_replica_capacity()) * replica_size if getattr(cfg, "elastic_hybrid_require_planner_signal", False): return 0 - target_train_gpus = int( - getattr(cfg, "runtime_training_pool_target_gpus", 0) or 0 - ) + target_train_gpus = int(cfg.runtime_training_pool_target_gpus or 0) if target_train_gpus <= 0 and plan is not None: # Preserve the generic executor contract for callers that do not # require planner-only EHP control. Production configs set @@ -1222,14 +1201,12 @@ def _desired_hybrid_workers( def _elastic_replica_size_gpus(self) -> int: cfg = self.config.global_resource_planner topology_width = ( - max(1, int(getattr(self.config, "train_tp_size", 1) or 1)) - * max(1, int(getattr(self.config, "train_ep_size", 1) or 1)) - * max(1, int(getattr(self.config, "train_pp_size", 1) or 1)) - * max(1, int(getattr(self.config, "train_cp_size", 1) or 1)) - ) - configured = int( - getattr(cfg, "elastic_hybrid_replica_size_gpus", 0) or 0 + max(1, int(self.config.train_tp_size or 1)) + * max(1, int(self.config.train_ep_size or 1)) + * max(1, int(self.config.train_pp_size or 1)) + * max(1, int(self.config.train_cp_size or 1)) ) + configured = int(cfg.elastic_hybrid_replica_size_gpus or 0) if configured > 0: if configured != topology_width: raise ValueError( @@ -1241,13 +1218,10 @@ def _elastic_replica_size_gpus(self) -> int: def _elastic_replica_capacity(self) -> int: cfg = self.config.global_resource_planner - reserve = max( - 0, - int(getattr(cfg, "elastic_hybrid_min_rollout_gpus", 0) or 0), - ) + reserve = max(0, int(cfg.elastic_hybrid_min_rollout_gpus or 0)) return max( 0, - (int(getattr(self.config, "rollout_gpus", 0) or 0) - reserve) + (int(self.config.rollout_gpus or 0) - reserve) // self._elastic_replica_size_gpus(), ) @@ -1271,10 +1245,7 @@ def _publish_hybrid_membership(self) -> dict[str, dict[str, Any]]: """ if self.elastic_pool is None: return {} - directory = Path(getattr( - self.config.global_resource_planner, - "hybrid_worker_task_dir", "./logs/elastic_training_tasks", - )) / "membership" + directory = Path(self.config.global_resource_planner.hybrid_worker_task_dir) / "membership" with self._membership_publication_lock: records = self.elastic_pool.membership_snapshot() for replica_id, record in records.items(): @@ -1458,13 +1429,7 @@ def _reconcile_pending_hybrid_joins_locked(self, result=None): for replica_id, handle in pending_items: if not handle.done(): started = self._pending_hybrid_join_started_at.get(replica_id, time.monotonic()) - timeout = float( - getattr( - self.config.global_resource_planner, - "elastic_hybrid_join_timeout_s", - 180.0, - ) - ) + timeout = float(self.config.global_resource_planner.elastic_hybrid_join_timeout_s) if timeout > 0 and time.monotonic() - started > timeout: # Serialize the cold-timeout decision with the boundary # handoff; ready joins now wait for their Core boundary. @@ -1635,32 +1600,20 @@ def _activate_hybrid_worker( receipt = self._wait_hybrid_worker_ready( worker_id, state_version=state_version, replica_world_size=replica_world_size, snapshot_path=snapshot_path, target_core_id=target_core_id, - timeout_s=float(getattr(self.config.global_resource_planner, - "elastic_hybrid_join_timeout_s", 180.0)), + timeout_s=float(self.config.global_resource_planner.elastic_hybrid_join_timeout_s), ) return self._queue_activation(replica_id or worker_id, receipt) @property def _hybrid_worker_remote_control_enabled(self) -> bool: - return bool( - getattr( - self.config.global_resource_planner, - "hybrid_worker_remote_control_enabled", - False, - ) - ) + return bool(self.config.global_resource_planner.hybrid_worker_remote_control_enabled) def _hybrid_worker_control_dir(self) -> Path: cfg = self.config.global_resource_planner - return Path( - getattr(cfg, "hybrid_worker_remote_control_dir", "") - or getattr(cfg, "hybrid_worker_task_dir", "./logs/elastic_training_tasks") - ) + return Path(cfg.hybrid_worker_remote_control_dir or cfg.hybrid_worker_task_dir) def _remote_hybrid_worker_slot(self, worker_id: str) -> dict[str, Any]: - instances = list( - getattr(self.config.heterogeneous_rollout, "instances", []) or [] - ) + instances = list(self.config.heterogeneous_rollout.instances or []) try: index = int(worker_id.removeprefix("rollout")) except ValueError: @@ -1669,9 +1622,9 @@ def _remote_hybrid_worker_slot(self, worker_id: str) -> dict[str, Any]: raise RuntimeError("remote EHP launch requires rollout instances") physical_slots = sorted( { - (str(getattr(instance, "host", "")), int(gpu)) + (str(instance.host), int(gpu)) for instance in instances - for gpu in getattr(instance, "gpus", []) + for gpu in instance.gpus } ) if index >= len(physical_slots): @@ -1759,9 +1712,8 @@ def _request_remote_hybrid_worker_locked( def _cluster_swap_enabled(self, strategy: str | None = None) -> bool: cfg = self.config.global_resource_planner return bool( - getattr(cfg, "runtime_cluster_swap_enabled", False) - or (strategy or getattr(cfg, "runtime_rollout_reconfigure_strategy", "")) - == "cluster_swap" + cfg.runtime_cluster_swap_enabled + or (strategy or cfg.runtime_rollout_reconfigure_strategy) == "cluster_swap" ) def _runtime_plan_already_applied( @@ -1772,7 +1724,7 @@ def _runtime_plan_already_applied( ) -> bool: planner_cfg = self.config.global_resource_planner if ( - getattr(planner_cfg, "runtime_reconfigure_training", False) + planner_cfg.runtime_reconfigure_training and int(getattr(plan, "train_gpus", current_train_gpus)) != current_train_gpus ): return False @@ -1780,10 +1732,7 @@ def _runtime_plan_already_applied( current_train_gpus, plan, ) - reconfigure_training = bool( - getattr(planner_cfg, "runtime_reconfigure_training", False) - ) - if reconfigure_training and target_train_gpus != current_train_gpus: + if planner_cfg.runtime_reconfigure_training and target_train_gpus != current_train_gpus: return False # The process builder reads the live config. A candidate with a new @@ -1811,12 +1760,8 @@ def _cluster_swap_rollout_training_pools( """Swap GPUs between rollout and training without spare prewarm GPUs.""" planner_cfg = self.config.global_resource_planner - reconfigure_training = bool( - getattr(planner_cfg, "runtime_reconfigure_training", False) - ) - plan_only = bool( - getattr(planner_cfg, "runtime_training_pool_plan_only", True) - ) + reconfigure_training = bool(planner_cfg.runtime_reconfigure_training) + plan_only = bool(planner_cfg.runtime_training_pool_plan_only) if reconfigure_training and not plan_only: self._ensure_elastic_pool() @@ -1844,7 +1789,7 @@ def _cluster_swap_rollout_training_pools( self._reconfigure_training_pool(current_train_gpus, plan, result) ) - if getattr(planner_cfg, "runtime_manage_rollout_processes", False): + if planner_cfg.runtime_manage_rollout_processes: stopped, started = self._reconfigure_rollout_processes( plan, strategy_override="cluster_swap", @@ -1867,7 +1812,7 @@ def _cluster_swap_rollout_training_pools( ) ) elif ( - getattr(planner_cfg, "apply_to_runtime", True) + planner_cfg.apply_to_runtime and self.rollout_engine is not None and hasattr(self.rollout_engine, "reconfigure_from_plan") ): @@ -1920,8 +1865,7 @@ def _assign_cluster_swap_training_slots( return assigned def _cluster_swap_training_slot(self, worker_id: str) -> dict[str, Any]: - slots = getattr(self, "_cluster_swap_training_slots", {}) - return dict(slots.get(worker_id, {})) + return dict(self._cluster_swap_training_slots.get(worker_id, {})) def _training_reconfiguration_targets( self, @@ -1941,7 +1885,7 @@ def _training_reconfiguration_targets( ] return core_ids, target_core, candidates - dp = max(1, int(getattr(self.config, "train_dp_size", 1) or 1)) + dp = max(1, int(self.config.train_dp_size or 1)) core_ids = [f"dp{i}" for i in range(dp)] target_core = core_ids[0] target_train_gpus = current_train_gpus + self._desired_hybrid_workers( @@ -1969,7 +1913,6 @@ def _plan_training_pool_reconfiguration( runtime_training_pool_plan_only to attach the gradient domain. """ - planner_cfg = self.config.global_resource_planner target_train_gpus = current_train_gpus + self._desired_hybrid_workers( current_train_gpus, plan, @@ -1978,7 +1921,7 @@ def _plan_training_pool_reconfiguration( if delta == 0: return [f"plan_training_gpus_unchanged:{target_train_gpus}"] - current_dp = max(1, int(getattr(self.config, "train_dp_size", 1) or 1)) + current_dp = max(1, int(self.config.train_dp_size or 1)) core_ids = [f"dp{i}" for i in range(current_dp)] replica_size = self._elastic_replica_size_gpus() @@ -2017,8 +1960,8 @@ def _apply_plan_to_runtime_config(self, plan: GlobalResourcePlan) -> None: planner_cfg = self.config.global_resource_planner preserve_training = bool( - getattr(planner_cfg, "runtime_training_pool_only", True) - and getattr(planner_cfg, "runtime_reconfigure_training", False) + planner_cfg.runtime_training_pool_only + and planner_cfg.runtime_reconfigure_training ) if not preserve_training: self.planner.apply_plan_to_config(plan, self.config) @@ -2066,7 +2009,7 @@ def _prewarm_capacity_issue(self, plan: GlobalResourcePlan) -> str: len(meta.gpus), ) hetero = self.config.heterogeneous_rollout - if getattr(hetero, "available_gpus", None): + if hetero.available_gpus: host = hetero.vllm_host or "127.0.0.1" if host == "0.0.0.0": host = "127.0.0.1" @@ -2100,14 +2043,13 @@ def _prewarm_capacity_issue(self, plan: GlobalResourcePlan) -> str: return "" def _coordination_dir(self) -> Path: - planner_cfg = self.config.global_resource_planner - configured = getattr(planner_cfg, "runtime_reconfiguration_coord_dir", "") + configured = self.config.global_resource_planner.runtime_reconfiguration_coord_dir if configured: return Path(configured) return Path(self.config.log_dir) / "runtime_reconfiguration" def _current_coordination_id(self, plan: GlobalResourcePlan) -> str: - return getattr(self, "_active_runtime_coord_id", "") or uuid.uuid4().hex + return self._active_runtime_coord_id or uuid.uuid4().hex def _write_peer_rank_reconfiguration_state( self, @@ -2126,7 +2068,7 @@ def _write_peer_rank_reconfiguration_state( coord_dir.mkdir(parents=True, exist_ok=True) pending = set(getattr(getattr(self, "trainer", None), "_restored_rollouts_pending_publication", ())) if coord_id is None: - coord_id = getattr(self, "_active_runtime_coord_id", "") + coord_id = self._active_runtime_coord_id payload = { "coord_id": coord_id, "run_id": self.runtime_run_id, @@ -2167,13 +2109,13 @@ def _peer_training_reconfiguration_state( elastic_signal: Any | None = None, ) -> dict[str, Any]: planner_cfg = self.config.global_resource_planner - if not getattr(planner_cfg, "runtime_reconfigure_training", False): + if not planner_cfg.runtime_reconfigure_training: return {"enabled": False} - current_train_gpus = int(getattr(self.config, "train_gpus", 0) or 0) + current_train_gpus = int(self.config.train_gpus or 0) desired_hybrid_workers = self._desired_hybrid_workers(current_train_gpus, plan) target_train_gpus = current_train_gpus + desired_hybrid_workers - dp = max(1, int(getattr(self.config, "train_dp_size", 1) or 1)) + dp = max(1, int(self.config.train_dp_size or 1)) core_ids = [f"dp{i}" for i in range(dp)] rollout_workers = [ f"rollout{i}" for i in range(max(0, int(self.config.rollout_gpus))) @@ -2213,9 +2155,7 @@ def _peer_training_reconfiguration_state( signal_payload = dict(elastic_signal) return { "enabled": True, - "plan_only": bool( - getattr(planner_cfg, "runtime_training_pool_plan_only", True) - ), + "plan_only": bool(planner_cfg.runtime_training_pool_plan_only), "target_train_gpus": target_train_gpus, "current_train_gpus": current_train_gpus, "core_replica_ids": core_ids, @@ -2328,15 +2268,11 @@ def _coordinate_peer_rank_drain( return if int(os.environ.get("RANK", "0") or "0") != 0: return - if not getattr( - self.config.global_resource_planner, - "runtime_coordinate_reconfiguration_ranks", - True, - ): + if not self.config.global_resource_planner.runtime_coordinate_reconfiguration_ranks: return coord_id = self._current_coordination_id(plan) if (resource_reconfiguration and self._peer_drain_request_coord_id != coord_id - and not getattr(self.config.global_resource_planner, "runtime_drain_before_reconfigure", True)): + and not self.config.global_resource_planner.runtime_drain_before_reconfigure): result.actions.append("peer_reconfig_drain_skipped") return @@ -2354,13 +2290,7 @@ def _coordinate_peer_rank_drain( rollout_drain_required=resource_reconfiguration, ) - timeout = float( - getattr( - self.config.global_resource_planner, - "runtime_drain_timeout_s", - 3600.0, - ) - ) + timeout = float(self.config.global_resource_planner.runtime_drain_timeout_s) deadline = time.time() + timeout if timeout > 0 else float("inf") expected_ranks = self._expected_peer_ready_ranks() expected = [ready_dir / f"rank_{rank}.json" for rank in expected_ranks] @@ -2371,7 +2301,7 @@ def ready_matches(path: Path) -> bool: return False try: payload = json.loads(path.read_text(encoding="utf-8")) - except Exception: + except (OSError, json.JSONDecodeError): return False if str(payload.get("coord_id", "")) != coord_id: return False @@ -2401,18 +2331,16 @@ def _expected_peer_ready_ranks(self) -> list[int]: if world_size <= 1: return [] planner_cfg = self.config.global_resource_planner - if (getattr(planner_cfg, "runtime_reconfigure_training", False) - or not getattr(planner_cfg, "runtime_coordinate_batch_source_only", True)): + if (planner_cfg.runtime_reconfigure_training + or not planner_cfg.runtime_coordinate_batch_source_only): return list(range(1, world_size)) model_parallel = ( - max(1, int(getattr(self.config, "train_tp_size", 1) or 1)) - * max(1, int(getattr(self.config, "train_pp_size", 1) or 1)) + max(1, int(self.config.train_tp_size or 1)) + * max(1, int(self.config.train_pp_size or 1)) ) - if getattr(self.config, "train_backend", "") == "megatron_core": - model_parallel *= max( - 1, int(getattr(self.config, "train_cp_size", 1) or 1) - ) + if self.config.train_backend == "megatron_core": + model_parallel *= max(1, int(self.config.train_cp_size or 1)) if model_parallel <= 1: return list(range(1, world_size)) @@ -2444,7 +2372,7 @@ def _initialize_elastic_pool(self): if hasattr(self.train_engine, "get_elastic_core_replica_ids"): core_ids = list(self.train_engine.get_elastic_core_replica_ids()) else: - dp = max(1, int(getattr(self.config, "train_dp_size", 1) or 1)) + dp = max(1, int(self.config.train_dp_size or 1)) core_ids = [f"dp{i}" for i in range(dp)] rollout_workers = [ @@ -2465,13 +2393,7 @@ def fetch_snapshot(worker_id: str, target_core_id: str) -> int: ) return int(getattr(self.train_engine, "current_version", 0)) - decoupled = bool( - getattr( - self.config.global_resource_planner, - "decouple_communication_domains", - True, - ) - ) + decoupled = bool(self.config.global_resource_planner.decouple_communication_domains) core_group = None hybrid_group = None if hasattr(self.train_engine, "get_elastic_core_process_group"): @@ -2488,11 +2410,7 @@ def fetch_snapshot(worker_id: str, target_core_id: str) -> int: decoupled=decoupled, ), require_isolated_process_group=bool( - getattr( - self.config.global_resource_planner, - "elastic_hybrid_require_isolated_ccl", - False, - ) + self.config.global_resource_planner.elastic_hybrid_require_isolated_ccl ), replica_world_size=self._elastic_replica_size_gpus(), local_replica_rank=( @@ -2519,21 +2437,12 @@ def fetch_snapshot(worker_id: str, target_core_id: str) -> int: @property def _hybrid_worker_launch_enabled(self) -> bool: - return bool( - getattr( - self.config.global_resource_planner, - "hybrid_worker_launch_enabled", - False, - ) - ) + return bool(self.config.global_resource_planner.hybrid_worker_launch_enabled) @property def _hybrid_training_prewarm_enabled(self) -> bool: cfg = self.config.global_resource_planner - return bool( - getattr(cfg, "hybrid_training_prewarm_enabled", False) - and getattr(cfg, "hybrid_worker_launch_enabled", False) - ) + return bool(cfg.hybrid_training_prewarm_enabled and cfg.hybrid_worker_launch_enabled) def _prewarm_hybrid_training_workers( self, @@ -2591,13 +2500,10 @@ def _hybrid_training_prewarm_worker_ids( candidates: list[str], ) -> list[str]: cfg = self.config.global_resource_planner - configured = [ - str(worker_id) - for worker_id in getattr(cfg, "hybrid_training_prewarm_worker_ids", []) - ] + configured = [str(worker_id) for worker_id in cfg.hybrid_training_prewarm_worker_ids] if configured: return configured - count = int(getattr(cfg, "hybrid_training_prewarm_count", 0) or 0) + count = int(cfg.hybrid_training_prewarm_count or 0) if count > 0: return candidates[:count] return candidates @@ -2686,8 +2592,7 @@ def wait_for_hybrid_training_tasks(self, worker_id: str | None = None) -> None: else: meta = self._hybrid_worker_meta.get(worker_id) worker_ids = {(meta.replica_id or meta.worker_id) if meta else worker_id} - timeout = float(getattr(self.config.global_resource_planner, - "hybrid_update_timeout_s", 300.0)) + timeout = float(self.config.global_resource_planner.hybrid_update_timeout_s) deadline = time.monotonic() + timeout if timeout > 0 else float("inf") assignments = self._hybrid_task_contexts for identity in worker_ids: @@ -2817,7 +2722,7 @@ def _initialize_gradient_server(self): return cfg = self.config.global_resource_planner on_payload = getattr(self.train_engine, "enqueue_hybrid_gradient_payload", lambda payload: None) - backend = getattr(cfg, "gradient_transport_backend", "tcp") + backend = cfg.gradient_transport_backend if backend == "native_rdma": from RL_Framework.infra.elastic.native_rdma import ( NativeRDMAConfig, @@ -2825,25 +2730,25 @@ def _initialize_gradient_server(self): ) self.gradient_server = NativeRDMAGradientServer( - host=getattr(cfg, "gradient_server_host", "127.0.0.1"), - port=int(getattr(cfg, "gradient_server_port", 0)), - authkey=getattr(cfg, "gradient_server_authkey", ""), + host=cfg.gradient_server_host, + port=int(cfg.gradient_server_port), + authkey=cfg.gradient_server_authkey, on_payload=on_payload, rdma_config=NativeRDMAConfig( - device=getattr(cfg, "native_rdma_device", "mlx5_0"), - gid_index=int(getattr(cfg, "native_rdma_gid_index", 0)), - ib_port=int(getattr(cfg, "native_rdma_ib_port", 1)), - max_bytes=int(getattr(cfg, "native_rdma_max_bytes", 67108864)), + device=cfg.native_rdma_device, + gid_index=int(cfg.native_rdma_gid_index), + ib_port=int(cfg.native_rdma_ib_port), + max_bytes=int(cfg.native_rdma_max_bytes), ), - work_dir=getattr(cfg, "hybrid_worker_task_dir", "./logs/elastic_training_tasks"), + work_dir=cfg.hybrid_worker_task_dir, ) else: from RL_Framework.infra.elastic.gradient_ipc import ElasticGradientServer self.gradient_server = ElasticGradientServer( - host=getattr(cfg, "gradient_server_host", "127.0.0.1"), - port=int(getattr(cfg, "gradient_server_port", 0)), - authkey=getattr(cfg, "gradient_server_authkey", ""), + host=cfg.gradient_server_host, + port=int(cfg.gradient_server_port), + authkey=cfg.gradient_server_authkey, on_payload=on_payload, ) self.gradient_server.start() @@ -2900,7 +2805,7 @@ def _wait_hybrid_worker_ready( target_core_id: str | None = None, timeout_s: float | None = None, ) -> dict[str, Any]: from RL_Framework.infra.elastic.readiness import read_ready_receipts, snapshot_contract - task_dir = Path(getattr(self.config.global_resource_planner, "hybrid_worker_task_dir", "./logs/elastic_training_tasks")) + task_dir = Path(self.config.global_resource_planner.hybrid_worker_task_dir) meta = self._hybrid_worker_meta.get(worker_id) if meta is None: meta = next((value for value in self._hybrid_worker_meta.values() if value.replica_id == worker_id), None) @@ -2918,8 +2823,11 @@ def _wait_hybrid_worker_ready( # Cold startup and its first installation use the overall join budget, # still bounded by the pool's original deadline through the guard below. # A running worker's catch-up installation keeps the shorter ACK budget. - timeout = float(timeout_s if timeout_s is not None else getattr( - self.config.global_resource_planner, "hybrid_worker_ready_timeout_s", 60.)) + timeout = float( + timeout_s + if timeout_s is not None + else self.config.global_resource_planner.hybrid_worker_ready_timeout_s + ) deadline = time.monotonic() + timeout if timeout > 0 else None while True: if self._closing.is_set(): @@ -2979,7 +2887,7 @@ def _build_hybrid_worker_command( replica_world_size: int = 1, ) -> str: cfg = self.config.global_resource_planner - if self._hybrid_worker_launch_enabled and hasattr(self.config, "to_yaml"): + if self._hybrid_worker_launch_enabled: config_path = self._coordination_dir() / f"hybrid-config-{self._active_runtime_coord_id}.yaml" config_path.parent.mkdir(parents=True, exist_ok=True) temporary = config_path.with_name(f".{config_path.name}.{uuid.uuid4().hex}.tmp") @@ -2987,15 +2895,15 @@ def _build_hybrid_worker_command( temporary.replace(config_path) cfg.hybrid_worker_config_path = str(config_path) endpoint = self.gradient_server.endpoint - gradient_host = getattr(cfg, "gradient_server_public_host", "") or endpoint.host + gradient_host = cfg.gradient_server_public_host or endpoint.host rl_root = Path(__file__).resolve().parents[2] - template = getattr(cfg, "hybrid_worker_command_template", "") + template = cfg.hybrid_worker_command_template assigned_gpus = [int(gpu) for gpu in (gpus or [])] cuda_visible_devices = ",".join(str(gpu) for gpu in assigned_gpus) values = { - "python": shlex.quote(getattr(cfg, "hybrid_worker_python", sys.executable)), + "python": shlex.quote(cfg.hybrid_worker_python or sys.executable), "rl_framework_path": shlex.quote(str(rl_root)), - "gradient_transport_backend": shlex.quote(getattr(cfg, "gradient_transport_backend", "tcp")), + "gradient_transport_backend": shlex.quote(cfg.gradient_transport_backend), "worker_id": shlex.quote(worker_id), "replica_id": shlex.quote(replica_id or worker_id), "replica_rank": int(replica_rank), @@ -3005,25 +2913,25 @@ def _build_hybrid_worker_command( "host": shlex.quote(host), "gpus": cuda_visible_devices, "cuda_visible_devices": shlex.quote(cuda_visible_devices), - "worker_mode": shlex.quote(getattr(cfg, "hybrid_worker_mode", "megatron_core")), + "worker_mode": shlex.quote(cfg.hybrid_worker_mode), "worker_config": shlex.quote( - getattr(cfg, "hybrid_worker_config_path", "") + cfg.hybrid_worker_config_path or os.environ.get("RUNTIME_CONFIG", os.environ.get("CONFIG_PATH", "")) ), "gradient_endpoint_dir": shlex.quote(str(Path( - getattr(cfg, "hybrid_worker_endpoint_dir", "") - or getattr(cfg, "hybrid_worker_task_dir", "") + cfg.hybrid_worker_endpoint_dir + or cfg.hybrid_worker_task_dir ) / "core_endpoints")), "replica_gpus": len(assigned_gpus) or int(replica_world_size), "gradient_host": shlex.quote(gradient_host), "gradient_port": endpoint.port, "authkey": shlex.quote(endpoint.authkey), - "task_dir": shlex.quote(getattr(cfg, "hybrid_worker_task_dir", "")), + "task_dir": shlex.quote(cfg.hybrid_worker_task_dir), "idle_flag": "--idle" if idle else "", - "native_rdma_device": shlex.quote(getattr(cfg, "native_rdma_device", "mlx5_0")), - "native_rdma_gid_index": int(getattr(cfg, "native_rdma_gid_index", 0)), - "native_rdma_ib_port": int(getattr(cfg, "native_rdma_ib_port", 1)), - "native_rdma_max_bytes": int(getattr(cfg, "native_rdma_max_bytes", 67108864)), + "native_rdma_device": shlex.quote(cfg.native_rdma_device), + "native_rdma_gid_index": int(cfg.native_rdma_gid_index), + "native_rdma_ib_port": int(cfg.native_rdma_ib_port), + "native_rdma_max_bytes": int(cfg.native_rdma_max_bytes), } if template: return template.format(**values) @@ -3034,7 +2942,7 @@ def _build_hybrid_worker_command( launcher = "" # MCore initializes env:// even for TP1; torchrun supplies an isolated # rank/rendezvous environment for every complete Hybrid replica. - if getattr(cfg, "hybrid_worker_mode", "megatron_core") == "megatron_core": + if cfg.hybrid_worker_mode == "megatron_core": launcher = f"{values['python']} -m torch.distributed.run --standalone --nproc_per_node={values['replica_gpus']} " else: launcher = f"{values['python']} " @@ -3081,11 +2989,7 @@ def _adopt_existing_rollout_processes(self) -> None: cfgs = getattr(self.rollout_engine, "instance_configs", None) if not cfgs or self._process_meta: return - if not getattr( - self.config.global_resource_planner, - "runtime_adopt_existing_rollout_processes", - True, - ): + if not self.config.global_resource_planner.runtime_adopt_existing_rollout_processes: return registry = self._load_rollout_pid_registry() for idx, cfg in enumerate(cfgs): @@ -3117,11 +3021,7 @@ def _adopt_existing_rollout_processes(self) -> None: def _load_rollout_pid_registry(self) -> dict[str, dict[str, Any]]: path = ( - getattr( - self.config.global_resource_planner, - "runtime_rollout_pid_registry_path", - "", - ) + self.config.global_resource_planner.runtime_rollout_pid_registry_path or os.getenv("GRP_ROLLOUT_PID_REGISTRY_PATH", "") ) if not path: @@ -3149,10 +3049,9 @@ def _reconfigure_rollout_processes( strategy_override: str | None = None, ) -> tuple[list[ManagedRolloutProcess], list[ManagedRolloutProcess]]: self._rollout_engine_reconfigured = False - strategy = strategy_override or getattr( - self.config.global_resource_planner, - "runtime_rollout_reconfigure_strategy", - "diff", + strategy = ( + strategy_override + or self.config.global_resource_planner.runtime_rollout_reconfigure_strategy ) if strategy == "restart_all": stopped = self._stop_managed_rollout_processes() @@ -3315,14 +3214,12 @@ def _finish_prewarmed_rollout_cutover( stopped: list[ManagedRolloutProcess] = [] self._reconfigure_rollout_engine(plan, wait_ready=True) self._rollout_engine_reconfigured = True - to_stop = list(getattr(self, "_prewarmed_rollout_to_stop", [])) - if to_stop or getattr(self, "_blue_green_old_processes", []): + to_stop = list(self._prewarmed_rollout_to_stop) + if to_stop or self._blue_green_old_processes: self._sleep_before_rollout_stop() for instance_id in to_stop: stopped.extend(self._stop_rollout_process(instance_id)) - for old_meta, old_proc in list( - getattr(self, "_blue_green_old_processes", []) - ): + for old_meta, old_proc in list(self._blue_green_old_processes): stopped.extend(self._stop_process_meta(old_meta, old_proc)) self._blue_green_old_processes = [] self._prewarmed_rollout_to_stop = [] @@ -3421,7 +3318,7 @@ def physical_gpus(meta): self._reconfigure_rollout_engine(plan, wait_ready=True) self._rollout_engine_reconfigured = True - if to_stop or getattr(self, "_blue_green_old_processes", []): + if to_stop or self._blue_green_old_processes: self._sleep_before_rollout_stop() for instance_id in to_stop: @@ -3433,9 +3330,7 @@ def physical_gpus(meta): stopped.extend(self._stop_rollout_process(instance_id)) # Stop old same-id processes that were replaced before metadata changed. - for old_meta, old_proc in list( - getattr(self, "_blue_green_old_processes", []) - ): + for old_meta, old_proc in list(self._blue_green_old_processes): stopped.extend(self._stop_process_meta(old_meta, old_proc)) self._blue_green_old_processes = [] return stopped, started @@ -3461,9 +3356,7 @@ def _desired_rollout_processes( base_port = int(hetero.vllm_base_port) desired: list[ManagedRolloutProcess] = [] for idx, inst in enumerate(hetero.instances): - port = base_port + idx - if getattr(inst, "port", 0): - port = int(inst.port) + port = int(inst.port) if inst.port else base_port + idx host = inst.host or hetero.vllm_host if host == "0.0.0.0": host = "127.0.0.1" @@ -3485,9 +3378,7 @@ def _start_one_rollout_process( ) -> ManagedRolloutProcess: old = self._process_meta.get(meta.instance_id) if old is not None and not self._same_rollout_process(old, meta): - old_list = getattr(self, "_blue_green_old_processes", []) - old_list.append((old, self._processes.get(meta.instance_id))) - self._blue_green_old_processes = old_list + self._blue_green_old_processes.append((old, self._processes.get(meta.instance_id))) env = self._rollout_launch_env(meta) stdout = None log_handle = None @@ -3545,7 +3436,7 @@ def _rollout_launch_env(self, meta: ManagedRolloutProcess) -> dict[str, str]: env["LIBRA_CAPTURE_BEHAVIOR"] = "1" env.setdefault("LIBRA_CHECK_PREFIX_CACHE", "1") env.setdefault("VLLM_ENABLE_V1_MULTIPROCESSING", "1") - backend = str(getattr(self.config.heterogeneous_rollout.scheduling, "cmlfq_kv_backend", "recompute")) + backend = str(self.config.heterogeneous_rollout.scheduling.cmlfq_kv_backend) if backend == "cpu_offload": directory = str(Path(self.config.rollout_weight_sync_control_dir) / "kv-store") env["LIBRA_KV_STORAGE_PATH"] = os.environ.get("LIBRA_KV_STORAGE_PATH", directory) @@ -3569,7 +3460,7 @@ def _stop_process_meta( proc: subprocess.Popen | None, ) -> list[ManagedRolloutProcess]: if meta.adopted or proc is None: - template = getattr(self.config.global_resource_planner, "vllm_stop_command_template", "") + template = self.config.global_resource_planner.vllm_stop_command_template if template: self._run_external_stop(meta) elif meta.pid > 0: @@ -3596,11 +3487,7 @@ def _same_rollout_process( ) def _rollout_log_path(self, instance_id: str) -> str: - log_dir = getattr( - self.config.global_resource_planner, - "runtime_rollout_log_dir", - "", - ) + log_dir = self.config.global_resource_planner.runtime_rollout_log_dir if not log_dir: log_dir = os.path.join(self.config.log_dir, "runtime_rollout") return str(Path(log_dir) / f"{instance_id}.log") @@ -3624,7 +3511,7 @@ def _reconfigure_rollout_engine( wait_ready: bool, ) -> None: if ( - not getattr(self.config.global_resource_planner, "apply_to_runtime", True) + not self.config.global_resource_planner.apply_to_runtime or self.rollout_engine is None or not hasattr(self.rollout_engine, "reconfigure_from_plan") ): @@ -3632,19 +3519,11 @@ def _reconfigure_rollout_engine( self.rollout_engine.reconfigure_from_plan(plan, self.config) if wait_ready and hasattr(self.rollout_engine, "wait_for_ready"): self.rollout_engine.wait_for_ready( - timeout=getattr( - self.config.global_resource_planner, - "vllm_ready_timeout_s", - 300.0, - ) + timeout=self.config.global_resource_planner.vllm_ready_timeout_s ) def _run_external_stop(self, meta: ManagedRolloutProcess) -> None: - template = getattr( - self.config.global_resource_planner, - "vllm_stop_command_template", - "", - ) + template = self.config.global_resource_planner.vllm_stop_command_template if not template: return values = { @@ -3672,7 +3551,7 @@ def _run_external_stop(self, meta: ManagedRolloutProcess) -> None: check=False, stdout=log_handle, stderr=subprocess.STDOUT, - timeout=(float(getattr(self.config.global_resource_planner, "vllm_stop_timeout_s", 60.0)) or None), + timeout=(float(self.config.global_resource_planner.vllm_stop_timeout_s) or None), ) log_handle.write( f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] " @@ -3688,19 +3567,10 @@ def _run_external_stop(self, meta: ManagedRolloutProcess) -> None: raise TimeoutError(f"rollout stop timed out for {meta.instance_id}") from exc def _wait_rollout_process_start_ready(self, meta: ManagedRolloutProcess) -> None: - if not getattr( - self.config.global_resource_planner, - "runtime_wait_rollout_process_start_ready", - False, - ): + planner_cfg = self.config.global_resource_planner + if not planner_cfg.runtime_wait_rollout_process_start_ready: return - timeout = float( - getattr( - self.config.global_resource_planner, - "vllm_ready_timeout_s", - 300.0, - ) - ) + timeout = float(planner_cfg.vllm_ready_timeout_s) url = f"http://{meta.host}:{meta.port}/health" deadline = time.time() + timeout log_path = meta.log_path or self._rollout_log_path(meta.instance_id) @@ -3725,7 +3595,7 @@ def _wait_rollout_process_start_ready(self, meta: ManagedRolloutProcess) -> None f"health ready {url}\n" ) return - except Exception: + except (OSError, urllib.error.URLError): time.sleep(5.0) raise TimeoutError( f"rollout process {meta.instance_id} not ready after {timeout:.0f}s" @@ -3734,28 +3604,12 @@ def _wait_rollout_process_start_ready(self, meta: ManagedRolloutProcess) -> None def _sleep_after_rollout_stop(self, stopped: list[ManagedRolloutProcess]) -> None: if not stopped: return - grace_s = float( - getattr( - self.config.global_resource_planner, - "runtime_post_rollout_stop_grace_s", - 0.0, - ) - ) + grace_s = float(self.config.global_resource_planner.runtime_post_rollout_stop_grace_s) if grace_s > 0: time.sleep(grace_s) def _sleep_before_rollout_stop(self) -> None: - grace_s = float( - getattr( - self.config.global_resource_planner, - "runtime_rollout_drain_grace_s", - getattr( - self.config.global_resource_planner, - "runtime_post_rollout_stop_grace_s", - 0.0, - ), - ) - ) + grace_s = float(self.config.global_resource_planner.runtime_post_rollout_stop_grace_s) if grace_s > 0: time.sleep(grace_s) @@ -3773,17 +3627,13 @@ def _write_rollout_manifest( *, phase: str, ) -> None: - path = getattr( - self.config.global_resource_planner, - "runtime_rollout_manifest_path", - "", - ) + path = self.config.global_resource_planner.runtime_rollout_manifest_path if not path: return payload = { "phase": phase, "run_id": self.runtime_run_id, - "coord_id": getattr(self, "_active_runtime_coord_id", ""), + "coord_id": self._active_runtime_coord_id, "updated_at": time.time(), "plan": plan.to_dict(), "instances": [ @@ -3806,12 +3656,12 @@ def _write_rollout_manifest( def _build_vllm_command(self, inst: Any, port: int) -> str: planner_cfg = self.config.global_resource_planner - template = getattr(planner_cfg, "vllm_launch_command_template", "") + template = planner_cfg.vllm_launch_command_template host = inst.host or self.config.heterogeneous_rollout.vllm_host max_model_len = self.config.heterogeneous_rollout.max_model_len or self.config.max_seq_length public_host = host if host != "0.0.0.0" else "127.0.0.1" module = os.environ.get("VLLM_SERVER_MODULE") or "RL_Framework.scripts.vllm_hot_reload_api_server" - control = str(getattr(self.config, "rollout_weight_sync_control_dir", "") or + control = str(self.config.rollout_weight_sync_control_dir or Path(self.config.log_dir) / "rollout_weight_sync") instance_id = str(inst.instance_id or f"tp{inst.tp}_{port}") devices = ",".join(str(gpu) for gpu in inst.gpus) @@ -3841,7 +3691,7 @@ def _build_vllm_command(self, inst: Any, port: int) -> str: "--max-num-seqs", str(self.config.max_concurrent_rollouts), "--seed", str(self.config.seed), "--worker-extension-cls", "RL_Framework.vllm_hot_reload.InplaceReloadWorkerExtension", "--enforce-eager", "--trust-remote-code", "--disable-log-requests"] - backend = str(getattr(self.config.heterogeneous_rollout.scheduling, "cmlfq_kv_backend", "recompute")) + backend = str(self.config.heterogeneous_rollout.scheduling.cmlfq_kv_backend) if backend == "cpu_offload": storage = os.environ.get("LIBRA_KV_STORAGE_PATH") or str(Path(control) / "kv-store") server += ["--kv-transfer-config", json.dumps(dict( diff --git a/infra/observability/history_collector.py b/infra/observability/history_collector.py index ccf9fd9..829ce33 100644 --- a/infra/observability/history_collector.py +++ b/infra/observability/history_collector.py @@ -250,6 +250,7 @@ def __init__( self._lock = threading.Lock() self._record_count = 0 self._initialized = False + self._last_resource_config: ResourceConfig = ResourceConfig() def initialize(self): """Initialize.""" @@ -446,7 +447,7 @@ def record_step( if resource_config is not None: self._last_resource_config = resource_config - rc = getattr(self, "_last_resource_config", ResourceConfig()) + rc = self._last_resource_config record = StepRecord( @@ -484,58 +485,29 @@ def record_step( @staticmethod def snapshot_resource_config(config) -> ResourceConfig: """Snapshot resource config.""" + if config is None: + return ResourceConfig() + hetero = config.heterogeneous_rollout return ResourceConfig( - n_total_gpus=getattr(config, "n_total_gpus", 0) or ( - getattr(config, "train_gpus", 0) + getattr(config, "rollout_gpus", 0) - ), - train_gpus=getattr(config, "train_gpus", 0), - rollout_gpus=getattr(config, "rollout_gpus", 0), - train_backend=getattr(config, "train_backend", "fsdp"), - train_tp=getattr( - config, - "train_tp_size", - getattr(config, "tp_size", 1), - ), - train_pp=getattr(config, "train_pp_size", 1), - train_dp=getattr(config, "train_dp_size", 1), - rollout_tp_list=( - list(getattr( - getattr(config, "heterogeneous_rollout", None), - "tp_list", - [], - )) - if getattr( - getattr(config, "heterogeneous_rollout", None), - "enabled", - False, - ) - else [] - ), - vllm_tp_size=getattr(config, "vllm_tp_size", 1), - vllm_num_instances=( - getattr( - getattr(config, "heterogeneous_rollout", None), - "n_instances", - 0, - ) - if getattr( - getattr(config, "heterogeneous_rollout", None), - "enabled", - False, - ) - else getattr(config, "vllm_num_instances", 1) - ), - batch_size=getattr(config, "batch_size", 32), - micro_batch_size=getattr(config, "micro_batch_size", 4), - B_global=getattr(config, "batch_size", 32), - max_new_tokens=getattr(config, "max_new_tokens", 1024), - max_seq_length=getattr(config, "max_seq_length", 2048), - n_samples=getattr(config, "n_samples", 4), - temperature=getattr(config, "temperature", 1.0), - model_path=getattr(config, "model_path", ""), - model_params=getattr( - getattr(config, "model_arch", None), "num_params", 0.0 - ), + n_total_gpus=config.n_total_gpus or (config.train_gpus + config.rollout_gpus), + train_gpus=config.train_gpus, + rollout_gpus=config.rollout_gpus, + train_backend=config.train_backend, + train_tp=config.train_tp_size or config.tp_size, + train_pp=config.train_pp_size, + train_dp=config.train_dp_size, + rollout_tp_list=list(hetero.tp_list) if hetero.enabled else [], + vllm_tp_size=config.vllm_tp_size, + vllm_num_instances=hetero.n_instances if hetero.enabled else config.vllm_num_instances, + batch_size=config.batch_size, + micro_batch_size=config.micro_batch_size, + B_global=config.batch_size, + max_new_tokens=config.max_new_tokens, + max_seq_length=config.max_seq_length, + n_samples=config.n_samples, + temperature=config.temperature, + model_path=config.model_path, + model_params=config.model_arch.num_params, ) diff --git a/scripts/benchmark_cpu_offload.py b/scripts/benchmark_cpu_offload.py deleted file mode 100644 index 69108cd..0000000 --- a/scripts/benchmark_cpu_offload.py +++ /dev/null @@ -1,184 +0,0 @@ -#!/usr/bin/env python3 -"""Real vLLM/CUDA CPU-offload benchmark; tool latency is controlled synthetic I/O. - -Run next to two Libra CPU-offload API servers with shared CPU storage. Records -raw timings and checks greedy continuation against a full-prefill baseline. -""" - -import argparse -import asyncio -import json -import statistics -import time -import uuid -from pathlib import Path - -import httpx - - -async def engine_smoke(args): - """Exercise the scheduler/backend/workflow hooks on the live endpoints. - - Synthetic costs force a move to test plumbing; they are not measurements. - Performance measurements are collected separately by main(). - """ - from urllib.parse import urlsplit - from RL_Framework.engine.heterogeneous_engine import HeterogeneousRolloutEngine - from RL_Framework.engine.cmlfq_backend import CMLFQGenerationBackend - from RL_Framework.infra.scheduling.cmlfq_cost_scheduler import CMLFQCostScheduler - from RL_Framework.infra.scheduling.cmlfq_cost import CMLFQRoutingCosts - from RL_Framework.infra.scheduling.cmlfq_prefix_tree import Trajectory - from RL_Framework.infra.scheduling.cmlfq_tool_state import DefaultToolStateExtractor - - costs = CMLFQRoutingCosts() - costs.decode_ms = {str(args.source_tp): {"long": 10000}, str(args.target_tp): {"long": 1000}} - src, dst = urlsplit(args.source), urlsplit(args.target) - costs.migrations = [{"source_tp": args.source_tp, "target_tp": args.target_tp, - "source_host": src.hostname, "target_host": dst.hostname, - "seq_len": 1000, "transfer_ms": 1, "recompute_ms": 100}] - scheduler = CMLFQCostScheduler(buckets={ - "short": {"tp_degrees": [args.source_tp], "max_tokens": 100}, - "long": {"tp_degrees": [args.target_tp], "max_tokens": 10000}, - }, routing_costs=costs) - engine = HeterogeneousRolloutEngine(model_path=args.model, scheduler=scheduler) - engine._cmlfq_backend = CMLFQGenerationBackend("cpu_offload", [(args.source_tp, args.target_tp)]) - engine.add_instance("source", src.hostname, src.port, args.source_tp) - engine.add_instance("target", dst.hostname, dst.port, args.target_tp) - event = {"tool_type": "test", "output": "ok"} - state = DefaultToolStateExtractor().extract(event) - scheduler.prefix_tree.insert(Trajectory("live", [state], [1000], 2000)) - prompt = "The number is seven. " * 64 - request_id = engine.begin_cmlfq_request("live", 400) - try: - first = await engine.generate(prompt, request_id=request_id, temperature=0, max_new_tokens=8) - await asyncio.sleep(.5) - decision = engine.route_cmlfq_tool_return(request_id, event, 8) - assert decision.should_migrate - second = await engine.generate(prompt + first["text"] + "\nTool: ok. Continue:", - request_id=request_id, temperature=0, max_new_tokens=8) - assert second["_schedule_info"]["instance_index"] == 1 - assert second["_cpu_offload_info"]["imported_tokens"] > 0 - assert scheduler._migration_count == 1 - return {"schedule": second["_schedule_info"], "offload": second["_cpu_offload_info"]} - finally: - engine.finish_cmlfq_request(request_id, 16) - await engine.close() - - -async def main(args): - async with httpx.AsyncClient(timeout=300) as client: - async def generate(url, prompt, params=None, max_tokens=16): - payload = {"model": args.model, "prompt": prompt, "max_tokens": max_tokens, - "temperature": 0, "seed": 123, "logprobs": 1} - if params: - payload["kv_transfer_params"] = params - response = await client.post(url + "/v1/completions", json=payload) - response.raise_for_status() - return response.json() - - async def ready(key, tp): - start = time.perf_counter() - while True: - response = await client.get(args.source + f"/libra/kv/{key}", params={"source_tp": tp}) - response.raise_for_status() - status = response.json() - if status.get("ready"): - return status, (time.perf_counter() - start) * 1000 - if time.perf_counter() - start > 60: - raise TimeoutError("CPU cache publication timed out") - await asyncio.sleep(.002) - - for url in (args.source, args.target): - for attempt in range(180): - try: - response = await client.get(url + "/health") - if response.status_code == 200: - break - except httpx.RequestError: - pass - await asyncio.sleep(1) - else: - raise TimeoutError(f"Server not ready: {url}") - - rows = [] - for words in args.words: - prompt = "Repeat the final number only.\n" + "The value is seven. " * words + "\nFinal number:" - # Warm kernels/model before measured trials. - await generate(args.source, "Hello", max_tokens=1) - await generate(args.target, "Hello", max_tokens=1) - for delay in args.tool_ms: - for trial in range(args.trials): - # Alternate mode order to avoid always warming one mode first. - modes = ("serial", "overlap") if trial % 2 == 0 else ("overlap", "serial") - for mode in modes: - key, next_key = uuid.uuid4().hex, uuid.uuid4().hex - first = await generate(args.source, prompt, {"libra_offload_key": key}) - descriptor = first["kv_transfer_params"] - returned_at = time.time() - after_generation = time.perf_counter() - if mode == "serial": - status, wait_ms = await ready(key, descriptor["source_tp"]) - await asyncio.sleep(delay / 1000) # synthetic asynchronous tool - if mode == "overlap": - status, wait_ms = await ready(key, descriptor["source_tp"]) - continuation = prompt + first["choices"][0]["text"] + "\nTool result: correct. Continue:" - decode_start = time.perf_counter() - loaded = await generate(args.target, continuation, { - "libra_load_key": key, "libra_offload_key": next_key, - }) - decode_ms = (time.perf_counter() - decode_start) * 1000 - elapsed = (time.perf_counter() - after_generation) * 1000 - # Drain the target's next-turn export before timing an - # independent recomputation baseline, otherwise its - # post-completion DMA would inflate baseline latency. - target_descriptor = loaded.get("kv_transfer_params", {}) - if target_descriptor.get("libra_offload_key"): - await ready(next_key, target_descriptor["source_tp"]) - baseline_start = time.perf_counter() - baseline = await generate(args.target, continuation) - baseline_ms = (time.perf_counter() - baseline_start) * 1000 - match = loaded["choices"][0]["text"] == baseline["choices"][0]["text"] - loaded_tokens = loaded.get("kv_transfer_params", {}).get("libra_imported_tokens", 0) - row = { - "words": words, "tool_ms": delay, "trial": trial, "mode": mode, - "cached_tokens": descriptor["cached_tokens"], "loaded_tokens": loaded_tokens, - "wait_ms": wait_ms, "resume_ms": decode_ms, "recompute_ms": baseline_ms, - "after_generation_ms": elapsed, "output_matches_recompute": match, - "completion_returned_at": returned_at, "workers": status["workers"], - } - rows.append(row) - print(json.dumps(row), flush=True) - Path(args.output).write_text(json.dumps({"rows": rows}, indent=2)) - for url, cache_key in ((args.source, key), (args.target, next_key)): - response = await client.delete(url + f"/libra/kv/{cache_key}") - response.raise_for_status() - if not match or not loaded_tokens: - raise AssertionError("KV continuation failed correctness/cache-hit check") - summaries = [] - for words in args.words: - for delay in args.tool_ms: - group = [row for row in rows if row["words"] == words and row["tool_ms"] == delay] - summary = {"words": words, "tool_ms": delay} - for mode in ("serial", "overlap"): - mode_rows = [row for row in group if row["mode"] == mode] - for metric in ("wait_ms", "resume_ms", "recompute_ms", "after_generation_ms"): - summary[mode + "_" + metric] = statistics.median(row[metric] for row in mode_rows) - summaries.append(summary) - smoke = await engine_smoke(args) if args.source_tp != args.target_tp else None - Path(args.output).write_text(json.dumps({"rows": rows, "summary": summaries, - "engine_smoke": smoke}, indent=2)) - print(json.dumps({"summary": summaries}, indent=2)) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--source", default="http://127.0.0.1:18910") - parser.add_argument("--target", default="http://127.0.0.1:18911") - parser.add_argument("--model", required=True) - parser.add_argument("--source-tp", type=int, default=1) - parser.add_argument("--target-tp", type=int, default=1) - parser.add_argument("--words", type=int, nargs="+", default=[256, 1024]) - parser.add_argument("--tool-ms", type=int, nargs="+", default=[0, 100, 500]) - parser.add_argument("--trials", type=int, default=3) - parser.add_argument("--output", required=True) - asyncio.run(main(parser.parse_args())) diff --git a/scripts/benchmark_scheduler_rl.slurm b/scripts/benchmark_scheduler_rl.slurm deleted file mode 100644 index 28a37b3..0000000 --- a/scripts/benchmark_scheduler_rl.slurm +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/bash -#SBATCH --job-name=libra_sched_rl -#SBATCH --partition=gpu -#SBATCH --nodes=1 -#SBATCH --gpus=4 -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=24 -#SBATCH --mem=180G -#SBATCH --time=02:00:00 -set -euo pipefail -cd /home-ssd/Users/nsgm_xu/kwchen/RL_Framework -export MODEL_PATH=/home-ssd/Users/nsgm_xu/kwchen/hf_models/Qwen3-4B -export PYTHONPATH=/home-ssd/Users/nsgm_xu/kwchen -exec /home-ssd/Users/nsgm_xu/rl_framework_env/bin/python3 scripts/run_scheduler_rl_comparison.py diff --git a/scripts/cleanup_slurm.sh b/scripts/cleanup_slurm.sh deleted file mode 100644 index 34a9b3b..0000000 --- a/scripts/cleanup_slurm.sh +++ /dev/null @@ -1,126 +0,0 @@ -#!/bin/bash -# ============================================================================= - -# - - -# - - - -# ============================================================================= - -CLEAN_GPU=false -if [ "$1" = "--gpu" ]; then - CLEAN_GPU=true -fi - -echo "=== Starting multi-node cleanup ===" - - -if [ -n "$SLURM_NODELIST" ]; then - mapfile -t NODES < <(scontrol show hostnames "$SLURM_NODELIST") - IS_SLURM=true - echo "Slurm environment, nodes: ${NODES[*]}" -else - NODES=("$(hostname)") - IS_SLURM=false - echo "Single-node mode: ${NODES[0]}" -fi - - -echo "" -echo "--- Stopping vLLM-related processes ---" - -if [ "$IS_SLURM" = true ]; then - for NODE in "${NODES[@]}"; do - echo " node $NODE: stopping vLLM/EngineCore processes..." - srun --overlap --nodes=1 --nodelist="$NODE" --ntasks=1 \ - bash -c ' - pkill -9 -f "vllm.entrypoints" 2>/dev/null || true - pkill -9 -f "vllm" 2>/dev/null || true - pkill -9 -f "EngineCore" 2>/dev/null || true - ' 2>/dev/null & - done - wait -else - pkill -9 -f "vllm.entrypoints" 2>/dev/null || true - pkill -9 -f "vllm" 2>/dev/null || true - pkill -9 -f "EngineCore" 2>/dev/null || true -fi - - -echo "" -echo "--- Stopping training processes ---" - -if [ "$IS_SLURM" = true ]; then - for NODE in "${NODES[@]}"; do - echo " node $NODE: stopping torchrun/training processes..." - srun --overlap --nodes=1 --nodelist="$NODE" --ntasks=1 \ - bash -c ' - pkill -9 -f "torch.distributed.run" 2>/dev/null || true - pkill -9 -f "torchrun" 2>/dev/null || true - pkill -9 -f "trainer.py" 2>/dev/null || true - pkill -9 -f "gsm8k_async_rl" 2>/dev/null || true - ' 2>/dev/null & - done - wait -else - pkill -9 -f "torch.distributed.run" 2>/dev/null || true - pkill -9 -f "torchrun" 2>/dev/null || true - pkill -9 -f "trainer.py" 2>/dev/null || true - pkill -9 -f "gsm8k_async_rl" 2>/dev/null || true -fi - -sleep 2 - - -if [ "$CLEAN_GPU" = true ]; then - echo "" - echo "--- Stopping processes using GPUs ---" - - if [ "$IS_SLURM" = true ]; then - for NODE in "${NODES[@]}"; do - echo " node $NODE: stopping GPU workloads..." - srun --overlap --nodes=1 --nodelist="$NODE" --ntasks=1 \ - bash -c ' - nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null | \ - awk "{print \$1}" | xargs -r kill -9 2>/dev/null || true - ' 2>/dev/null & - done - wait - else - nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null | \ - awk '{print $1}' | xargs -r kill -9 2>/dev/null || true - fi - - sleep 2 -fi - - -echo "" -echo "--- Checking for residual processes ---" - -if [ "$IS_SLURM" = true ]; then - for NODE in "${NODES[@]}"; do - REMAINING=$(srun --overlap --nodes=1 --nodelist="$NODE" --ntasks=1 \ - bash -c 'ps aux | grep -E "(vllm|trainer.py|EngineCore|torchrun)" | grep -v grep | wc -l' 2>/dev/null || echo "0") - REMAINING=$(echo "$REMAINING" | tr -d '[:space:]') - if [ "$REMAINING" -eq 0 ] 2>/dev/null; then - echo " node $NODE: all processes stopped" - else - echo " node $NODE: still has $REMAINING residual processes" - fi - done -else - REMAINING=$(ps aux | grep -E "(vllm|trainer.py|EngineCore|torchrun)" | grep -v grep | wc -l) - if [ "$REMAINING" -eq 0 ]; then - echo " all processes stopped" - else - echo " still has $REMAINING residual processes:" - ps aux | grep -E "(vllm|trainer.py|EngineCore|torchrun)" | grep -v grep - fi -fi - -echo "" -echo "=== Cleanup complete ===" diff --git a/scripts/cleanup_zombie.sh b/scripts/cleanup_zombie.sh deleted file mode 100644 index 7bf1252..0000000 --- a/scripts/cleanup_zombie.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/bin/bash - - -echo "=== Starting residual-process cleanup ===" - - -echo "Stopping vLLM-related processes..." -pkill -9 -f "vllm" 2>/dev/null -pkill -9 -f "EngineCore" 2>/dev/null -pkill -9 -f "trainer.py" 2>/dev/null - -pkill -9 -f "torch.distributed.run" 2>/dev/null -pkill -9 -f "pilot.trainer" 2>/dev/null - -echo "Stopping torchrun-related processes..." -pkill -9 -f "torch.distributed.run" 2>/dev/null -pkill -9 -f "torchrun" 2>/dev/null - - -sleep 2 - - -echo "Checking GPU utilization..." -nvidia-smi --query-compute-apps=pid,process_name --format=csv,noheader 2>/dev/null -if [ $? -eq 0 ]; then - echo "Stopping processes using GPUs..." - nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null | \ - awk '{print $1}' | xargs -r kill -9 2>/dev/null -fi - - -sleep 2 - - -echo "=== Cleanup complete; current GPU status ===" -nvidia-smi --query-gpu=index,memory.used,memory.total --format=csv,noheader - - -echo "" -echo "=== Checking for residual processes ===" -REMAINING=$(ps aux | grep -E "(vllm|trainer.py|EngineCore)" | grep -v grep | wc -l) -if [ "$REMAINING" -eq 0 ]; then - echo "✓ All residual processes have been stopped" -else - echo "⚠ still has $REMAINING processes remain; inspect them manually:" - ps aux | grep -E "(vllm|trainer.py|EngineCore)" | grep -v grep -fi - -echo "" -echo "=== Cleanup complete ===" diff --git a/scripts/collect_r2e_grp_profile.py b/scripts/collect_r2e_grp_profile.py deleted file mode 100644 index 0846913..0000000 --- a/scripts/collect_r2e_grp_profile.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python3 -"""Collect real R2E-Gym length samples for startup GRP planning.""" - -from __future__ import annotations - -import argparse -import json -from pathlib import Path - -from transformers import AutoTokenizer - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.cost_model.startup_profile import ( - load_jsonl_rows, - load_profile_summary, - profile_jsonl_has_records, - profile_metadata_matches, - startup_profile_metadata, - summarize_length_profile, - write_profile_jsonl, - write_profile_summary, -) -from RL_Framework.workflow.r2e_gym_profile import build_r2e_gym_length_profile - - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--config", required=True, help="AsyncRL YAML config") - parser.add_argument("--dataset-jsonl", required=True, help="R2E-Gym index JSONL") - parser.add_argument("--output-jsonl", required=True, help="Planner history JSONL") - parser.add_argument("--summary-json", default="", help="Optional profile summary JSON") - parser.add_argument("--sample-size", type=int, default=0) - parser.add_argument("--strategy", default="") - parser.add_argument("--seed", type=int, default=None) - parser.add_argument("--samples-per-prompt", type=int, default=0) - parser.add_argument( - "--reuse-existing", - action="store_true", - help="Reuse an existing output JSONL when it already contains usable profile rows", - ) - parser.add_argument( - "--row-load-limit", - type=int, - default=0, - help="Optional cap on loaded dataset rows before sampling", - ) - return parser.parse_args() - - -def main() -> None: - args = parse_args() - config = AsyncRLConfig.from_yaml(args.config) - planner_cfg = config.global_resource_planner - - dataset_path = Path(args.dataset_jsonl) - if not dataset_path.exists(): - raise FileNotFoundError(f"R2E-Gym profile dataset not found: {dataset_path}") - - sample_size = ( - args.sample_size - if args.sample_size > 0 - else int(planner_cfg.startup_profile_sample_size) - ) - strategy = args.strategy or planner_cfg.startup_profile_strategy - seed = ( - int(args.seed) - if args.seed is not None - else int(planner_cfg.startup_profile_seed) - ) - samples_per_prompt = ( - args.samples_per_prompt - if args.samples_per_prompt > 0 - else int(planner_cfg.startup_profile_samples_per_prompt) - ) - - reuse_existing = args.reuse_existing or planner_cfg.startup_profile_reuse_existing - output_path = Path(args.output_jsonl) - summary_path = Path(args.summary_json) if args.summary_json else None - expected_metadata = startup_profile_metadata( - dataset_jsonl=dataset_path, - model_path=config.model_path, - tokenizer_path=( - config.tokenizer_path if config.tokenizer_path else config.model_path - ), - sample_size=sample_size, - strategy=strategy, - seed=seed, - samples_per_prompt=samples_per_prompt, - max_new_tokens=config.max_new_tokens, - max_seq_length=config.max_seq_length, - r2e_max_turns=config.r2e_max_turns, - r2e_max_prompt_tokens=config.r2e_max_prompt_tokens, - ) - if reuse_existing and profile_jsonl_has_records(output_path): - existing_summary = load_profile_summary(summary_path) if summary_path else None - if summary_path is None or existing_summary is None or profile_metadata_matches(existing_summary, expected_metadata): - records = load_jsonl_rows(output_path) - if records: - summary = summarize_length_profile(records) - summary.update(expected_metadata) - summary["reused"] = True - if summary_path: - write_profile_summary(summary, summary_path) - print( - "[R2EGRPProfile] " - f"reused records={summary['records']} " - f"input_mean={summary['input_len']['mean']:.1f} " - f"output_mean={summary['output_len']['mean']:.1f} " - f"output_max={summary['output_len']['max']:.0f} " - f"output={args.output_jsonl}" - ) - print(json.dumps(summary, ensure_ascii=False)) - return - - rows = load_jsonl_rows(dataset_path, limit=args.row_load_limit) - if not rows: - raise ValueError(f"No R2E-Gym rows loaded from {dataset_path}") - - tokenizer = AutoTokenizer.from_pretrained( - config.tokenizer_path if config.tokenizer_path else config.model_path, - trust_remote_code=True, - ) - if tokenizer.pad_token is None: - tokenizer.pad_token = tokenizer.eos_token - - records = build_r2e_gym_length_profile( - rows, - tokenizer=tokenizer, - sample_size=sample_size, - strategy=strategy, - seed=seed, - samples_per_prompt=samples_per_prompt, - max_turns=config.r2e_max_turns, - max_new_tokens=config.max_new_tokens, - max_seq_length=config.max_seq_length, - max_prompt_tokens=config.r2e_max_prompt_tokens or None, - ) - if not records: - raise ValueError("R2E-Gym startup profile produced no records") - - write_profile_jsonl(records, output_path) - summary = summarize_length_profile(records) - summary.update(expected_metadata) - if summary_path: - write_profile_summary(summary, summary_path) - print( - "[R2EGRPProfile] " - f"records={summary['records']} " - f"input_mean={summary['input_len']['mean']:.1f} " - f"output_mean={summary['output_len']['mean']:.1f} " - f"output_max={summary['output_len']['max']:.0f} " - f"output={args.output_jsonl}" - ) - print(json.dumps(summary, ensure_ascii=False)) - - -if __name__ == "__main__": - main() diff --git a/scripts/compare_dynarl_libra.py b/scripts/compare_dynarl_libra.py deleted file mode 100644 index c2e42d1..0000000 --- a/scripts/compare_dynarl_libra.py +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env python3 -"""Summarize RLinf/DynaRL logs and Libra direct-NCCL probe results.""" - -from __future__ import annotations - -import argparse -import json -from pathlib import Path -import re -import statistics -from typing import Any - - -ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]") -NUMBER_PATTERN = r"-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?" -METRIC_RE = re.compile(rf"([A-Za-z0-9_/.-]+)=({NUMBER_PATTERN})") -MIGRATION_RE = re.compile( - rf"nccl_build_cost=(?P{NUMBER_PATTERN})ms, " - rf"transfer_cost=(?P{NUMBER_PATTERN})ms, " - rf"update_model_cost=(?P{NUMBER_PATTERN})ms, " - rf"transfer_bytes=(?P{NUMBER_PATTERN})GB, " - rf"bandwidth=(?P{NUMBER_PATTERN}) GB/s" -) - - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser() - parser.add_argument("--dynarl-log", type=Path) - parser.add_argument("--static-log", type=Path) - parser.add_argument("--libra-result", type=Path) - parser.add_argument("--output", type=Path, required=True) - return parser.parse_args() - - -def _mean(values: list[float]) -> float | None: - return statistics.fmean(values) if values else None - - -def parse_rlinf_log(path: Path) -> dict[str, Any]: - text = ANSI_RE.sub("", path.read_text(encoding="utf-8", errors="replace")) - steps = [] - for line in text.splitlines(): - if "Global Step:" not in line or "step_time=" not in line: - continue - metrics = {name: float(value) for name, value in METRIC_RE.findall(line)} - if metrics: - steps.append(metrics) - - migrations = [] - for match in MIGRATION_RE.finditer(text): - migrations.append( - { - "nccl_build_ms": float(match.group("build")), - "transfer_ms": float(match.group("transfer")), - "update_model_ms": float(match.group("update")), - "transfer_gb": float(match.group("bytes")), - "bandwidth_gbps": float(match.group("bandwidth")), - } - ) - - warm_steps = steps[1:] if len(steps) > 1 else steps - return { - "path": str(path), - "num_steps": len(steps), - "steps": steps, - "warm_step_time_mean_s": _mean( - [step["step_time"] for step in warm_steps if "step_time" in step] - ), - "warm_sync_time_mean_s": _mean( - [ - step["sync_weights_time"] - for step in warm_steps - if "sync_weights_time" in step - ] - ), - "migrations": migrations, - "migration_transfer_mean_ms": _mean( - [migration["transfer_ms"] for migration in migrations] - ), - } - - -def parse_libra_result(path: Path) -> dict[str, Any]: - payload = json.loads(path.read_text(encoding="utf-8")) - rounds = payload.get("rounds") or [payload] - return { - "path": str(path), - "model": payload.get("model"), - "outputs_stable": payload.get("outputs_stable"), - "rounds": rounds, - "cold_reload_s": rounds[0].get("send_seconds"), - "steady_reload_s": rounds[-1].get("send_seconds"), - "steady_payload_gib_per_second": rounds[-1].get( - "payload_gib_per_second" - ), - } - - -def main() -> int: - args = parse_args() - result: dict[str, Any] = {} - if args.dynarl_log: - result["dynarl"] = parse_rlinf_log(args.dynarl_log) - if args.static_log: - result["rlinf_static"] = parse_rlinf_log(args.static_log) - if args.libra_result: - result["libra"] = parse_libra_result(args.libra_result) - - dynarl = result.get("dynarl", {}) - static = result.get("rlinf_static", {}) - dynarl_step = dynarl.get("warm_step_time_mean_s") - static_step = static.get("warm_step_time_mean_s") - if dynarl_step and static_step: - result["pilot_dynarl_vs_static_step_speedup"] = static_step / dynarl_step - - args.output.parent.mkdir(parents=True, exist_ok=True) - args.output.write_text(json.dumps(result, indent=2), encoding="utf-8") - print(json.dumps(result, indent=2)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/direct_nccl_qwen3_probe.py b/scripts/direct_nccl_qwen3_probe.py deleted file mode 100644 index ec97cd8..0000000 --- a/scripts/direct_nccl_qwen3_probe.py +++ /dev/null @@ -1,215 +0,0 @@ -#!/usr/bin/env python3 -"""End-to-end Megatron Bridge to two vLLM NCCL reload probe.""" - -from __future__ import annotations - -import argparse -import concurrent.futures -import hashlib -import json -import os -from pathlib import Path -import time -import urllib.error -import urllib.request - -import torch -import torch.distributed as dist - -from RL_Framework.engine.megatron_core_train_engine import MegatronCoreTrainEngine -from RL_Framework.infra.sync.nccl_weight_sync import NcclReloadSpec, send_weights - - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser() - parser.add_argument("--model", required=True) - parser.add_argument("--endpoints", required=True) - parser.add_argument("--served-model-name", default="qwen3-probe") - parser.add_argument("--transport-host", required=True) - parser.add_argument("--transport-port", type=int, default=29620) - parser.add_argument("--train-tp", type=int, default=1) - parser.add_argument("--train-ep", type=int, default=1) - parser.add_argument("--chunk-mb", type=int, default=256) - parser.add_argument("--repeats", type=int, default=1) - parser.add_argument("--output", required=True) - return parser.parse_args() - - -def post_json(url: str, payload: dict, timeout: float) -> dict: - request = urllib.request.Request( - url, - data=json.dumps(payload).encode("utf-8"), - headers={"Content-Type": "application/json"}, - method="POST", - ) - try: - with urllib.request.urlopen(request, timeout=timeout) as response: - return json.loads(response.read().decode("utf-8")) - except urllib.error.HTTPError as exc: - detail = exc.read().decode("utf-8", errors="replace") - raise RuntimeError(f"POST {url} returned HTTP {exc.code}: {detail}") from exc - - -def completion(endpoint: str, served_model_name: str) -> dict: - body = post_json( - f"{endpoint}/v1/completions", - { - "model": served_model_name, - "prompt": "Compute 17 * 19. The answer is", - "max_tokens": 8, - "temperature": 0.0, - }, - 120.0, - ) - text = body["choices"][0]["text"] - return { - "text": text, - "sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), - } - - -def main() -> int: - args = parse_args() - rank = int(os.environ.get("RANK", "0")) - world_size = int(os.environ.get("WORLD_SIZE", "1")) - endpoints = [value.rstrip("/") for value in args.endpoints.split(",")] - if len(endpoints) != 2: - raise ValueError("The probe requires exactly two vLLM endpoints") - if world_size != args.train_tp: - raise ValueError("torchrun world size must equal --train-tp") - - engine = MegatronCoreTrainEngine( - model_path=args.model, - train_tp_size=args.train_tp, - train_ep_size=args.train_ep, - expert_tensor_parallel_size=1, - sequence_parallel=args.train_tp > 1, - use_distributed_optimizer=False, - streaming_export=True, - use_transformer_engine=False, - use_cpu_initialization=False, - ) - engine.initialize(max_seq_length=512, initialize_optimizer=False) - if dist.is_initialized(): - dist.barrier() - - if args.repeats <= 0: - raise ValueError("--repeats must be positive") - before = None - rounds = [] - transport_keepalive: list[object] = [] - if rank == 0: - before = { - endpoint: completion(endpoint, args.served_model_name) - for endpoint in endpoints - } - for round_index in range(args.repeats): - futures = None - executor = None - if rank == 0: - executor = concurrent.futures.ThreadPoolExecutor(max_workers=2) - futures = { - endpoint: executor.submit( - post_json, - f"{endpoint}/reload_weights_nccl", - { - "host": args.transport_host, - "port": args.transport_port, - "world_size": 3, - "rank_offset": index, - "timeout_seconds": 1800.0, - "chunk_bytes": args.chunk_mb * 1024 * 1024, - }, - 1810.0, - ) - for index, endpoint in enumerate(endpoints) - } - if dist.is_initialized(): - dist.barrier() - weights = engine.stream_rollout_weights() - started = time.perf_counter() - tensor_count = 0 - transferred_bytes = 0 - if rank == 0: - def record_tensor(_name: str, size_bytes: int) -> None: - nonlocal transferred_bytes - transferred_bytes += size_bytes - - tensor_count = send_weights( - weights, - NcclReloadSpec( - host=args.transport_host, - port=args.transport_port, - world_size=3, - rank=0, - device=torch.cuda.current_device(), - timeout_s=1800.0, - chunk_bytes=args.chunk_mb * 1024 * 1024, - ), - on_tensor=record_tensor, - keepalive=transport_keepalive, - ) - else: - for _name, tensor in weights: - del tensor - if dist.is_initialized(): - dist.barrier() - if rank == 0: - send_finished = time.perf_counter() - responses = { - endpoint: future.result() - for endpoint, future in futures.items() - } - executor.shutdown(wait=True) - transport_keepalive.clear() - after = { - endpoint: completion(endpoint, args.served_model_name) - for endpoint in endpoints - } - total_seconds = time.perf_counter() - started - rounds.append( - { - "round": round_index + 1, - "tensor_count": tensor_count, - "transferred_bytes": transferred_bytes, - "fanout_bytes": transferred_bytes * 2, - "total_seconds": total_seconds, - "send_seconds": send_finished - started, - "payload_gib_per_second": ( - transferred_bytes - / (1024**3) - / total_seconds - ), - "after": after, - "responses": responses, - } - ) - if rank == 0: - final_round = rounds[-1] - payload = { - "model": args.model, - "train_tp": args.train_tp, - "train_ep": args.train_ep, - "repeats": args.repeats, - "tensor_count": final_round["tensor_count"], - "transferred_bytes": final_round["transferred_bytes"], - "fanout_bytes": final_round["fanout_bytes"], - "total_seconds": final_round["total_seconds"], - "send_seconds": final_round["send_seconds"], - "payload_gib_per_second": final_round["payload_gib_per_second"], - "before": before, - "after": final_round["after"], - "outputs_stable": all( - before == round_result["after"] for round_result in rounds - ), - "rounds": rounds, - } - output = Path(args.output) - output.parent.mkdir(parents=True, exist_ok=True) - output.write_text(json.dumps(payload, indent=2), encoding="utf-8") - print(json.dumps(payload, indent=2), flush=True) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/elastic_hybrid_controller.py b/scripts/elastic_hybrid_controller.py deleted file mode 100644 index d67a919..0000000 --- a/scripts/elastic_hybrid_controller.py +++ /dev/null @@ -1,194 +0,0 @@ -#!/usr/bin/env python3 -"""Jump-host controller for remote project-owned elastic hybrid workers. - -Training ranks create ``.launch_.json`` requests in the shared task -directory. This controller consumes them, launches the worker through the -existing password-authenticated internal SSH helper, and records the remote -PID. A ``.stop_.json`` request terminates only the recorded worker. -""" - -from __future__ import annotations - -import argparse -import json -import os -import re -import signal -import shlex -import subprocess -import time -from pathlib import Path - - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser() - parser.add_argument("--task-dir", required=True, type=Path) - parser.add_argument("--project-dir", default="/opt/libra/RL_Framework_NPU") - parser.add_argument("--poll-interval", type=float, default=0.5) - return parser.parse_args() - - -def _read_json(path: Path) -> dict: - return json.loads(path.read_text(encoding="utf-8")) - - -def _write_json(path: Path, payload: dict) -> None: - tmp = path.with_suffix(path.suffix + ".tmp") - tmp.write_text(json.dumps(payload, sort_keys=True), encoding="utf-8") - tmp.replace(path) - - -def _remote_stop_code(pid): - """Terminate the owned session and verify no live worker descendants remain.""" - return f"""import os, signal, time -pid = {int(pid)} -def live(): - result = [] - for entry in os.listdir('/proc'): - if not entry.isdigit(): - continue - try: - fields = open('/proc/' + entry + '/stat').read().rsplit(')', 1)[1].split() - if (int(fields[2]) == pid or int(entry) == pid) and fields[0] != 'Z': - result.append(int(entry)) - except (FileNotFoundError, ProcessLookupError, PermissionError): - pass - return result -for sig in (signal.SIGTERM, signal.SIGKILL): - for owned in live(): - try: os.kill(owned, sig) - except ProcessLookupError: pass - deadline = time.monotonic() + 10 - while live() and time.monotonic() < deadline: - time.sleep(.1) - if not live(): - break -if live(): - raise RuntimeError('owned worker session still alive') -""" - - -class Controller: - def __init__(self, args: argparse.Namespace): - self.args = args - self.task_dir = args.task_dir - self.task_dir.mkdir(parents=True, exist_ok=True) - self.stopped = False - self.remote_pids: dict[str, tuple[str, int]] = {} - - def stop(self, *_args) -> None: - self.stopped = True - - def run(self) -> None: - signal.signal(signal.SIGTERM, self.stop) - signal.signal(signal.SIGINT, self.stop) - while not self.stopped: - handled = self._handle_stop_requests() - handled |= self._handle_launch_requests() - if not handled: - time.sleep(self.args.poll_interval) - self._stop_all_workers() - - def _handle_launch_requests(self) -> bool: - handled = False - for pending in sorted(self.task_dir.glob(".launch_*.json")): - worker_id = pending.stem[len(".launch_") :] - running = pending.with_suffix(".running") - try: - pending.replace(running) - except OSError: - continue - handled = True - started = self.task_dir / f".launch_{worker_id}.started" - error = self.task_dir / f".launch_{worker_id}.error" - try: - request = _read_json(running) - host = str(request["host"]) - command = str(request["command"]) - log_path = self.task_dir / f"{worker_id}.controller.log" - remote_command = ( - f"nohup setsid sh -c {shlex.quote(command)} >{shlex.quote(str(log_path))} 2>&1 & echo $!" - ) - env = os.environ.copy() - env.setdefault("INTERNAL_SSH_TIMEOUT", "30") - helper = str(Path(self.args.project_dir) / "scripts" / "internal_ssh.sh") - proc = subprocess.run( - [helper, host, "--", remote_command], - env=env, - capture_output=True, - text=True, - timeout=45, - check=False, - ) - pids = re.findall(r"\b(\d+)\b", proc.stdout or "") - if proc.returncode != 0 or not pids: - raise RuntimeError( - f"internal ssh launch failed rc={proc.returncode}: " - f"{(proc.stderr or proc.stdout)[-500:]}" - ) - pid = int(pids[-1]) - self.remote_pids[worker_id] = (host, pid) - _write_json(started, {"worker_id": worker_id, "host": host, "pid": pid}) - except Exception as exc: - _write_json(error, {"worker_id": worker_id, "error": str(exc)}) - finally: - running.unlink(missing_ok=True) - return handled - - def _handle_stop_requests(self) -> bool: - handled = False - for request_path in sorted(self.task_dir.glob(".stop_*.json")): - worker_id = request_path.stem[len(".stop_") :] - running = request_path.with_suffix(".running") - try: - request_path.replace(running) - except FileNotFoundError: - continue - handled = True - request = _read_json(running) - request_id = request.get("request_id") - try: - # Withdraw launches that the controller has not claimed. - (self.task_dir / f".launch_{worker_id}.json").unlink(missing_ok=True) - record = self.remote_pids.get(worker_id) - if record is None: - started = self.task_dir / f".launch_{worker_id}.started" - if started.exists(): - raise RuntimeError("controller lost process ownership; refusing a stale PID") - host, pid = record if record is not None else (str(request.get("host", "")), -1) - if pid > 0: - helper = str(Path(self.args.project_dir) / "scripts" / "internal_ssh.sh") - code = _remote_stop_code(pid) - proc = subprocess.run( - [helper, host, "--", "python3 -c " + shlex.quote(code)], - env=os.environ.copy(), capture_output=True, text=True, - timeout=45, check=False, - ) - if proc.returncode != 0: - raise RuntimeError(f"remote worker did not exit rc={proc.returncode}: {proc.stderr[-500:]}") - self.remote_pids.pop(worker_id, None) - _write_json(self.task_dir / f".stop_{worker_id}.done", { - "worker_id": worker_id, "host": host, "pid": pid, - "request_id": request_id, "exited": True, "finished_at": time.time(), - }) - except Exception as exc: - _write_json(self.task_dir / f".stop_{worker_id}.error", { - "worker_id": worker_id, "request_id": request_id, "error": str(exc), - }) - finally: - running.unlink(missing_ok=True) - return handled - - def _stop_all_workers(self) -> None: - for worker_id in list(self.remote_pids): - path = self.task_dir / f".stop_{worker_id}.json" - _write_json(path, {"worker_id": worker_id}) - self._handle_stop_requests() - - -def main() -> None: - Controller(parse_args()).run() - - -if __name__ == "__main__": - main() diff --git a/scripts/install_megatron_core.sh b/scripts/install_megatron_core.sh deleted file mode 100644 index 5825595..0000000 --- a/scripts/install_megatron_core.sh +++ /dev/null @@ -1,71 +0,0 @@ -#!/bin/bash - -set -euo pipefail - -PROJECT_DIR="${PROJECT_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" -VENV_PATH="${VENV_PATH:-${HOME}/rl_framework_env/bin/activate}" -WHEELHOUSE="${MCORE_WHEELHOUSE:-$PROJECT_DIR/vendor/megatron}" -MCORE_ARCHIVE="${MEGATRON_CORE_ARCHIVE:-$WHEELHOUSE/megatron_core-0.14.0.tar.gz}" -BRIDGE_WHEEL="${MEGATRON_BRIDGE_WHEEL:-$WHEELHOUSE/megatron_bridge-0.2.0rc6-py3-none-any.whl}" -GROUPED_GEMM_ARCHIVE="${GROUPED_GEMM_ARCHIVE:-$WHEELHOUSE/grouped_gemm-1.1.4-with-cutlass.tar.gz}" -GROUPED_GEMM_WHEEL="${GROUPED_GEMM_WHEEL:-$WHEELHOUSE/grouped_gemm-1.1.4-cp312-cp312-linux_x86_64.whl}" - -source "$VENV_PATH" -export PYTHONPATH="$(dirname "$PROJECT_DIR"):${PYTHONPATH:-}" -if [ -f "$MCORE_ARCHIVE" ] && [ -f "$BRIDGE_WHEEL" ]; then - python -m pip install --no-index --no-build-isolation --no-deps \ - --find-links "$WHEELHOUSE" \ - "pybind11==2.13.6" \ - "$WHEELHOUSE/antlr4-python3-runtime-4.7.2.tar.gz" - # Bridge only uses OmegaConf's object/config APIs on this path. Keeping - # ANTLR 4.7.2 also preserves latex2sympy2 compatibility in math rewards. - python -m pip install --no-index --no-deps \ - --find-links "$WHEELHOUSE" \ - "omegaconf==2.3.0" \ - "hydra-core==1.3.2" \ - "accelerate==1.10.1" - python -m pip install --no-build-isolation --no-deps "$MCORE_ARCHIVE" - python -m pip install --no-deps "$BRIDGE_WHEEL" - if [ -f "$GROUPED_GEMM_WHEEL" ]; then - python -m pip install --no-deps "$GROUPED_GEMM_WHEEL" - elif [ -f "$GROUPED_GEMM_ARCHIVE" ]; then - if [ -f /opt/rh/gcc-toolset-11/enable ]; then - source /opt/rh/gcc-toolset-11/enable - fi - export CC="${CC:-gcc}" - export CXX="${CXX:-g++}" - export CUDAHOSTCXX="${CUDAHOSTCXX:-$CXX}" - TORCH_CUDA_ARCH_LIST="${TORCH_CUDA_ARCH_LIST:-8.0}" \ - MAX_JOBS="${MAX_JOBS:-1}" \ - python -m pip install --no-build-isolation --no-deps \ - "$GROUPED_GEMM_ARCHIVE" - fi -else - python -m pip install -r "$PROJECT_DIR/requirements-megatron.txt" - python -m pip install --no-deps "megatron-bridge==0.2.0rc6" -fi - -python - <<'PY' -import importlib.metadata as metadata - -expected = { - "megatron-core": "0.14.0", - "megatron-bridge": "0.2.0rc6", - "grouped-gemm": "1.1.4", -} -for package, version in expected.items(): - actual = metadata.version(package) - if actual != version: - raise RuntimeError(f"{package}: expected {version}, found {actual}") - print(f"{package}={actual}") - -from megatron.bridge.models.qwen.qwen3_moe_bridge import Qwen3MoEBridge -from megatron.core import dist_checkpointing -from RL_Framework.engine.megatron_core_attention import ( - TorchSDPADotProductAttention, -) - -print("Qwen3MoEBridge", Qwen3MoEBridge.__name__) -print("dist_checkpointing", dist_checkpointing.__name__) -print("attention", TorchSDPADotProductAttention.__name__) -PY diff --git a/scripts/materialize_6node48_config.py b/scripts/materialize_6node48_config.py deleted file mode 100644 index ce0cee5..0000000 --- a/scripts/materialize_6node48_config.py +++ /dev/null @@ -1,189 +0,0 @@ -#!/usr/bin/env python3 -"""Materialize a six-node config for an arbitrary idle-node placement.""" - -from __future__ import annotations - -import argparse -import os -from pathlib import Path - -import yaml - - -def _absolute_reference(value: object, source_dir: Path) -> object: - if not isinstance(value, str) or os.path.isabs(value): - return value - return str((source_dir / value).resolve()) - - -def _deep_merge(base: dict, override: dict) -> dict: - """Recursively merge config mappings without mutating either input.""" - merged = dict(base) - for key, value in override.items(): - if isinstance(value, dict) and isinstance(merged.get(key), dict): - merged[key] = _deep_merge(merged[key], value) - else: - merged[key] = value - return merged - - -def load_inherited_config(template: Path, seen: set[Path] | None = None) -> dict: - """Load a YAML config and flatten its recursive ``base_config`` chain. - - The production EHP and no-EHP arms intentionally inherit one common - training config. Materialization must therefore resolve inheritance before - rewriting node- and run-specific fields. - """ - template = template.resolve() - seen = set() if seen is None else set(seen) - if template in seen: - chain = " -> ".join(str(path) for path in [*seen, template]) - raise ValueError(f"cyclic base_config chain: {chain}") - seen.add(template) - - with template.open("r", encoding="utf-8") as handle: - raw = yaml.safe_load(handle) or {} - if not isinstance(raw, dict): - raise ValueError(f"configuration root must be a mapping: {template}") - - source_dir = template.parent - base_value = raw.pop("base_config", None) - base = {} - if base_value: - base_path = Path(_absolute_reference(base_value, source_dir)) - base = load_inherited_config(base_path, seen) - - # These references are resolved relative to the file that declares them, - # not relative to the eventual run directory containing effective_config. - for key in ("hardware_config", "model_arch_config"): - if key in raw: - raw[key] = _absolute_reference(raw[key], source_dir) - return _deep_merge(base, raw) - - -def materialize( - template: Path, - output: Path, - master_addr: str, - master_port: int, - rollout_hosts: list[str], - run_root: Path, - gradient_port: int, - model_path: str | None = None, -) -> None: - if not rollout_hosts or len(set(rollout_hosts)) != len(rollout_hosts): - raise ValueError("at least one distinct rollout host is required") - - config = load_inherited_config(template) - - if model_path: - config["model_path"] = model_path - - config["master_addr"] = master_addr - config["master_port"] = master_port - config["rollout_weight_sync_control_dir"] = str(run_root / "rollout_weight_sync") - config["sync_path"] = str(run_root / "weights") - config["log_dir"] = str(run_root / "logs") - config["history_output_dir"] = str(run_root / "history") - - rollout = config.setdefault("heterogeneous_rollout", {}) - rollout["vllm_host"] = rollout_hosts[0] - instances = rollout.get("instances") or [] - planner = config.setdefault("global_resource_planner", {}) - node_pattern = [int(tp) for tp in planner.get("rollout_node_tp_pattern", [])] - if not node_pattern: - raise ValueError("global_resource_planner.rollout_node_tp_pattern is required") - if any(tp <= 0 for tp in node_pattern) or sum(node_pattern) != 8: - raise ValueError( - "rollout_node_tp_pattern must contain positive TP degrees totaling 8 GPUs: " - f"{node_pattern}" - ) - expected_instances = len(rollout_hosts) * len(node_pattern) - if len(instances) != expected_instances: - raise ValueError( - "planned rollout instance count does not match the per-node pattern: " - f"instances={len(instances)} hosts={len(rollout_hosts)} " - f"pattern={node_pattern}" - ) - - legacy_suffixes = { - (1, 0): "short_tp1_0", - (1, 1): "short_tp1_1", - (2, 0): "medium_tp2", - (4, 0): "long_tp4", - } - for host_index, host in enumerate(rollout_hosts): - node_id = f"n{host.rsplit('.', 1)[-1]}" - device_offset = 0 - tp_occurrences: dict[int, int] = {} - start = host_index * len(node_pattern) - host_instances = instances[start:start + len(node_pattern)] - actual_pattern = [ - max(1, int(instance.get("tp", len(instance.get("gpus", [])) or 1))) - for instance in host_instances - ] - if actual_pattern != node_pattern: - raise ValueError( - f"rollout host {host} receives pattern {actual_pattern}, " - f"expected {node_pattern}" - ) - for local_index, (instance, tp) in enumerate(zip(host_instances, node_pattern)): - occurrence = tp_occurrences.get(tp, 0) - if node_pattern == [1, 1, 2, 4]: - suffix = legacy_suffixes[(tp, occurrence)] - else: - suffix = f"tp{tp}_{occurrence}" - tp_occurrences[tp] = occurrence + 1 - instance["host"] = host - instance["gpus"] = list(range(device_offset, device_offset + tp)) - instance["port"] = 8000 + local_index - instance["instance_id"] = f"{node_id}_{suffix}" - device_offset += tp - - scheduling = rollout.setdefault("scheduling", {}) - scheduling["cmlfq_tree_path"] = str(run_root / "cmlfq_tree.json") - scheduling["cmlfq_shared_load_dir"] = str(run_root / "cmlfq_shared_load") - - planner["gradient_server_public_host"] = master_addr - planner["gradient_server_port"] = gradient_port - if "hybrid_worker_task_dir" in planner: - planner["hybrid_worker_task_dir"] = str(run_root / "elastic_training_tasks") - if "hybrid_worker_remote_control_dir" in planner: - planner["hybrid_worker_remote_control_dir"] = str( - run_root / "elastic_training_tasks" - ) - planner["runtime_length_profile_enabled"] = True - planner["runtime_length_profile_jsonl"] = str( - run_root / "history" / "runtime_length_profile.jsonl" - ) - - output.parent.mkdir(parents=True, exist_ok=True) - with output.open("w", encoding="utf-8") as handle: - yaml.safe_dump(config, handle, sort_keys=False, allow_unicode=True) - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("--template", required=True, type=Path) - parser.add_argument("--output", required=True, type=Path) - parser.add_argument("--master-addr", required=True) - parser.add_argument("--master-port", required=True, type=int) - parser.add_argument("--rollout-host", action="append", required=True) - parser.add_argument("--run-root", required=True, type=Path) - parser.add_argument("--gradient-port", required=True, type=int) - parser.add_argument("--model-path") - args = parser.parse_args() - materialize( - template=args.template, - output=args.output, - master_addr=args.master_addr, - master_port=args.master_port, - rollout_hosts=args.rollout_host, - run_root=args.run_root, - gradient_port=args.gradient_port, - model_path=args.model_path, - ) - - -if __name__ == "__main__": - main() diff --git a/scripts/monitor_run_progress.sh b/scripts/monitor_run_progress.sh deleted file mode 100644 index 551d486..0000000 --- a/scripts/monitor_run_progress.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env bash -# Read-only progress monitor for a detached formal run. -set -u - -launcher_pid="${1:?usage: $0 LAUNCHER_PID RUN_DIR HISTORY_GLOB [INTERVAL]}" -run_dir="${2:?usage: $0 LAUNCHER_PID RUN_DIR HISTORY_GLOB [INTERVAL]}" -history_glob="${3:?usage: $0 LAUNCHER_PID RUN_DIR HISTORY_GLOB [INTERVAL]}" -interval="${4:-50}" - -while true; do - alive=0 - kill -0 "$launcher_pid" 2>/dev/null && alive=1 - history_files=() - while IFS= read -r path; do history_files+=("$path"); done < <( - compgen -G "$history_glob" || true - ) - steps=0 - if ((${#history_files[@]})); then - steps="$(wc -l "${history_files[@]}" | awk 'END {print $1 + 0}')" - fi - error_count="$(grep -h -E -c 'Traceback|RuntimeError|ERROR' \ - "$run_dir"/driver_node_*.log 2>/dev/null | awk '{sum += $1} END {print sum + 0}')" - last_grp="$(grep -h -E 'GlobalResourcePlanner.*step=' \ - "$run_dir"/driver_node_0.log 2>/dev/null | tail -n 1 || true)" - printf '%s alive=%s history_steps=%s errors=%s grp=%s\n' \ - "$(date '+%F %T')" "$alive" "$steps" "$error_count" "$last_grp" - if [[ "$alive" -eq 0 || "$steps" -ge 100 ]]; then - break - fi - sleep "$interval" -done diff --git a/scripts/nccl_allgather_preflight.py b/scripts/nccl_allgather_preflight.py deleted file mode 100644 index 416eb6d..0000000 --- a/scripts/nccl_allgather_preflight.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python3 -"""Cross-node NCCL all-gather health check used before FSDP startup.""" - -from __future__ import annotations - -import os -import time -from datetime import timedelta - -import torch -import torch.distributed as dist - - -def main() -> None: - local_rank = int(os.environ["LOCAL_RANK"]) - torch.cuda.set_device(local_rank) - device = torch.device("cuda", local_rank) - timeout = timedelta( - seconds=int(os.environ.get("NCCL_PREFLIGHT_TIMEOUT", "600")) - ) - try: - dist.init_process_group("nccl", device_id=device, timeout=timeout) - except TypeError: - dist.init_process_group("nccl", timeout=timeout) - - rank = dist.get_rank() - world_size = dist.get_world_size() - elements = int(os.environ.get("NCCL_PREFLIGHT_ELEMENTS", "16777216")) - iterations = int(os.environ.get("NCCL_PREFLIGHT_ITERATIONS", "3")) - source = torch.full( - (elements,), rank, dtype=torch.bfloat16, device=device - ) - gathered = torch.empty( - (world_size * elements,), dtype=torch.bfloat16, device=device - ) - - dist.all_gather_into_tensor(gathered, source) - torch.cuda.synchronize(device) - dist.barrier() - started = time.perf_counter() - for _ in range(iterations): - dist.all_gather_into_tensor(gathered, source) - torch.cuda.synchronize(device) - elapsed = time.perf_counter() - started - - expected = torch.arange(world_size, dtype=torch.bfloat16, device=device) - observed = gathered[::elements] - if not torch.equal(observed, expected): - raise RuntimeError( - f"NCCL all-gather data mismatch on rank {rank}: {observed.tolist()}" - ) - bytes_per_iteration = world_size * elements * source.element_size() - bandwidth_gib_s = bytes_per_iteration * iterations / elapsed / (1024 ** 3) - print( - f"[NCCL preflight] rank={rank}/{world_size} device={device} " - f"message_mib={source.nbytes / (1024 ** 2):.1f} " - f"elapsed_s={elapsed:.3f} effective_gib_s={bandwidth_gib_s:.2f}", - flush=True, - ) - dist.barrier() - dist.destroy_process_group() - - -if __name__ == "__main__": - main() diff --git a/scripts/nccl_membership_probe.py b/scripts/nccl_membership_probe.py deleted file mode 100644 index 9943f4b..0000000 --- a/scripts/nccl_membership_probe.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Exercise the production weight transport with one sender and eight receivers.""" -import argparse -import json -import os -import socket -import torch -from RL_Framework.infra.sync.nccl_weight_sync import NcclReloadSpec, send_weights, receive_weights - -parser = argparse.ArgumentParser() -parser.add_argument("--host", required=True) -parser.add_argument("--port", type=int, default=29731) -args = parser.parse_args() -rank = int(os.environ["SLURM_PROCID"]) -size = int(os.environ["SLURM_NTASKS"]) -torch.cuda.set_device(0) -spec = NcclReloadSpec(args.host, args.port, size, rank, "cuda:0", timeout_s=120, chunk_bytes=4096) -expected = torch.arange(32768, device="cuda:0", dtype=torch.float32) -# Reuse the communicator for two generations, as in real weight refreshes. -for version in range(2): - if rank == 0: - send_weights([("probe", expected + version)], spec) - else: - received = list(receive_weights(spec)) - assert len(received) == 1 and received[0][0] == "probe" - torch.testing.assert_close(received[0][1], expected + version, rtol=0, atol=0) - torch.cuda.synchronize() - print(json.dumps(dict(rank=rank, world_size=size, host=socket.gethostname(), version=version, verified=True)), flush=True) -# Keep the sender TCPStore alive until every receiver consumed the end marker. -from RL_Framework.infra.sync.nccl_weight_sync import _communicator -_communicator(spec).group.barrier() -# This standalone probe owns no persistent service. Avoid interpreter teardown -# racing vLLM's cached TCPStore/NCCL background threads after verification. -import sys -sys.stdout.flush() -sys.stderr.flush() -os._exit(0) diff --git a/scripts/run_distributed.sh b/scripts/run_distributed.sh deleted file mode 100644 index f5e55fa..0000000 --- a/scripts/run_distributed.sh +++ /dev/null @@ -1,208 +0,0 @@ -#!/bin/bash -# ============================================================================= - -# - - -# - - - -# ============================================================================= - -set -e - - -cd "$(dirname "$0")/.." - - -MODEL_PATH="/path/to/Qwen3-4B" -export WANDB_API_KEY="${WANDB_API_KEY:-}" - -TRAIN_GPUS="0,1" -ROLLOUT_GPUS="2,3" -TRAIN_NPROC=2 - - -VLLM_HOST="127.0.0.1" -VLLM_BASE_PORT=8000 -VLLM_TP_SIZE=1 -MAX_MODEL_LEN=2048 - - -MASTER_ADDR="localhost" -MASTER_PORT="29500" - - -LOG_DIR="/path/to/RL_Framework/logs" -mkdir -p "$LOG_DIR" -TIMESTAMP=$(date +%Y%m%d_%H%M%S) -TRAIN_LOG="$LOG_DIR/training_${TIMESTAMP}.log" - -# PYTHONPATH -export PYTHONPATH=/path/to/user:$PYTHONPATH -cd /path/to/user - - - -IFS=',' read -ra GPU_ARRAY <<< "$ROLLOUT_GPUS" -NUM_ROLLOUT_GPUS=${#GPU_ARRAY[@]} -NUM_INSTANCES=$((NUM_ROLLOUT_GPUS / VLLM_TP_SIZE)) - -if [ "$NUM_INSTANCES" -le 0 ]; then - echo "ERROR: GPU count ($NUM_ROLLOUT_GPUS) is insufficient to start a TP=$VLLM_TP_SIZE instance" - exit 1 -fi - -if [ $((NUM_ROLLOUT_GPUS % VLLM_TP_SIZE)) -ne 0 ]; then - echo "WARNING: GPU count($NUM_ROLLOUT_GPUS)is not divisible by TP($VLLM_TP_SIZE); extra GPUs will remain idle" -fi - -echo "==========================================" -echo "Multi-instance vLLM configuration summary" -echo "==========================================" -echo " Rollout GPUs: $ROLLOUT_GPUS ($NUM_ROLLOUT_GPUS )" -echo " TP size: $VLLM_TP_SIZE" -echo " Number of instances: $NUM_INSTANCES" -echo " Port range: ${VLLM_BASE_PORT}-$((VLLM_BASE_PORT + NUM_INSTANCES - 1))" -echo "" - - -echo "==========================================" -echo "[Stage 1] Cleaning residual processes" -echo "==========================================" -pkill -f "vllm.entrypoints" 2>/dev/null || true -sleep 2 -echo "Cleanup complete" - - -echo "" -echo "==========================================" -echo "[Stage 2] Starting $NUM_INSTANCES vLLM inference instances" -echo "==========================================" - -VLLM_PIDS=() - -for ((i=0; i "$VLLM_LOG" 2>&1 & - - VLLM_PIDS+=($!) - echo " PID: ${VLLM_PIDS[$i]}" -done - - -echo "${VLLM_PIDS[@]}" > "$LOG_DIR/.vllm_pids" - - -echo "" -echo "==========================================" -echo "[Stage 3] Waiting for all vLLM instances" -echo "==========================================" - -MAX_WAIT=300 -for ((i=0; i/dev/null; then - echo " ERROR: vLLMInstance $i exited, See log: $LOG_DIR/vllm_instance${i}_${TIMESTAMP}.log" - - for pid in "${VLLM_PIDS[@]}"; do - kill $pid 2>/dev/null || true - done - exit 1 - fi - - - if curl -s -o /dev/null -w "%{http_code}" "http://${VLLM_HOST}:${INSTANCE_PORT}/health" 2>/dev/null | grep -q "200"; then - echo " Instance $i is ready! (waited${ELAPSED}s)" - break - fi - - if [ $((ELAPSED % 30)) -eq 0 ] && [ $ELAPSED -gt 0 ]; then - echo " Waiting... (${ELAPSED}s)" - fi - - sleep 2 - ELAPSED=$((ELAPSED + 2)) - done - - if [ $ELAPSED -ge $MAX_WAIT ]; then - echo " ERROR: vLLMInstance $i startup timed out (${MAX_WAIT}s)" - for pid in "${VLLM_PIDS[@]}"; do - kill $pid 2>/dev/null || true - done - exit 1 - fi -done - -echo "All $NUM_INSTANCES vLLM instances are ready!" - - -echo "" -echo "==========================================" -echo "[Stage 4] Starting FSDP training" -echo "==========================================" -echo " Training GPUs: $TRAIN_GPUS" -echo " Processes: $TRAIN_NPROC" -echo " Log: $TRAIN_LOG" - -CUDA_VISIBLE_DEVICES=$TRAIN_GPUS \ -MASTER_ADDR=$MASTER_ADDR \ -MASTER_PORT=$MASTER_PORT \ -nohup torchrun \ - --nproc_per_node=$TRAIN_NPROC \ - --master_addr=$MASTER_ADDR \ - --master_port=$MASTER_PORT \ - RL_Framework/examples/gsm8k_async_rl.py "$@" \ - > "$TRAIN_LOG" 2>&1 & - -TRAIN_PID=$! -echo " PID: $TRAIN_PID" -echo "$TRAIN_PID" > "$LOG_DIR/.train_pid" - - -echo "" -echo "==========================================" -echo "All services started" -echo "==========================================" -echo " vLLM instances: $NUM_INSTANCES" -for ((i=0; i Training (FSDP) - - - - -# - - -# ============================================================================= - -set -e - - -cd "$(dirname "$0")/.." - - -MODEL_PATH="/path/to/Qwen3-4B" -export WANDB_API_KEY="${WANDB_API_KEY:-}" -export WANDB_MODE=offline -export TOKENIZERS_PARALLELISM=false -export CUDA_LAUNCH_BLOCKING=1 - -TRAIN_GPUS="0,1" -TRAIN_NPROC=2 - -# ============================================================================= - -# ============================================================================= - -if [ -n "$SLURM_NODELIST" ]; then - NODES=($(scontrol show hostnames "$SLURM_NODELIST")) -else - echo "WARNING: SLURM_NODELIST is not set; using localhost" - NODES=("$(hostname)") -fi - -NODE0=${NODES[0]} -NODE1=${NODES[1]:-$NODE0} - -echo "=========================================" -echo "Node information" -echo "=========================================" -echo " Node 0 (Master): $NODE0" -echo " Node 1 (Rollout): $NODE1" -echo "" - -# ============================================================================= - -# - - - -# ============================================================================= -HETERO_INSTANCES=( - "tp1_inst0:1:2:0" # Node 0, GPU 2, TP=1 - "tp1_inst1:1:3:0" # Node 0, GPU 3, TP=1 - "tp2_inst0:2:0,1:1" # Node 1, GPU 0,1, TP=2 - "tp2_inst1:2:2,3:1" # Node 1, GPU 2,3, TP=2 -) - - -VLLM_HOST="0.0.0.0" -VLLM_BASE_PORT=8000 -MAX_MODEL_LEN=4096 -GPU_MEM_UTIL=0.90 - - -MASTER_ADDR="$NODE0" -MASTER_PORT="29500" - - -LOG_DIR="/path/to/RL_Framework/logs" -mkdir -p "$LOG_DIR" -TIMESTAMP=$(date +%Y%m%d_%H%M%S) -TRAIN_LOG="$LOG_DIR/training_hetero_${TIMESTAMP}.log" - -# PYTHONPATH -export PYTHONPATH=/path/to/user:$PYTHONPATH -cd /path/to/user - - - -PROCESSED_ARGS=() -while [[ $# -gt 0 ]]; do - case "$1" in - --config) - CONFIG_PATH="$2" - - if [[ "$CONFIG_PATH" != /* ]]; then - CONFIG_PATH="$(pwd)/$CONFIG_PATH" - fi - PROCESSED_ARGS+=("$1" "$CONFIG_PATH") - shift 2 - ;; - *) - PROCESSED_ARGS+=("$1") - shift - ;; - esac -done - - -NUM_INSTANCES=${#HETERO_INSTANCES[@]} - -echo "==========================================" -echo "Heterogeneous rollout cluster summary (multi-node)" -echo "==========================================" -echo " Training: Node 0 ($NODE0), GPU $TRAIN_GPUS (${TRAIN_NPROC} processes)" -echo " Rollout Number of instances: $NUM_INSTANCES" -echo "" - -for ((i=0; i/dev/null || true -sleep 2 -echo "Cleanup complete" - - -echo "" -echo "==========================================" -echo "[Stage 2] Starting $NUM_INSTANCES heterogeneous vLLM instances across nodes" -echo "==========================================" - -VLLM_PIDS=() -VLLM_HOSTS=() - -for ((i=0; i $VLLM_LOG 2>&1 & - PID=$! - else - - - - GPU_COUNT=$(echo "$INST_GPUS" | tr ',' '\n' | wc -l) - echo " remote node $INST_NODE starting instance $i ($INST_NAME), GPU=$INST_GPUS, gres=gpu:$GPU_COUNT" - - srun --exact --nodelist="$INST_NODE" --nodes=1 --ntasks=1 -c 16 \ - -G $GPU_COUNT \ - --export=ALL,CUDA_VISIBLE_DEVICES=$INST_GPUS,MASTER_ADDR=127.0.0.1,MASTER_PORT=$((20000 + i)),TOKENIZERS_PARALLELISM=false \ - python3 -m vllm.entrypoints.openai.api_server \ - --model $MODEL_PATH \ - --host $VLLM_HOST \ - --port $INST_PORT \ - --tensor-parallel-size $INST_TP \ - --max-model-len $MAX_MODEL_LEN \ - --dtype float16 \ - --gpu-memory-utilization $GPU_MEM_UTIL \ - --enforce-eager \ - --trust-remote-code \ - --disable-custom-all-reduce \ - > $VLLM_LOG 2>&1 & - - PID=$! - fi - - VLLM_PIDS+=($PID) - echo " PID: $PID, Log: $VLLM_LOG" - - - - if [ "$INST_NODE" != "$(hostname)" ] && [ "$INST_NODE_IDX" != "0" ]; then - echo " Waiting for remote instance $INST_NAME before continuing..." - WAIT_ELAPSED=0 - while [ $WAIT_ELAPSED -lt 300 ]; do - if ! kill -0 $PID 2>/dev/null; then - echo " ERROR: Instance $INST_NAME (node $INST_NODE) exited!" - echo " See log: $VLLM_LOG" - exit 1 - fi - if curl -s -o /dev/null -w "%{http_code}" "http://${INST_NODE}:${INST_PORT}/health" 2>/dev/null | grep -q "200"; then - echo " Remote instance $INST_NAME is ready!" - break - fi - if [ $((WAIT_ELAPSED % 30)) -eq 0 ] && [ $WAIT_ELAPSED -gt 0 ]; then - echo " Waiting... (${WAIT_ELAPSED}s)" - fi - sleep 2 - WAIT_ELAPSED=$((WAIT_ELAPSED + 2)) - done - if [ $WAIT_ELAPSED -ge 300 ]; then - echo " ERROR: Remote instance $INST_NAME startup timed out" - exit 1 - fi - fi -done - - -echo "${VLLM_PIDS[@]}" > "$LOG_DIR/.vllm_pids_hetero" - - -echo "" -echo "==========================================" -echo "[Stage 3] Waiting for all heterogeneous vLLM instances" -echo "==========================================" - -MAX_WAIT=300 -for ((i=0; i/dev/null; then - if [ "$INST_NODE" = "$(hostname)" ]; then - echo " ERROR: Instance $INST_NAME exited!" - else - echo " ERROR: Instance $INST_NAME (node $INST_NODE) exited!" - fi - echo " See log: $LOG_DIR/vllm_${INST_NAME}_${TIMESTAMP}.log" - exit 1 - fi - - - if curl -s -o /dev/null -w "%{http_code}" "http://${INST_NODE}:${INST_PORT}/health" 2>/dev/null | grep -q "200"; then - echo " Instance $INST_NAME is ready! (waited${ELAPSED}s)" - break - fi - - if [ $((ELAPSED % 30)) -eq 0 ] && [ $ELAPSED -gt 0 ]; then - echo " Waiting... (${ELAPSED}s)" - fi - - sleep 2 - ELAPSED=$((ELAPSED + 2)) - done - - if [ $ELAPSED -ge $MAX_WAIT ]; then - echo " ERROR: Instance $INST_NAME startup timed out (${MAX_WAIT}s)" - exit 1 - fi -done - -echo "" -echo "All $NUM_INSTANCES heterogeneous vLLM instancesis ready!" -echo " TP layout: $(for inst in "${HETERO_INSTANCES[@]}"; do IFS=':' read -r _ tp _ _ <<< "$inst"; printf "%s " "$tp"; done)" - - -echo "" -echo "==========================================" -echo "[Stage 4] Starting FSDP training (Node 0: $NODE0)" -echo "==========================================" -echo " Training GPUs: $TRAIN_GPUS" -echo " Processes: $TRAIN_NPROC" -echo " MASTER_ADDR: $MASTER_ADDR" -echo " Log: $TRAIN_LOG" - - -HETERO_INSTANCE_HOSTS="" -for ((i=0; i "$TRAIN_LOG" 2>&1 & - -TRAIN_PID=$! -echo " PID: $TRAIN_PID" -echo "$TRAIN_PID" > "$LOG_DIR/.train_pid_hetero" - - -echo "" -echo "==========================================" -echo "Heterogeneous cluster started across nodes" -echo "==========================================" -echo "" -echo " node: $NODE0 (Master), $NODE1 (Rollout)" -echo " Heterogeneous vLLM instances:" -for ((i=0; i/dev/null || true -sleep 2 -echo "Cleanup complete" - - -echo "" -echo "==========================================" -echo "[Stage 2] Starting $NUM_INSTANCES heterogeneous vLLM instances" -echo "==========================================" - -VLLM_PIDS=() - -for ((i=0; i "$VLLM_LOG" 2>&1 & - - VLLM_PIDS+=($!) - echo " PID: ${VLLM_PIDS[$i]}, Log: $VLLM_LOG" -done - - -echo "${VLLM_PIDS[@]}" > "$LOG_DIR/.vllm_pids_hetero" - - -echo "" -echo "==========================================" -echo "[Stage 3] Waiting for all heterogeneous vLLM instances" -echo "==========================================" - -MAX_WAIT=300 -for ((i=0; i/dev/null; then - echo " ERROR: Instance $INST_NAME exited!" - echo " See log: $LOG_DIR/vllm_${INST_NAME}_${TIMESTAMP}.log" - for pid in "${VLLM_PIDS[@]}"; do - kill $pid 2>/dev/null || true - done - exit 1 - fi - - - if curl -s -o /dev/null -w "%{http_code}" "http://${VLLM_HOST}:${INST_PORT}/health" 2>/dev/null | grep -q "200"; then - echo " Instance $INST_NAME is ready! (waited${ELAPSED}s)" - break - fi - - if [ $((ELAPSED % 30)) -eq 0 ] && [ $ELAPSED -gt 0 ]; then - echo " Waiting... (${ELAPSED}s)" - fi - - sleep 2 - ELAPSED=$((ELAPSED + 2)) - done - - if [ $ELAPSED -ge $MAX_WAIT ]; then - echo " ERROR: Instance $INST_NAME startup timed out (${MAX_WAIT}s)" - for pid in "${VLLM_PIDS[@]}"; do - kill $pid 2>/dev/null || true - done - exit 1 - fi -done - -echo "" -echo "All $NUM_INSTANCES heterogeneous vLLM instancesis ready!" -echo " TP layout: $(for inst in "${HETERO_INSTANCES[@]}"; do IFS=':' read -r _ tp _ <<< "$inst"; printf "%s " "$tp"; done)" - - - -HETERO_INSTANCE_HOSTS="" -for ((i=0; i "$TRAIN_LOG" 2>&1 & - -TRAIN_PID=$! -echo " PID: $TRAIN_PID" -echo "$TRAIN_PID" > "$LOG_DIR/.train_pid_hetero" - - -echo "" -echo "==========================================" -echo "Heterogeneous cluster started" -echo "==========================================" -echo "" -echo " Heterogeneous vLLM instances:" -for ((i=0; i/dev/null || true - pkill -9 -f "EngineCore" 2>/dev/null || true - ' 2>/dev/null & - done - wait - sleep 3 - - - INSTANCE_ID=0 - for ((n=0; n/dev/null); [ -n \"\$pids\" ] && echo \"\$pids\" | xargs kill -9 2>/dev/null || true" 2>/dev/null & - INSTANCE_ID=$((INSTANCE_ID + 1)) - done - done - wait -else - - pkill -9 -f "vllm.entrypoints" 2>/dev/null || true - sleep 2 -fi - -sleep 2 -echo "Cleanup complete" - - -echo "" -echo "==========================================" -echo "[Stage 2] Starting $TOTAL_ROLLOUT_INSTANCES vLLM inference instances" -echo "==========================================" - -WORK_DIR="$(pwd)" -VLLM_PIDS=() -INSTANCE_GLOBAL_ID=0 - -for ((n=0; n ${VLLM_LOG} 2>&1" & - else - - CUDA_VISIBLE_DEVICES=$INSTANCE_GPUS nohup python3 -m vllm.entrypoints.openai.api_server \ - --model "$MODEL_PATH" \ - --host 0.0.0.0 \ - --port "$PORT" \ - --tensor-parallel-size "$VLLM_TP_SIZE" \ - --max-model-len "$MAX_MODEL_LEN" \ - --dtype bfloat16 \ - --gpu-memory-utilization "$GPU_MEM_UTIL" \ - --enforce-eager \ - --trust-remote-code \ - > "$VLLM_LOG" 2>&1 & - fi - - VLLM_PIDS+=($!) - INSTANCE_GLOBAL_ID=$((INSTANCE_GLOBAL_ID + 1)) - done -done - -echo " Started ${#VLLM_PIDS[@]} vLLM instances" -echo "${VLLM_PIDS[@]}" > "$LOG_DIR/.vllm_pids_${TIMESTAMP}" - - -echo "" -echo "==========================================" -echo "[Stage 3] Waiting for all vLLM instances" -echo "==========================================" - -IFS=',' read -ra EP_ARRAY <<< "$VLLM_ENDPOINTS" - -for ((idx=0; idx<${#EP_ARRAY[@]}; idx++)); do - EP="${EP_ARRAY[$idx]}" - HOST_PART=$(echo "$EP" | cut -d: -f1) - PORT_PART=$(echo "$EP" | cut -d: -f2) - ELAPSED=0 - - echo " Waiting for instance $idx ($EP)..." - - while [ $ELAPSED -lt $MAX_WAIT ]; do - - if curl -s -o /dev/null -w "%{http_code}" "http://${EP}/health" 2>/dev/null | grep -q "200"; then - echo " Instance $idx ($EP) is ready! (${ELAPSED}s)" - break - fi - - if [ $((ELAPSED % 30)) -eq 0 ] && [ $ELAPSED -gt 0 ]; then - echo " Waiting... (${ELAPSED}s)" - fi - - sleep 5 - ELAPSED=$((ELAPSED + 5)) - done - - if [ $ELAPSED -ge $MAX_WAIT ]; then - echo " ERROR: Instance $idx ($EP) startup timed out (${MAX_WAIT}s)" - echo " See log: $LOG_DIR/vllm_*_${TIMESTAMP}.log" - - bash scripts/cleanup_slurm.sh 2>/dev/null || true - exit 1 - fi -done - -echo "All $TOTAL_ROLLOUT_INSTANCES vLLM instancesis ready!" - - -echo "" -echo "==========================================" -echo "[Stage 4] Starting multi-node FSDP training" -echo "==========================================" - - -TRAIN_GPU_IDS="" -for ((g=0; g ${NODE_TRAIN_LOG} 2>&1" & - - NODE_RANK=$((NODE_RANK + 1)) - done - - TRAIN_PID=$! - echo " Multi-node training started (last node PID: $TRAIN_PID)" -else - - CUDA_VISIBLE_DEVICES=$TRAIN_GPU_IDS \ - VLLM_ENDPOINTS="$VLLM_ENDPOINTS" \ - MASTER_ADDR=$HEAD_NODE \ - MASTER_PORT=$MASTER_PORT \ - nohup torchrun \ - --nproc_per_node=$TRAIN_GPUS_PER_NODE \ - --master_addr=$HEAD_NODE \ - --master_port=$MASTER_PORT \ - $TRAIN_SCRIPT $TRAIN_ARGS \ - > "$TRAIN_LOG" 2>&1 & - - TRAIN_PID=$! - echo " Single-node training PID: $TRAIN_PID" -fi - -echo "$TRAIN_PID" > "$LOG_DIR/.train_pid_${TIMESTAMP}" - - -echo "" -echo "==========================================" -echo "All services started!" -echo "==========================================" -echo " vLLM instances: $TOTAL_ROLLOUT_INSTANCES" -echo " vLLM endpoints: $VLLM_ENDPOINTS" -echo " Training nodes: $NUM_NODES" -echo " Training GPUs: $TOTAL_TRAIN_GPUS" -echo "" -echo "Log directory: $LOG_DIR" -echo " vLLM: $LOG_DIR/vllm_*_${TIMESTAMP}.log" -echo " Training: $LOG_DIR/training_*${TIMESTAMP}.log" -echo "" -echo "Stop all services:" -echo " bash scripts/cleanup_slurm.sh" -echo "" - - -wait $TRAIN_PID 2>/dev/null -TRAIN_EXIT_CODE=$? -echo "Training process exited with code: $TRAIN_EXIT_CODE" - - -echo "Stopping vLLM instances..." -bash scripts/cleanup_slurm.sh 2>/dev/null || true - -echo "Job complete! $(date)" -exit $TRAIN_EXIT_CODE diff --git a/scripts/scan_cluster_nodes.py b/scripts/scan_cluster_nodes.py deleted file mode 100644 index 0b73e77..0000000 --- a/scripts/scan_cluster_nodes.py +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env python3 -"""Read-only helper to identify SSH-reachable cluster nodes.""" - -from __future__ import annotations - -import argparse -import concurrent.futures -import functools -import socket - - -def probe(host: str, *, port: int, timeout: float) -> str | None: - try: - with socket.create_connection((host, port), timeout=timeout): - return host - except OSError: - return None - - -def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("hosts", nargs="+", help="hostnames or IP addresses to probe") - parser.add_argument("--port", type=int, default=22, help="SSH port") - parser.add_argument("--timeout", type=float, default=0.75) - parser.add_argument("--workers", type=int, default=32) - args = parser.parse_args() - - probe_host = functools.partial(probe, port=args.port, timeout=args.timeout) - with concurrent.futures.ThreadPoolExecutor(max_workers=args.workers) as executor: - reachable = [host for host in executor.map(probe_host, args.hosts) if host] - print("\n".join(reachable)) - - -if __name__ == "__main__": - main() diff --git a/scripts/start_formal_run_remote.sh b/scripts/start_formal_run_remote.sh deleted file mode 100644 index 0dbba54..0000000 --- a/scripts/start_formal_run_remote.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -run_name="${1:?usage: start_formal_run_remote.sh RUN_NAME MASTER_PORT}" -master_port="${2:?master port required}" -project_dir="${PROJECT_DIR:-/opt/libra/RL_Framework_NPU}" -run_root="${RUN_ROOT:-/opt/libra/runs/r2e_gym_qwen3_14b_6node48}" - -if [[ ! "${run_name}" =~ ^formal_[A-Za-z0-9_.-]+$ ]]; then - echo "invalid run name: ${run_name}" >&2 - exit 2 -fi -if [[ ! "${master_port}" =~ ^[0-9]+$ ]] || ((master_port < 1024 || master_port > 65535)); then - echo "invalid master port: ${master_port}" >&2 - exit 2 -fi - -run_dir="${run_root}/${run_name}" -launcher_log="${run_dir}_launcher.log" -mkdir -p "${run_root}" - -if [[ -e "${run_dir}" || -e "${launcher_log}" ]]; then - echo "refusing to overwrite existing run artifacts: ${run_dir}" >&2 - exit 3 -fi - -nohup env \ - NODE_PASSWORD="${NODE_PASSWORD:?set NODE_PASSWORD}" \ - INTERNAL_SSH_TIMEOUT="${INTERNAL_SSH_TIMEOUT:-30}" \ - RUN_NAME="${run_name}" \ - MASTER_PORT="${master_port}" \ - bash "${project_dir}/scripts/run_6node48_r2e_mcore_npu.sh" \ - >"${launcher_log}" 2>&1 "${run_root}/current_launcher_pid" -printf '%s\n' "${master_port}" >"${run_root}/current_master_port" -printf 'RUN_NAME=%s MASTER_PORT=%s LAUNCHER_PID=%s LAUNCHER_LOG=%s\n' \ - "${run_name}" "${master_port}" "${launcher_pid}" "${launcher_log}" diff --git a/scripts/stop_formal_run_remote.sh b/scripts/stop_formal_run_remote.sh deleted file mode 100644 index f900872..0000000 --- a/scripts/stop_formal_run_remote.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -launcher_pid="${1:?usage: stop_formal_run_remote.sh LAUNCHER_PID RUN_NAME}" -run_name="${2:?run name required}" -project_dir="${PROJECT_DIR:-/opt/libra/RL_Framework_NPU}" -run_root="${RUN_ROOT:-/opt/libra/runs/r2e_gym_qwen3_14b_6node48}" -remote_rollout_host="${REMOTE_ROLLOUT_HOST:-192.0.2.22}" -train_hosts=(192.0.2.10 192.0.2.11 192.0.2.12 192.0.2.13) -export INTERNAL_SSH_TIMEOUT="${INTERNAL_SSH_TIMEOUT:-30}" - -launcher_command="$(tr '\0' ' ' <"/proc/${launcher_pid}/cmdline" 2>/dev/null || true)" -run_dir="${run_root}/${run_name}" -if [[ -n "${launcher_command}" ]]; then - if [[ "${launcher_command}" != *"run_6node48_r2e_mcore_npu.sh"* ]]; then - echo "refusing to stop unverified live launcher pid=${launcher_pid}: ${launcher_command}" >&2 - exit 2 - fi -else - if [[ ! "${run_name}" =~ ^formal_[A-Za-z0-9_.-]+$ || ! -d "${run_dir}" ]]; then - echo "refusing orphan cleanup for unverified run=${run_name} run_dir=${run_dir}" >&2 - exit 2 - fi - echo "launcher pid=${launcher_pid} is gone; using verified run directory and exact JOB_ID cleanup" -fi - -remote_cleanup="target_job='${run_name}'; pids=(); for proc in /proc/[0-9]*; do [[ -r \"\$proc/environ\" ]] || continue; if tr '\\0' '\\n' <\"\$proc/environ\" 2>/dev/null | grep -Fxq \"JOB_ID=\$target_job\"; then pids+=(\"\${proc##*/}\"); fi; done; if ((\${#pids[@]})); then kill -TERM \"\${pids[@]}\" 2>/dev/null || true; sleep 8; for pid in \"\${pids[@]}\"; do kill -0 \"\$pid\" 2>/dev/null && kill -KILL \"\$pid\" 2>/dev/null || true; done; fi; printf 'job=%s cleaned_pids=%s\\n' \"\$target_job\" \"\${pids[*]:-none}\"" - -for host in "${train_hosts[@]}"; do - echo "cleaning training job on ${host}" - "${project_dir}/scripts/internal_ssh.sh" "${host}" -- "${remote_cleanup}" || true -done - -descendants=() -collect_descendants() { - local parent="$1" child - while read -r child; do - [[ -n "${child}" ]] || continue - collect_descendants "${child}" - descendants+=("${child}") - done < <(pgrep -P "${parent}" 2>/dev/null || true) -} -collect_descendants "${launcher_pid}" -if ((${#descendants[@]})); then - kill -TERM "${descendants[@]}" 2>/dev/null || true -fi -kill -TERM "${launcher_pid}" 2>/dev/null || true -sleep 5 -for pid in "${descendants[@]}" "${launcher_pid}"; do - kill -0 "${pid}" 2>/dev/null && kill -KILL "${pid}" 2>/dev/null || true -done - -RUN_ROOT="${run_root}" bash "${project_dir}/scripts/start_r2e_rollout_pool_npu.sh" stop rollout_a || true -ssh -o BatchMode=yes root@"${remote_rollout_host}" \ - "cd '${project_dir}' && RUN_ROOT='${run_root}' bash scripts/start_r2e_rollout_pool_npu.sh stop n17" || true - -echo "stopped run=${run_name} launcher_pid=${launcher_pid}" diff --git a/scripts/stop_verified_hybrid_worker.sh b/scripts/stop_verified_hybrid_worker.sh deleted file mode 100644 index 8b4f462..0000000 --- a/scripts/stop_verified_hybrid_worker.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env bash -# Stop only the exact stale worker from the prior validated run. -set -euo pipefail -pid="${1:?pid required}" -cmd="$(tr '\0' ' ' <"/proc/${pid}/cmdline" 2>/dev/null || true)" -case "$cmd" in - *elastic_hybrid_worker.py*"/opt/libra/runs/r2e_gym_qwen3_14b_6node48/elastic_training_state"*) - echo "verified pid=${pid}: ${cmd}" - kill -TERM "$pid" 2>/dev/null || true - for _ in $(seq 1 10); do - kill -0 "$pid" 2>/dev/null || exit 0 - sleep 1 - done - kill -KILL "$pid" 2>/dev/null || true - ;; - *) - echo "refusing unverified pid=${pid}: ${cmd}" >&2 - exit 2 - ;; -esac diff --git a/scripts/submit_dapo_math_cmlfq_train.slurm b/scripts/submit_dapo_math_cmlfq_train.slurm deleted file mode 100755 index eaf4d8e..0000000 --- a/scripts/submit_dapo_math_cmlfq_train.slurm +++ /dev/null @@ -1,264 +0,0 @@ -#!/bin/bash -#SBATCH -J dapo_math_cmlfq_train -#SBATCH -o logs/dapo_math_cmlfq_train_%j.out -#SBATCH -e logs/dapo_math_cmlfq_train_%j.err -#SBATCH -N 3 -#SBATCH -G 12 -#SBATCH --ntasks-per-node=2 -#SBATCH --cpus-per-task=16 -#SBATCH -p gpu -#SBATCH --time=72:00:00 -#SBATCH --exclude=gn019 - -set -euo pipefail - -PROJECT_DIR="${PROJECT_DIR:-/path/to/RL_Framework}" -VENV_PATH="${VENV_PATH:-/path/to/rl_framework_env/bin/activate}" -MODEL_PATH="${MODEL_PATH:-/path/to/Qwen3-4B}" -DAPO_MATH_ROOT="${DAPO_MATH_ROOT:-$PROJECT_DIR/data/DAPO-Math-17K}" -DAPO_MATH_SPLIT="${DAPO_MATH_SPLIT:-all}" -DAPO_MAX_TURNS="${DAPO_MAX_TURNS:-2}" -DAPO_MIN_ROWS="${DAPO_MIN_ROWS:-1000}" -TOTAL_STEPS="${TOTAL_STEPS:-1000}" -MAX_MODEL_LEN="${MAX_MODEL_LEN:-32768}" -MAX_NEW_TOKENS="${MAX_NEW_TOKENS:-32768}" -TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-16}" -TRAIN_MICRO_BATCH_SIZE="${TRAIN_MICRO_BATCH_SIZE:-1}" -EVAL_INTERVAL="${EVAL_INTERVAL:-100}" -EVAL_MAX_SAMPLES="${EVAL_MAX_SAMPLES:-0}" -EVAL_CONCURRENCY="${EVAL_CONCURRENCY:-16}" -EVAL_MAX_NEW_TOKENS="${EVAL_MAX_NEW_TOKENS:-32768}" -EVAL_ACCURACY_THRESHOLD="${EVAL_ACCURACY_THRESHOLD:-1.0}" -EVAL_WAIT_TIMEOUT="${EVAL_WAIT_TIMEOUT:-172800}" -GPU_MEMORY_UTILIZATION="${GPU_MEMORY_UTILIZATION:-0.90}" -VLLM_BASE_PORT="${VLLM_BASE_PORT:-8000}" -MASTER_PORT="${MASTER_PORT:-29500}" -MAX_WAIT="${MAX_WAIT:-900}" - -source "$VENV_PATH" -cd "$PROJECT_DIR" - -mkdir -p logs -JOB_ID="${SLURM_JOB_ID:-manual}" -JOB_LOG_DIR="$PROJECT_DIR/logs/dapo_math_cmlfq/job_${JOB_ID}" -mkdir -p "$JOB_LOG_DIR" - -export PYTHONPATH="$(dirname "$PROJECT_DIR"):${PYTHONPATH:-}" -export TOKENIZERS_PARALLELISM=false -export WANDB_MODE="${WANDB_MODE:-offline}" -export WANDB_DIR="${PROJECT_DIR}/wandb_dapo_math_cmlfq" -export NO_PROXY="localhost,127.0.0.1,${NO_PROXY:-}" -export NCCL_ASYNC_ERROR_HANDLING=1 -export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}" - -mapfile -t NODES < <(scontrol show hostnames "$SLURM_NODELIST") -if [ "${#NODES[@]}" -lt 3 ]; then - echo "ERROR: DAPO-Math C-MLFQ training requires 3 nodes; got ${#NODES[@]}" >&2 - exit 2 -fi - -TRAIN_NODE="${NODES[0]}" -ROLLOUT_NODE_A="${NODES[1]}" -ROLLOUT_NODE_B="${NODES[2]}" -MASTER_ADDR="$TRAIN_NODE" -RUNTIME_CONFIG="$PROJECT_DIR/configs/.dapo_math_cmlfq_${JOB_ID}.yaml" - -echo "============================================================" -echo "DAPO-Math-17K full RL post-training with C-MLFQ" -echo "============================================================" -echo "Job: $JOB_ID" -echo "Model: $MODEL_PATH" -echo "Data root: $DAPO_MATH_ROOT" -echo "Data split: $DAPO_MATH_SPLIT" -echo "Train node: $TRAIN_NODE (4 GPUs)" -echo "Rollout node A: $ROLLOUT_NODE_A (TP=4 long bucket)" -echo "Rollout node B: $ROLLOUT_NODE_B (2 x TP=2 short/medium buckets)" -echo "Total steps: $TOTAL_STEPS" -echo "Eval interval: $EVAL_INTERVAL" -echo "Eval samples: ${EVAL_MAX_SAMPLES:-0} (0 means all)" -echo "Logs: $JOB_LOG_DIR" -python3 -c 'import torch, transformers, vllm; print("torch", torch.__version__, "transformers", transformers.__version__, "vllm", vllm.__version__)' - -VLLM_STEP_PIDS=() -declare -A VLLM_PID_BY_NAME=() - -cleanup() { - local exit_code=$? - trap - EXIT INT TERM - echo "[cleanup] stopping vLLM processes..." - for pid in "${VLLM_STEP_PIDS[@]:-}"; do - kill "$pid" 2>/dev/null || true - done - for node in "$ROLLOUT_NODE_A" "$ROLLOUT_NODE_B"; do - for port in "$VLLM_BASE_PORT" "$((VLLM_BASE_PORT + 1))" "$((VLLM_BASE_PORT + 2))"; do - srun --overlap --nodes=1 --ntasks=1 --nodelist="$node" \ - bash -lc "pkill -f 'vllm.entrypoints.openai.api_server.*--port ${port}' 2>/dev/null || true" \ - >/dev/null 2>&1 || true - done - done - echo "[cleanup] complete, exit=$exit_code" - exit "$exit_code" -} -trap cleanup EXIT INT TERM - -echo "[1/7] Writing runtime config" -export PROJECT_DIR MODEL_PATH TOTAL_STEPS MAX_MODEL_LEN MAX_NEW_TOKENS EVAL_INTERVAL -export TRAIN_BATCH_SIZE TRAIN_MICRO_BATCH_SIZE VLLM_BASE_PORT GPU_MEMORY_UTILIZATION JOB_ID -python3 - <<'PY' -import os -from pathlib import Path - -import yaml - -project = Path(os.environ["PROJECT_DIR"]) -base = project / "configs" / "dapo_math_cmlfq_qwen3_4b.yaml" -config = { - "base_config": str(base), - "model_path": os.environ["MODEL_PATH"], - "tokenizer_path": os.environ["MODEL_PATH"], - "batch_size": int(os.environ["TRAIN_BATCH_SIZE"]), - "micro_batch_size": int(os.environ["TRAIN_MICRO_BATCH_SIZE"]), - "total_steps": int(os.environ["TOTAL_STEPS"]), - "eval_interval": int(os.environ["EVAL_INTERVAL"]), - "max_new_tokens": int(os.environ["MAX_NEW_TOKENS"]), - "max_seq_length": int(os.environ["MAX_MODEL_LEN"]), - "sync_path": str(project / "logs" / "dapo_math_cmlfq" / f"weights_{os.environ['JOB_ID']}"), - "log_dir": str(project / "logs" / "dapo_math_cmlfq"), - "wandb_run_name": f"dapo-math-cmlfq-{os.environ['JOB_ID']}", - "heterogeneous_rollout": { - "vllm_base_port": int(os.environ["VLLM_BASE_PORT"]), - "max_model_len": int(os.environ["MAX_MODEL_LEN"]), - "gpu_memory_utilization": float(os.environ["GPU_MEMORY_UTILIZATION"]), - "scheduling": { - "cmlfq_tree_path": str(project / "logs" / "dapo_math_cmlfq" / f"cmlfq_tree_{os.environ['JOB_ID']}.json") - }, - }, -} -path = project / "configs" / f".dapo_math_cmlfq_{os.environ['JOB_ID']}.yaml" -path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") -print(path) -PY - -echo "[2/7] Checking DAPO-Math data before reserving rollout services" -export DAPO_MATH_ROOT DAPO_MATH_SPLIT DAPO_MIN_ROWS -python3 examples/test_dapo_math_data.py - -start_vllm() { - local node="$1" - local tp="$2" - local port="$3" - local name="$4" - local log_file="$JOB_LOG_DIR/vllm_${name}.log" - echo "Starting $name on $node TP=$tp port=$port" - srun --exclusive \ - --nodes=1 --ntasks=1 --nodelist="$node" \ - --gpus="$tp" \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - export TOKENIZERS_PARALLELISM=false - export MASTER_ADDR=127.0.0.1 - export MASTER_PORT=$((20000 + port)) - python3 -m vllm.entrypoints.openai.api_server \ - --model '$MODEL_PATH' \ - --host 0.0.0.0 \ - --port '$port' \ - --tensor-parallel-size '$tp' \ - --max-model-len '$MAX_MODEL_LEN' \ - --dtype bfloat16 \ - --gpu-memory-utilization '$GPU_MEMORY_UTILIZATION' \ - --trust-remote-code \ - --enforce-eager \ - --disable-custom-all-reduce - " >"$log_file" 2>&1 & - VLLM_STEP_PIDS+=("$!") - VLLM_PID_BY_NAME["$name"]="$!" -} - -wait_for_health() { - local host="$1" - local port="$2" - local name="$3" - local elapsed=0 - local pid="${VLLM_PID_BY_NAME[$name]}" - while [ "$elapsed" -lt "$MAX_WAIT" ]; do - if curl -fsS "http://${host}:${port}/health" >/dev/null 2>&1; then - echo "READY: $name at $host:$port (${elapsed}s)" - return 0 - fi - if ! kill -0 "$pid" 2>/dev/null; then - echo "ERROR: $name exited before ready" >&2 - tail -120 "$JOB_LOG_DIR/vllm_${name}.log" || true - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - echo "ERROR: $name not ready after ${MAX_WAIT}s" >&2 - tail -120 "$JOB_LOG_DIR/vllm_${name}.log" || true - return 1 -} - -echo "[3/7] Starting heterogeneous rollout vLLM instances" -start_vllm "$ROLLOUT_NODE_A" 4 "$VLLM_BASE_PORT" "long_tp4" -start_vllm "$ROLLOUT_NODE_B" 2 "$((VLLM_BASE_PORT + 1))" "short_tp2_0" - -echo "[4/7] Waiting for initial rollout services" -wait_for_health "$ROLLOUT_NODE_A" "$VLLM_BASE_PORT" "long_tp4" -wait_for_health "$ROLLOUT_NODE_B" "$((VLLM_BASE_PORT + 1))" "short_tp2_0" - -start_vllm "$ROLLOUT_NODE_B" 2 "$((VLLM_BASE_PORT + 2))" "short_tp2_1" -wait_for_health "$ROLLOUT_NODE_B" "$((VLLM_BASE_PORT + 2))" "short_tp2_1" - -echo "[5/7] OpenAI-compatible API check" -curl -fsS "http://${ROLLOUT_NODE_A}:${VLLM_BASE_PORT}/v1/completions" \ - -H "Content-Type: application/json" \ - -d "{\"model\":\"$MODEL_PATH\",\"prompt\":\"Compute 1+1. Answer with the number only.\",\"max_tokens\":8,\"temperature\":0}" \ - | python3 -m json.tool - -export HETERO_INSTANCE_HOSTS="${ROLLOUT_NODE_A},${ROLLOUT_NODE_B},${ROLLOUT_NODE_B}" -export EVAL_MAX_SAMPLES="$EVAL_MAX_SAMPLES" -export EVAL_CONCURRENCY="$EVAL_CONCURRENCY" -export EVAL_MAX_NEW_TOKENS="$EVAL_MAX_NEW_TOKENS" -export EVAL_ACCURACY_THRESHOLD="$EVAL_ACCURACY_THRESHOLD" -export EVAL_WAIT_TIMEOUT="$EVAL_WAIT_TIMEOUT" -export EVAL_METRICS_FILE="${EVAL_METRICS_FILE:-eval_metrics.jsonl}" - -echo "[6/7] Starting full DAPO-Math AsyncRLTrainer run" -srun --exclusive \ - --nodes=1 --ntasks=1 --nodelist="$TRAIN_NODE" \ - --gpus=4 \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - cd '$PROJECT_DIR' - export PYTHONPATH='$(dirname "$PROJECT_DIR")':\${PYTHONPATH:-} - export HETERO_INSTANCE_HOSTS='$HETERO_INSTANCE_HOSTS' - export DAPO_MATH_ROOT='$DAPO_MATH_ROOT' - export DAPO_MATH_SPLIT='$DAPO_MATH_SPLIT' - export DAPO_MAX_TURNS='$DAPO_MAX_TURNS' - export EVAL_MAX_SAMPLES='$EVAL_MAX_SAMPLES' - export EVAL_CONCURRENCY='$EVAL_CONCURRENCY' - export EVAL_MAX_NEW_TOKENS='$EVAL_MAX_NEW_TOKENS' - export EVAL_ACCURACY_THRESHOLD='$EVAL_ACCURACY_THRESHOLD' - export EVAL_WAIT_TIMEOUT='$EVAL_WAIT_TIMEOUT' - export EVAL_METRICS_FILE='$EVAL_METRICS_FILE' - export MASTER_ADDR='$MASTER_ADDR' - export MASTER_PORT='$MASTER_PORT' - export TOKENIZERS_PARALLELISM=false - export WANDB_MODE='$WANDB_MODE' - export WANDB_DIR='$WANDB_DIR' - torchrun \ - --nproc_per_node=4 \ - --master_addr='$MASTER_ADDR' \ - --master_port='$MASTER_PORT' \ - examples/dapo_math_async_rl.py \ - --config '$RUNTIME_CONFIG' - " 2>&1 | tee "$JOB_LOG_DIR/training.log" - -echo "[7/7] DAPO-Math C-MLFQ training completed" -echo "Logs: $JOB_LOG_DIR" -echo "C-MLFQ tree: $PROJECT_DIR/logs/dapo_math_cmlfq/cmlfq_tree_${JOB_ID}.json" -echo "History: $PROJECT_DIR/logs/dapo_math_cmlfq/history" -echo "Eval metrics: $PROJECT_DIR/logs/dapo_math_cmlfq/eval/eval_metrics.jsonl" -echo "============================================================" diff --git a/scripts/submit_grouped_gemm_install.slurm b/scripts/submit_grouped_gemm_install.slurm deleted file mode 100644 index 2068f9c..0000000 --- a/scripts/submit_grouped_gemm_install.slurm +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/bash -#SBATCH -J install_grouped_gemm -#SBATCH -o logs/install_grouped_gemm_%j.out -#SBATCH -e logs/install_grouped_gemm_%j.err -#SBATCH -N 1 -#SBATCH -G 1 -#SBATCH --ntasks-per-node=1 -#SBATCH --cpus-per-task=12 -#SBATCH -p gpu -#SBATCH --time=00:30:00 - -set -euo pipefail - -PROJECT_DIR="${PROJECT_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" -VENV_PATH="${VENV_PATH:-${HOME}/rl_framework_env/bin/activate}" -ARCHIVE="$PROJECT_DIR/vendor/megatron/grouped_gemm-1.1.4-with-cutlass.tar.gz" -WHEEL="$PROJECT_DIR/vendor/megatron/grouped_gemm-1.1.4-cp312-cp312-linux_x86_64.whl" - -source "$VENV_PATH" -cd "$PROJECT_DIR" -mkdir -p logs - -if [ -f "$WHEEL" ]; then - python -m pip install --no-deps --force-reinstall "$WHEEL" -else - python -m pip install --no-build-isolation --no-deps --force-reinstall "$ARCHIVE" -fi - -python - <<'PY' -import importlib.metadata as metadata - -import grouped_gemm -import torch -from megatron.core.transformer.moe.grouped_gemm_util import ( - grouped_gemm_is_available, -) - -assert grouped_gemm_is_available() -assert metadata.version("grouped-gemm") == "1.1.4" -a = torch.randn(8, 16, device="cuda", dtype=torch.bfloat16, requires_grad=True) -b = torch.randn( - 2, - 16, - 8, - device="cuda", - dtype=torch.bfloat16, - requires_grad=True, -) -batch_sizes = torch.tensor([4, 4], dtype=torch.long) -actual = grouped_gemm.ops.gmm(a, b, batch_sizes) -expected = torch.cat((a[:4] @ b[0], a[4:] @ b[1])) -torch.testing.assert_close(actual, expected, rtol=2e-2, atol=2e-2) -actual.float().sum().backward() -assert a.grad is not None and b.grad is not None -print("GROUPED_GEMM_INSTALL_OK", grouped_gemm.__file__) -PY diff --git a/scripts/submit_hetero.slurm b/scripts/submit_hetero.slurm deleted file mode 100644 index 8e0f85f..0000000 --- a/scripts/submit_hetero.slurm +++ /dev/null @@ -1,89 +0,0 @@ -#!/bin/bash -# ============================================================================= -# ============================================================================= - - - - - - - - - - - -#SBATCH --mail-type=BEGIN,END,FAIL -#SBATCH --mail-user=you@example.com - -# ============================================================================= - -# ============================================================================= -echo "==========================================" -echo "Job information" -echo "==========================================" -echo "Job started at: $(date)" -echo "Running on host: $(hostname)" -echo "SLURM_JOBID: $SLURM_JOBID" -echo "SLURM_NODELIST: $SLURM_NODELIST" -echo "SLURM_JOB_GPUS: $SLURM_JOB_GPUS" -echo "CUDA_VISIBLE_DEVICES: $CUDA_VISIBLE_DEVICES" -echo "" - -# ============================================================================= - -# ============================================================================= - - -source ~/rl_framework_env/bin/activate - -echo "Python: $(which python3)" -echo "Python version: $(python3 --version 2>&1)" -echo "CUDA devices: $(python3 -c 'import torch; print(torch.cuda.device_count(), "GPUs")' 2>/dev/null || echo 'torch not available')" - - -PROJECT_DIR="/path/to/RL_Framework" -cd "$PROJECT_DIR" - -export PYTHONPATH="/path/to/user:${PYTHONPATH}" -export NO_PROXY="localhost,127.0.0.1" - - -mkdir -p logs - -# ============================================================================= - -# ============================================================================= -echo "" -echo "==========================================" -echo "Starting heterogeneous rollout training on 8 GPUs (2 nodes)" -echo "==========================================" -echo " Configuration: configs/gsm8k_hetero.yaml" -echo " Node 0: Training GPU 0,1 (FSDP) + vLLM GPU 2 (TP=1), GPU 3 (TP=1)" -echo " Node 1: vLLM GPU 0,1 (TP=2), GPU 2,3 (TP=2)" -echo "" - -bash scripts/run_hetero_distributed.sh --config /path/to/RL_Framework/configs/gsm8k_hetero.yaml - - -TRAIN_PID=$(cat logs/.train_pid_hetero 2>/dev/null || echo "") -if [ -n "$TRAIN_PID" ]; then - echo "Waiting for training process (PID=$TRAIN_PID) to complete..." - while kill -0 $TRAIN_PID 2>/dev/null; do - sleep 10 - done - echo "Training process ended" -else - echo "WARNING: Training process PID was not found" -fi - -# ============================================================================= - -# ============================================================================= -echo "" -echo "==========================================" -echo "Job ended; cleaning processes" -echo "==========================================" - - -pkill -f "vllm.entrypoints" 2>/dev/null || true -echo "Job finished at: $(date)" diff --git a/scripts/submit_hetero_4gpu.slurm b/scripts/submit_hetero_4gpu.slurm deleted file mode 100644 index b75bcec..0000000 --- a/scripts/submit_hetero_4gpu.slurm +++ /dev/null @@ -1,96 +0,0 @@ -#!/bin/bash -# ============================================================================= - -# - -# sbatch scripts/submit_hetero_4gpu.slurm -# - - - - -# ============================================================================= - - - - - - - - - - -#SBATCH --exclude=gn019 -#SBATCH --mail-type=BEGIN,END,FAIL -#SBATCH --mail-user=you@example.com - -# ============================================================================= - -# ============================================================================= -echo "==========================================" -echo "Job information" -echo "==========================================" -echo "Job started at: $(date)" -echo "Running on host: $(hostname)" -echo "SLURM_JOBID: $SLURM_JOBID" -echo "SLURM_NODELIST: $SLURM_NODELIST" -echo "SLURM_JOB_GPUS: $SLURM_JOB_GPUS" -echo "CUDA_VISIBLE_DEVICES: $CUDA_VISIBLE_DEVICES" -echo "" - -# ============================================================================= - -# ============================================================================= - - -source ~/rl_framework_env/bin/activate - -echo "Python: $(which python3)" -echo "Python version: $(python3 --version 2>&1)" -echo "CUDA devices: $(python3 -c 'import torch; print(torch.cuda.device_count(), "GPUs")' 2>/dev/null || echo 'torch not available')" - - -PROJECT_DIR="/path/to/RL_Framework" -cd "$PROJECT_DIR" - -export PYTHONPATH="/path/to/user:${PYTHONPATH}" -export NO_PROXY="localhost,127.0.0.1" - - -mkdir -p logs - -# ============================================================================= - -# ============================================================================= -echo "" -echo "==========================================" -echo "Starting heterogeneous rollout training on 4 GPUs" -echo "==========================================" -echo " Configuration: configs/gsm8k_hetero_4gpu.yaml" -echo " Training: GPU 0,1 (FSDP, 2 processes)" -echo " Rollout: GPU 2 (TP=1), GPU 3 (TP=1)" -echo "" - -bash scripts/run_hetero_distributed_4GPU.sh --config /path/to/RL_Framework/configs/gsm8k_hetero_4gpu.yaml - - -TRAIN_PID=$(cat logs/.train_pid_hetero 2>/dev/null || echo "") -if [ -n "$TRAIN_PID" ]; then - echo "Waiting for training process (PID=$TRAIN_PID) to complete..." - while kill -0 $TRAIN_PID 2>/dev/null; do - sleep 10 - done - echo "Training process ended" -else - echo "WARNING: Training process PID was not found" -fi - -# ============================================================================= - -# ============================================================================= -echo "" -echo "==========================================" -echo "Job ended; cleaning processes" -echo "==========================================" -pkill -f "vllm.entrypoints" 2>/dev/null || true -echo "Job finished at: $(date)" diff --git a/scripts/submit_libra_validation_baseline.slurm b/scripts/submit_libra_validation_baseline.slurm deleted file mode 100644 index 658fe33..0000000 --- a/scripts/submit_libra_validation_baseline.slurm +++ /dev/null @@ -1,63 +0,0 @@ -#!/bin/bash -# Baseline Qwen3-4B validation run: fixed layout, no C-MLFQ/GRP/EHP. - -#SBATCH -J libra_base -#SBATCH -o logs/libra_base_%j.out -#SBATCH -e logs/libra_base_%j.err -#SBATCH -N 3 -#SBATCH -G 12 -#SBATCH --ntasks-per-node=4 -#SBATCH --cpus-per-task=16 -#SBATCH --mem=900G -#SBATCH --exclude=gn002,gn019 -#SBATCH -p gpu -#SBATCH --time=01:00:00 - -set -euo pipefail - -export PROJECT_DIR="${PROJECT_DIR:-/home-ssd/Users/nsgm_xu/kwchen/RL_Framework}" -export EXPERIMENT_TAG="${EXPERIMENT_TAG:-baseline_lenaware_qwen4}" -export MODEL_PATH="${MODEL_PATH:-/home-ssd/Users/nsgm_xu/kwchen/hf_models/Qwen3-4B}" -export MODEL_ARCH_CONFIG="${MODEL_ARCH_CONFIG:-model_arch_config/qwen3-4b.yaml}" -export TOTAL_STEPS="${TOTAL_STEPS:-12}" -export MAX_MODEL_LEN="${MAX_MODEL_LEN:-4096}" -export MAX_NEW_TOKENS="${MAX_NEW_TOKENS:-128}" -export R2E_MAX_PROMPT_TOKENS="${R2E_MAX_PROMPT_TOKENS:-1024}" -export R2E_MAX_TURNS="${R2E_MAX_TURNS:-1}" -export TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-8}" -export N_SAMPLES="${N_SAMPLES:-2}" -export MAX_CONCURRENT_ROLLOUTS="${MAX_CONCURRENT_ROLLOUTS:-8}" -export QUEUE_SIZE="${QUEUE_SIZE:-32}" -export EVAL_INTERVAL="${EVAL_INTERVAL:-999}" -export SYNC_INTERVAL="${SYNC_INTERVAL:-999}" -export RUN_NCCL_PREFLIGHT="${RUN_NCCL_PREFLIGHT:-0}" -export ALLOW_QWEN30_FALLBACK="${ALLOW_QWEN30_FALLBACK:-1}" - -export TRAIN_BACKEND="${TRAIN_BACKEND:-megatron_core}" -export TRAIN_GPUS="${TRAIN_GPUS:-4}" -export TRAIN_TP_SIZE="${TRAIN_TP_SIZE:-1}" -export TRAIN_PP_SIZE="${TRAIN_PP_SIZE:-1}" -export TRAIN_CP_SIZE="${TRAIN_CP_SIZE:-1}" -export MEGATRON_USE_PRECISION_AWARE_OPTIMIZER="${MEGATRON_USE_PRECISION_AWARE_OPTIMIZER:-1}" -export MEGATRON_OPTIMIZER_CPU_OFFLOAD="${MEGATRON_OPTIMIZER_CPU_OFFLOAD:-1}" -export MEGATRON_OPTIMIZER_OFFLOAD_FRACTION="${MEGATRON_OPTIMIZER_OFFLOAD_FRACTION:-1.0}" - -export SCHEDULER_TYPE="${SCHEDULER_TYPE:-length_aware}" -export GRP_ENABLED="${GRP_ENABLED:-0}" -export GRP_DYNAMIC_RECONFIG_ENABLED="${GRP_DYNAMIC_RECONFIG_ENABLED:-0}" -export GRP_RUNTIME_ASYNC_PLANNING="${GRP_RUNTIME_ASYNC_PLANNING:-0}" -export GRP_ONLINE_REPLANNING="${GRP_ONLINE_REPLANNING:-0}" -export GRP_MANAGE_ROLLOUT_PROCESSES="${GRP_MANAGE_ROLLOUT_PROCESSES:-0}" -export GRP_RECONFIGURE_TRAINING="${GRP_RECONFIGURE_TRAINING:-0}" -export GRP_TRAINING_POOL_PLAN_ONLY="${GRP_TRAINING_POOL_PLAN_ONLY:-1}" -export GRP_CLUSTER_SWAP_ENABLED="${GRP_CLUSTER_SWAP_ENABLED:-0}" -export GRP_HYBRID_WORKER_LAUNCH_ENABLED="${GRP_HYBRID_WORKER_LAUNCH_ENABLED:-0}" -export GRP_HYBRID_TRAINING_PREWARM_ENABLED="${GRP_HYBRID_TRAINING_PREWARM_ENABLED:-0}" -export GRP_INITIAL_ROLLOUT_TP_LIST="${GRP_INITIAL_ROLLOUT_TP_LIST:-4:2:2}" -export GRP_FORCE_RUNTIME_RECONFIGURE="${GRP_FORCE_RUNTIME_RECONFIGURE:-0}" -export GRP_TRAINING_POOL_TARGET_GPUS="${GRP_TRAINING_POOL_TARGET_GPUS:-0}" - -export ROLLOUT_WEIGHT_SYNC_MODE="${ROLLOUT_WEIGHT_SYNC_MODE:-none}" -export REQUIRE_ROLLOUT_WEIGHT_SYNC="${REQUIRE_ROLLOUT_WEIGHT_SYNC:-0}" - -exec bash "$PROJECT_DIR/scripts/submit_r2e_gym_cmlfq_24gpu_qwen3_30b_a3b.slurm" diff --git a/scripts/submit_libra_validation_full.slurm b/scripts/submit_libra_validation_full.slurm deleted file mode 100644 index e3f4f95..0000000 --- a/scripts/submit_libra_validation_full.slurm +++ /dev/null @@ -1,72 +0,0 @@ -#!/bin/bash -# Full Libra Qwen3-4B validation run: C-MLFQ + GRP + EHP cluster swap. - -#SBATCH -J libra_full -#SBATCH -o logs/libra_full_%j.out -#SBATCH -e logs/libra_full_%j.err -#SBATCH -N 3 -#SBATCH -G 12 -#SBATCH --ntasks-per-node=4 -#SBATCH --cpus-per-task=16 -#SBATCH --mem=900G -#SBATCH --exclude=gn002,gn019 -#SBATCH -p gpu -#SBATCH --time=01:00:00 - -set -euo pipefail - -export PROJECT_DIR="${PROJECT_DIR:-/home-ssd/Users/nsgm_xu/kwchen/RL_Framework}" -export EXPERIMENT_TAG="${EXPERIMENT_TAG:-full_libra_qwen4}" -export MODEL_PATH="${MODEL_PATH:-/home-ssd/Users/nsgm_xu/kwchen/hf_models/Qwen3-4B}" -export MODEL_ARCH_CONFIG="${MODEL_ARCH_CONFIG:-model_arch_config/qwen3-4b.yaml}" -export TOTAL_STEPS="${TOTAL_STEPS:-12}" -export MAX_MODEL_LEN="${MAX_MODEL_LEN:-4096}" -export MAX_NEW_TOKENS="${MAX_NEW_TOKENS:-128}" -export R2E_MAX_PROMPT_TOKENS="${R2E_MAX_PROMPT_TOKENS:-1024}" -export R2E_MAX_TURNS="${R2E_MAX_TURNS:-1}" -export TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-8}" -export N_SAMPLES="${N_SAMPLES:-2}" -export MAX_CONCURRENT_ROLLOUTS="${MAX_CONCURRENT_ROLLOUTS:-8}" -export QUEUE_SIZE="${QUEUE_SIZE:-32}" -export EVAL_INTERVAL="${EVAL_INTERVAL:-999}" -export SYNC_INTERVAL="${SYNC_INTERVAL:-999}" -export RUN_NCCL_PREFLIGHT="${RUN_NCCL_PREFLIGHT:-0}" - -export TRAIN_BACKEND="${TRAIN_BACKEND:-megatron_core}" -export TRAIN_GPUS="${TRAIN_GPUS:-4}" -export TRAIN_TP_SIZE="${TRAIN_TP_SIZE:-4}" -export TRAIN_PP_SIZE="${TRAIN_PP_SIZE:-1}" -export TRAIN_CP_SIZE="${TRAIN_CP_SIZE:-1}" -export MEGATRON_USE_PRECISION_AWARE_OPTIMIZER="${MEGATRON_USE_PRECISION_AWARE_OPTIMIZER:-1}" -export MEGATRON_OPTIMIZER_CPU_OFFLOAD="${MEGATRON_OPTIMIZER_CPU_OFFLOAD:-1}" -export MEGATRON_OPTIMIZER_OFFLOAD_FRACTION="${MEGATRON_OPTIMIZER_OFFLOAD_FRACTION:-1.0}" - -export SCHEDULER_TYPE="${SCHEDULER_TYPE:-cmlfq}" -export GRP_ENABLED="${GRP_ENABLED:-1}" -export GRP_DYNAMIC_RECONFIG_ENABLED="${GRP_DYNAMIC_RECONFIG_ENABLED:-1}" -export GRP_RUNTIME_ASYNC_PLANNING="${GRP_RUNTIME_ASYNC_PLANNING:-0}" -export GRP_ONLINE_REPLANNING="${GRP_ONLINE_REPLANNING:-1}" -export GRP_INTERVAL="${GRP_INTERVAL:-1}" -export GRP_REPLAN_COOLDOWN_STEPS="${GRP_REPLAN_COOLDOWN_STEPS:-999}" -export GRP_WARMUP_STEPS="${GRP_WARMUP_STEPS:-0}" -export GRP_MIN_HISTORY="${GRP_MIN_HISTORY:-4}" -export GRP_MIN_GAIN_RATIO="${GRP_MIN_GAIN_RATIO:-0.0}" -export GRP_MANAGE_ROLLOUT_PROCESSES="${GRP_MANAGE_ROLLOUT_PROCESSES:-1}" -export GRP_RECONFIGURE_TRAINING="${GRP_RECONFIGURE_TRAINING:-1}" -export GRP_TRAINING_POOL_PLAN_ONLY="${GRP_TRAINING_POOL_PLAN_ONLY:-0}" -export GRP_CLUSTER_SWAP_ENABLED="${GRP_CLUSTER_SWAP_ENABLED:-1}" -export GRP_ROLLOUT_RECONFIGURE_STRATEGY="${GRP_ROLLOUT_RECONFIGURE_STRATEGY:-cluster_swap}" -export GRP_DRAIN_BEFORE_RECONFIGURE="${GRP_DRAIN_BEFORE_RECONFIGURE:-0}" -export GRP_BATCH_COLLECTION_TIMEOUT_S="${GRP_BATCH_COLLECTION_TIMEOUT_S:-180}" -export GRP_BATCH_COLLECTION_MAX_RETRIES="${GRP_BATCH_COLLECTION_MAX_RETRIES:-1}" -export GRP_INITIAL_ROLLOUT_TP_LIST="${GRP_INITIAL_ROLLOUT_TP_LIST:-4:2:2}" -export GRP_FORCE_RUNTIME_RECONFIGURE="${GRP_FORCE_RUNTIME_RECONFIGURE:-1}" -export GRP_FORCE_TRAIN_GPUS="${GRP_FORCE_TRAIN_GPUS:-8}" -export GRP_FORCE_ROLLOUT_TP_LIST="${GRP_FORCE_ROLLOUT_TP_LIST:-2:2}" -export GRP_TRAINING_POOL_TARGET_GPUS="${GRP_TRAINING_POOL_TARGET_GPUS:-8}" -export GRP_DECOUPLE_COMMUNICATION_DOMAINS="${GRP_DECOUPLE_COMMUNICATION_DOMAINS:-1}" - -export ROLLOUT_WEIGHT_SYNC_MODE="${ROLLOUT_WEIGHT_SYNC_MODE:-none}" -export REQUIRE_ROLLOUT_WEIGHT_SYNC="${REQUIRE_ROLLOUT_WEIGHT_SYNC:-0}" - -exec bash "$PROJECT_DIR/scripts/submit_r2e_gym_cmlfq_24gpu_qwen3_30b_a3b.slurm" diff --git a/scripts/submit_libra_validation_pilot.slurm b/scripts/submit_libra_validation_pilot.slurm deleted file mode 100644 index a2ea32a..0000000 --- a/scripts/submit_libra_validation_pilot.slurm +++ /dev/null @@ -1,71 +0,0 @@ -#!/bin/bash -# Short Qwen3-4B pilot for Libra validation. - -#SBATCH -J libra_pilot -#SBATCH -o logs/libra_pilot_%j.out -#SBATCH -e logs/libra_pilot_%j.err -#SBATCH -N 3 -#SBATCH -G 12 -#SBATCH --ntasks-per-node=4 -#SBATCH --cpus-per-task=16 -#SBATCH --mem=900G -#SBATCH --exclude=gn002,gn019 -#SBATCH -p gpu -#SBATCH --time=01:00:00 - -set -euo pipefail - -export PROJECT_DIR="${PROJECT_DIR:-/home-ssd/Users/nsgm_xu/kwchen/RL_Framework}" -export EXPERIMENT_TAG="${EXPERIMENT_TAG:-pilot_libra_full_qwen4}" -export MODEL_PATH="${MODEL_PATH:-/home-ssd/Users/nsgm_xu/kwchen/hf_models/Qwen3-4B}" -export MODEL_ARCH_CONFIG="${MODEL_ARCH_CONFIG:-model_arch_config/qwen3-4b.yaml}" -export TOTAL_STEPS="${TOTAL_STEPS:-6}" -export MAX_MODEL_LEN="${MAX_MODEL_LEN:-4096}" -export MAX_NEW_TOKENS="${MAX_NEW_TOKENS:-128}" -export R2E_MAX_PROMPT_TOKENS="${R2E_MAX_PROMPT_TOKENS:-1024}" -export R2E_MAX_TURNS="${R2E_MAX_TURNS:-1}" -export TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-8}" -export N_SAMPLES="${N_SAMPLES:-2}" -export MAX_CONCURRENT_ROLLOUTS="${MAX_CONCURRENT_ROLLOUTS:-8}" -export QUEUE_SIZE="${QUEUE_SIZE:-32}" -export EVAL_INTERVAL="${EVAL_INTERVAL:-999}" -export SYNC_INTERVAL="${SYNC_INTERVAL:-999}" -export RUN_NCCL_PREFLIGHT="${RUN_NCCL_PREFLIGHT:-0}" - -export TRAIN_BACKEND="${TRAIN_BACKEND:-megatron_core}" -export TRAIN_GPUS="${TRAIN_GPUS:-4}" -export TRAIN_TP_SIZE="${TRAIN_TP_SIZE:-1}" -export TRAIN_PP_SIZE="${TRAIN_PP_SIZE:-1}" -export TRAIN_CP_SIZE="${TRAIN_CP_SIZE:-1}" -export MEGATRON_USE_PRECISION_AWARE_OPTIMIZER="${MEGATRON_USE_PRECISION_AWARE_OPTIMIZER:-1}" -export MEGATRON_OPTIMIZER_CPU_OFFLOAD="${MEGATRON_OPTIMIZER_CPU_OFFLOAD:-1}" -export MEGATRON_OPTIMIZER_OFFLOAD_FRACTION="${MEGATRON_OPTIMIZER_OFFLOAD_FRACTION:-1.0}" - -export SCHEDULER_TYPE="${SCHEDULER_TYPE:-cmlfq}" -export GRP_ENABLED="${GRP_ENABLED:-1}" -export GRP_DYNAMIC_RECONFIG_ENABLED="${GRP_DYNAMIC_RECONFIG_ENABLED:-1}" -export GRP_RUNTIME_ASYNC_PLANNING="${GRP_RUNTIME_ASYNC_PLANNING:-0}" -export GRP_ONLINE_REPLANNING="${GRP_ONLINE_REPLANNING:-1}" -export GRP_INTERVAL="${GRP_INTERVAL:-1}" -export GRP_WARMUP_STEPS="${GRP_WARMUP_STEPS:-0}" -export GRP_MIN_HISTORY="${GRP_MIN_HISTORY:-4}" -export GRP_MIN_GAIN_RATIO="${GRP_MIN_GAIN_RATIO:-0.0}" -export GRP_MANAGE_ROLLOUT_PROCESSES="${GRP_MANAGE_ROLLOUT_PROCESSES:-1}" -export GRP_RECONFIGURE_TRAINING="${GRP_RECONFIGURE_TRAINING:-1}" -export GRP_TRAINING_POOL_PLAN_ONLY="${GRP_TRAINING_POOL_PLAN_ONLY:-0}" -export GRP_CLUSTER_SWAP_ENABLED="${GRP_CLUSTER_SWAP_ENABLED:-1}" -export GRP_ROLLOUT_RECONFIGURE_STRATEGY="${GRP_ROLLOUT_RECONFIGURE_STRATEGY:-cluster_swap}" -export GRP_DRAIN_BEFORE_RECONFIGURE="${GRP_DRAIN_BEFORE_RECONFIGURE:-0}" -export GRP_BATCH_COLLECTION_TIMEOUT_S="${GRP_BATCH_COLLECTION_TIMEOUT_S:-180}" -export GRP_BATCH_COLLECTION_MAX_RETRIES="${GRP_BATCH_COLLECTION_MAX_RETRIES:-1}" -export GRP_INITIAL_ROLLOUT_TP_LIST="${GRP_INITIAL_ROLLOUT_TP_LIST:-4:2:2}" -export GRP_FORCE_RUNTIME_RECONFIGURE="${GRP_FORCE_RUNTIME_RECONFIGURE:-1}" -export GRP_FORCE_TRAIN_GPUS="${GRP_FORCE_TRAIN_GPUS:-8}" -export GRP_FORCE_ROLLOUT_TP_LIST="${GRP_FORCE_ROLLOUT_TP_LIST:-2:2}" -export GRP_TRAINING_POOL_TARGET_GPUS="${GRP_TRAINING_POOL_TARGET_GPUS:-8}" -export GRP_DECOUPLE_COMMUNICATION_DOMAINS="${GRP_DECOUPLE_COMMUNICATION_DOMAINS:-1}" - -export ROLLOUT_WEIGHT_SYNC_MODE="${ROLLOUT_WEIGHT_SYNC_MODE:-none}" -export REQUIRE_ROLLOUT_WEIGHT_SYNC="${REQUIRE_ROLLOUT_WEIGHT_SYNC:-0}" - -exec bash "$PROJECT_DIR/scripts/submit_r2e_gym_cmlfq_24gpu_qwen3_30b_a3b.slurm" diff --git a/scripts/submit_nccl_membership_probe.slurm b/scripts/submit_nccl_membership_probe.slurm deleted file mode 100644 index 0e01f91..0000000 --- a/scripts/submit_nccl_membership_probe.slurm +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -#SBATCH --partition=gpu -#SBATCH --account=nsgm_xu -#SBATCH --nodes=3 -#SBATCH --ntasks-per-node=3 -#SBATCH --gpus-per-task=1 -#SBATCH --cpus-per-task=4 -#SBATCH --time=00:10:00 -#SBATCH --output=logs/nccl_membership_%j.log -set -euo pipefail -source /home-ssd/Users/nsgm_xu/rl_framework_env/bin/activate -cd /home-ssd/Users/nsgm_xu/kwchen/RL_Framework -export PYTHONPATH=/home-ssd/Users/nsgm_xu/kwchen:${PYTHONPATH:-} -export NCCL_CUMEM_ENABLE=0 -export NCCL_P2P_DISABLE=1 -mapfile -t probe_nodes < <(scontrol show hostnames "$SLURM_JOB_NODELIST") -timeout 240 srun --kill-on-bad-exit=1 python scripts/nccl_membership_probe.py --host "${probe_nodes[0]}" diff --git a/scripts/submit_qwen3_cmlfq_train.slurm b/scripts/submit_qwen3_cmlfq_train.slurm deleted file mode 100644 index 44613b5..0000000 --- a/scripts/submit_qwen3_cmlfq_train.slurm +++ /dev/null @@ -1,309 +0,0 @@ -#!/bin/bash -# ============================================================================= -# Qwen3-14B + C-MLFQ Slurm training -# -# Topology (3 nodes, 4 GPUs per node, 12 GPUs total): -# node 0: training, 4 x GPU (FSDP) -# node 1: rollout TP=4 -# node 2: rollout TP=2 + TP=2 -# -# Submit: -# MODEL_PATH=/shared/models/Qwen3-14B \ -# sbatch --export=ALL,MODEL_PATH scripts/submit_qwen3_cmlfq_train.slurm -# -# Optional: -# SERPER_KEY_ID=... TOTAL_STEPS=1000 MAX_MODEL_LEN=40960 \ -# VENV_PATH=$HOME/rl_framework_env/bin/activate \ -# sbatch --export=ALL scripts/submit_qwen3_cmlfq_train.slurm -# ============================================================================= - -#SBATCH -J qwen3_cmlfq_train -#SBATCH -o logs/qwen3_cmlfq_train_%j.out -#SBATCH -e logs/qwen3_cmlfq_train_%j.err -#SBATCH -N 3 -#SBATCH -G 12 -#SBATCH --ntasks-per-node=2 -#SBATCH --cpus-per-task=16 -#SBATCH -p gpu -#SBATCH --time=06:00:00 -#SBATCH --exclude=gn019 - -set -euo pipefail - -PROJECT_DIR="${PROJECT_DIR:-/path/to/RL_Framework}" -VENV_PATH="${VENV_PATH:-$HOME/rl_framework_env/bin/activate}" -MODEL_PATH="${MODEL_PATH:-}" -TOTAL_STEPS="${TOTAL_STEPS:-1000}" -MAX_MODEL_LEN="${MAX_MODEL_LEN:-40960}" -TRAIN_MAX_SEQ_LENGTH="${TRAIN_MAX_SEQ_LENGTH:-40960}" -TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-4}" -TRAIN_MICRO_BATCH_SIZE="${TRAIN_MICRO_BATCH_SIZE:-1}" -MAX_NEW_TOKENS="${MAX_NEW_TOKENS:-1024}" -GPU_MEMORY_UTILIZATION="${GPU_MEMORY_UTILIZATION:-0.90}" -VLLM_BASE_PORT="${VLLM_BASE_PORT:-8000}" -MASTER_PORT="${MASTER_PORT:-29500}" -MAX_WAIT="${MAX_WAIT:-900}" - -if [ -z "$MODEL_PATH" ]; then - echo "ERROR: MODEL_PATH is required." - echo "Example:" - echo " MODEL_PATH=/shared/models/Qwen3-14B \\" - echo " sbatch --export=ALL,MODEL_PATH scripts/submit_qwen3_cmlfq_train.slurm" - exit 2 -fi - -source "$VENV_PATH" -cd "$PROJECT_DIR" - -mkdir -p logs -JOB_LOG_DIR="$PROJECT_DIR/logs/qwen3_cmlfq_${SLURM_JOB_ID}" -mkdir -p "$JOB_LOG_DIR" - -export PYTHONPATH="$(dirname "$PROJECT_DIR"):${PYTHONPATH:-}" -export TOKENIZERS_PARALLELISM=false -export WANDB_MODE="${WANDB_MODE:-offline}" -export NO_PROXY="localhost,127.0.0.1,${NO_PROXY:-}" -export NCCL_ASYNC_ERROR_HANDLING=1 -export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}" - -mapfile -t NODES < <(scontrol show hostnames "$SLURM_NODELIST") -if [ "${#NODES[@]}" -lt 3 ]; then - echo "ERROR: this training run requires 3 nodes; got ${#NODES[@]}" - exit 2 -fi - -TRAIN_NODE="${NODES[0]}" -ROLLOUT_NODE_A="${NODES[1]}" -ROLLOUT_NODE_B="${NODES[2]}" -MASTER_ADDR="$TRAIN_NODE" - -echo "============================================================" -echo "Qwen3-14B + C-MLFQ training" -echo "============================================================" -echo "Job: ${SLURM_JOB_ID}" -echo "Model: $MODEL_PATH" -echo "Train node: $TRAIN_NODE (4 GPUs, FSDP)" -echo "Rollout node A: $ROLLOUT_NODE_A (TP4)" -echo "Rollout node B: $ROLLOUT_NODE_B (TP2 + TP2)" -echo "Steps: $TOTAL_STEPS" -echo "Logs: $JOB_LOG_DIR" -echo "Python: $(which python3)" -python3 -c 'import torch, transformers, vllm; print("torch", torch.__version__, "transformers", transformers.__version__, "vllm", vllm.__version__)' - -VLLM_STEP_PIDS=() -declare -A VLLM_PID_BY_NAME=() -RUNTIME_CONFIG="" - -cleanup() { - local exit_code=$? - trap - EXIT INT TERM - echo "" - echo "[cleanup] stopping training and vLLM processes..." - - for pid in "${VLLM_STEP_PIDS[@]:-}"; do - kill "$pid" 2>/dev/null || true - done - - for node in "$ROLLOUT_NODE_A" "$ROLLOUT_NODE_B"; do - for port in \ - "$VLLM_BASE_PORT" \ - "$((VLLM_BASE_PORT + 1))" \ - "$((VLLM_BASE_PORT + 2))"; do - srun --overlap --nodes=1 --ntasks=1 --nodelist="$node" \ - bash -lc "pkill -f 'vllm.entrypoints.openai.api_server.*--port ${port}' 2>/dev/null || true" \ - >/dev/null 2>&1 || true - done - done - - if [ -n "$RUNTIME_CONFIG" ]; then - rm -f "$RUNTIME_CONFIG" - fi - echo "[cleanup] complete, exit=$exit_code" - exit "$exit_code" -} -trap cleanup EXIT INT TERM - -echo "" -echo "[1/4] Writing runtime configuration" -RUNTIME_CONFIG="$PROJECT_DIR/configs/.qwen3_cmlfq_train_${SLURM_JOB_ID}.yaml" -export PROJECT_DIR MODEL_PATH TOTAL_STEPS MAX_MODEL_LEN VLLM_BASE_PORT -export TRAIN_MAX_SEQ_LENGTH TRAIN_BATCH_SIZE TRAIN_MICRO_BATCH_SIZE -export MAX_NEW_TOKENS -python3 - <<'PY' -import os -from pathlib import Path - -import yaml - -project = Path(os.environ["PROJECT_DIR"]) -config = { - "base_config": str( - project / "configs" / "search_r1_cmlfq_qwen3_14b.yaml" - ), - "model_path": os.environ["MODEL_PATH"], - "tokenizer_path": os.environ["MODEL_PATH"], - "train_gpus": 4, - "tp_size": 1, - "train_tp_size": 1, - "train_pp_size": 1, - "train_dp_size": 4, - "batch_size": int(os.environ["TRAIN_BATCH_SIZE"]), - "micro_batch_size": int(os.environ["TRAIN_MICRO_BATCH_SIZE"]), - "total_steps": int(os.environ["TOTAL_STEPS"]), - "max_seq_length": int(os.environ["TRAIN_MAX_SEQ_LENGTH"]), - "max_new_tokens": int(os.environ["MAX_NEW_TOKENS"]), - "n_samples": 1, - "max_concurrent_rollouts": int(os.environ["TRAIN_BATCH_SIZE"]), - "rollout_gpus": 8, - "eval_interval": 1000, - "save_interval": 1000, - "sync_path": str( - project / "logs" / "qwen3_cmlfq_train_weights" - ), - "log_dir": str(project / "logs" / "qwen3_cmlfq_train"), - "heterogeneous_rollout": { - "total_gpus": 8, - "vllm_host": "0.0.0.0", - "vllm_base_port": int(os.environ["VLLM_BASE_PORT"]), - "max_model_len": int(os.environ["MAX_MODEL_LEN"]), - "instances": [ - { - "instance_id": "short_tp4", - "tp": 4, - "gpus": [0, 1, 2, 3], - }, - { - "instance_id": "medium_tp2_0", - "tp": 2, - "gpus": [0, 1], - }, - { - "instance_id": "medium_tp2_1", - "tp": 2, - "gpus": [2, 3], - }, - ], - "scheduling": { - "cmlfq_tree_path": str( - project / "logs" / "qwen3_cmlfq_train" / "cmlfq_tree.json" - ), - }, - }, -} - -path = project / "configs" / ( - f".qwen3_cmlfq_train_{os.environ['SLURM_JOB_ID']}.yaml" -) -path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") -print(f"Wrote runtime config: {path}") -PY - -start_vllm() { - local node="$1" - local gpu_ids="$2" - local tp="$3" - local port="$4" - local name="$5" - local log_file="$JOB_LOG_DIR/vllm_${name}.log" - - echo "Starting $name on $node: GPUs=$gpu_ids TP=$tp port=$port" - srun --exclusive \ - --nodes=1 --ntasks=1 --nodelist="$node" \ - --gpus="$tp" \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - export TOKENIZERS_PARALLELISM=false - export MASTER_ADDR=127.0.0.1 - export MASTER_PORT=$((20000 + port)) - python3 -m vllm.entrypoints.openai.api_server \ - --model '$MODEL_PATH' \ - --host 0.0.0.0 \ - --port '$port' \ - --tensor-parallel-size '$tp' \ - --max-model-len '$MAX_MODEL_LEN' \ - --dtype bfloat16 \ - --gpu-memory-utilization '$GPU_MEMORY_UTILIZATION' \ - --trust-remote-code \ - --enforce-eager \ - --disable-custom-all-reduce - " >"$log_file" 2>&1 & - VLLM_STEP_PIDS+=("$!") - VLLM_PID_BY_NAME["$name"]="$!" -} - -echo "" -echo "[2/4] Starting heterogeneous vLLM rollout instances" -start_vllm "$ROLLOUT_NODE_A" "0,1,2,3" 4 "$VLLM_BASE_PORT" "short_tp4" -start_vllm "$ROLLOUT_NODE_B" "0,1" 2 "$((VLLM_BASE_PORT + 1))" "medium_tp2_0" - -wait_for_health() { - local host="$1" - local port="$2" - local name="$3" - local elapsed=0 - local pid="${VLLM_PID_BY_NAME[$name]}" - - while [ "$elapsed" -lt "$MAX_WAIT" ]; do - if curl -fsS "http://${host}:${port}/health" >/dev/null 2>&1; then - echo " READY: $name at $host:$port (${elapsed}s)" - return 0 - fi - if ! kill -0 "$pid" 2>/dev/null; then - echo "ERROR: $name exited before becoming ready" - tail -100 "$JOB_LOG_DIR/vllm_${name}.log" || true - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - - echo "ERROR: $name did not become ready in ${MAX_WAIT}s" - echo "Log: $JOB_LOG_DIR/vllm_${name}.log" - return 1 -} - -echo "" -echo "[3/4] Waiting for vLLM health endpoints" -wait_for_health "$ROLLOUT_NODE_A" "$VLLM_BASE_PORT" "short_tp4" -wait_for_health "$ROLLOUT_NODE_B" "$((VLLM_BASE_PORT + 1))" "medium_tp2_0" - -# Start the second service only after the first TP=2 step owns its two GPUs. -# Slurm then assigns and remaps the remaining two GPUs to local IDs 0 and 1. -start_vllm "$ROLLOUT_NODE_B" "2,3" 2 "$((VLLM_BASE_PORT + 2))" "medium_tp2_1" -wait_for_health "$ROLLOUT_NODE_B" "$((VLLM_BASE_PORT + 2))" "medium_tp2_1" - -export HETERO_INSTANCE_HOSTS="${ROLLOUT_NODE_A},${ROLLOUT_NODE_B},${ROLLOUT_NODE_B}" - -echo "" -echo "[4/4] Starting ${TOTAL_STEPS}-step Search-R1 training" -srun --exclusive \ - --nodes=1 --ntasks=1 --nodelist="$TRAIN_NODE" \ - --gpus=4 \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - cd '$PROJECT_DIR' - export PYTHONPATH='$(dirname "$PROJECT_DIR")':\${PYTHONPATH:-} - export HETERO_INSTANCE_HOSTS='$HETERO_INSTANCE_HOSTS' - export MASTER_ADDR='$MASTER_ADDR' - export MASTER_PORT='$MASTER_PORT' - export TOKENIZERS_PARALLELISM=false - export WANDB_MODE='$WANDB_MODE' - export SERPER_KEY_ID='${SERPER_KEY_ID:-}' - export SEARCH_BACKEND='${SEARCH_BACKEND:-serper}' - export SEARXNG_URL='${SEARXNG_URL:-http://127.0.0.1:18080}' - torchrun \ - --nproc_per_node=4 \ - --master_addr='$MASTER_ADDR' \ - --master_port='$MASTER_PORT' \ - examples/search_r1_async_rl.py \ - --config '$RUNTIME_CONFIG' - " 2>&1 | tee "$JOB_LOG_DIR/training.log" - -echo "" -echo "============================================================" -echo "Training completed successfully" -echo "Logs: $JOB_LOG_DIR" -echo "Trie: $PROJECT_DIR/logs/qwen3_cmlfq_train/cmlfq_tree.json" -echo "============================================================" diff --git a/scripts/submit_qwen3_direct_nccl_probe.slurm b/scripts/submit_qwen3_direct_nccl_probe.slurm deleted file mode 100644 index 04fa7cf..0000000 --- a/scripts/submit_qwen3_direct_nccl_probe.slurm +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env bash -#SBATCH -J qwen3-direct-nccl -#SBATCH -A nsgm_xu -#SBATCH --qos=normal -#SBATCH -p gpu -#SBATCH --exclude=gn005,gn021 -#SBATCH -N 1 -#SBATCH -G 3 -#SBATCH --ntasks-per-node=1 -#SBATCH --cpus-per-task=48 -#SBATCH --mem=384G -#SBATCH --time=02:00:00 - -set -euo pipefail - -MODEL_NAME="${MODEL_NAME:?MODEL_NAME is required}" -TRAIN_TP="${TRAIN_TP:-2}" -TRAIN_EP="${TRAIN_EP:-1}" -BASE_PORT="${BASE_PORT:-18500}" -TRANSPORT_PORT="${TRANSPORT_PORT:-29620}" -VLLM_GPU_MEMORY_UTILIZATION="${VLLM_GPU_MEMORY_UTILIZATION:-0.82}" -PROBE_REPEATS="${PROBE_REPEATS:-1}" -ROOT="$HOME/kwchen/rlinf_baseline" -PROJECT="$ROOT/libra_nccl_dev/RL_Framework" -MODEL="$HOME/kwchen/hf_models/$MODEL_NAME" -RESULTS="$ROOT/libra_results/direct_nccl_${MODEL_NAME}_${SLURM_JOB_ID}" - -source "$HOME/rl_framework_env/bin/activate" -export PYTHONPATH="$ROOT/libra_nccl_dev:${PYTHONPATH:-}" -export VLLM_WORKER_MULTIPROC_METHOD=spawn -export NCCL_DEBUG="${NCCL_DEBUG:-INFO}" -export NCCL_DEBUG_SUBSYS="${NCCL_DEBUG_SUBSYS:-INIT,ENV}" -export NCCL_CUMEM_ENABLE="${NCCL_CUMEM_ENABLE:-0}" -mkdir -p "$RESULTS" - -ALLOCATED_CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0,1,2,3}" -IFS=',' read -r -a GPU_IDS <<< "$ALLOCATED_CUDA_VISIBLE_DEVICES" -REQUIRED_GPUS=$((2 + TRAIN_TP)) -if ((${#GPU_IDS[@]} < REQUIRED_GPUS)); then - echo "Expected $REQUIRED_GPUS allocated GPUs, got: $ALLOCATED_CUDA_VISIBLE_DEVICES" >&2 - exit 1 -fi - -server_steps=() -cleanup() { - if ((${#server_steps[@]})); then - kill "${server_steps[@]}" >/dev/null 2>&1 || true - wait "${server_steps[@]}" >/dev/null 2>&1 || true - fi -} -trap cleanup EXIT - -for instance in 0 1; do - port=$((BASE_PORT + instance)) - CUDA_VISIBLE_DEVICES="${GPU_IDS[$instance]}" \ - python "$PROJECT/scripts/vllm_hot_reload_api_server.py" \ - --model "$MODEL" \ - --served-model-name qwen3-probe \ - --host 0.0.0.0 \ - --port "$port" \ - --tensor-parallel-size 1 \ - --max-model-len 512 \ - --max-num-seqs 4 \ - --dtype bfloat16 \ - --gpu-memory-utilization "$VLLM_GPU_MEMORY_UTILIZATION" \ - --enforce-eager \ - --enable-prefix-caching \ - --trust-remote-code \ - --worker-extension-cls RL_Framework.vllm_hot_reload.InplaceReloadWorkerExtension \ - >"$RESULTS/vllm_${instance}.log" 2>&1 & - server_steps+=("$!") -done - -for instance in 0 1; do - port=$((BASE_PORT + instance)) - ready=0 - for _ in $(seq 1 600); do - if curl -fsS "http://127.0.0.1:${port}/health" >/dev/null 2>&1; then - ready=1 - break - fi - if ! kill -0 "${server_steps[$instance]}" 2>/dev/null; then - break - fi - sleep 2 - done - if [[ "$ready" != 1 ]]; then - echo "vLLM instance $instance failed to become ready" >&2 - tail -100 "$RESULTS/vllm_${instance}.log" >&2 || true - exit 1 - fi -done - -NODE_IP="127.0.0.1" -MASTER_PORT=$((TRANSPORT_PORT + 1000)) -TRAINER_CUDA_VISIBLE_DEVICES="${GPU_IDS[2]}" -if ((TRAIN_TP > 1)); then - for ((index = 3; index < REQUIRED_GPUS; index++)); do - TRAINER_CUDA_VISIBLE_DEVICES+=",${GPU_IDS[$index]}" - done -fi -CUDA_VISIBLE_DEVICES="$TRAINER_CUDA_VISIBLE_DEVICES" \ - torchrun --standalone --nnodes=1 --nproc-per-node="$TRAIN_TP" \ - --master-port="$MASTER_PORT" \ - "$PROJECT/scripts/direct_nccl_qwen3_probe.py" \ - --model "$MODEL" \ - --endpoints "http://127.0.0.1:${BASE_PORT},http://127.0.0.1:$((BASE_PORT + 1))" \ - --transport-host "$NODE_IP" \ - --transport-port "$TRANSPORT_PORT" \ - --train-tp "$TRAIN_TP" \ - --train-ep "$TRAIN_EP" \ - --repeats "$PROBE_REPEATS" \ - --output "$RESULTS/result.json" \ - >"$RESULTS/trainer.log" 2>&1 diff --git a/scripts/submit_r2e_gym_cmlfq_24gpu_qwen3_30b_a3b.slurm b/scripts/submit_r2e_gym_cmlfq_24gpu_qwen3_30b_a3b.slurm deleted file mode 100755 index 01b4d0b..0000000 --- a/scripts/submit_r2e_gym_cmlfq_24gpu_qwen3_30b_a3b.slurm +++ /dev/null @@ -1,1267 +0,0 @@ -#!/bin/bash -#SBATCH -J r2e_qwen30_cmlfq -#SBATCH -o logs/r2e_qwen30_cmlfq_%j.out -#SBATCH -e logs/r2e_qwen30_cmlfq_%j.err -#SBATCH -N 4 -#SBATCH -G 16 -#SBATCH --ntasks-per-node=4 -#SBATCH --cpus-per-task=16 -#SBATCH --mem=900G -#SBATCH --exclude=gn002,gn019 -#SBATCH -p gpu -#SBATCH --time=24:00:00 - -set -euo pipefail - -source /etc/profile.d/modules.sh 2>/dev/null || true -module load compiler/gcc/10.1.0 || true -if [ -x /usr/local/cuda-12.3/bin/nvcc ]; then - export CUDA_HOME=/usr/local/cuda-12.3 -elif [ -x /usr/local/cuda/bin/nvcc ]; then - export CUDA_HOME=/usr/local/cuda -else - export CUDA_HOME=/usr/local/cuda-12.1 -fi -export PATH="$CUDA_HOME/bin:$PATH" -export LD_LIBRARY_PATH="$CUDA_HOME/lib64:${LD_LIBRARY_PATH:-}" -export VLLM_WORKER_MULTIPROC_METHOD=spawn - -PROJECT_DIR="${PROJECT_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" -VENV_PATH="${VENV_PATH:-${HOME}/rl_framework_env/bin/activate}" -MODEL_PATH="${MODEL_PATH:-${HOME}/hf_models/Qwen3-30B-A3B}" -MODEL_ARCH_CONFIG="${MODEL_ARCH_CONFIG:-model_arch_config/qwen3-30b-a3b.yaml}" -if [ -f "$PROJECT_DIR/.slurm/slurm.conf" ]; then - export SLURM_CONF="$PROJECT_DIR/.slurm/slurm.conf" -fi -TOTAL_STEPS="${TOTAL_STEPS:-100}" -MAX_MODEL_LEN="${MAX_MODEL_LEN:-8192}" -MAX_NEW_TOKENS="${MAX_NEW_TOKENS:-512}" -TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-32}" -TRAIN_MICRO_BATCH_SIZE="${TRAIN_MICRO_BATCH_SIZE:-1}" -N_SAMPLES="${N_SAMPLES:-4}" -TRAIN_GPUS="${TRAIN_GPUS:-8}" -TRAIN_BACKEND="${TRAIN_BACKEND:-megatron_core}" -TRAIN_TP_SIZE="${TRAIN_TP_SIZE:-4}" -TRAIN_PP_SIZE="${TRAIN_PP_SIZE:-1}" -TRAIN_CP_SIZE="${TRAIN_CP_SIZE:-1}" -TRAIN_EP_SIZE="${TRAIN_EP_SIZE:-1}" -EXPERT_TENSOR_PARALLEL_SIZE="${EXPERT_TENSOR_PARALLEL_SIZE:-1}" -USE_DISTRIBUTED_OPTIMIZER="${USE_DISTRIBUTED_OPTIMIZER:-1}" -MEGATRON_USE_CPU_INITIALIZATION="${MEGATRON_USE_CPU_INITIALIZATION:-0}" -MCORE_MOE_GROUPED_GEMM="${MCORE_MOE_GROUPED_GEMM:-1}" -MEGATRON_USE_PRECISION_AWARE_OPTIMIZER="${MEGATRON_USE_PRECISION_AWARE_OPTIMIZER:-1}" -MEGATRON_OPTIMIZER_CPU_OFFLOAD="${MEGATRON_OPTIMIZER_CPU_OFFLOAD:-1}" -MEGATRON_OPTIMIZER_OFFLOAD_FRACTION="${MEGATRON_OPTIMIZER_OFFLOAD_FRACTION:-1.0}" -ALLOW_QWEN30_FALLBACK="${ALLOW_QWEN30_FALLBACK:-0}" -MAX_CONCURRENT_ROLLOUTS="${MAX_CONCURRENT_ROLLOUTS:-32}" -QUEUE_SIZE="${QUEUE_SIZE:-256}" -EVAL_INTERVAL="${EVAL_INTERVAL:-20}" -RL_TRAIN_PHASE_TRACE="${RL_TRAIN_PHASE_TRACE:-0}" -EVAL_MAX_SAMPLES="${EVAL_MAX_SAMPLES:-32}" -EVAL_CONCURRENCY="${EVAL_CONCURRENCY:-16}" -EVAL_MAX_NEW_TOKENS="${EVAL_MAX_NEW_TOKENS:-512}" -SYNC_INTERVAL="${SYNC_INTERVAL:-5}" -GPU_MEMORY_UTILIZATION="${GPU_MEMORY_UTILIZATION:-0.80}" -VLLM_BASE_PORT="${VLLM_BASE_PORT:-8000}" -MASTER_PORT="${MASTER_PORT:-29500}" -MAX_WAIT="${MAX_WAIT:-1800}" -R2E_MAX_TURNS="${R2E_MAX_TURNS:-4}" -R2E_MAX_PROMPT_TOKENS="${R2E_MAX_PROMPT_TOKENS:-4096}" -GRP_PROFILE_DATASET_JSONL="${GRP_PROFILE_DATASET_JSONL:-$PROJECT_DIR/data/r2e_gym_v1/index.jsonl}" -GRP_PROFILE_SAMPLE_SIZE="${GRP_PROFILE_SAMPLE_SIZE:-64}" -GRP_PROFILE_STRATEGY="${GRP_PROFILE_STRATEGY:-spread}" -GRP_PROFILE_SEED="${GRP_PROFILE_SEED:-0}" -GRP_PROFILE_SAMPLES_PER_PROMPT="${GRP_PROFILE_SAMPLES_PER_PROMPT:-1}" -R2E_EVAL_MULTI_TURN="${R2E_EVAL_MULTI_TURN:-1}" -R2E_EVAL_RECORD_SAMPLES="${R2E_EVAL_RECORD_SAMPLES:-16}" -R2E_EVAL_STRATEGY="${R2E_EVAL_STRATEGY:-spread}" -LONG_CONTEXT_TP_FIRST="${LONG_CONTEXT_TP_FIRST:-0}" -VLLM_READ_TIMEOUT="${VLLM_READ_TIMEOUT:-600}" -VLLM_CONNECT_TIMEOUT="${VLLM_CONNECT_TIMEOUT:-30}" -VLLM_WRITE_TIMEOUT="${VLLM_WRITE_TIMEOUT:-30}" -VLLM_POOL_TIMEOUT="${VLLM_POOL_TIMEOUT:-30}" -VLLM_NCCL_P2P_DISABLE="${VLLM_NCCL_P2P_DISABLE:-1}" -VLLM_NCCL_IB_DISABLE="${VLLM_NCCL_IB_DISABLE:-0}" -VLLM_CUDA_LAUNCH_BLOCKING="${VLLM_CUDA_LAUNCH_BLOCKING:-0}" -VLLM_DISABLE_CUSTOM_ALL_REDUCE="${VLLM_DISABLE_CUSTOM_ALL_REDUCE:-1}" -NCCL_P2P_DISABLE="${NCCL_P2P_DISABLE:-1}" -NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-0}" -TORCH_DISTRIBUTED_TIMEOUT="${TORCH_DISTRIBUTED_TIMEOUT:-3600}" -FSDP_ALIGN_SEQUENCE_LENGTHS="${FSDP_ALIGN_SEQUENCE_LENGTHS:-1}" -FSDP_LOCKSTEP_BARRIERS="${FSDP_LOCKSTEP_BARRIERS:-1}" -FSDP_GRADIENT_CHECKPOINTING="${FSDP_GRADIENT_CHECKPOINTING:-0}" -FSDP_ACTIVATION_CHECKPOINTING="${FSDP_ACTIVATION_CHECKPOINTING:-1}" -CMLFQ_SHARED_LOAD_TTL="${CMLFQ_SHARED_LOAD_TTL:-60}" -CMLFQ_SHARED_LOAD_HEARTBEAT="${CMLFQ_SHARED_LOAD_HEARTBEAT:-10}" -CMLFQ_TREE_PERSIST_INTERVAL="${CMLFQ_TREE_PERSIST_INTERVAL:-8}" -CMLFQ_WARM_START_TREE="${CMLFQ_WARM_START_TREE:-}" -EXPERIMENT_TAG="${EXPERIMENT_TAG:-r2e_qwen_cmlfq}" -SCHEDULER_TYPE="${SCHEDULER_TYPE:-cmlfq}" -GRP_ENABLED="${GRP_ENABLED:-1}" -GRP_DYNAMIC_RECONFIG_ENABLED="${GRP_DYNAMIC_RECONFIG_ENABLED:-0}" -GRP_RUNTIME_ASYNC_PLANNING="${GRP_RUNTIME_ASYNC_PLANNING:-1}" -GRP_ONLINE_REPLANNING="${GRP_ONLINE_REPLANNING:-1}" -GRP_REPLAN_COOLDOWN_STEPS="${GRP_REPLAN_COOLDOWN_STEPS:-5}" -GRP_QUEUE_PRESSURE_THRESHOLD="${GRP_QUEUE_PRESSURE_THRESHOLD:-0.75}" -GRP_ACTIVE_ROLLOUT_PRESSURE_THRESHOLD="${GRP_ACTIVE_ROLLOUT_PRESSURE_THRESHOLD:-0.85}" -GRP_REJECTED_ROLLOUT_DELTA_THRESHOLD="${GRP_REJECTED_ROLLOUT_DELTA_THRESHOLD:-8}" -GRP_ROLLOUT_TRAIN_IMBALANCE_THRESHOLD="${GRP_ROLLOUT_TRAIN_IMBALANCE_THRESHOLD:-1.25}" -GRP_INTERVAL="${GRP_INTERVAL:-20}" -GRP_WARMUP_STEPS="${GRP_WARMUP_STEPS:-5}" -GRP_MIN_HISTORY="${GRP_MIN_HISTORY:-16}" -GRP_MIN_GAIN_RATIO="${GRP_MIN_GAIN_RATIO:-${GRP_GAIN_THRESHOLD:-0.02}}" -GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP="${GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP:-1}" -GRP_MANAGE_ROLLOUT_PROCESSES="${GRP_MANAGE_ROLLOUT_PROCESSES:-0}" -GRP_RECONFIGURE_TRAINING="${GRP_RECONFIGURE_TRAINING:-0}" -GRP_TRAINING_POOL_ONLY="${GRP_TRAINING_POOL_ONLY:-1}" -GRP_TRAINING_POOL_TARGET_GPUS="${GRP_TRAINING_POOL_TARGET_GPUS:-0}" -GRP_TRAINING_POOL_PLAN_ONLY="${GRP_TRAINING_POOL_PLAN_ONLY:-1}" -GRP_CLUSTER_SWAP_ENABLED="${GRP_CLUSTER_SWAP_ENABLED:-0}" -GRP_HYBRID_WORKER_LAUNCH_ENABLED="${GRP_HYBRID_WORKER_LAUNCH_ENABLED:-0}" -GRP_HYBRID_TRAINING_PREWARM_ENABLED="${GRP_HYBRID_TRAINING_PREWARM_ENABLED:-0}" -GRP_HYBRID_TRAINING_PREWARM_COUNT="${GRP_HYBRID_TRAINING_PREWARM_COUNT:-0}" -GRP_HYBRID_TRAINING_PREWARM_WORKER_IDS="${GRP_HYBRID_TRAINING_PREWARM_WORKER_IDS:-}" -GRP_HYBRID_WORKER_TASK_DIR="${GRP_HYBRID_WORKER_TASK_DIR:-}" -GRP_HYBRID_WORKER_COMMAND_TEMPLATE="${GRP_HYBRID_WORKER_COMMAND_TEMPLATE:-}" -GRP_HYBRID_WORKER_READY_TIMEOUT_S="${GRP_HYBRID_WORKER_READY_TIMEOUT_S:-120}" -GRP_GRADIENT_TRANSPORT_BACKEND="${GRP_GRADIENT_TRANSPORT_BACKEND:-tcp}" -GRP_DECOUPLE_COMMUNICATION_DOMAINS="${GRP_DECOUPLE_COMMUNICATION_DOMAINS:-1}" -GRP_GRADIENT_SERVER_HOST="${GRP_GRADIENT_SERVER_HOST:-127.0.0.1}" -GRP_GRADIENT_SERVER_PUBLIC_HOST="${GRP_GRADIENT_SERVER_PUBLIC_HOST:-}" -GRP_GRADIENT_SERVER_PORT="${GRP_GRADIENT_SERVER_PORT:-0}" -GRP_GRADIENT_SERVER_AUTHKEY="${GRP_GRADIENT_SERVER_AUTHKEY:-rl-framework-elastic}" -GRP_ROLLOUT_RECONFIGURE_STRATEGY="${GRP_ROLLOUT_RECONFIGURE_STRATEGY:-blue_green}" -GRP_PREWARM_NO_SPARE_FALLBACK_STRATEGY="${GRP_PREWARM_NO_SPARE_FALLBACK_STRATEGY:-restart_all}" -GRP_DRAIN_BEFORE_RECONFIGURE="${GRP_DRAIN_BEFORE_RECONFIGURE:-1}" -GRP_RUNTIME_PEER_REQUEST_WAIT_S="${GRP_RUNTIME_PEER_REQUEST_WAIT_S:-45}" -GRP_BATCH_COLLECTION_TIMEOUT_S="${GRP_BATCH_COLLECTION_TIMEOUT_S:-300}" -GRP_BATCH_COLLECTION_MAX_RETRIES="${GRP_BATCH_COLLECTION_MAX_RETRIES:-2}" -GRP_USE_NCCL_BARRIER_AFTER_ROLLOUT="${GRP_USE_NCCL_BARRIER_AFTER_ROLLOUT:-0}" -GRP_USE_NCCL_BARRIER_BEFORE_WEIGHT_SYNC="${GRP_USE_NCCL_BARRIER_BEFORE_WEIGHT_SYNC:-0}" -GRP_INITIAL_ROLLOUT_TP_LIST="${GRP_INITIAL_ROLLOUT_TP_LIST:-}" -GRP_FORCE_TRAIN_GPUS="${GRP_FORCE_TRAIN_GPUS:-}" -GRP_ROLLOUT_MANIFEST_PATH="${GRP_ROLLOUT_MANIFEST_PATH:-}" -GRP_ROLLOUT_PID_REGISTRY_PATH="${GRP_ROLLOUT_PID_REGISTRY_PATH:-}" -GRP_WAIT_ROLLOUT_PROCESS_START_READY="${GRP_WAIT_ROLLOUT_PROCESS_START_READY:-1}" -GRP_POST_ROLLOUT_STOP_GRACE_S="${GRP_POST_ROLLOUT_STOP_GRACE_S:-45}" -GRP_VLLM_LAUNCH_COMMAND_TEMPLATE="${GRP_VLLM_LAUNCH_COMMAND_TEMPLATE:-}" -GRP_VLLM_STOP_COMMAND_TEMPLATE="${GRP_VLLM_STOP_COMMAND_TEMPLATE:-}" -ROLLOUT_WEIGHT_SYNC_MODE="${ROLLOUT_WEIGHT_SYNC_MODE:-restart}" -REQUIRE_ROLLOUT_WEIGHT_SYNC="${REQUIRE_ROLLOUT_WEIGHT_SYNC:-1}" -ROLLOUT_WEIGHT_SYNC_EXPORT_ONLY="${ROLLOUT_WEIGHT_SYNC_EXPORT_ONLY:-1}" -ROLLOUT_WEIGHT_RELOAD_METHOD="${ROLLOUT_WEIGHT_RELOAD_METHOD:-restart}" -ROLLOUT_WEIGHT_RELOAD_STRATEGY="${ROLLOUT_WEIGHT_RELOAD_STRATEGY:-parallel}" -MEGATRON_STREAMING_EXPORT="${MEGATRON_STREAMING_EXPORT:-1}" -PREFERRED_TRAIN_NODE="${PREFERRED_TRAIN_NODE:-gn026}" -AVOID_TRAIN_NODE="${AVOID_TRAIN_NODE:-gn019}" -RUN_NCCL_PREFLIGHT="${RUN_NCCL_PREFLIGHT:-1}" -NCCL_PREFLIGHT_REQUIRED="${NCCL_PREFLIGHT_REQUIRED:-1}" -NCCL_PREFLIGHT_ELEMENTS="${NCCL_PREFLIGHT_ELEMENTS:-1048576}" -NCCL_PREFLIGHT_ITERATIONS="${NCCL_PREFLIGHT_ITERATIONS:-1}" -NCCL_PREFLIGHT_WALLTIME="${NCCL_PREFLIGHT_WALLTIME:-300}" - -source "$VENV_PATH" -cd "$PROJECT_DIR" - -mkdir -p logs -JOB_ID="${SLURM_JOB_ID:-manual}" -JOB_LOG_DIR="$PROJECT_DIR/logs/r2e_gym_cmlfq_24gpu/job_${JOB_ID}" -ROLLOUT_SYNC_DIR="$JOB_LOG_DIR/rollout_weight_sync" -CMLFQ_TREE_PATH="$PROJECT_DIR/logs/r2e_gym_cmlfq_24gpu/cmlfq_tree_${JOB_ID}.json" -CMLFQ_SHARED_LOAD_DIR="$JOB_LOG_DIR/cmlfq_shared_load" -GRP_ROLLOUT_MANIFEST_PATH="${GRP_ROLLOUT_MANIFEST_PATH:-$JOB_LOG_DIR/global_resource_rollout_manifest.json}" -GRP_ROLLOUT_PID_REGISTRY_PATH="${GRP_ROLLOUT_PID_REGISTRY_PATH:-$JOB_LOG_DIR/rollout_process_registry.jsonl}" -GRP_HYBRID_WORKER_TASK_DIR="${GRP_HYBRID_WORKER_TASK_DIR:-$JOB_LOG_DIR/elastic_training_tasks}" -GRP_VLLM_READY_TIMEOUT_S="${GRP_VLLM_READY_TIMEOUT_S:-$MAX_WAIT}" -VLLM_CUSTOM_ALL_REDUCE_FLAG="" -if [ "$VLLM_DISABLE_CUSTOM_ALL_REDUCE" = "1" ]; then - VLLM_CUSTOM_ALL_REDUCE_FLAG="--disable-custom-all-reduce" -fi -if [ "$GRP_MANAGE_ROLLOUT_PROCESSES" = "1" ] && [ -z "$GRP_VLLM_LAUNCH_COMMAND_TEMPLATE" ]; then - GRP_VLLM_LAUNCH_COMMAND_TEMPLATE="srun --exclusive --nodes=1 --ntasks=1 --nodelist={host} --gpus={tp} --cpus-per-task=16 bash -lc \"source '$VENV_PATH' && export TOKENIZERS_PARALLELISM=false && export PLANNED_CUDA_VISIBLE_DEVICES={gpus} && if [ -z \\\"\\\${{CUDA_VISIBLE_DEVICES:-}}\\\" ]; then export CUDA_VISIBLE_DEVICES=\\\"\\\$PLANNED_CUDA_VISIBLE_DEVICES\\\"; fi && echo \\\"CUDA_VISIBLE_DEVICES=\\\${{CUDA_VISIBLE_DEVICES}} planned=\\\${{PLANNED_CUDA_VISIBLE_DEVICES}}\\\" && export MASTER_ADDR=127.0.0.1 && export MASTER_PORT=\\\$((20000 + {port})) && export NCCL_P2P_DISABLE='$VLLM_NCCL_P2P_DISABLE' && export NCCL_IB_DISABLE='$VLLM_NCCL_IB_DISABLE' && export CUDA_LAUNCH_BLOCKING='$VLLM_CUDA_LAUNCH_BLOCKING' && {python} '$PROJECT_DIR/scripts/restartable_vllm_server.py' --instance-id {instance_id} --control-dir {control_dir} --health-url {local_health_url} --initial-model {initial_model} --ready-timeout '$MAX_WAIT' --reload-method '$ROLLOUT_WEIGHT_RELOAD_METHOD' --reload-strategy '$ROLLOUT_WEIGHT_RELOAD_STRATEGY' -- python3 '$PROJECT_DIR/scripts/vllm_hot_reload_api_server.py' --worker-extension-cls RL_Framework.vllm_hot_reload.InplaceReloadWorkerExtension --model __MODEL_PATH__ --served-model-name {model_path} --host 0.0.0.0 --port {port} --tensor-parallel-size {tp} --max-model-len {max_model_len} --dtype bfloat16 --gpu-memory-utilization {gpu_memory_utilization} --trust-remote-code --enforce-eager $VLLM_CUSTOM_ALL_REDUCE_FLAG\"" -fi -if [ "$GRP_MANAGE_ROLLOUT_PROCESSES" = "1" ] && [ -z "$GRP_VLLM_STOP_COMMAND_TEMPLATE" ]; then - GRP_VLLM_STOP_COMMAND_TEMPLATE="srun --overlap --nodes=1 --ntasks=1 --nodelist={host} bash -lc \"pkill -TERM -f 'restartable_vllm_server.py.*--instance-id {instance_id}' || pkill -TERM -f 'vllm.entrypoints.openai.api_server.*--port {port}' || true\"" -fi -if [ "$GRP_HYBRID_WORKER_LAUNCH_ENABLED" = "1" ] && [ -z "$GRP_HYBRID_WORKER_COMMAND_TEMPLATE" ]; then - GRP_HYBRID_WORKER_COMMAND_TEMPLATE="srun --overlap --nodes=1 --ntasks=1 --nodelist={host} --gpus=1 --cpus-per-task=8 bash -lc \"source '$VENV_PATH' && export TOKENIZERS_PARALLELISM=false && export PLANNED_CUDA_VISIBLE_DEVICES={gpus} && if [ -z \\\"\\\${{CUDA_VISIBLE_DEVICES:-}}\\\" ]; then export CUDA_VISIBLE_DEVICES=\\\"\\\$PLANNED_CUDA_VISIBLE_DEVICES\\\"; fi && {python} {rl_framework_path}/scripts/elastic_hybrid_worker.py --worker-id {worker_id} --target-core-id {target_core_id} --snapshot-path {snapshot_path} --gradient-host {gradient_host} --gradient-port {gradient_port} --authkey {authkey} --task-dir {task_dir} --gradient-transport {gradient_transport_backend} --native-rdma-device {native_rdma_device} --native-rdma-gid-index {native_rdma_gid_index} --native-rdma-ib-port {native_rdma_ib_port} --native-rdma-max-bytes {native_rdma_max_bytes}\"" -fi -export GRP_DYNAMIC_RECONFIG_ENABLED -export GRP_RUNTIME_ASYNC_PLANNING -export GRP_ONLINE_REPLANNING -export GRP_REPLAN_COOLDOWN_STEPS -export GRP_QUEUE_PRESSURE_THRESHOLD -export GRP_ACTIVE_ROLLOUT_PRESSURE_THRESHOLD -export GRP_REJECTED_ROLLOUT_DELTA_THRESHOLD -export GRP_ROLLOUT_TRAIN_IMBALANCE_THRESHOLD -export GRP_INTERVAL -export GRP_WARMUP_STEPS -export GRP_MIN_HISTORY -export GRP_MIN_GAIN_RATIO -export GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP -export GRP_MANAGE_ROLLOUT_PROCESSES -export GRP_RECONFIGURE_TRAINING -export GRP_TRAINING_POOL_ONLY -export GRP_TRAINING_POOL_TARGET_GPUS -export GRP_TRAINING_POOL_PLAN_ONLY -export GRP_CLUSTER_SWAP_ENABLED -export GRP_HYBRID_WORKER_LAUNCH_ENABLED -export GRP_HYBRID_TRAINING_PREWARM_ENABLED -export GRP_HYBRID_TRAINING_PREWARM_COUNT -export GRP_HYBRID_TRAINING_PREWARM_WORKER_IDS -export GRP_HYBRID_WORKER_TASK_DIR -export GRP_HYBRID_WORKER_COMMAND_TEMPLATE -export GRP_HYBRID_WORKER_READY_TIMEOUT_S -export GRP_GRADIENT_TRANSPORT_BACKEND -export GRP_DECOUPLE_COMMUNICATION_DOMAINS -export GRP_GRADIENT_SERVER_HOST -export GRP_GRADIENT_SERVER_PUBLIC_HOST -export GRP_GRADIENT_SERVER_PORT -export GRP_GRADIENT_SERVER_AUTHKEY -export GRP_ROLLOUT_RECONFIGURE_STRATEGY -export GRP_PREWARM_NO_SPARE_FALLBACK_STRATEGY -export GRP_DRAIN_BEFORE_RECONFIGURE -export GRP_RUNTIME_PEER_REQUEST_WAIT_S -export GRP_BATCH_COLLECTION_TIMEOUT_S -export GRP_BATCH_COLLECTION_MAX_RETRIES -export GRP_USE_NCCL_BARRIER_AFTER_ROLLOUT -export GRP_USE_NCCL_BARRIER_BEFORE_WEIGHT_SYNC -export GRP_INITIAL_ROLLOUT_TP_LIST -export GRP_FORCE_TRAIN_GPUS -export GRP_ROLLOUT_MANIFEST_PATH -export GRP_ROLLOUT_PID_REGISTRY_PATH -export GRP_WAIT_ROLLOUT_PROCESS_START_READY -export GRP_POST_ROLLOUT_STOP_GRACE_S -export GRP_VLLM_READY_TIMEOUT_S -export GRP_VLLM_LAUNCH_COMMAND_TEMPLATE -export GRP_VLLM_STOP_COMMAND_TEMPLATE -export ROLLOUT_WEIGHT_SYNC_MODE -export REQUIRE_ROLLOUT_WEIGHT_SYNC -export ROLLOUT_WEIGHT_SYNC_EXPORT_ONLY -export ROLLOUT_WEIGHT_RELOAD_METHOD -export ROLLOUT_WEIGHT_RELOAD_STRATEGY -export MEGATRON_STREAMING_EXPORT -mkdir -p "$JOB_LOG_DIR" -mkdir -p "$ROLLOUT_SYNC_DIR" -mkdir -p "$CMLFQ_SHARED_LOAD_DIR" - -if [ -n "$CMLFQ_WARM_START_TREE" ] && [ ! -e "$CMLFQ_TREE_PATH" ]; then - if [ ! -s "$CMLFQ_WARM_START_TREE" ]; then - echo "ERROR: CMLFQ warm-start tree does not exist or is empty: $CMLFQ_WARM_START_TREE" >&2 - exit 2 - fi - cp "$CMLFQ_WARM_START_TREE" "$CMLFQ_TREE_PATH" - echo "C-MLFQ warm-start tree: $CMLFQ_WARM_START_TREE -> $CMLFQ_TREE_PATH" -fi - -export PYTHONPATH="$(dirname "$PROJECT_DIR"):${PYTHONPATH:-}" -export TOKENIZERS_PARALLELISM=false -export WANDB_MODE="${WANDB_MODE:-offline}" -export WANDB_DIR="${PROJECT_DIR}/wandb_r2e_gym_cmlfq_24gpu" -export NO_PROXY="localhost,127.0.0.1,${NO_PROXY:-}" -unset NCCL_ASYNC_ERROR_HANDLING -export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 -export TORCH_NCCL_ENABLE_MONITORING=0 -export TORCH_NCCL_TRACE_BUFFER_SIZE=0 -export TORCH_NCCL_DUMP_ON_TIMEOUT=0 -export TORCH_NCCL_DESYNC_DEBUG=0 -export TORCH_NCCL_ENABLE_TIMING=0 -export TORCH_NCCL_HIGH_PRIORITY=0 -export NCCL_DEBUG="${NCCL_DEBUG:-WARN}" -export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}" -export PYTHONUNBUFFERED=1 -export CUDA_DEVICE_MAX_CONNECTIONS="${CUDA_DEVICE_MAX_CONNECTIONS:-1}" - -mapfile -t NODES < <(scontrol show hostnames "$SLURM_NODELIST" 2>/dev/null || true) -if [ "${#NODES[@]}" -eq 0 ]; then - mapfile -t NODES < <(python3 - <<'PY' -import os -import re - -value = os.environ.get("SLURM_NODELIST", "") - -def expand_part(part: str) -> list[str]: - match = re.fullmatch(r"([^\[]+)\[(.+)\]", part) - if not match: - return [part] if part else [] - prefix, body = match.groups() - out: list[str] = [] - for item in body.split(","): - if "-" in item: - start, end = item.split("-", 1) - width = max(len(start), len(end)) - for number in range(int(start), int(end) + 1): - out.append(f"{prefix}{number:0{width}d}") - else: - out.append(f"{prefix}{item}") - return out - -for chunk in re.split(r",(?![^\[]*\])", value): - for node in expand_part(chunk): - print(node) -PY -) -fi -MIN_NODE_COUNT=$((TRAIN_GPUS / 4 + 1)) -if [ "${#NODES[@]}" -lt "$MIN_NODE_COUNT" ]; then - echo "ERROR: R2E-Gym C-MLFQ training requires at least ${MIN_NODE_COUNT} nodes for TRAIN_GPUS=${TRAIN_GPUS}; got ${#NODES[@]}" >&2 - exit 2 -fi - -# Keep a known cross-node participant in the FSDP group when Slurm allocates -# it, regardless of lexical node ordering. This makes communication regressions -# reproducible while still allowing Slurm to choose the remaining nodes. -if [ -n "$PREFERRED_TRAIN_NODE" ] && [ "${NODES[0]}" != "$PREFERRED_TRAIN_NODE" ]; then - preferred_found=0 - reordered_nodes=("${NODES[0]}") - for node in "${NODES[@]}"; do - if [ "$node" = "$PREFERRED_TRAIN_NODE" ]; then - reordered_nodes+=("$node") - preferred_found=1 - break - fi - done - if [ "$preferred_found" = "1" ]; then - for node in "${NODES[@]:1}"; do - if [ "$node" != "$PREFERRED_TRAIN_NODE" ]; then - reordered_nodes+=("$node") - fi - done - NODES=("${reordered_nodes[@]}") - fi -fi - -# Keep a suspect-but-usable node in the rollout pool. vLLM health and API -# checks validate it before training, while FSDP remains on known-good nodes. -if [ -n "$AVOID_TRAIN_NODE" ]; then - reordered_nodes=() - deferred_nodes=() - for node in "${NODES[@]}"; do - if [ "$node" = "$AVOID_TRAIN_NODE" ]; then - deferred_nodes+=("$node") - else - reordered_nodes+=("$node") - fi - done - NODES=("${reordered_nodes[@]}" "${deferred_nodes[@]}") -fi - -if [ $((TRAIN_GPUS % 4)) -ne 0 ]; then - echo "ERROR: TRAIN_GPUS must be a multiple of 4 for full-node training placement; got ${TRAIN_GPUS}" >&2 - exit 2 -fi -TRAIN_NODE_COUNT=$((TRAIN_GPUS / 4)) -if [ "$TRAIN_NODE_COUNT" -lt 1 ] || [ "$TRAIN_NODE_COUNT" -ge "${#NODES[@]}" ]; then - echo "ERROR: TRAIN_GPUS=${TRAIN_GPUS} leaves no rollout node in ${#NODES[@]} allocated nodes" >&2 - exit 2 -fi -TRAIN_MODEL_PARALLEL_SIZE=$((TRAIN_TP_SIZE * TRAIN_PP_SIZE * TRAIN_CP_SIZE)) -if [ $((TRAIN_GPUS % TRAIN_MODEL_PARALLEL_SIZE)) -ne 0 ]; then - echo "ERROR: TRAIN_GPUS must be divisible by TP*PP*CP: ${TRAIN_GPUS} vs ${TRAIN_MODEL_PARALLEL_SIZE}" >&2 - exit 2 -fi -TRAIN_DP_SIZE=$((TRAIN_GPUS / TRAIN_MODEL_PARALLEL_SIZE)) -if [ $((TRAIN_BATCH_SIZE % (TRAIN_DP_SIZE * TRAIN_MICRO_BATCH_SIZE))) -ne 0 ]; then - echo "ERROR: TRAIN_BATCH_SIZE must be divisible by DP * TRAIN_MICRO_BATCH_SIZE: ${TRAIN_BATCH_SIZE} vs ${TRAIN_DP_SIZE}*${TRAIN_MICRO_BATCH_SIZE}" >&2 - exit 2 -fi -LOCAL_BATCH_SIZE=$((TRAIN_BATCH_SIZE / TRAIN_DP_SIZE)) -if [ $((LOCAL_BATCH_SIZE % N_SAMPLES)) -ne 0 ]; then - echo "ERROR: local batch per DP replica must be divisible by N_SAMPLES: local_batch_size=${LOCAL_BATCH_SIZE}, N_SAMPLES=${N_SAMPLES}" >&2 - exit 2 -fi -TRAIN_NODES=("${NODES[@]:0:$TRAIN_NODE_COUNT}") -ROLLOUT_NODES=("${NODES[@]:$TRAIN_NODE_COUNT}") -ROLLOUT_GPUS=$((${#ROLLOUT_NODES[@]} * 4)) -TOTAL_GPUS=$((TRAIN_GPUS + ROLLOUT_GPUS)) -MASTER_ADDR="${TRAIN_NODES[0]}" -RUNTIME_CONFIG="$PROJECT_DIR/configs/.r2e_gym_cmlfq_24gpu_${JOB_ID}.yaml" -PLAN_ENV="$JOB_LOG_DIR/planned_rollout.env" - -echo "============================================================" -echo "R2E-Gym full RL post-training with C-MLFQ, Qwen3-30B-A3B, ${TOTAL_GPUS} GPUs" -echo "============================================================" -echo "Job: $JOB_ID" -echo "Model: $MODEL_PATH" -echo "Model arch config: $MODEL_ARCH_CONFIG" -echo "Train backend: $TRAIN_BACKEND" -echo "Train topology: TP=$TRAIN_TP_SIZE PP=$TRAIN_PP_SIZE CP=$TRAIN_CP_SIZE EP=$TRAIN_EP_SIZE" -echo "Megatron CPU initialization: $MEGATRON_USE_CPU_INITIALIZATION" -echo "Megatron grouped GEMM: ${MCORE_MOE_GROUPED_GEMM:-1}" -echo "Train nodes: ${TRAIN_NODES[*]} (${TRAIN_GPUS} GPUs)" -echo "Rollout nodes: ${ROLLOUT_NODES[*]} (GlobalResourcePlanner decides TP layout)" -echo "Total GPUs: $TOTAL_GPUS (train=${TRAIN_GPUS}, rollout=${ROLLOUT_GPUS})" -echo "Total steps: $TOTAL_STEPS" -echo "Max model len: $MAX_MODEL_LEN" -echo "Max new tokens: $MAX_NEW_TOKENS" -echo "Train batch size: $TRAIN_BATCH_SIZE" -echo "Local batch per DP replica: $LOCAL_BATCH_SIZE" -echo "N samples: $N_SAMPLES" -echo "Max concurrent rollouts: $MAX_CONCURRENT_ROLLOUTS" -echo "Queue size: $QUEUE_SIZE" -echo "R2E max turns: $R2E_MAX_TURNS" -echo "R2E max prompt tokens: $R2E_MAX_PROMPT_TOKENS" -echo "Eval samples: $EVAL_MAX_SAMPLES ($R2E_EVAL_STRATEGY)" -echo "Long-context TP first: $LONG_CONTEXT_TP_FIRST" -echo "vLLM read timeout: $VLLM_READ_TIMEOUT" -echo "vLLM NCCL_P2P_DISABLE: $VLLM_NCCL_P2P_DISABLE" -echo "Train NCCL_P2P_DISABLE: $NCCL_P2P_DISABLE" -echo "Train NCCL_IB_DISABLE: $NCCL_IB_DISABLE" -echo "Logs: $JOB_LOG_DIR" -python3 -c 'import torch, transformers, vllm; print("torch", torch.__version__, "transformers", transformers.__version__, "vllm", vllm.__version__)' - -VLLM_STEP_PIDS=() -declare -A VLLM_PID_BY_NAME=() -ROLLOUT_NODE_LIST=() -ROLLOUT_TP_LIST=() -ROLLOUT_PORT_LIST=() -ROLLOUT_NAME_LIST=() -ROLLOUT_GPU_LIST=() - -cleanup() { - local exit_code=$? - trap - EXIT INT TERM - echo "[cleanup] stopping vLLM processes..." - for pid in "${VLLM_STEP_PIDS[@]:-}"; do - kill "$pid" 2>/dev/null || true - done - for i in "${!ROLLOUT_NODE_LIST[@]}"; do - local node="${ROLLOUT_NODE_LIST[$i]}" - local port="${ROLLOUT_PORT_LIST[$i]}" - srun --overlap --nodes=1 --ntasks=1 --nodelist="$node" \ - bash -lc "pkill -f 'vllm.entrypoints.openai.api_server.*--port ${port}' 2>/dev/null || true" \ - >/dev/null 2>&1 || true - done - python3 "$PROJECT_DIR/scripts/merge_cmlfq_prefix_trees.py" \ - --output "$CMLFQ_TREE_PATH" || true - echo "[cleanup] complete, exit=$exit_code" - exit "$exit_code" -} -trap cleanup EXIT INT TERM - -echo "[1/6] Running GlobalResourcePlanner preflight for ${TOTAL_GPUS}-GPU runtime config" -export PROJECT_DIR MODEL_PATH MODEL_ARCH_CONFIG TOTAL_STEPS MAX_MODEL_LEN MAX_NEW_TOKENS EVAL_INTERVAL MAX_WAIT SYNC_INTERVAL RL_TRAIN_PHASE_TRACE -export TRAIN_BATCH_SIZE TRAIN_MICRO_BATCH_SIZE N_SAMPLES MAX_CONCURRENT_ROLLOUTS QUEUE_SIZE VLLM_BASE_PORT GPU_MEMORY_UTILIZATION JOB_ID -export JOB_LOG_DIR EXPERIMENT_TAG SCHEDULER_TYPE GRP_ENABLED -export LONG_CONTEXT_TP_FIRST VLLM_READ_TIMEOUT VLLM_CONNECT_TIMEOUT VLLM_WRITE_TIMEOUT VLLM_POOL_TIMEOUT -export VLLM_NCCL_P2P_DISABLE VLLM_NCCL_IB_DISABLE VLLM_CUDA_LAUNCH_BLOCKING -export NCCL_P2P_DISABLE NCCL_IB_DISABLE -export TRAIN_GPUS ROLLOUT_GPUS TOTAL_GPUS -export TRAIN_BACKEND TRAIN_TP_SIZE TRAIN_PP_SIZE TRAIN_CP_SIZE TRAIN_EP_SIZE -export EXPERT_TENSOR_PARALLEL_SIZE USE_DISTRIBUTED_OPTIMIZER -export MEGATRON_USE_PRECISION_AWARE_OPTIMIZER MEGATRON_OPTIMIZER_CPU_OFFLOAD -export MEGATRON_OPTIMIZER_OFFLOAD_FRACTION -export RUNTIME_CONFIG PLAN_ENV -export ALLOW_QWEN30_FALLBACK -export GRP_PROFILE_DATASET_JSONL GRP_PROFILE_SAMPLE_SIZE GRP_PROFILE_STRATEGY GRP_PROFILE_SEED GRP_PROFILE_SAMPLES_PER_PROMPT -export CMLFQ_TREE_PATH CMLFQ_SHARED_LOAD_DIR CMLFQ_SHARED_LOAD_TTL CMLFQ_SHARED_LOAD_HEARTBEAT CMLFQ_TREE_PERSIST_INTERVAL -ROLLOUT_NODES_CSV="$(IFS=,; echo "${ROLLOUT_NODES[*]}")" -export ROLLOUT_NODES_CSV -python3 - <<'PY' -import os -import shlex -from pathlib import Path -import yaml - -from transformers import AutoTokenizer - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.cost_model.preflight_planner import PreflightPlanner -from RL_Framework.infra.cost_model.startup_profile import ( - load_jsonl_rows, - load_profile_summary, - profile_jsonl_has_records, - profile_metadata_matches, - startup_profile_metadata, - summarize_length_profile, - write_profile_jsonl, - write_profile_summary, -) -from RL_Framework.workflow.r2e_gym_profile import build_r2e_gym_length_profile - -project = Path(os.environ["PROJECT_DIR"]) -base = project / "configs" / "r2e_gym_cmlfq_qwen3_4b.yaml" -seed_path = project / "configs" / f".r2e_gym_cmlfq_24gpu_seed_{os.environ['JOB_ID']}.yaml" -runtime_path = Path(os.environ["RUNTIME_CONFIG"]) -plan_env = Path(os.environ["PLAN_ENV"]) -job_log_dir = Path(os.environ["JOB_LOG_DIR"]) -rollout_nodes = [n for n in os.environ["ROLLOUT_NODES_CSV"].split(",") if n] -base_port = int(os.environ["VLLM_BASE_PORT"]) -max_model_len = int(os.environ["MAX_MODEL_LEN"]) -max_new_tokens = int(os.environ["MAX_NEW_TOKENS"]) -r2e_max_turns = int(os.environ["R2E_MAX_TURNS"]) -r2e_max_prompt_tokens = int(os.environ.get("R2E_MAX_PROMPT_TOKENS", "0") or "0") -profile_dataset = Path(os.environ["GRP_PROFILE_DATASET_JSONL"]) -profile_cache_dir = project / "logs" / "r2e_gym_cmlfq_24gpu" / "startup_profile_cache" -profile_jsonl = profile_cache_dir / "grp_startup_profile.jsonl" -profile_summary_json = profile_cache_dir / "grp_startup_profile_summary.json" -train_gpus = int(os.environ["TRAIN_GPUS"]) -rollout_gpus = int(os.environ["ROLLOUT_GPUS"]) -total_gpus = int(os.environ["TOTAL_GPUS"]) -train_tp = int(os.environ["TRAIN_TP_SIZE"]) -train_pp = int(os.environ["TRAIN_PP_SIZE"]) -train_cp = int(os.environ["TRAIN_CP_SIZE"]) -train_dp = train_gpus // (train_tp * train_pp * train_cp) - -seed = { - "base_config": str(base), - "model_arch_config": os.environ["MODEL_ARCH_CONFIG"], - "model_path": os.environ["MODEL_PATH"], - "tokenizer_path": os.environ["MODEL_PATH"], - "train_gpus": train_gpus, - "rollout_gpus": rollout_gpus, - "n_total_gpus": total_gpus, - "train_backend": os.environ["TRAIN_BACKEND"], - "train_tp_size": train_tp, - "train_pp_size": train_pp, - "train_cp_size": train_cp, - "train_ep_size": int(os.environ["TRAIN_EP_SIZE"]), - "expert_tensor_parallel_size": int(os.environ["EXPERT_TENSOR_PARALLEL_SIZE"]), - "train_dp_size": train_dp, - "use_distributed_optimizer": os.environ["USE_DISTRIBUTED_OPTIMIZER"] == "1", - "megatron_grad_reduce_in_fp32": ( - os.environ.get("MEGATRON_GRAD_REDUCE_IN_FP32", "0") == "1" - ), - "megatron_use_precision_aware_optimizer": ( - os.environ.get("MEGATRON_USE_PRECISION_AWARE_OPTIMIZER", "0") == "1" - ), - "megatron_optimizer_cpu_offload": ( - os.environ.get("MEGATRON_OPTIMIZER_CPU_OFFLOAD", "0") == "1" - ), - "megatron_optimizer_offload_fraction": float( - os.environ.get("MEGATRON_OPTIMIZER_OFFLOAD_FRACTION", "0.0") - ), - "megatron_optimizer_pin_cpu_grads": ( - os.environ.get("MEGATRON_OPTIMIZER_PIN_CPU_GRADS", "1") == "1" - ), - "megatron_optimizer_pin_cpu_params": ( - os.environ.get("MEGATRON_OPTIMIZER_PIN_CPU_PARAMS", "1") == "1" - ), - "megatron_checkpoint_format": "torch_dist", - "megatron_fully_parallel_save": True, - "megatron_async_save": False, - "megatron_streaming_export": os.environ.get("MEGATRON_STREAMING_EXPORT", "1") == "1", - "megatron_use_transformer_engine": False, - "megatron_use_cpu_initialization": ( - os.environ.get("MEGATRON_USE_CPU_INITIALIZATION", "0") == "1" - ), - "megatron_recompute_num_layers": 1, - "batch_size": int(os.environ["TRAIN_BATCH_SIZE"]), - "micro_batch_size": int(os.environ["TRAIN_MICRO_BATCH_SIZE"]), - "n_samples": int(os.environ["N_SAMPLES"]), - "total_steps": int(os.environ["TOTAL_STEPS"]), - "sync_interval": int(os.environ["SYNC_INTERVAL"]), - "eval_interval": int(os.environ["EVAL_INTERVAL"]), - "max_new_tokens": int(os.environ["MAX_NEW_TOKENS"]), - "max_seq_length": int(os.environ["MAX_MODEL_LEN"]), - "r2e_max_turns": r2e_max_turns, - "r2e_max_prompt_tokens": r2e_max_prompt_tokens, - "max_concurrent_rollouts": int(os.environ["MAX_CONCURRENT_ROLLOUTS"]), - "queue_size": int(os.environ["QUEUE_SIZE"]), - "sync_path": str(project / "logs" / "r2e_gym_cmlfq_24gpu" / f"weights_{os.environ['JOB_ID']}"), - "rollout_weight_sync_mode": os.environ["ROLLOUT_WEIGHT_SYNC_MODE"], - "rollout_weight_sync_control_dir": str(project / "logs" / "r2e_gym_cmlfq_24gpu" / f"job_{os.environ['JOB_ID']}" / "rollout_weight_sync"), - "rollout_weight_sync_timeout_s": int(os.environ["MAX_WAIT"]), - "rollout_weight_sync_export_only": os.environ.get("ROLLOUT_WEIGHT_SYNC_EXPORT_ONLY", "1") == "1", - "rollout_weight_reload_method": os.environ.get("ROLLOUT_WEIGHT_RELOAD_METHOD", "restart"), - "rollout_weight_reload_strategy": os.environ.get("ROLLOUT_WEIGHT_RELOAD_STRATEGY", "parallel"), - "require_rollout_weight_sync": os.environ.get("REQUIRE_ROLLOUT_WEIGHT_SYNC", "1") == "1", - "log_dir": str(project / "logs" / "r2e_gym_cmlfq_24gpu"), - "wandb_run_name": f"{os.environ['EXPERIMENT_TAG']}-{os.environ['JOB_ID']}", - "enable_history_collection": True, - "history_output_dir": str(Path(os.environ["JOB_LOG_DIR"]) / "history"), - "history_save_raw_lengths": True, - "history_flush_interval": 1, - "history_experiment_name": os.environ["EXPERIMENT_TAG"], - "heterogeneous_rollout": { - "enabled": True, - "total_gpus": rollout_gpus, - "available_gpus": list(range(train_gpus, total_gpus)), - "vllm_base_port": int(os.environ["VLLM_BASE_PORT"]), - "max_model_len": int(os.environ["MAX_MODEL_LEN"]), - "gpu_memory_utilization": float(os.environ["GPU_MEMORY_UTILIZATION"]), - "instances": [], - "scheduling": { - "scheduler_type": os.environ["SCHEDULER_TYPE"], - "load_balance_strategy": "least_connections", - "max_queue_length": int(os.environ["QUEUE_SIZE"]), - "enable_fallback": True, - "cmlfq_tree_path": os.environ["CMLFQ_TREE_PATH"], - "cmlfq_tree_persist_interval": int(os.environ["CMLFQ_TREE_PERSIST_INTERVAL"]), - "cmlfq_shared_load_dir": os.environ["CMLFQ_SHARED_LOAD_DIR"], - "cmlfq_shared_load_ttl_s": float(os.environ["CMLFQ_SHARED_LOAD_TTL"]), - "cmlfq_shared_load_heartbeat_s": float(os.environ["CMLFQ_SHARED_LOAD_HEARTBEAT"]), - "cmlfq_buckets": { - "short": { - "tp_degrees": [2], - "max_tokens": 3000, - }, - "medium": { - "tp_degrees": [2], - "max_tokens": 6000, - }, - "long": {"tp_degrees": [4, 2], "max_tokens": max_model_len}, - }, - }, - }, - "global_resource_planner": { - "enabled": os.environ["GRP_ENABLED"] == "1", - "train_backend": "analytic", - "rollout_backend": "analytic", - "plan_interval": int(os.environ["GRP_INTERVAL"]), - "warmup_steps": int(os.environ["GRP_WARMUP_STEPS"]), - "min_history_size": int(os.environ["GRP_MIN_HISTORY"]), - "min_gain_ratio": float(os.environ["GRP_MIN_GAIN_RATIO"]), - "reconfiguration_cost_s": 15.0, - "allowed_rollout_tp": [2, 4], - "require_heterogeneous_rollout_tp": ( - os.environ["GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP"] == "1" - ), - "allowed_train_tp": [train_tp], - "allowed_train_pp": [train_pp], - "fixed_train_gpus": train_gpus, - "micro_batch_sizes": [1], - "startup_profile_enabled": True, - "startup_profile_sample_size": int(os.environ["GRP_PROFILE_SAMPLE_SIZE"]), - "startup_profile_strategy": os.environ["GRP_PROFILE_STRATEGY"], - "startup_profile_seed": int(os.environ["GRP_PROFILE_SEED"]), - "startup_profile_samples_per_prompt": int(os.environ["GRP_PROFILE_SAMPLES_PER_PROMPT"]), - "startup_profile_dataset_jsonl": str(profile_dataset), - "startup_profile_history_jsonl": str(profile_jsonl), - "startup_profile_summary_json": str(profile_summary_json), - "runtime_length_profile_enabled": True, - "runtime_length_profile_jsonl": str(job_log_dir / "runtime_length_profile.jsonl"), - "apply_to_runtime": True, - "verbose": True, - "runtime_async_planning": os.environ["GRP_RUNTIME_ASYNC_PLANNING"] == "1", - "runtime_max_pending_plans": 1, - "runtime_dynamic_reconfiguration_enabled": os.environ["GRP_DYNAMIC_RECONFIG_ENABLED"] == "1", - "runtime_online_replanning": os.environ["GRP_ONLINE_REPLANNING"] == "1", - "runtime_replan_cooldown_steps": int(os.environ["GRP_REPLAN_COOLDOWN_STEPS"]), - "runtime_queue_pressure_threshold": float(os.environ["GRP_QUEUE_PRESSURE_THRESHOLD"]), - "runtime_active_rollout_pressure_threshold": float(os.environ["GRP_ACTIVE_ROLLOUT_PRESSURE_THRESHOLD"]), - "runtime_rejected_rollout_delta_threshold": int(os.environ["GRP_REJECTED_ROLLOUT_DELTA_THRESHOLD"]), - "runtime_rollout_train_imbalance_threshold": float(os.environ["GRP_ROLLOUT_TRAIN_IMBALANCE_THRESHOLD"]), - "runtime_manage_rollout_processes": os.environ["GRP_MANAGE_ROLLOUT_PROCESSES"] == "1", - "runtime_reconfigure_training": os.environ["GRP_RECONFIGURE_TRAINING"] == "1", - "runtime_training_pool_only": os.environ["GRP_TRAINING_POOL_ONLY"] == "1", - "runtime_training_pool_target_gpus": int(os.environ["GRP_TRAINING_POOL_TARGET_GPUS"]), - "runtime_training_pool_plan_only": os.environ["GRP_TRAINING_POOL_PLAN_ONLY"] == "1", - "runtime_cluster_swap_enabled": os.environ["GRP_CLUSTER_SWAP_ENABLED"] == "1", - "hybrid_worker_launch_enabled": os.environ["GRP_HYBRID_WORKER_LAUNCH_ENABLED"] == "1", - "hybrid_training_prewarm_enabled": os.environ["GRP_HYBRID_TRAINING_PREWARM_ENABLED"] == "1", - "hybrid_training_prewarm_count": int(os.environ["GRP_HYBRID_TRAINING_PREWARM_COUNT"]), - "hybrid_training_prewarm_worker_ids": [ - item.strip() - for item in os.environ["GRP_HYBRID_TRAINING_PREWARM_WORKER_IDS"].split(",") - if item.strip() - ], - "hybrid_worker_task_dir": os.environ["GRP_HYBRID_WORKER_TASK_DIR"], - "hybrid_worker_command_template": os.environ["GRP_HYBRID_WORKER_COMMAND_TEMPLATE"], - "hybrid_worker_ready_timeout_s": float(os.environ["GRP_HYBRID_WORKER_READY_TIMEOUT_S"]), - "gradient_transport_backend": os.environ["GRP_GRADIENT_TRANSPORT_BACKEND"], - "decouple_communication_domains": os.environ["GRP_DECOUPLE_COMMUNICATION_DOMAINS"] == "1", - "gradient_server_host": os.environ["GRP_GRADIENT_SERVER_HOST"], - "gradient_server_public_host": os.environ["GRP_GRADIENT_SERVER_PUBLIC_HOST"], - "gradient_server_port": int(os.environ["GRP_GRADIENT_SERVER_PORT"]), - "gradient_server_authkey": os.environ["GRP_GRADIENT_SERVER_AUTHKEY"], - "runtime_rollout_reconfigure_strategy": os.environ["GRP_ROLLOUT_RECONFIGURE_STRATEGY"], - "runtime_prewarm_no_spare_fallback_strategy": os.environ["GRP_PREWARM_NO_SPARE_FALLBACK_STRATEGY"], - "runtime_drain_before_reconfigure": os.environ["GRP_DRAIN_BEFORE_RECONFIGURE"] == "1", - "runtime_peer_request_wait_s": float(os.environ["GRP_RUNTIME_PEER_REQUEST_WAIT_S"]), - "runtime_batch_collection_timeout_s": float(os.environ["GRP_BATCH_COLLECTION_TIMEOUT_S"]), - "runtime_batch_collection_max_retries": int(os.environ["GRP_BATCH_COLLECTION_MAX_RETRIES"]), - "runtime_use_nccl_barrier_after_rollout": os.environ["GRP_USE_NCCL_BARRIER_AFTER_ROLLOUT"] == "1", - "runtime_use_nccl_barrier_before_weight_sync": os.environ["GRP_USE_NCCL_BARRIER_BEFORE_WEIGHT_SYNC"] == "1", - "runtime_rollout_manifest_path": os.environ["GRP_ROLLOUT_MANIFEST_PATH"], - "runtime_rollout_pid_registry_path": os.environ["GRP_ROLLOUT_PID_REGISTRY_PATH"], - "runtime_wait_rollout_process_start_ready": os.environ["GRP_WAIT_ROLLOUT_PROCESS_START_READY"] == "1", - "runtime_post_rollout_stop_grace_s": float(os.environ["GRP_POST_ROLLOUT_STOP_GRACE_S"]), - "runtime_rollout_log_dir": str(project / "logs" / "r2e_gym_cmlfq_24gpu" / f"job_{os.environ['JOB_ID']}" / "runtime_rollout"), - "vllm_ready_timeout_s": float(os.environ["GRP_VLLM_READY_TIMEOUT_S"]), - "vllm_launch_command_template": os.environ["GRP_VLLM_LAUNCH_COMMAND_TEMPLATE"], - "vllm_stop_command_template": os.environ["GRP_VLLM_STOP_COMMAND_TEMPLATE"], - "simulator_allow_fallback": True, - "simulator_timeout_s": 240.0, - }, -} -seed_path.write_text(yaml.safe_dump(seed, sort_keys=False), encoding="utf-8") - -cfg = AsyncRLConfig.from_yaml(str(seed_path)) -profile_metadata = startup_profile_metadata( - dataset_jsonl=profile_dataset, - model_path=cfg.model_path, - tokenizer_path=cfg.tokenizer_path if cfg.tokenizer_path else cfg.model_path, - sample_size=int(os.environ["GRP_PROFILE_SAMPLE_SIZE"]), - strategy=os.environ["GRP_PROFILE_STRATEGY"], - seed=int(os.environ["GRP_PROFILE_SEED"]), - samples_per_prompt=int(os.environ["GRP_PROFILE_SAMPLES_PER_PROMPT"]), - max_new_tokens=max_new_tokens, - max_seq_length=max_model_len, - r2e_max_turns=r2e_max_turns, - r2e_max_prompt_tokens=r2e_max_prompt_tokens, -) -history = None -summary = None -if profile_jsonl_has_records(profile_jsonl): - existing_summary = load_profile_summary(profile_summary_json) - if ( - existing_summary is None - or profile_metadata_matches(existing_summary, profile_metadata) - ): - history = load_jsonl_rows(profile_jsonl) - if not history: - raise RuntimeError(f"startup profile JSONL is empty: {profile_jsonl}") - summary = summarize_length_profile(history) - summary.update(profile_metadata) - summary["reused"] = True - write_profile_summary(summary, profile_summary_json) -if history is None: - rows = load_jsonl_rows(profile_dataset) - if not rows: - raise RuntimeError(f"GRP startup profile dataset is empty: {profile_dataset}") - tokenizer = AutoTokenizer.from_pretrained( - cfg.tokenizer_path if cfg.tokenizer_path else cfg.model_path, - trust_remote_code=True, - ) - if tokenizer.pad_token is None: - tokenizer.pad_token = tokenizer.eos_token - history = build_r2e_gym_length_profile( - rows, - tokenizer=tokenizer, - sample_size=int(os.environ["GRP_PROFILE_SAMPLE_SIZE"]), - strategy=os.environ["GRP_PROFILE_STRATEGY"], - seed=int(os.environ["GRP_PROFILE_SEED"]), - samples_per_prompt=int(os.environ["GRP_PROFILE_SAMPLES_PER_PROMPT"]), - max_turns=r2e_max_turns, - max_new_tokens=max_new_tokens, - max_seq_length=max_model_len, - max_prompt_tokens=r2e_max_prompt_tokens or None, - ) - summary = summarize_length_profile(history) - summary.update(profile_metadata) - write_profile_jsonl(history, profile_jsonl) - write_profile_summary(summary, profile_summary_json) -result = PreflightPlanner(cfg, apply_best_candidate=True).run(history) -planned = result.planned_config -planned.train_backend = os.environ["TRAIN_BACKEND"] -planned.train_tp_size = train_tp -planned.tp_size = train_tp -planned.train_pp_size = train_pp -planned.train_cp_size = train_cp -planned.train_ep_size = int(os.environ["TRAIN_EP_SIZE"]) -planned.expert_tensor_parallel_size = int( - os.environ["EXPERT_TENSOR_PARALLEL_SIZE"] -) -planned.train_dp_size = train_dp -planned.use_distributed_optimizer = ( - os.environ["USE_DISTRIBUTED_OPTIMIZER"] == "1" -) -planned.megatron_grad_reduce_in_fp32 = ( - os.environ.get("MEGATRON_GRAD_REDUCE_IN_FP32", "0") == "1" -) -planned.megatron_use_precision_aware_optimizer = ( - os.environ.get("MEGATRON_USE_PRECISION_AWARE_OPTIMIZER", "0") == "1" -) -planned.megatron_optimizer_cpu_offload = ( - os.environ.get("MEGATRON_OPTIMIZER_CPU_OFFLOAD", "0") == "1" -) -planned.megatron_optimizer_offload_fraction = float( - os.environ.get("MEGATRON_OPTIMIZER_OFFLOAD_FRACTION", "0.0") -) -planned.megatron_optimizer_pin_cpu_grads = ( - os.environ.get("MEGATRON_OPTIMIZER_PIN_CPU_GRADS", "1") == "1" -) -planned.megatron_optimizer_pin_cpu_params = ( - os.environ.get("MEGATRON_OPTIMIZER_PIN_CPU_PARAMS", "1") == "1" -) -planned.megatron_use_cpu_initialization = ( - os.environ.get("MEGATRON_USE_CPU_INITIALIZATION", "0") == "1" -) - -if not planned.heterogeneous_rollout.instances: - if os.environ.get("ALLOW_QWEN30_FALLBACK", "0") != "1": - raise RuntimeError( - "GlobalResourcePlanner produced no feasible candidate. " - "Refusing Qwen30 fallback because it can hide train-memory OOM. " - "Set ALLOW_QWEN30_FALLBACK=1 only for diagnostic rollout runs." - ) - fallback_layout_by_gpus = { - 4: [2, 2], - 8: [4, 2, 2], - 12: [4, 4, 2, 2], - 20: [4, 4, 4, 4, 2, 2], - } - fallback_tp_layout = fallback_layout_by_gpus.get(rollout_gpus) - if fallback_tp_layout is None: - fallback_tp_layout = [] - remaining_gpus_for_layout = rollout_gpus - while remaining_gpus_for_layout >= 4: - fallback_tp_layout.append(4) - remaining_gpus_for_layout -= 4 - if remaining_gpus_for_layout == 2: - fallback_tp_layout.append(2) - elif remaining_gpus_for_layout: - raise RuntimeError(f"Cannot create Qwen30 fallback TP layout for rollout_gpus={rollout_gpus}") - print( - "GlobalResourcePlanner produced no feasible rollout candidate; " - f"using Qwen30 fallback TP layout {fallback_tp_layout}" - ) - planned.train_gpus = train_gpus - planned.rollout_gpus = rollout_gpus - planned.n_total_gpus = total_gpus - planned.train_tp_size = train_tp - planned.tp_size = train_tp - planned.train_pp_size = train_pp - planned.train_cp_size = train_cp - planned.train_dp_size = train_dp - planned.heterogeneous_rollout.enabled = True - planned.heterogeneous_rollout.total_gpus = rollout_gpus - planned.heterogeneous_rollout.instances = [] - from RL_Framework.config import HeterogeneousInstanceConfig - for idx, tp in enumerate(fallback_tp_layout): - planned.heterogeneous_rollout.instances.append( - HeterogeneousInstanceConfig( - instance_id=f"qwen30_fallback_tp{tp}_{idx}", - tp=tp, - gpus=list(range(tp)), - host=planned.heterogeneous_rollout.vllm_host, - description="qwen30_fallback_after_no_feasible_grp_candidate", - ) - ) -if os.environ.get("GRP_INITIAL_ROLLOUT_TP_LIST", "").strip(): - from RL_Framework.config import HeterogeneousInstanceConfig - override_tps = [ - int(item.strip()) - for item in os.environ["GRP_INITIAL_ROLLOUT_TP_LIST"].replace(";", ":").replace(",", ":").split(":") - if item.strip() - ] - if sum(override_tps) != rollout_gpus: - raise RuntimeError( - "GRP_INITIAL_ROLLOUT_TP_LIST must sum to rollout_gpus=" - f"{rollout_gpus}, got {override_tps} sum={sum(override_tps)}" - ) - planned.heterogeneous_rollout.instances = [ - HeterogeneousInstanceConfig( - instance_id=f"initial_override_tp{tp}_{idx}", - tp=tp, - gpus=[], - host=planned.heterogeneous_rollout.vllm_host, - description="initial_rollout_layout_override_for_online_replanning", - ) - for idx, tp in enumerate(override_tps) - ] - planned.train_gpus = train_gpus - planned.rollout_gpus = rollout_gpus - planned.n_total_gpus = total_gpus - planned.train_tp_size = train_tp - planned.train_pp_size = train_pp - planned.train_dp_size = train_dp - print(f"Using initial rollout TP override: {override_tps}") -tp_list = [int(inst.tp) for inst in planned.heterogeneous_rollout.instances] -require_heterogeneous_rollout_tp = ( - os.environ.get("GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP", "1") == "1" -) -if ( - require_heterogeneous_rollout_tp - and len(set(tp_list)) <= 1 - and not os.environ.get("GRP_INITIAL_ROLLOUT_TP_LIST", "").strip() -): - raise RuntimeError(f"GlobalResourcePlanner/fallback did not produce heterogeneous TP degrees: {tp_list}") -if sum(tp_list) != rollout_gpus: - raise RuntimeError(f"GlobalResourcePlanner/fallback rollout GPUs must sum to {rollout_gpus}, got {sum(tp_list)} from {tp_list}") -if planned.train_gpus != train_gpus: - raise RuntimeError(f"GlobalResourcePlanner/fallback must keep train_gpus={train_gpus}, got {planned.train_gpus}") - -remaining = {node: 4 for node in rollout_nodes} -next_gpu = {node: 0 for node in rollout_nodes} -assigned_nodes: list[str] = [] -assigned_tps: list[int] = [] -assigned_ports: list[int] = [] -assigned_names: list[str] = [] -assigned_gpus: list[str] = [] - -for idx, inst in enumerate(planned.heterogeneous_rollout.instances): - tp = int(inst.tp) - node = next((candidate for candidate in rollout_nodes if remaining[candidate] >= tp), None) - if node is None: - raise RuntimeError(f"Cannot pack planned TP list {tp_list} onto nodes {rollout_nodes}") - start_gpu = next_gpu[node] - inst.gpus = list(range(start_gpu, start_gpu + tp)) - inst.host = node - if not inst.instance_id: - inst.instance_id = f"grp_tp{tp}_{idx}" - remaining[node] -= tp - next_gpu[node] += tp - assigned_nodes.append(node) - assigned_tps.append(tp) - assigned_ports.append(base_port + idx) - assigned_names.append(inst.instance_id) - assigned_gpus.append(",".join(str(gpu) for gpu in inst.gpus)) - -planned.vllm_port = base_port -planned.vllm_num_instances = len(assigned_tps) -planned.rollout_gpus = sum(assigned_tps) -planned.n_total_gpus = planned.train_gpus + planned.rollout_gpus -planned.max_concurrent_rollouts = int(os.environ["MAX_CONCURRENT_ROLLOUTS"]) -planned.queue_size = int(os.environ["QUEUE_SIZE"]) -planned.heterogeneous_rollout.vllm_base_port = base_port -planned.heterogeneous_rollout.total_gpus = planned.rollout_gpus - -grp = planned.global_resource_planner -grp.train_backend = "sailor" -grp.rollout_backend = "vidur" -grp.runtime_async_planning = os.environ["GRP_RUNTIME_ASYNC_PLANNING"] == "1" -grp.runtime_max_pending_plans = 1 -grp.simulator_allow_fallback = True -grp.simulator_timeout_s = 240.0 -grp.allowed_rollout_tp = [2, 4] -grp.require_heterogeneous_rollout_tp = ( - os.environ["GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP"] == "1" -) -grp.allowed_train_tp = [train_tp] -grp.allowed_train_pp = [train_pp] -grp.fixed_train_gpus = train_gpus -grp.micro_batch_sizes = [1] - -planned.to_yaml(str(runtime_path)) - -def bash_array(values): - return "(" + " ".join(shlex.quote(str(v)) for v in values) + ")" - -plan_env.write_text( - "\n".join( - [ - f"ROLLOUT_COUNT={len(assigned_tps)}", - f"ROLLOUT_NODE_LIST={bash_array(assigned_nodes)}", - f"ROLLOUT_TP_LIST={bash_array(assigned_tps)}", - f"ROLLOUT_PORT_LIST={bash_array(assigned_ports)}", - f"ROLLOUT_NAME_LIST={bash_array(assigned_names)}", - f"ROLLOUT_GPU_LIST={bash_array(assigned_gpus)}", - f"HETERO_INSTANCE_HOSTS={shlex.quote(','.join(assigned_nodes))}", - f"PLANNED_ROLLOUT_TP_LIST={shlex.quote(','.join(str(v) for v in assigned_tps))}", - f"PLANNED_RUNTIME_CONFIG={shlex.quote(str(runtime_path))}", - ] - ) - + "\n", - encoding="utf-8", -) -print(f"seed_config={seed_path}") -print(f"runtime_config={runtime_path}") -print(f"profile_jsonl={profile_jsonl}") -print(f"profile_summary={summary}") -print(f"decision={result.decision.to_dict()}") -print(f"planned_rollout_tp={assigned_tps}") -print(f"planned_rollout_nodes={assigned_nodes}") -PY - -source "$PLAN_ENV" -echo "GlobalResourcePlanner rollout TP list: ${PLANNED_ROLLOUT_TP_LIST}" -echo "GlobalResourcePlanner rollout nodes: ${ROLLOUT_NODE_LIST[*]}" -TRAIN_NODE_LIST_CSV="$(IFS=,; echo "${TRAIN_NODES[*]}")" - -if [ "$RUN_NCCL_PREFLIGHT" = "1" ]; then - echo "[2/7] Running cross-node NCCL all-gather preflight" - PREFLIGHT_PORT=$((MASTER_PORT + 1)) - PREFLIGHT_STATUS=0 - timeout "$((NCCL_PREFLIGHT_WALLTIME + 30))" srun --overlap \ - --nodes="$TRAIN_NODE_COUNT" \ - --ntasks="$TRAIN_NODE_COUNT" \ - --ntasks-per-node=1 \ - --nodelist="$TRAIN_NODE_LIST_CSV" \ - --gpus-per-task=4 \ - --cpus-per-task=8 \ - --mem=32G \ - bash -lc " - source '$VENV_PATH' - cd '$PROJECT_DIR' - node_rank=\"\${SLURM_PROCID:-0}\" - preflight_log='$JOB_LOG_DIR/nccl_preflight_rank'\${node_rank}'_'\${HOSTNAME}'.log' - { - export PYTHONPATH='$(dirname "$PROJECT_DIR")':\${PYTHONPATH:-} - export MASTER_ADDR='$MASTER_ADDR' - export MASTER_PORT='$PREFLIGHT_PORT' - export CUDA_VISIBLE_DEVICES=0,1,2,3 - echo \"[NCCL preflight launcher] node_rank=\${node_rank} host=\${HOSTNAME} cuda_visible_devices=\${CUDA_VISIBLE_DEVICES}\" - export NCCL_PREFLIGHT_ELEMENTS='$NCCL_PREFLIGHT_ELEMENTS' - export NCCL_PREFLIGHT_ITERATIONS='$NCCL_PREFLIGHT_ITERATIONS' - export NCCL_PREFLIGHT_TIMEOUT='$NCCL_PREFLIGHT_WALLTIME' - export NCCL_P2P_DISABLE='$NCCL_P2P_DISABLE' - export NCCL_IB_DISABLE='$NCCL_IB_DISABLE' - export TORCH_NCCL_ASYNC_ERROR_HANDLING='$TORCH_NCCL_ASYNC_ERROR_HANDLING' - export TORCH_NCCL_TRACE_BUFFER_SIZE='$TORCH_NCCL_TRACE_BUFFER_SIZE' - timeout '$NCCL_PREFLIGHT_WALLTIME' torchrun \ - --nnodes='$TRAIN_NODE_COUNT' \ - --nproc_per_node=4 \ - --node_rank=\"\${node_rank}\" \ - --master_addr='$MASTER_ADDR' \ - --master_port='$PREFLIGHT_PORT' \ - scripts/nccl_allgather_preflight.py - } >\"\$preflight_log\" 2>&1 - " || PREFLIGHT_STATUS=$? - if compgen -G "$JOB_LOG_DIR/nccl_preflight_rank*.log" >/dev/null; then - cat "$JOB_LOG_DIR"/nccl_preflight_rank*.log - fi - if [ "$PREFLIGHT_STATUS" -ne 0 ]; then - if [ "$NCCL_PREFLIGHT_REQUIRED" = "1" ]; then - echo "ERROR: NCCL preflight failed with status ${PREFLIGHT_STATUS}" >&2 - exit "$PREFLIGHT_STATUS" - fi - echo "WARNING: NCCL preflight failed with status ${PREFLIGHT_STATUS}; continuing because NCCL_PREFLIGHT_REQUIRED=0" >&2 - fi -fi - -start_vllm() { - local node="$1" - local tp="$2" - local port="$3" - local name="$4" - local gpu_list="$5" - local log_file="$JOB_LOG_DIR/vllm_${name}.log" - echo "Starting $name on $node TP=$tp planned_GPUs=$gpu_list port=$port" - srun --exclusive \ - --nodes=1 --ntasks=1 --nodelist="$node" \ - --gpus="$tp" \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - export TOKENIZERS_PARALLELISM=false - export PLANNED_CUDA_VISIBLE_DEVICES='$gpu_list' - if [ -z \"\${CUDA_VISIBLE_DEVICES:-}\" ]; then - export CUDA_VISIBLE_DEVICES=\"\$PLANNED_CUDA_VISIBLE_DEVICES\" - fi - echo \"CUDA_VISIBLE_DEVICES=\${CUDA_VISIBLE_DEVICES} planned=\${PLANNED_CUDA_VISIBLE_DEVICES}\" - export MASTER_ADDR=127.0.0.1 - export MASTER_PORT=$((20000 + port)) - export NCCL_P2P_DISABLE='$VLLM_NCCL_P2P_DISABLE' - export NCCL_IB_DISABLE='$VLLM_NCCL_IB_DISABLE' - export CUDA_LAUNCH_BLOCKING='$VLLM_CUDA_LAUNCH_BLOCKING' - python3 '$PROJECT_DIR/scripts/restartable_vllm_server.py' \ - --instance-id '$name' \ - --control-dir '$ROLLOUT_SYNC_DIR' \ - --health-url 'http://127.0.0.1:$port/health' \ - --initial-model '$MODEL_PATH' \ - --ready-timeout '$MAX_WAIT' \ - --reload-method '$ROLLOUT_WEIGHT_RELOAD_METHOD' \ - --reload-strategy '$ROLLOUT_WEIGHT_RELOAD_STRATEGY' \ - -- python3 '$PROJECT_DIR/scripts/vllm_hot_reload_api_server.py' \ - --worker-extension-cls RL_Framework.vllm_hot_reload.InplaceReloadWorkerExtension \ - --model '__MODEL_PATH__' \ - --served-model-name '$MODEL_PATH' \ - --host 0.0.0.0 \ - --port '$port' \ - --tensor-parallel-size '$tp' \ - --max-model-len '$MAX_MODEL_LEN' \ - --dtype bfloat16 \ - --gpu-memory-utilization '$GPU_MEMORY_UTILIZATION' \ - --trust-remote-code \ - --enforce-eager \ - $VLLM_CUSTOM_ALL_REDUCE_FLAG - " >"$log_file" 2>&1 & - VLLM_STEP_PIDS+=("$!") - VLLM_PID_BY_NAME["$name"]="$!" - python3 - </dev/null 2>&1; then - echo "READY: $name at $host:$port (${elapsed}s)" - return 0 - fi - if ! kill -0 "$pid" 2>/dev/null; then - echo "ERROR: $name exited before ready" >&2 - tail -120 "$JOB_LOG_DIR/vllm_${name}.log" || true - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - echo "ERROR: $name not ready after ${MAX_WAIT}s" >&2 - tail -120 "$JOB_LOG_DIR/vllm_${name}.log" || true - return 1 -} - -echo "[3/7] Starting GlobalResourcePlanner rollout vLLM instances" -PRIMARY_INDICES=() -DEFERRED_INDICES=() -declare -A NODE_HAS_PRIMARY=() -for i in "${!ROLLOUT_NODE_LIST[@]}"; do - node="${ROLLOUT_NODE_LIST[$i]}" - if [ -z "${NODE_HAS_PRIMARY[$node]:-}" ]; then - NODE_HAS_PRIMARY["$node"]=1 - PRIMARY_INDICES+=("$i") - else - DEFERRED_INDICES+=("$i") - fi -done - -for i in "${PRIMARY_INDICES[@]}"; do - start_vllm \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_TP_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" \ - "${ROLLOUT_GPU_LIST[$i]}" -done - -echo "[4/7] Waiting for primary rollout services" -for i in "${PRIMARY_INDICES[@]}"; do - wait_for_health \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" -done - -if [ "${#DEFERRED_INDICES[@]}" -gt 0 ]; then - echo "[3b/6] Starting deferred same-node rollout services" - for i in "${DEFERRED_INDICES[@]}"; do - start_vllm \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_TP_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" \ - "${ROLLOUT_GPU_LIST[$i]}" - wait_for_health \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" - done -fi - -echo "[5/7] Checking R2E-Gym data and C-MLFQ flow" -python3 examples/test_r2e_gym.py -python3 examples/test_r2e_cmlfq_flow.py - -echo "[6/7] OpenAI-compatible API check" -curl -fsS "http://${ROLLOUT_NODE_LIST[0]}:${ROLLOUT_PORT_LIST[0]}/v1/completions" \ - -H "Content-Type: application/json" \ - -d "{\"model\":\"$MODEL_PATH\",\"prompt\":\"Write one short sentence.\",\"max_tokens\":8,\"temperature\":0}" \ - | python3 -m json.tool - -export HETERO_INSTANCE_HOSTS -export R2E_GYM_INDEX="${PROJECT_DIR}/data/r2e_gym_v1/index.jsonl" -export R2E_MAX_TURNS -export R2E_MAX_PROMPT_TOKENS -export R2E_EVAL_MAX_SAMPLES="$EVAL_MAX_SAMPLES" -export R2E_EVAL_CONCURRENCY="$EVAL_CONCURRENCY" -export R2E_EVAL_MAX_NEW_TOKENS="$EVAL_MAX_NEW_TOKENS" -export R2E_EVAL_MULTI_TURN -export R2E_EVAL_RECORD_SAMPLES -export R2E_EVAL_STRATEGY -export VLLM_READ_TIMEOUT -export VLLM_CONNECT_TIMEOUT -export VLLM_WRITE_TIMEOUT -export VLLM_POOL_TIMEOUT -export TORCH_DISTRIBUTED_TIMEOUT -export FSDP_ALIGN_SEQUENCE_LENGTHS -export FSDP_LOCKSTEP_BARRIERS -export FSDP_GRADIENT_CHECKPOINTING -export FSDP_ACTIVATION_CHECKPOINTING -export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}" - -echo "[7/7] Starting full R2E-Gym AsyncRLTrainer run on ${TOTAL_GPUS} GPUs" -TRAIN_STEP_PIDS=() -for node_rank in "${!TRAIN_NODES[@]}"; do - node="${TRAIN_NODES[$node_rank]}" - train_log="$JOB_LOG_DIR/training_rank${node_rank}_${node}.log" - echo "Starting training rank $node_rank on $node" - srun --exclusive \ - --nodes=1 \ - --ntasks=1 \ - --nodelist="$node" \ - --gpus=4 \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - cd '$PROJECT_DIR' - export PYTHONPATH='$(dirname "$PROJECT_DIR")':\${PYTHONPATH:-} - export HETERO_INSTANCE_HOSTS='$HETERO_INSTANCE_HOSTS' - export R2E_GYM_INDEX='$R2E_GYM_INDEX' - export R2E_MAX_TURNS='$R2E_MAX_TURNS' - export R2E_MAX_PROMPT_TOKENS='$R2E_MAX_PROMPT_TOKENS' - export R2E_EVAL_MAX_SAMPLES='$R2E_EVAL_MAX_SAMPLES' - export R2E_EVAL_CONCURRENCY='$R2E_EVAL_CONCURRENCY' - export R2E_EVAL_MAX_NEW_TOKENS='$R2E_EVAL_MAX_NEW_TOKENS' - export R2E_EVAL_MULTI_TURN='$R2E_EVAL_MULTI_TURN' - export R2E_EVAL_RECORD_SAMPLES='$R2E_EVAL_RECORD_SAMPLES' - export R2E_EVAL_STRATEGY='$R2E_EVAL_STRATEGY' - export VLLM_READ_TIMEOUT='$VLLM_READ_TIMEOUT' - export VLLM_CONNECT_TIMEOUT='$VLLM_CONNECT_TIMEOUT' - export VLLM_WRITE_TIMEOUT='$VLLM_WRITE_TIMEOUT' - export VLLM_POOL_TIMEOUT='$VLLM_POOL_TIMEOUT' - export TORCH_DISTRIBUTED_TIMEOUT='$TORCH_DISTRIBUTED_TIMEOUT' - export FSDP_ALIGN_SEQUENCE_LENGTHS='$FSDP_ALIGN_SEQUENCE_LENGTHS' - export FSDP_LOCKSTEP_BARRIERS='$FSDP_LOCKSTEP_BARRIERS' - export FSDP_GRADIENT_CHECKPOINTING='$FSDP_GRADIENT_CHECKPOINTING' - export FSDP_ACTIVATION_CHECKPOINTING='$FSDP_ACTIVATION_CHECKPOINTING' - export PYTORCH_CUDA_ALLOC_CONF='$PYTORCH_CUDA_ALLOC_CONF' - export MCORE_MOE_GROUPED_GEMM='$MCORE_MOE_GROUPED_GEMM' - export FSDP_PROGRESS_DIR='$JOB_LOG_DIR/fsdp_progress' - export TORCH_NCCL_ASYNC_ERROR_HANDLING='$TORCH_NCCL_ASYNC_ERROR_HANDLING' - export TORCH_NCCL_TRACE_BUFFER_SIZE='$TORCH_NCCL_TRACE_BUFFER_SIZE' - export TORCH_NCCL_DUMP_ON_TIMEOUT='$TORCH_NCCL_DUMP_ON_TIMEOUT' - export TORCH_NCCL_DESYNC_DEBUG='$TORCH_NCCL_DESYNC_DEBUG' - export TORCH_NCCL_ENABLE_MONITORING='$TORCH_NCCL_ENABLE_MONITORING' - export TORCH_NCCL_ENABLE_TIMING='$TORCH_NCCL_ENABLE_TIMING' - export TORCH_NCCL_HIGH_PRIORITY='$TORCH_NCCL_HIGH_PRIORITY' - export NCCL_DEBUG='$NCCL_DEBUG' - export NCCL_P2P_DISABLE='$NCCL_P2P_DISABLE' - export NCCL_IB_DISABLE='$NCCL_IB_DISABLE' - export PYTHONUNBUFFERED=1 - export MASTER_ADDR='$MASTER_ADDR' - export MASTER_PORT='$MASTER_PORT' - export TOKENIZERS_PARALLELISM=false - export WANDB_MODE='$WANDB_MODE' - export WANDB_DIR='$WANDB_DIR' - torchrun \ - --nnodes='$TRAIN_NODE_COUNT' \ - --nproc_per_node=4 \ - --node_rank='$node_rank' \ - --master_addr='$MASTER_ADDR' \ - --master_port='$MASTER_PORT' \ - examples/r2e_gym_async_rl.py \ - --config '$RUNTIME_CONFIG' - " >"$train_log" 2>&1 & - TRAIN_STEP_PIDS+=("$!") -done - -train_exit=0 -for pid in "${TRAIN_STEP_PIDS[@]}"; do - if ! wait "$pid"; then - train_exit=1 - fi -done -cat "$JOB_LOG_DIR"/training_rank*.log > "$JOB_LOG_DIR/training.log" 2>/dev/null || true -if [ "$train_exit" -ne 0 ]; then - echo "ERROR: one or more training ranks failed" >&2 - exit "$train_exit" -fi - -echo "============================================================" -echo "R2E-Gym C-MLFQ ${TOTAL_GPUS}-GPU training completed" -echo "Logs: $JOB_LOG_DIR" -echo "C-MLFQ tree: $CMLFQ_TREE_PATH" -echo "History: $PROJECT_DIR/logs/r2e_gym_cmlfq/history and logs/r2e_gym_cmlfq_24gpu" -echo "============================================================" diff --git a/scripts/submit_r2e_gym_cmlfq_24gpu_train.slurm b/scripts/submit_r2e_gym_cmlfq_24gpu_train.slurm deleted file mode 100644 index 5315792..0000000 --- a/scripts/submit_r2e_gym_cmlfq_24gpu_train.slurm +++ /dev/null @@ -1,547 +0,0 @@ -#!/bin/bash -#SBATCH -J r2e_cmlfq_24gpu -#SBATCH -o logs/r2e_cmlfq_24gpu_%j.out -#SBATCH -e logs/r2e_cmlfq_24gpu_%j.err -#SBATCH -N 6 -#SBATCH -G 24 -#SBATCH --ntasks-per-node=4 -#SBATCH --cpus-per-task=16 -#SBATCH -p gpu -#SBATCH --time=24:00:00 - -set -euo pipefail - -PROJECT_DIR="${PROJECT_DIR:-/path/to/RL_Framework}" -VENV_PATH="${VENV_PATH:-/path/to/rl_framework_env/bin/activate}" -MODEL_PATH="${MODEL_PATH:-/path/to/Qwen3-4B}" -TOTAL_STEPS="${TOTAL_STEPS:-100}" -MAX_MODEL_LEN="${MAX_MODEL_LEN:-4096}" -MAX_NEW_TOKENS="${MAX_NEW_TOKENS:-128}" -TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-16}" -TRAIN_MICRO_BATCH_SIZE="${TRAIN_MICRO_BATCH_SIZE:-1}" -EVAL_INTERVAL="${EVAL_INTERVAL:-1000}" -EVAL_MAX_SAMPLES="${EVAL_MAX_SAMPLES:-0}" -EVAL_CONCURRENCY="${EVAL_CONCURRENCY:-16}" -EVAL_MAX_NEW_TOKENS="${EVAL_MAX_NEW_TOKENS:-128}" -GPU_MEMORY_UTILIZATION="${GPU_MEMORY_UTILIZATION:-0.85}" -VLLM_BASE_PORT="${VLLM_BASE_PORT:-8000}" -MASTER_PORT="${MASTER_PORT:-29500}" -MAX_WAIT="${MAX_WAIT:-1200}" -R2E_MAX_TURNS="${R2E_MAX_TURNS:-3}" -R2E_MAX_PROMPT_TOKENS="${R2E_MAX_PROMPT_TOKENS:-0}" -GRP_PROFILE_DATASET_JSONL="${GRP_PROFILE_DATASET_JSONL:-$PROJECT_DIR/data/r2e_gym_v1/index.jsonl}" -GRP_PROFILE_SAMPLE_SIZE="${GRP_PROFILE_SAMPLE_SIZE:-64}" -GRP_PROFILE_STRATEGY="${GRP_PROFILE_STRATEGY:-spread}" -GRP_PROFILE_SEED="${GRP_PROFILE_SEED:-0}" -GRP_PROFILE_SAMPLES_PER_PROMPT="${GRP_PROFILE_SAMPLES_PER_PROMPT:-1}" - -source "$VENV_PATH" -cd "$PROJECT_DIR" - -mkdir -p logs -JOB_ID="${SLURM_JOB_ID:-manual}" -JOB_LOG_DIR="$PROJECT_DIR/logs/r2e_gym_cmlfq_24gpu/job_${JOB_ID}" -mkdir -p "$JOB_LOG_DIR" - -export PYTHONPATH="$(dirname "$PROJECT_DIR"):${PYTHONPATH:-}" -export TOKENIZERS_PARALLELISM=false -export WANDB_MODE="${WANDB_MODE:-offline}" -export WANDB_DIR="${PROJECT_DIR}/wandb_r2e_gym_cmlfq_24gpu" -export NO_PROXY="localhost,127.0.0.1,${NO_PROXY:-}" -export NCCL_ASYNC_ERROR_HANDLING=1 -export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}" - -mapfile -t NODES < <(scontrol show hostnames "$SLURM_NODELIST") -if [ "${#NODES[@]}" -lt 6 ]; then - echo "ERROR: 24-GPU R2E-Gym C-MLFQ training requires 6 nodes; got ${#NODES[@]}" >&2 - exit 2 -fi - -TRAIN_NODE="${NODES[0]}" -ROLLOUT_NODES=("${NODES[@]:1:5}") -MASTER_ADDR="$TRAIN_NODE" -RUNTIME_CONFIG="$PROJECT_DIR/configs/.r2e_gym_cmlfq_24gpu_${JOB_ID}.yaml" -PLAN_ENV="$JOB_LOG_DIR/planned_rollout.env" - -echo "============================================================" -echo "R2E-Gym full RL post-training with C-MLFQ, 24 GPUs" -echo "============================================================" -echo "Job: $JOB_ID" -echo "Model: $MODEL_PATH" -echo "Train node: $TRAIN_NODE (4 GPUs)" -echo "Rollout nodes: ${ROLLOUT_NODES[*]} (GlobalResourcePlanner decides TP layout)" -echo "Total GPUs: 24 (train fixed to 4, rollout planned by GRP)" -echo "Total steps: $TOTAL_STEPS" -echo "Max model len: $MAX_MODEL_LEN" -echo "Max new tokens: $MAX_NEW_TOKENS" -echo "Logs: $JOB_LOG_DIR" -python3 -c 'import torch, transformers, vllm; print("torch", torch.__version__, "transformers", transformers.__version__, "vllm", vllm.__version__)' - -VLLM_STEP_PIDS=() -declare -A VLLM_PID_BY_NAME=() -ROLLOUT_NODE_LIST=() -ROLLOUT_TP_LIST=() -ROLLOUT_PORT_LIST=() -ROLLOUT_NAME_LIST=() -ROLLOUT_GPU_LIST=() - -cleanup() { - local exit_code=$? - trap - EXIT INT TERM - echo "[cleanup] stopping vLLM processes..." - for pid in "${VLLM_STEP_PIDS[@]:-}"; do - kill "$pid" 2>/dev/null || true - done - for i in "${!ROLLOUT_NODE_LIST[@]}"; do - local node="${ROLLOUT_NODE_LIST[$i]}" - local port="${ROLLOUT_PORT_LIST[$i]}" - srun --overlap --nodes=1 --ntasks=1 --nodelist="$node" \ - bash -lc "pkill -f 'vllm.entrypoints.openai.api_server.*--port ${port}' 2>/dev/null || true" \ - >/dev/null 2>&1 || true - done - echo "[cleanup] complete, exit=$exit_code" - exit "$exit_code" -} -trap cleanup EXIT INT TERM - -echo "[1/6] Running GlobalResourcePlanner preflight for 24-GPU runtime config" -export PROJECT_DIR MODEL_PATH TOTAL_STEPS MAX_MODEL_LEN MAX_NEW_TOKENS EVAL_INTERVAL -export TRAIN_BATCH_SIZE TRAIN_MICRO_BATCH_SIZE VLLM_BASE_PORT GPU_MEMORY_UTILIZATION JOB_ID -export RUNTIME_CONFIG PLAN_ENV JOB_LOG_DIR -export R2E_MAX_TURNS R2E_MAX_PROMPT_TOKENS -export GRP_PROFILE_DATASET_JSONL GRP_PROFILE_SAMPLE_SIZE GRP_PROFILE_STRATEGY GRP_PROFILE_SEED GRP_PROFILE_SAMPLES_PER_PROMPT -ROLLOUT_NODES_CSV="$(IFS=,; echo "${ROLLOUT_NODES[*]}")" -export ROLLOUT_NODES_CSV -python3 - <<'PY' -import os -import shlex -from pathlib import Path -import yaml - -from transformers import AutoTokenizer - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.cost_model.preflight_planner import PreflightPlanner -from RL_Framework.infra.cost_model.startup_profile import ( - load_jsonl_rows, - load_profile_summary, - profile_jsonl_has_records, - profile_metadata_matches, - startup_profile_metadata, - summarize_length_profile, - write_profile_jsonl, - write_profile_summary, -) -from RL_Framework.workflow.r2e_gym_profile import build_r2e_gym_length_profile - -project = Path(os.environ["PROJECT_DIR"]) -base = project / "configs" / "r2e_gym_cmlfq_qwen3_4b.yaml" -seed_path = project / "configs" / f".r2e_gym_cmlfq_24gpu_seed_{os.environ['JOB_ID']}.yaml" -runtime_path = Path(os.environ["RUNTIME_CONFIG"]) -plan_env = Path(os.environ["PLAN_ENV"]) -job_log_dir = Path(os.environ["JOB_LOG_DIR"]) -rollout_nodes = [n for n in os.environ["ROLLOUT_NODES_CSV"].split(",") if n] -base_port = int(os.environ["VLLM_BASE_PORT"]) -max_model_len = int(os.environ["MAX_MODEL_LEN"]) -max_new_tokens = int(os.environ["MAX_NEW_TOKENS"]) -r2e_max_turns = int(os.environ["R2E_MAX_TURNS"]) -r2e_max_prompt_tokens = int(os.environ.get("R2E_MAX_PROMPT_TOKENS", "0") or "0") -profile_dataset = Path(os.environ["GRP_PROFILE_DATASET_JSONL"]) -profile_cache_dir = project / "logs" / "r2e_gym_cmlfq_24gpu" / "startup_profile_cache" -profile_jsonl = profile_cache_dir / "grp_startup_profile.jsonl" -profile_summary_json = profile_cache_dir / "grp_startup_profile_summary.json" - -seed = { - "base_config": str(base), - "model_path": os.environ["MODEL_PATH"], - "tokenizer_path": os.environ["MODEL_PATH"], - "train_gpus": 4, - "rollout_gpus": 20, - "n_total_gpus": 24, - "train_tp_size": 1, - "train_pp_size": 1, - "train_dp_size": 4, - "batch_size": int(os.environ["TRAIN_BATCH_SIZE"]), - "micro_batch_size": int(os.environ["TRAIN_MICRO_BATCH_SIZE"]), - "total_steps": int(os.environ["TOTAL_STEPS"]), - "eval_interval": int(os.environ["EVAL_INTERVAL"]), - "max_new_tokens": int(os.environ["MAX_NEW_TOKENS"]), - "max_seq_length": int(os.environ["MAX_MODEL_LEN"]), - "r2e_max_turns": r2e_max_turns, - "r2e_max_prompt_tokens": r2e_max_prompt_tokens, - "max_concurrent_rollouts": 32, - "sync_path": str(project / "logs" / "r2e_gym_cmlfq_24gpu" / f"weights_{os.environ['JOB_ID']}"), - "log_dir": str(project / "logs" / "r2e_gym_cmlfq_24gpu"), - "wandb_run_name": f"r2e-gym-cmlfq-24gpu-{os.environ['JOB_ID']}", - "enable_history_collection": True, - "history_output_dir": str(job_log_dir / "history"), - "history_save_raw_lengths": True, - "history_flush_interval": 1, - "history_experiment_name": f"r2e-gym-cmlfq-24gpu-{os.environ['JOB_ID']}", - "heterogeneous_rollout": { - "enabled": True, - "total_gpus": 20, - "available_gpus": list(range(4, 24)), - "vllm_base_port": int(os.environ["VLLM_BASE_PORT"]), - "max_model_len": int(os.environ["MAX_MODEL_LEN"]), - "gpu_memory_utilization": float(os.environ["GPU_MEMORY_UTILIZATION"]), - "instances": [], - "scheduling": { - "scheduler_type": "cmlfq", - "load_balance_strategy": "least_connections", - "max_queue_length": 64, - "enable_fallback": True, - "cmlfq_tree_path": str(project / "logs" / "r2e_gym_cmlfq_24gpu" / f"cmlfq_tree_{os.environ['JOB_ID']}.json"), - "cmlfq_buckets": { - "short": {"tp_degrees": [2, 4], "max_tokens": 3000}, - "medium": {"tp_degrees": [2, 4], "max_tokens": 6000}, - "long": {"tp_degrees": [4, 2], "max_tokens": max_model_len}, - }, - }, - }, - "global_resource_planner": { - "enabled": True, - "train_backend": "analytic", - "rollout_backend": "analytic", - "plan_interval": 20, - "warmup_steps": 5, - "min_history_size": 16, - "min_gain_ratio": 0.02, - "reconfiguration_cost_s": 15.0, - "allowed_rollout_tp": [2, 4], - "require_heterogeneous_rollout_tp": True, - "allowed_train_tp": [1], - "allowed_train_pp": [1], - "fixed_train_gpus": 4, - "micro_batch_sizes": [1], - "startup_profile_enabled": True, - "startup_profile_sample_size": int(os.environ["GRP_PROFILE_SAMPLE_SIZE"]), - "startup_profile_strategy": os.environ["GRP_PROFILE_STRATEGY"], - "startup_profile_seed": int(os.environ["GRP_PROFILE_SEED"]), - "startup_profile_samples_per_prompt": int(os.environ["GRP_PROFILE_SAMPLES_PER_PROMPT"]), - "startup_profile_dataset_jsonl": str(profile_dataset), - "startup_profile_history_jsonl": str(profile_jsonl), - "startup_profile_summary_json": str(profile_summary_json), - "runtime_length_profile_enabled": True, - "runtime_length_profile_jsonl": str(job_log_dir / "runtime_length_profile.jsonl"), - "apply_to_runtime": True, - "verbose": True, - "runtime_async_planning": True, - "runtime_max_pending_plans": 1, - "simulator_allow_fallback": True, - "simulator_timeout_s": 240.0, - }, -} -seed_path.write_text(yaml.safe_dump(seed, sort_keys=False), encoding="utf-8") - -cfg = AsyncRLConfig.from_yaml(str(seed_path)) -profile_metadata = startup_profile_metadata( - dataset_jsonl=profile_dataset, - model_path=cfg.model_path, - tokenizer_path=cfg.tokenizer_path if cfg.tokenizer_path else cfg.model_path, - sample_size=int(os.environ["GRP_PROFILE_SAMPLE_SIZE"]), - strategy=os.environ["GRP_PROFILE_STRATEGY"], - seed=int(os.environ["GRP_PROFILE_SEED"]), - samples_per_prompt=int(os.environ["GRP_PROFILE_SAMPLES_PER_PROMPT"]), - max_new_tokens=max_new_tokens, - max_seq_length=max_model_len, - r2e_max_turns=r2e_max_turns, - r2e_max_prompt_tokens=r2e_max_prompt_tokens, -) -history = None -summary = None -if profile_jsonl_has_records(profile_jsonl): - existing_summary = load_profile_summary(profile_summary_json) - if ( - existing_summary is None - or profile_metadata_matches(existing_summary, profile_metadata) - ): - history = load_jsonl_rows(profile_jsonl) - if not history: - raise RuntimeError(f"startup profile JSONL is empty: {profile_jsonl}") - summary = summarize_length_profile(history) - summary.update(profile_metadata) - summary["reused"] = True - write_profile_summary(summary, profile_summary_json) -if history is None: - rows = load_jsonl_rows(profile_dataset) - if not rows: - raise RuntimeError(f"GRP startup profile dataset is empty: {profile_dataset}") - tokenizer = AutoTokenizer.from_pretrained( - cfg.tokenizer_path if cfg.tokenizer_path else cfg.model_path, - trust_remote_code=True, - ) - if tokenizer.pad_token is None: - tokenizer.pad_token = tokenizer.eos_token - history = build_r2e_gym_length_profile( - rows, - tokenizer=tokenizer, - sample_size=int(os.environ["GRP_PROFILE_SAMPLE_SIZE"]), - strategy=os.environ["GRP_PROFILE_STRATEGY"], - seed=int(os.environ["GRP_PROFILE_SEED"]), - samples_per_prompt=int(os.environ["GRP_PROFILE_SAMPLES_PER_PROMPT"]), - max_turns=r2e_max_turns, - max_new_tokens=max_new_tokens, - max_seq_length=max_model_len, - max_prompt_tokens=r2e_max_prompt_tokens or None, - ) - summary = summarize_length_profile(history) - summary.update(profile_metadata) - write_profile_jsonl(history, profile_jsonl) - write_profile_summary(summary, profile_summary_json) -result = PreflightPlanner(cfg, apply_best_candidate=True).run(history) -planned = result.planned_config - -if not planned.heterogeneous_rollout.instances: - raise RuntimeError("GlobalResourcePlanner produced no rollout instances") -tp_list = [int(inst.tp) for inst in planned.heterogeneous_rollout.instances] -if len(set(tp_list)) <= 1: - raise RuntimeError(f"GlobalResourcePlanner did not produce heterogeneous TP degrees: {tp_list}") -if sum(tp_list) != 20: - raise RuntimeError(f"GlobalResourcePlanner rollout GPUs must sum to 20, got {sum(tp_list)} from {tp_list}") -if planned.train_gpus != 4: - raise RuntimeError(f"GlobalResourcePlanner must keep train_gpus=4, got {planned.train_gpus}") - -remaining = {node: 4 for node in rollout_nodes} -next_gpu = {node: 0 for node in rollout_nodes} -assigned_nodes: list[str] = [] -assigned_tps: list[int] = [] -assigned_ports: list[int] = [] -assigned_names: list[str] = [] -assigned_gpus: list[str] = [] - -for idx, inst in enumerate(planned.heterogeneous_rollout.instances): - tp = int(inst.tp) - node = next((candidate for candidate in rollout_nodes if remaining[candidate] >= tp), None) - if node is None: - raise RuntimeError(f"Cannot pack planned TP list {tp_list} onto nodes {rollout_nodes}") - start_gpu = next_gpu[node] - inst.gpus = list(range(start_gpu, start_gpu + tp)) - inst.host = node - if not inst.instance_id: - inst.instance_id = f"grp_tp{tp}_{idx}" - remaining[node] -= tp - next_gpu[node] += tp - assigned_nodes.append(node) - assigned_tps.append(tp) - assigned_ports.append(base_port + idx) - assigned_names.append(inst.instance_id) - assigned_gpus.append(",".join(str(gpu) for gpu in inst.gpus)) - -planned.vllm_port = base_port -planned.vllm_num_instances = len(assigned_tps) -planned.rollout_gpus = sum(assigned_tps) -planned.n_total_gpus = planned.train_gpus + planned.rollout_gpus -planned.max_concurrent_rollouts = max(planned.max_concurrent_rollouts, len(assigned_tps) * planned.batch_size) -planned.heterogeneous_rollout.vllm_base_port = base_port -planned.heterogeneous_rollout.total_gpus = planned.rollout_gpus - -grp = planned.global_resource_planner -grp.train_backend = "sailor" -grp.rollout_backend = "vidur" -grp.runtime_async_planning = True -grp.runtime_max_pending_plans = 1 -grp.simulator_allow_fallback = True -grp.simulator_timeout_s = 240.0 -grp.allowed_rollout_tp = [2, 4] -grp.require_heterogeneous_rollout_tp = True -grp.allowed_train_tp = [1] -grp.allowed_train_pp = [1] -grp.fixed_train_gpus = 4 -grp.micro_batch_sizes = [1] - -planned.to_yaml(str(runtime_path)) - -def bash_array(values): - return "(" + " ".join(shlex.quote(str(v)) for v in values) + ")" - -plan_env.write_text( - "\n".join( - [ - f"ROLLOUT_COUNT={len(assigned_tps)}", - f"ROLLOUT_NODE_LIST={bash_array(assigned_nodes)}", - f"ROLLOUT_TP_LIST={bash_array(assigned_tps)}", - f"ROLLOUT_PORT_LIST={bash_array(assigned_ports)}", - f"ROLLOUT_NAME_LIST={bash_array(assigned_names)}", - f"ROLLOUT_GPU_LIST={bash_array(assigned_gpus)}", - f"HETERO_INSTANCE_HOSTS={shlex.quote(','.join(assigned_nodes))}", - f"PLANNED_ROLLOUT_TP_LIST={shlex.quote(','.join(str(v) for v in assigned_tps))}", - f"PLANNED_RUNTIME_CONFIG={shlex.quote(str(runtime_path))}", - ] - ) - + "\n", - encoding="utf-8", -) -print(f"seed_config={seed_path}") -print(f"runtime_config={runtime_path}") -print(f"profile_jsonl={profile_jsonl}") -print(f"profile_summary={summary}") -print(f"decision={result.decision.to_dict()}") -print(f"planned_rollout_tp={assigned_tps}") -print(f"planned_rollout_nodes={assigned_nodes}") -PY - -source "$PLAN_ENV" -echo "GlobalResourcePlanner rollout TP list: ${PLANNED_ROLLOUT_TP_LIST}" -echo "GlobalResourcePlanner rollout nodes: ${ROLLOUT_NODE_LIST[*]}" - -start_vllm() { - local node="$1" - local tp="$2" - local port="$3" - local name="$4" - local gpu_list="$5" - local log_file="$JOB_LOG_DIR/vllm_${name}.log" - echo "Starting $name on $node TP=$tp planned_GPUs=$gpu_list port=$port" - srun --exclusive \ - --nodes=1 --ntasks=1 --nodelist="$node" \ - --gpus="$tp" \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - export TOKENIZERS_PARALLELISM=false - export PLANNED_CUDA_VISIBLE_DEVICES='$gpu_list' - if [ -z \"\${CUDA_VISIBLE_DEVICES:-}\" ]; then - export CUDA_VISIBLE_DEVICES=\"\$PLANNED_CUDA_VISIBLE_DEVICES\" - fi - echo \"CUDA_VISIBLE_DEVICES=\${CUDA_VISIBLE_DEVICES} planned=\${PLANNED_CUDA_VISIBLE_DEVICES}\" - export MASTER_ADDR=127.0.0.1 - export MASTER_PORT=$((20000 + port)) - python3 -m vllm.entrypoints.openai.api_server \ - --model '$MODEL_PATH' \ - --host 0.0.0.0 \ - --port '$port' \ - --tensor-parallel-size '$tp' \ - --max-model-len '$MAX_MODEL_LEN' \ - --dtype bfloat16 \ - --gpu-memory-utilization '$GPU_MEMORY_UTILIZATION' \ - --trust-remote-code \ - --enforce-eager \ - --disable-custom-all-reduce - " >"$log_file" 2>&1 & - VLLM_STEP_PIDS+=("$!") - VLLM_PID_BY_NAME["$name"]="$!" -} - -wait_for_health() { - local host="$1" - local port="$2" - local name="$3" - local elapsed=0 - local pid="${VLLM_PID_BY_NAME[$name]}" - while [ "$elapsed" -lt "$MAX_WAIT" ]; do - if curl -fsS "http://${host}:${port}/health" >/dev/null 2>&1; then - echo "READY: $name at $host:$port (${elapsed}s)" - return 0 - fi - if ! kill -0 "$pid" 2>/dev/null; then - echo "ERROR: $name exited before ready" >&2 - tail -120 "$JOB_LOG_DIR/vllm_${name}.log" || true - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - echo "ERROR: $name not ready after ${MAX_WAIT}s" >&2 - tail -120 "$JOB_LOG_DIR/vllm_${name}.log" || true - return 1 -} - -echo "[2/6] Starting GlobalResourcePlanner rollout vLLM instances" -PRIMARY_INDICES=() -DEFERRED_INDICES=() -declare -A NODE_HAS_PRIMARY=() -for i in "${!ROLLOUT_NODE_LIST[@]}"; do - node="${ROLLOUT_NODE_LIST[$i]}" - if [ -z "${NODE_HAS_PRIMARY[$node]:-}" ]; then - NODE_HAS_PRIMARY["$node"]=1 - PRIMARY_INDICES+=("$i") - else - DEFERRED_INDICES+=("$i") - fi -done - -for i in "${PRIMARY_INDICES[@]}"; do - start_vllm \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_TP_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" \ - "${ROLLOUT_GPU_LIST[$i]}" -done - -echo "[3/6] Waiting for primary rollout services" -for i in "${PRIMARY_INDICES[@]}"; do - wait_for_health \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" -done - -if [ "${#DEFERRED_INDICES[@]}" -gt 0 ]; then - echo "[3b/6] Starting deferred same-node rollout services" - for i in "${DEFERRED_INDICES[@]}"; do - start_vllm \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_TP_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" \ - "${ROLLOUT_GPU_LIST[$i]}" - wait_for_health \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" - done -fi - -echo "[4/6] Checking R2E-Gym data and C-MLFQ flow" -python3 examples/test_r2e_gym.py -python3 examples/test_r2e_cmlfq_flow.py - -echo "[5/6] OpenAI-compatible API check" -curl -fsS "http://${ROLLOUT_NODE_LIST[0]}:${ROLLOUT_PORT_LIST[0]}/v1/completions" \ - -H "Content-Type: application/json" \ - -d "{\"model\":\"$MODEL_PATH\",\"prompt\":\"Write one short sentence.\",\"max_tokens\":8,\"temperature\":0}" \ - | python3 -m json.tool - -export HETERO_INSTANCE_HOSTS -export R2E_GYM_INDEX="${PROJECT_DIR}/data/r2e_gym_v1/index.jsonl" -export R2E_MAX_TURNS -export R2E_EVAL_MAX_SAMPLES="$EVAL_MAX_SAMPLES" -export R2E_EVAL_CONCURRENCY="$EVAL_CONCURRENCY" -export R2E_EVAL_MAX_NEW_TOKENS="$EVAL_MAX_NEW_TOKENS" - -echo "[6/6] Starting full R2E-Gym AsyncRLTrainer run on 24 GPUs" -srun --exclusive \ - --nodes=1 --ntasks=1 --nodelist="$TRAIN_NODE" \ - --gpus=4 \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - cd '$PROJECT_DIR' - export PYTHONPATH='$(dirname "$PROJECT_DIR")':\${PYTHONPATH:-} - export HETERO_INSTANCE_HOSTS='$HETERO_INSTANCE_HOSTS' - export R2E_GYM_INDEX='$R2E_GYM_INDEX' - export R2E_MAX_TURNS='$R2E_MAX_TURNS' - export R2E_EVAL_MAX_SAMPLES='$R2E_EVAL_MAX_SAMPLES' - export R2E_EVAL_CONCURRENCY='$R2E_EVAL_CONCURRENCY' - export R2E_EVAL_MAX_NEW_TOKENS='$R2E_EVAL_MAX_NEW_TOKENS' - export MASTER_ADDR='$MASTER_ADDR' - export MASTER_PORT='$MASTER_PORT' - export TOKENIZERS_PARALLELISM=false - export WANDB_MODE='$WANDB_MODE' - export WANDB_DIR='$WANDB_DIR' - torchrun \ - --nproc_per_node=4 \ - --master_addr='$MASTER_ADDR' \ - --master_port='$MASTER_PORT' \ - examples/r2e_gym_async_rl.py \ - --config '$RUNTIME_CONFIG' - " 2>&1 | tee "$JOB_LOG_DIR/training.log" - -echo "============================================================" -echo "R2E-Gym C-MLFQ 24-GPU training completed" -echo "Logs: $JOB_LOG_DIR" -echo "C-MLFQ tree: $PROJECT_DIR/logs/r2e_gym_cmlfq_24gpu/cmlfq_tree_${JOB_ID}.json" -echo "History: $PROJECT_DIR/logs/r2e_gym_cmlfq/history and logs/r2e_gym_cmlfq_24gpu" -echo "============================================================" diff --git a/scripts/submit_r2e_gym_cmlfq_megatron_core_qwen3_30b_a3b.slurm b/scripts/submit_r2e_gym_cmlfq_megatron_core_qwen3_30b_a3b.slurm deleted file mode 100644 index fd25127..0000000 --- a/scripts/submit_r2e_gym_cmlfq_megatron_core_qwen3_30b_a3b.slurm +++ /dev/null @@ -1,53 +0,0 @@ -#!/bin/bash -#SBATCH -J r2e_qwen30_mcore -#SBATCH -o logs/r2e_qwen30_mcore_%j.out -#SBATCH -e logs/r2e_qwen30_mcore_%j.err -#SBATCH -N 4 -#SBATCH -G 16 -#SBATCH --ntasks-per-node=4 -#SBATCH --cpus-per-task=16 -#SBATCH --mem=900G -#SBATCH --exclude=gn002,gn019 -#SBATCH -p gpu -#SBATCH --time=24:00:00 - -set -euo pipefail - -PROJECT_DIR="${PROJECT_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" -export PROJECT_DIR -export TRAIN_BACKEND=megatron_core -export TRAIN_GPUS="${TRAIN_GPUS:-8}" -export TRAIN_TP_SIZE="${TRAIN_TP_SIZE:-4}" -export TRAIN_PP_SIZE="${TRAIN_PP_SIZE:-1}" -export TRAIN_CP_SIZE="${TRAIN_CP_SIZE:-1}" -export TRAIN_EP_SIZE="${TRAIN_EP_SIZE:-1}" -export EXPERT_TENSOR_PARALLEL_SIZE="${EXPERT_TENSOR_PARALLEL_SIZE:-4}" -export USE_DISTRIBUTED_OPTIMIZER=1 -export MEGATRON_GRAD_REDUCE_IN_FP32="${MEGATRON_GRAD_REDUCE_IN_FP32:-0}" -export MEGATRON_USE_PRECISION_AWARE_OPTIMIZER="${MEGATRON_USE_PRECISION_AWARE_OPTIMIZER:-1}" -export MEGATRON_OPTIMIZER_CPU_OFFLOAD="${MEGATRON_OPTIMIZER_CPU_OFFLOAD:-1}" -export MEGATRON_OPTIMIZER_OFFLOAD_FRACTION="${MEGATRON_OPTIMIZER_OFFLOAD_FRACTION:-1.0}" -export MEGATRON_OPTIMIZER_PIN_CPU_GRADS="${MEGATRON_OPTIMIZER_PIN_CPU_GRADS:-0}" -export MEGATRON_OPTIMIZER_PIN_CPU_PARAMS="${MEGATRON_OPTIMIZER_PIN_CPU_PARAMS:-0}" -export MEGATRON_ROLLOUT_EXPORT_ONLY="${MEGATRON_ROLLOUT_EXPORT_ONLY:-1}" -export MCORE_MOE_GROUPED_GEMM="${MCORE_MOE_GROUPED_GEMM:-1}" -export TOTAL_STEPS="${TOTAL_STEPS:-100}" -export MAX_MODEL_LEN="${MAX_MODEL_LEN:-8192}" -export MAX_NEW_TOKENS="${MAX_NEW_TOKENS:-1024}" -export R2E_MAX_TURNS="${R2E_MAX_TURNS:-2}" -export R2E_MAX_PROMPT_TOKENS="${R2E_MAX_PROMPT_TOKENS:-2048}" -export SYNC_INTERVAL="${SYNC_INTERVAL:-5}" -export NCCL_P2P_DISABLE="${NCCL_P2P_DISABLE:-1}" -export NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-0}" -export NCCL_PREFLIGHT_ELEMENTS="${NCCL_PREFLIGHT_ELEMENTS:-1048576}" -export NCCL_PREFLIGHT_ITERATIONS="${NCCL_PREFLIGHT_ITERATIONS:-1}" -export NCCL_PREFLIGHT_WALLTIME="${NCCL_PREFLIGHT_WALLTIME:-300}" -export GRP_ONLINE_REPLANNING="${GRP_ONLINE_REPLANNING:-1}" -export GRP_DYNAMIC_RECONFIG_ENABLED="${GRP_DYNAMIC_RECONFIG_ENABLED:-0}" -export GRP_MANAGE_ROLLOUT_PROCESSES="${GRP_MANAGE_ROLLOUT_PROCESSES:-0}" -export GRP_RECONFIGURE_TRAINING="${GRP_RECONFIGURE_TRAINING:-0}" -export GRP_CLUSTER_SWAP_ENABLED="${GRP_CLUSTER_SWAP_ENABLED:-0}" -export GRP_DECOUPLE_COMMUNICATION_DOMAINS="${GRP_DECOUPLE_COMMUNICATION_DOMAINS:-1}" -export GRP_ROLLOUT_RECONFIGURE_STRATEGY="${GRP_ROLLOUT_RECONFIGURE_STRATEGY:-blue_green}" - -exec bash "$PROJECT_DIR/scripts/submit_r2e_gym_cmlfq_24gpu_qwen3_30b_a3b.slurm" diff --git a/scripts/submit_r2e_gym_cmlfq_train.slurm b/scripts/submit_r2e_gym_cmlfq_train.slurm deleted file mode 100644 index e10e777..0000000 --- a/scripts/submit_r2e_gym_cmlfq_train.slurm +++ /dev/null @@ -1,248 +0,0 @@ -#!/bin/bash -#SBATCH -J r2e_cmlfq_train -#SBATCH -o logs/r2e_cmlfq_train_%j.out -#SBATCH -e logs/r2e_cmlfq_train_%j.err -#SBATCH -N 3 -#SBATCH -G 12 -#SBATCH --ntasks-per-node=2 -#SBATCH --cpus-per-task=16 -#SBATCH -p gpu -#SBATCH --time=24:00:00 -#SBATCH --exclude=gn019 - -set -euo pipefail - -PROJECT_DIR="${PROJECT_DIR:-/path/to/RL_Framework}" -VENV_PATH="${VENV_PATH:-/path/to/rl_framework_env/bin/activate}" -MODEL_PATH="${MODEL_PATH:-/path/to/Qwen3-4B}" -TOTAL_STEPS="${TOTAL_STEPS:-1000}" -MAX_MODEL_LEN="${MAX_MODEL_LEN:-32768}" -MAX_NEW_TOKENS="${MAX_NEW_TOKENS:-32768}" -TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-16}" -TRAIN_MICRO_BATCH_SIZE="${TRAIN_MICRO_BATCH_SIZE:-1}" -EVAL_INTERVAL="${EVAL_INTERVAL:-100}" -EVAL_MAX_SAMPLES="${EVAL_MAX_SAMPLES:-0}" -EVAL_CONCURRENCY="${EVAL_CONCURRENCY:-16}" -EVAL_MAX_NEW_TOKENS="${EVAL_MAX_NEW_TOKENS:-32768}" -GPU_MEMORY_UTILIZATION="${GPU_MEMORY_UTILIZATION:-0.90}" -VLLM_BASE_PORT="${VLLM_BASE_PORT:-8000}" -MASTER_PORT="${MASTER_PORT:-29500}" -MAX_WAIT="${MAX_WAIT:-900}" - -source "$VENV_PATH" -cd "$PROJECT_DIR" - -mkdir -p logs -JOB_ID="${SLURM_JOB_ID:-manual}" -JOB_LOG_DIR="$PROJECT_DIR/logs/r2e_gym_cmlfq/job_${JOB_ID}" -mkdir -p "$JOB_LOG_DIR" - -export PYTHONPATH="$(dirname "$PROJECT_DIR"):${PYTHONPATH:-}" -export TOKENIZERS_PARALLELISM=false -export WANDB_MODE="${WANDB_MODE:-offline}" -export WANDB_DIR="${PROJECT_DIR}/wandb_r2e_gym_cmlfq" -export NO_PROXY="localhost,127.0.0.1,${NO_PROXY:-}" -export NCCL_ASYNC_ERROR_HANDLING=1 -export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}" - -mapfile -t NODES < <(scontrol show hostnames "$SLURM_NODELIST") -if [ "${#NODES[@]}" -lt 3 ]; then - echo "ERROR: R2E-Gym C-MLFQ training requires 3 nodes; got ${#NODES[@]}" >&2 - exit 2 -fi - -TRAIN_NODE="${NODES[0]}" -ROLLOUT_NODE_A="${NODES[1]}" -ROLLOUT_NODE_B="${NODES[2]}" -MASTER_ADDR="$TRAIN_NODE" -RUNTIME_CONFIG="$PROJECT_DIR/configs/.r2e_gym_cmlfq_${JOB_ID}.yaml" - -echo "============================================================" -echo "R2E-Gym full RL post-training with C-MLFQ" -echo "============================================================" -echo "Job: $JOB_ID" -echo "Model: $MODEL_PATH" -echo "Train node: $TRAIN_NODE (4 GPUs)" -echo "Rollout node A: $ROLLOUT_NODE_A (TP=4 long bucket)" -echo "Rollout node B: $ROLLOUT_NODE_B (2 x TP=2 short/medium buckets)" -echo "Total steps: $TOTAL_STEPS" -echo "Logs: $JOB_LOG_DIR" -python3 -c 'import torch, transformers, vllm; print("torch", torch.__version__, "transformers", transformers.__version__, "vllm", vllm.__version__)' - -VLLM_STEP_PIDS=() -declare -A VLLM_PID_BY_NAME=() - -cleanup() { - local exit_code=$? - trap - EXIT INT TERM - echo "[cleanup] stopping vLLM processes..." - for pid in "${VLLM_STEP_PIDS[@]:-}"; do - kill "$pid" 2>/dev/null || true - done - for node in "$ROLLOUT_NODE_A" "$ROLLOUT_NODE_B"; do - for port in "$VLLM_BASE_PORT" "$((VLLM_BASE_PORT + 1))" "$((VLLM_BASE_PORT + 2))"; do - srun --overlap --nodes=1 --ntasks=1 --nodelist="$node" \ - bash -lc "pkill -f 'vllm.entrypoints.openai.api_server.*--port ${port}' 2>/dev/null || true" \ - >/dev/null 2>&1 || true - done - done - echo "[cleanup] complete, exit=$exit_code" - exit "$exit_code" -} -trap cleanup EXIT INT TERM - -echo "[1/6] Writing runtime config" -export PROJECT_DIR MODEL_PATH TOTAL_STEPS MAX_MODEL_LEN MAX_NEW_TOKENS EVAL_INTERVAL -export TRAIN_BATCH_SIZE TRAIN_MICRO_BATCH_SIZE VLLM_BASE_PORT GPU_MEMORY_UTILIZATION JOB_ID -python3 - <<'PY' -import os -from pathlib import Path -import yaml - -project = Path(os.environ["PROJECT_DIR"]) -base = project / "configs" / "r2e_gym_cmlfq_qwen3_4b.yaml" -config = { - "base_config": str(base), - "model_path": os.environ["MODEL_PATH"], - "tokenizer_path": os.environ["MODEL_PATH"], - "batch_size": int(os.environ["TRAIN_BATCH_SIZE"]), - "micro_batch_size": int(os.environ["TRAIN_MICRO_BATCH_SIZE"]), - "total_steps": int(os.environ["TOTAL_STEPS"]), - "eval_interval": int(os.environ["EVAL_INTERVAL"]), - "max_new_tokens": int(os.environ["MAX_NEW_TOKENS"]), - "max_seq_length": int(os.environ["MAX_MODEL_LEN"]), - "sync_path": str(project / "logs" / "r2e_gym_cmlfq" / f"weights_{os.environ['JOB_ID']}"), - "log_dir": str(project / "logs" / "r2e_gym_cmlfq"), - "wandb_run_name": f"r2e-gym-cmlfq-{os.environ['JOB_ID']}", - "heterogeneous_rollout": { - "vllm_base_port": int(os.environ["VLLM_BASE_PORT"]), - "max_model_len": int(os.environ["MAX_MODEL_LEN"]), - "gpu_memory_utilization": float(os.environ["GPU_MEMORY_UTILIZATION"]), - "scheduling": { - "cmlfq_tree_path": str(project / "logs" / "r2e_gym_cmlfq" / f"cmlfq_tree_{os.environ['JOB_ID']}.json") - }, - }, -} -path = project / "configs" / f".r2e_gym_cmlfq_{os.environ['JOB_ID']}.yaml" -path.write_text(yaml.safe_dump(config, sort_keys=False), encoding="utf-8") -print(path) -PY - -start_vllm() { - local node="$1" - local tp="$2" - local port="$3" - local name="$4" - local log_file="$JOB_LOG_DIR/vllm_${name}.log" - echo "Starting $name on $node TP=$tp port=$port" - srun --exclusive \ - --nodes=1 --ntasks=1 --nodelist="$node" \ - --gpus="$tp" \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - export TOKENIZERS_PARALLELISM=false - export MASTER_ADDR=127.0.0.1 - export MASTER_PORT=$((20000 + port)) - python3 -m vllm.entrypoints.openai.api_server \ - --model '$MODEL_PATH' \ - --host 0.0.0.0 \ - --port '$port' \ - --tensor-parallel-size '$tp' \ - --max-model-len '$MAX_MODEL_LEN' \ - --dtype bfloat16 \ - --gpu-memory-utilization '$GPU_MEMORY_UTILIZATION' \ - --trust-remote-code \ - --enforce-eager \ - --disable-custom-all-reduce - " >"$log_file" 2>&1 & - VLLM_STEP_PIDS+=("$!") - VLLM_PID_BY_NAME["$name"]="$!" -} - -wait_for_health() { - local host="$1" - local port="$2" - local name="$3" - local elapsed=0 - local pid="${VLLM_PID_BY_NAME[$name]}" - while [ "$elapsed" -lt "$MAX_WAIT" ]; do - if curl -fsS "http://${host}:${port}/health" >/dev/null 2>&1; then - echo "READY: $name at $host:$port (${elapsed}s)" - return 0 - fi - if ! kill -0 "$pid" 2>/dev/null; then - echo "ERROR: $name exited before ready" >&2 - tail -120 "$JOB_LOG_DIR/vllm_${name}.log" || true - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - echo "ERROR: $name not ready after ${MAX_WAIT}s" >&2 - tail -120 "$JOB_LOG_DIR/vllm_${name}.log" || true - return 1 -} - -echo "[2/6] Starting heterogeneous rollout vLLM instances" -start_vllm "$ROLLOUT_NODE_A" 4 "$VLLM_BASE_PORT" "long_tp4" -start_vllm "$ROLLOUT_NODE_B" 2 "$((VLLM_BASE_PORT + 1))" "short_tp2_0" - -echo "[3/6] Waiting for initial rollout services" -wait_for_health "$ROLLOUT_NODE_A" "$VLLM_BASE_PORT" "long_tp4" -wait_for_health "$ROLLOUT_NODE_B" "$((VLLM_BASE_PORT + 1))" "short_tp2_0" - -start_vllm "$ROLLOUT_NODE_B" 2 "$((VLLM_BASE_PORT + 2))" "short_tp2_1" -wait_for_health "$ROLLOUT_NODE_B" "$((VLLM_BASE_PORT + 2))" "short_tp2_1" - -echo "[4/6] Checking R2E-Gym data and C-MLFQ flow" -python3 examples/test_r2e_gym.py -python3 examples/test_r2e_cmlfq_flow.py - -echo "[5/6] OpenAI-compatible API check" -curl -fsS "http://${ROLLOUT_NODE_A}:${VLLM_BASE_PORT}/v1/completions" \ - -H "Content-Type: application/json" \ - -d "{\"model\":\"$MODEL_PATH\",\"prompt\":\"Write one short sentence.\",\"max_tokens\":8,\"temperature\":0}" \ - | python3 -m json.tool - -export HETERO_INSTANCE_HOSTS="${ROLLOUT_NODE_A},${ROLLOUT_NODE_B},${ROLLOUT_NODE_B}" -export R2E_GYM_INDEX="${PROJECT_DIR}/data/r2e_gym_v1/index.jsonl" -export R2E_MAX_TURNS="${R2E_MAX_TURNS:-3}" -export R2E_EVAL_MAX_SAMPLES="$EVAL_MAX_SAMPLES" -export R2E_EVAL_CONCURRENCY="$EVAL_CONCURRENCY" -export R2E_EVAL_MAX_NEW_TOKENS="$EVAL_MAX_NEW_TOKENS" - -echo "[6/6] Starting full R2E-Gym AsyncRLTrainer run" -srun --exclusive \ - --nodes=1 --ntasks=1 --nodelist="$TRAIN_NODE" \ - --gpus=4 \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - cd '$PROJECT_DIR' - export PYTHONPATH='$(dirname "$PROJECT_DIR")':\${PYTHONPATH:-} - export HETERO_INSTANCE_HOSTS='$HETERO_INSTANCE_HOSTS' - export R2E_GYM_INDEX='$R2E_GYM_INDEX' - export R2E_MAX_TURNS='$R2E_MAX_TURNS' - export R2E_EVAL_MAX_SAMPLES='$R2E_EVAL_MAX_SAMPLES' - export R2E_EVAL_CONCURRENCY='$R2E_EVAL_CONCURRENCY' - export R2E_EVAL_MAX_NEW_TOKENS='$R2E_EVAL_MAX_NEW_TOKENS' - export MASTER_ADDR='$MASTER_ADDR' - export MASTER_PORT='$MASTER_PORT' - export TOKENIZERS_PARALLELISM=false - export WANDB_MODE='$WANDB_MODE' - export WANDB_DIR='$WANDB_DIR' - torchrun \ - --nproc_per_node=4 \ - --master_addr='$MASTER_ADDR' \ - --master_port='$MASTER_PORT' \ - examples/r2e_gym_async_rl.py \ - --config '$RUNTIME_CONFIG' - " 2>&1 | tee "$JOB_LOG_DIR/training.log" - -echo "============================================================" -echo "R2E-Gym C-MLFQ training completed" -echo "Logs: $JOB_LOG_DIR" -echo "C-MLFQ tree: $PROJECT_DIR/logs/r2e_gym_cmlfq/cmlfq_tree_${JOB_ID}.json" -echo "History: $PROJECT_DIR/logs/r2e_gym_cmlfq/history" -echo "============================================================" diff --git a/scripts/submit_r2e_gym_qwen3_14b_48gpu_direct_nccl.slurm b/scripts/submit_r2e_gym_qwen3_14b_48gpu_direct_nccl.slurm deleted file mode 100755 index 5192206..0000000 --- a/scripts/submit_r2e_gym_qwen3_14b_48gpu_direct_nccl.slurm +++ /dev/null @@ -1,1267 +0,0 @@ -#!/bin/bash -#SBATCH -J r2e_qwen14_direct_nccl -#SBATCH -o logs/r2e_qwen14_direct_nccl_%j.out -#SBATCH -e logs/r2e_qwen14_direct_nccl_%j.err -#SBATCH -N 12 -#SBATCH -G 48 -#SBATCH --ntasks-per-node=1 -#SBATCH --cpus-per-task=64 -#SBATCH --mem=900G -#SBATCH -p gpu -#SBATCH --time=24:00:00 - -set -euo pipefail - -source /etc/profile.d/modules.sh 2>/dev/null || true -module load compiler/gcc/10.1.0 || true -if [ -x /usr/local/cuda-12.3/bin/nvcc ]; then - export CUDA_HOME=/usr/local/cuda-12.3 -elif [ -x /usr/local/cuda/bin/nvcc ]; then - export CUDA_HOME=/usr/local/cuda -else - export CUDA_HOME=/usr/local/cuda-12.1 -fi -export PATH="$CUDA_HOME/bin:$PATH" -export LD_LIBRARY_PATH="$CUDA_HOME/lib64:${LD_LIBRARY_PATH:-}" -export VLLM_WORKER_MULTIPROC_METHOD=spawn - -PROJECT_DIR="${PROJECT_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" -VENV_PATH="${VENV_PATH:-${HOME}/rl_framework_env/bin/activate}" -MODEL_PATH="${MODEL_PATH:-${HOME}/hf_models/Qwen3-14B}" -MODEL_ARCH_CONFIG="${MODEL_ARCH_CONFIG:-model_arch_config/qwen3-14b.yaml}" -if [ -f "$PROJECT_DIR/.slurm/slurm.conf" ]; then - export SLURM_CONF="$PROJECT_DIR/.slurm/slurm.conf" -fi -TOTAL_STEPS="${TOTAL_STEPS:-200}" -MAX_MODEL_LEN="${MAX_MODEL_LEN:-8192}" -MAX_NEW_TOKENS="${MAX_NEW_TOKENS:-512}" -TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-32}" -TRAIN_MICRO_BATCH_SIZE="${TRAIN_MICRO_BATCH_SIZE:-1}" -N_SAMPLES="${N_SAMPLES:-4}" -GPUS_PER_NODE="${GPUS_PER_NODE:-4}" -TRAIN_GPUS="${TRAIN_GPUS:-32}" -TRAIN_BACKEND="${TRAIN_BACKEND:-megatron_core}" -TRAIN_TP_SIZE="${TRAIN_TP_SIZE:-8}" -TRAIN_PP_SIZE="${TRAIN_PP_SIZE:-1}" -TRAIN_CP_SIZE="${TRAIN_CP_SIZE:-1}" -TRAIN_EP_SIZE="${TRAIN_EP_SIZE:-1}" -EXPERT_TENSOR_PARALLEL_SIZE="${EXPERT_TENSOR_PARALLEL_SIZE:-1}" -USE_DISTRIBUTED_OPTIMIZER="${USE_DISTRIBUTED_OPTIMIZER:-1}" -MEGATRON_USE_CPU_INITIALIZATION="${MEGATRON_USE_CPU_INITIALIZATION:-0}" -MCORE_MOE_GROUPED_GEMM="${MCORE_MOE_GROUPED_GEMM:-1}" -MEGATRON_USE_PRECISION_AWARE_OPTIMIZER="${MEGATRON_USE_PRECISION_AWARE_OPTIMIZER:-1}" -MEGATRON_OPTIMIZER_CPU_OFFLOAD="${MEGATRON_OPTIMIZER_CPU_OFFLOAD:-1}" -MEGATRON_OPTIMIZER_OFFLOAD_FRACTION="${MEGATRON_OPTIMIZER_OFFLOAD_FRACTION:-1.0}" -ALLOW_QWEN30_FALLBACK="${ALLOW_QWEN30_FALLBACK:-0}" -MAX_CONCURRENT_ROLLOUTS="${MAX_CONCURRENT_ROLLOUTS:-32}" -QUEUE_SIZE="${QUEUE_SIZE:-256}" -EVAL_INTERVAL="${EVAL_INTERVAL:-20}" -RL_TRAIN_PHASE_TRACE="${RL_TRAIN_PHASE_TRACE:-0}" -EVAL_MAX_SAMPLES="${EVAL_MAX_SAMPLES:-32}" -EVAL_CONCURRENCY="${EVAL_CONCURRENCY:-16}" -EVAL_MAX_NEW_TOKENS="${EVAL_MAX_NEW_TOKENS:-512}" -SYNC_INTERVAL="${SYNC_INTERVAL:-5}" -ROLLOUT_SYNC_DRAIN_LEAD_STEPS="${ROLLOUT_SYNC_DRAIN_LEAD_STEPS:-2}" -GPU_MEMORY_UTILIZATION="${GPU_MEMORY_UTILIZATION:-0.80}" -VLLM_BASE_PORT="${VLLM_BASE_PORT:-8000}" -MASTER_PORT="${MASTER_PORT:-29500}" -NCCL_RELOAD_PORT="${NCCL_RELOAD_PORT:-29620}" -MAX_WAIT="${MAX_WAIT:-1800}" -R2E_MAX_TURNS="${R2E_MAX_TURNS:-4}" -R2E_MAX_PROMPT_TOKENS="${R2E_MAX_PROMPT_TOKENS:-4096}" -GRP_PROFILE_DATASET_JSONL="${GRP_PROFILE_DATASET_JSONL:-$PROJECT_DIR/data/r2e_gym_v1/index.jsonl}" -GRP_PROFILE_SAMPLE_SIZE="${GRP_PROFILE_SAMPLE_SIZE:-64}" -GRP_PROFILE_STRATEGY="${GRP_PROFILE_STRATEGY:-spread}" -GRP_PROFILE_SEED="${GRP_PROFILE_SEED:-0}" -GRP_PROFILE_SAMPLES_PER_PROMPT="${GRP_PROFILE_SAMPLES_PER_PROMPT:-1}" -R2E_EVAL_MULTI_TURN="${R2E_EVAL_MULTI_TURN:-1}" -R2E_EVAL_RECORD_SAMPLES="${R2E_EVAL_RECORD_SAMPLES:-16}" -R2E_EVAL_STRATEGY="${R2E_EVAL_STRATEGY:-spread}" -LONG_CONTEXT_TP_FIRST="${LONG_CONTEXT_TP_FIRST:-0}" -VLLM_READ_TIMEOUT="${VLLM_READ_TIMEOUT:-600}" -VLLM_CONNECT_TIMEOUT="${VLLM_CONNECT_TIMEOUT:-30}" -VLLM_WRITE_TIMEOUT="${VLLM_WRITE_TIMEOUT:-30}" -VLLM_POOL_TIMEOUT="${VLLM_POOL_TIMEOUT:-30}" -VLLM_NCCL_P2P_DISABLE="${VLLM_NCCL_P2P_DISABLE:-1}" -VLLM_NCCL_IB_DISABLE="${VLLM_NCCL_IB_DISABLE:-0}" -VLLM_CUDA_LAUNCH_BLOCKING="${VLLM_CUDA_LAUNCH_BLOCKING:-0}" -VLLM_DISABLE_CUSTOM_ALL_REDUCE="${VLLM_DISABLE_CUSTOM_ALL_REDUCE:-1}" -NCCL_P2P_DISABLE="${NCCL_P2P_DISABLE:-1}" -NCCL_IB_DISABLE="${NCCL_IB_DISABLE:-0}" -TORCH_DISTRIBUTED_TIMEOUT="${TORCH_DISTRIBUTED_TIMEOUT:-3600}" -FSDP_ALIGN_SEQUENCE_LENGTHS="${FSDP_ALIGN_SEQUENCE_LENGTHS:-1}" -FSDP_LOCKSTEP_BARRIERS="${FSDP_LOCKSTEP_BARRIERS:-1}" -FSDP_GRADIENT_CHECKPOINTING="${FSDP_GRADIENT_CHECKPOINTING:-0}" -FSDP_ACTIVATION_CHECKPOINTING="${FSDP_ACTIVATION_CHECKPOINTING:-1}" -CMLFQ_SHARED_LOAD_TTL="${CMLFQ_SHARED_LOAD_TTL:-60}" -CMLFQ_SHARED_LOAD_HEARTBEAT="${CMLFQ_SHARED_LOAD_HEARTBEAT:-10}" -CMLFQ_TREE_PERSIST_INTERVAL="${CMLFQ_TREE_PERSIST_INTERVAL:-8}" -CMLFQ_WARM_START_TREE="${CMLFQ_WARM_START_TREE:-}" -EXPERIMENT_TAG="${EXPERIMENT_TAG:-r2e_qwen_cmlfq}" -SCHEDULER_TYPE="${SCHEDULER_TYPE:-cmlfq}" -GRP_ENABLED="${GRP_ENABLED:-1}" -GRP_DYNAMIC_RECONFIG_ENABLED="${GRP_DYNAMIC_RECONFIG_ENABLED:-0}" -GRP_RUNTIME_ASYNC_PLANNING="${GRP_RUNTIME_ASYNC_PLANNING:-1}" -GRP_ONLINE_REPLANNING="${GRP_ONLINE_REPLANNING:-1}" -GRP_REPLAN_COOLDOWN_STEPS="${GRP_REPLAN_COOLDOWN_STEPS:-5}" -GRP_QUEUE_PRESSURE_THRESHOLD="${GRP_QUEUE_PRESSURE_THRESHOLD:-0.75}" -GRP_ACTIVE_ROLLOUT_PRESSURE_THRESHOLD="${GRP_ACTIVE_ROLLOUT_PRESSURE_THRESHOLD:-0.85}" -GRP_REJECTED_ROLLOUT_DELTA_THRESHOLD="${GRP_REJECTED_ROLLOUT_DELTA_THRESHOLD:-8}" -GRP_ROLLOUT_TRAIN_IMBALANCE_THRESHOLD="${GRP_ROLLOUT_TRAIN_IMBALANCE_THRESHOLD:-1.25}" -GRP_INTERVAL="${GRP_INTERVAL:-20}" -GRP_WARMUP_STEPS="${GRP_WARMUP_STEPS:-5}" -GRP_MIN_HISTORY="${GRP_MIN_HISTORY:-16}" -GRP_MIN_GAIN_RATIO="${GRP_MIN_GAIN_RATIO:-${GRP_GAIN_THRESHOLD:-0.02}}" -GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP="${GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP:-1}" -GRP_MANAGE_ROLLOUT_PROCESSES="${GRP_MANAGE_ROLLOUT_PROCESSES:-0}" -GRP_RECONFIGURE_TRAINING="${GRP_RECONFIGURE_TRAINING:-0}" -GRP_TRAINING_POOL_ONLY="${GRP_TRAINING_POOL_ONLY:-1}" -GRP_TRAINING_POOL_TARGET_GPUS="${GRP_TRAINING_POOL_TARGET_GPUS:-0}" -GRP_TRAINING_POOL_PLAN_ONLY="${GRP_TRAINING_POOL_PLAN_ONLY:-1}" -GRP_CLUSTER_SWAP_ENABLED="${GRP_CLUSTER_SWAP_ENABLED:-0}" -GRP_HYBRID_WORKER_LAUNCH_ENABLED="${GRP_HYBRID_WORKER_LAUNCH_ENABLED:-0}" -GRP_HYBRID_TRAINING_PREWARM_ENABLED="${GRP_HYBRID_TRAINING_PREWARM_ENABLED:-0}" -GRP_HYBRID_TRAINING_PREWARM_COUNT="${GRP_HYBRID_TRAINING_PREWARM_COUNT:-0}" -GRP_HYBRID_TRAINING_PREWARM_WORKER_IDS="${GRP_HYBRID_TRAINING_PREWARM_WORKER_IDS:-}" -GRP_HYBRID_WORKER_TASK_DIR="${GRP_HYBRID_WORKER_TASK_DIR:-}" -GRP_HYBRID_WORKER_COMMAND_TEMPLATE="${GRP_HYBRID_WORKER_COMMAND_TEMPLATE:-}" -GRP_HYBRID_WORKER_READY_TIMEOUT_S="${GRP_HYBRID_WORKER_READY_TIMEOUT_S:-120}" -GRP_GRADIENT_TRANSPORT_BACKEND="${GRP_GRADIENT_TRANSPORT_BACKEND:-tcp}" -GRP_DECOUPLE_COMMUNICATION_DOMAINS="${GRP_DECOUPLE_COMMUNICATION_DOMAINS:-1}" -GRP_GRADIENT_SERVER_HOST="${GRP_GRADIENT_SERVER_HOST:-127.0.0.1}" -GRP_GRADIENT_SERVER_PUBLIC_HOST="${GRP_GRADIENT_SERVER_PUBLIC_HOST:-}" -GRP_GRADIENT_SERVER_PORT="${GRP_GRADIENT_SERVER_PORT:-0}" -GRP_GRADIENT_SERVER_AUTHKEY="${GRP_GRADIENT_SERVER_AUTHKEY:-rl-framework-elastic}" -GRP_ROLLOUT_RECONFIGURE_STRATEGY="${GRP_ROLLOUT_RECONFIGURE_STRATEGY:-blue_green}" -GRP_PREWARM_NO_SPARE_FALLBACK_STRATEGY="${GRP_PREWARM_NO_SPARE_FALLBACK_STRATEGY:-restart_all}" -GRP_DRAIN_BEFORE_RECONFIGURE="${GRP_DRAIN_BEFORE_RECONFIGURE:-1}" -GRP_RUNTIME_PEER_REQUEST_WAIT_S="${GRP_RUNTIME_PEER_REQUEST_WAIT_S:-45}" -GRP_BATCH_COLLECTION_TIMEOUT_S="${GRP_BATCH_COLLECTION_TIMEOUT_S:-300}" -GRP_BATCH_COLLECTION_MAX_RETRIES="${GRP_BATCH_COLLECTION_MAX_RETRIES:-2}" -GRP_USE_NCCL_BARRIER_AFTER_ROLLOUT="${GRP_USE_NCCL_BARRIER_AFTER_ROLLOUT:-0}" -GRP_USE_NCCL_BARRIER_BEFORE_WEIGHT_SYNC="${GRP_USE_NCCL_BARRIER_BEFORE_WEIGHT_SYNC:-0}" -GRP_INITIAL_ROLLOUT_TP_LIST="${GRP_INITIAL_ROLLOUT_TP_LIST:-}" -GRP_FORCE_TRAIN_GPUS="${GRP_FORCE_TRAIN_GPUS:-}" -GRP_ROLLOUT_MANIFEST_PATH="${GRP_ROLLOUT_MANIFEST_PATH:-}" -GRP_ROLLOUT_PID_REGISTRY_PATH="${GRP_ROLLOUT_PID_REGISTRY_PATH:-}" -GRP_WAIT_ROLLOUT_PROCESS_START_READY="${GRP_WAIT_ROLLOUT_PROCESS_START_READY:-1}" -GRP_POST_ROLLOUT_STOP_GRACE_S="${GRP_POST_ROLLOUT_STOP_GRACE_S:-45}" -GRP_VLLM_LAUNCH_COMMAND_TEMPLATE="${GRP_VLLM_LAUNCH_COMMAND_TEMPLATE:-}" -GRP_VLLM_STOP_COMMAND_TEMPLATE="${GRP_VLLM_STOP_COMMAND_TEMPLATE:-}" -ROLLOUT_WEIGHT_SYNC_MODE="${ROLLOUT_WEIGHT_SYNC_MODE:-nccl}" -REQUIRE_ROLLOUT_WEIGHT_SYNC="${REQUIRE_ROLLOUT_WEIGHT_SYNC:-1}" -ROLLOUT_WEIGHT_SYNC_EXPORT_ONLY="${ROLLOUT_WEIGHT_SYNC_EXPORT_ONLY:-1}" -MEGATRON_STREAMING_EXPORT="${MEGATRON_STREAMING_EXPORT:-1}" -PREFERRED_TRAIN_NODE="${PREFERRED_TRAIN_NODE:-gn026}" -AVOID_TRAIN_NODE="${AVOID_TRAIN_NODE:-gn019}" -RUN_NCCL_PREFLIGHT="${RUN_NCCL_PREFLIGHT:-1}" -NCCL_PREFLIGHT_REQUIRED="${NCCL_PREFLIGHT_REQUIRED:-1}" -NCCL_PREFLIGHT_ELEMENTS="${NCCL_PREFLIGHT_ELEMENTS:-1048576}" -NCCL_PREFLIGHT_ITERATIONS="${NCCL_PREFLIGHT_ITERATIONS:-1}" -NCCL_PREFLIGHT_WALLTIME="${NCCL_PREFLIGHT_WALLTIME:-300}" - -source "$VENV_PATH" -cd "$PROJECT_DIR" - -mkdir -p logs -JOB_ID="${SLURM_JOB_ID:-manual}" -JOB_LOG_DIR="$PROJECT_DIR/logs/r2e_gym_cmlfq_24gpu/job_${JOB_ID}" -ROLLOUT_SYNC_DIR="$JOB_LOG_DIR/rollout_weight_sync" -CMLFQ_TREE_PATH="$PROJECT_DIR/logs/r2e_gym_cmlfq_24gpu/cmlfq_tree_${JOB_ID}.json" -CMLFQ_SHARED_LOAD_DIR="$JOB_LOG_DIR/cmlfq_shared_load" -GRP_ROLLOUT_MANIFEST_PATH="${GRP_ROLLOUT_MANIFEST_PATH:-$JOB_LOG_DIR/global_resource_rollout_manifest.json}" -GRP_ROLLOUT_PID_REGISTRY_PATH="${GRP_ROLLOUT_PID_REGISTRY_PATH:-$JOB_LOG_DIR/rollout_process_registry.jsonl}" -GRP_HYBRID_WORKER_TASK_DIR="${GRP_HYBRID_WORKER_TASK_DIR:-$JOB_LOG_DIR/elastic_training_tasks}" -GRP_VLLM_READY_TIMEOUT_S="${GRP_VLLM_READY_TIMEOUT_S:-$MAX_WAIT}" -VLLM_CUSTOM_ALL_REDUCE_FLAG="" -if [ "$VLLM_DISABLE_CUSTOM_ALL_REDUCE" = "1" ]; then - VLLM_CUSTOM_ALL_REDUCE_FLAG="--disable-custom-all-reduce" -fi -if [ "$GRP_MANAGE_ROLLOUT_PROCESSES" = "1" ] && [ -z "$GRP_VLLM_LAUNCH_COMMAND_TEMPLATE" ]; then - GRP_VLLM_LAUNCH_COMMAND_TEMPLATE="srun --exclusive --nodes=1 --ntasks=1 --nodelist={host} --gpus={tp} --cpus-per-task=16 bash -lc \"source '$VENV_PATH' && export TOKENIZERS_PARALLELISM=false && export PLANNED_CUDA_VISIBLE_DEVICES={gpus} && if [ -z \\\"\\\${{CUDA_VISIBLE_DEVICES:-}}\\\" ]; then export CUDA_VISIBLE_DEVICES=\\\"\\\$PLANNED_CUDA_VISIBLE_DEVICES\\\"; fi && echo \\\"CUDA_VISIBLE_DEVICES=\\\${{CUDA_VISIBLE_DEVICES}} planned=\\\${{PLANNED_CUDA_VISIBLE_DEVICES}}\\\" && export MASTER_ADDR=127.0.0.1 && export MASTER_PORT=\\\$((20000 + {port})) && export NCCL_P2P_DISABLE='$VLLM_NCCL_P2P_DISABLE' && export NCCL_IB_DISABLE='$VLLM_NCCL_IB_DISABLE' && export CUDA_LAUNCH_BLOCKING='$VLLM_CUDA_LAUNCH_BLOCKING' && {python} '$PROJECT_DIR/scripts/restartable_vllm_server.py' --instance-id {instance_id} --control-dir {control_dir} --health-url {local_health_url} --initial-model {initial_model} --ready-timeout '$MAX_WAIT' -- python3 '$PROJECT_DIR/scripts/vllm_hot_reload_api_server.py' --model __MODEL_PATH__ --served-model-name {model_path} --host 0.0.0.0 --port {port} --tensor-parallel-size {tp} --max-model-len {max_model_len} --dtype bfloat16 --gpu-memory-utilization {gpu_memory_utilization} --trust-remote-code --enforce-eager $VLLM_CUSTOM_ALL_REDUCE_FLAG\"" -fi -if [ "$GRP_MANAGE_ROLLOUT_PROCESSES" = "1" ] && [ -z "$GRP_VLLM_STOP_COMMAND_TEMPLATE" ]; then - GRP_VLLM_STOP_COMMAND_TEMPLATE="srun --overlap --nodes=1 --ntasks=1 --nodelist={host} bash -lc \"pkill -TERM -f 'restartable_vllm_server.py.*--instance-id {instance_id}' || pkill -TERM -f 'vllm.entrypoints.openai.api_server.*--port {port}' || true\"" -fi -if [ "$GRP_HYBRID_WORKER_LAUNCH_ENABLED" = "1" ] && [ -z "$GRP_HYBRID_WORKER_COMMAND_TEMPLATE" ]; then - GRP_HYBRID_WORKER_COMMAND_TEMPLATE="srun --overlap --nodes=1 --ntasks=1 --nodelist={host} --gpus=1 --cpus-per-task=8 bash -lc \"source '$VENV_PATH' && export TOKENIZERS_PARALLELISM=false && export PLANNED_CUDA_VISIBLE_DEVICES={gpus} && if [ -z \\\"\\\${{CUDA_VISIBLE_DEVICES:-}}\\\" ]; then export CUDA_VISIBLE_DEVICES=\\\"\\\$PLANNED_CUDA_VISIBLE_DEVICES\\\"; fi && {python} {rl_framework_path}/scripts/elastic_hybrid_worker.py --worker-id {worker_id} --target-core-id {target_core_id} --snapshot-path {snapshot_path} --gradient-host {gradient_host} --gradient-port {gradient_port} --authkey {authkey} --task-dir {task_dir} --gradient-transport {gradient_transport_backend} --native-rdma-device {native_rdma_device} --native-rdma-gid-index {native_rdma_gid_index} --native-rdma-ib-port {native_rdma_ib_port} --native-rdma-max-bytes {native_rdma_max_bytes}\"" -fi -export GRP_DYNAMIC_RECONFIG_ENABLED -export GRP_RUNTIME_ASYNC_PLANNING -export GRP_ONLINE_REPLANNING -export GRP_REPLAN_COOLDOWN_STEPS -export GRP_QUEUE_PRESSURE_THRESHOLD -export GRP_ACTIVE_ROLLOUT_PRESSURE_THRESHOLD -export GRP_REJECTED_ROLLOUT_DELTA_THRESHOLD -export GRP_ROLLOUT_TRAIN_IMBALANCE_THRESHOLD -export GRP_INTERVAL -export GRP_WARMUP_STEPS -export GRP_MIN_HISTORY -export GRP_MIN_GAIN_RATIO -export GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP -export GRP_MANAGE_ROLLOUT_PROCESSES -export GRP_RECONFIGURE_TRAINING -export GRP_TRAINING_POOL_ONLY -export GRP_TRAINING_POOL_TARGET_GPUS -export GRP_TRAINING_POOL_PLAN_ONLY -export GRP_CLUSTER_SWAP_ENABLED -export GRP_HYBRID_WORKER_LAUNCH_ENABLED -export GRP_HYBRID_TRAINING_PREWARM_ENABLED -export GRP_HYBRID_TRAINING_PREWARM_COUNT -export GRP_HYBRID_TRAINING_PREWARM_WORKER_IDS -export GRP_HYBRID_WORKER_TASK_DIR -export GRP_HYBRID_WORKER_COMMAND_TEMPLATE -export GRP_HYBRID_WORKER_READY_TIMEOUT_S -export GRP_GRADIENT_TRANSPORT_BACKEND -export GRP_DECOUPLE_COMMUNICATION_DOMAINS -export GRP_GRADIENT_SERVER_HOST -export GRP_GRADIENT_SERVER_PUBLIC_HOST -export GRP_GRADIENT_SERVER_PORT -export GRP_GRADIENT_SERVER_AUTHKEY -export GRP_ROLLOUT_RECONFIGURE_STRATEGY -export GRP_PREWARM_NO_SPARE_FALLBACK_STRATEGY -export GRP_DRAIN_BEFORE_RECONFIGURE -export GRP_RUNTIME_PEER_REQUEST_WAIT_S -export GRP_BATCH_COLLECTION_TIMEOUT_S -export GRP_BATCH_COLLECTION_MAX_RETRIES -export GRP_USE_NCCL_BARRIER_AFTER_ROLLOUT -export GRP_USE_NCCL_BARRIER_BEFORE_WEIGHT_SYNC -export GRP_INITIAL_ROLLOUT_TP_LIST -export GRP_FORCE_TRAIN_GPUS -export GRP_ROLLOUT_MANIFEST_PATH -export GRP_ROLLOUT_PID_REGISTRY_PATH -export GRP_WAIT_ROLLOUT_PROCESS_START_READY -export GRP_POST_ROLLOUT_STOP_GRACE_S -export GRP_VLLM_READY_TIMEOUT_S -export GRP_VLLM_LAUNCH_COMMAND_TEMPLATE -export GRP_VLLM_STOP_COMMAND_TEMPLATE -export ROLLOUT_WEIGHT_SYNC_MODE -export REQUIRE_ROLLOUT_WEIGHT_SYNC -export ROLLOUT_WEIGHT_SYNC_EXPORT_ONLY -export MEGATRON_STREAMING_EXPORT -mkdir -p "$JOB_LOG_DIR" -mkdir -p "$ROLLOUT_SYNC_DIR" -mkdir -p "$CMLFQ_SHARED_LOAD_DIR" - -if [ -n "$CMLFQ_WARM_START_TREE" ] && [ ! -e "$CMLFQ_TREE_PATH" ]; then - if [ ! -s "$CMLFQ_WARM_START_TREE" ]; then - echo "ERROR: CMLFQ warm-start tree does not exist or is empty: $CMLFQ_WARM_START_TREE" >&2 - exit 2 - fi - cp "$CMLFQ_WARM_START_TREE" "$CMLFQ_TREE_PATH" - echo "C-MLFQ warm-start tree: $CMLFQ_WARM_START_TREE -> $CMLFQ_TREE_PATH" -fi - -export PYTHONPATH="$(dirname "$PROJECT_DIR"):${PYTHONPATH:-}" -export TOKENIZERS_PARALLELISM=false -export WANDB_MODE="${WANDB_MODE:-offline}" -export WANDB_DIR="${PROJECT_DIR}/wandb_r2e_gym_cmlfq_24gpu" -export NO_PROXY="localhost,127.0.0.1,${NO_PROXY:-}" -unset NCCL_ASYNC_ERROR_HANDLING -export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 -export TORCH_NCCL_ENABLE_MONITORING=0 -export TORCH_NCCL_TRACE_BUFFER_SIZE=0 -export TORCH_NCCL_DUMP_ON_TIMEOUT=0 -export TORCH_NCCL_DESYNC_DEBUG=0 -export TORCH_NCCL_ENABLE_TIMING=0 -export TORCH_NCCL_HIGH_PRIORITY=0 -export NCCL_DEBUG="${NCCL_DEBUG:-WARN}" -export OMP_NUM_THREADS="${OMP_NUM_THREADS:-8}" -export PYTHONUNBUFFERED=1 -export CUDA_DEVICE_MAX_CONNECTIONS="${CUDA_DEVICE_MAX_CONNECTIONS:-1}" - -mapfile -t NODES < <(scontrol show hostnames "$SLURM_NODELIST" 2>/dev/null || true) -if [ "${#NODES[@]}" -eq 0 ]; then - mapfile -t NODES < <(python3 - <<'PY' -import os -import re - -value = os.environ.get("SLURM_NODELIST", "") - -def expand_part(part: str) -> list[str]: - match = re.fullmatch(r"([^\[]+)\[(.+)\]", part) - if not match: - return [part] if part else [] - prefix, body = match.groups() - out: list[str] = [] - for item in body.split(","): - if "-" in item: - start, end = item.split("-", 1) - width = max(len(start), len(end)) - for number in range(int(start), int(end) + 1): - out.append(f"{prefix}{number:0{width}d}") - else: - out.append(f"{prefix}{item}") - return out - -for chunk in re.split(r",(?![^\[]*\])", value): - for node in expand_part(chunk): - print(node) -PY -) -fi -MIN_NODE_COUNT=$((TRAIN_GPUS / GPUS_PER_NODE + 1)) -if [ "${#NODES[@]}" -lt "$MIN_NODE_COUNT" ]; then - echo "ERROR: R2E-Gym C-MLFQ training requires at least ${MIN_NODE_COUNT} nodes for TRAIN_GPUS=${TRAIN_GPUS}; got ${#NODES[@]}" >&2 - exit 2 -fi - -# Keep a known cross-node participant in the FSDP group when Slurm allocates -# it, regardless of lexical node ordering. This makes communication regressions -# reproducible while still allowing Slurm to choose the remaining nodes. -if [ -n "$PREFERRED_TRAIN_NODE" ] && [ "${NODES[0]}" != "$PREFERRED_TRAIN_NODE" ]; then - preferred_found=0 - reordered_nodes=("${NODES[0]}") - for node in "${NODES[@]}"; do - if [ "$node" = "$PREFERRED_TRAIN_NODE" ]; then - reordered_nodes+=("$node") - preferred_found=1 - break - fi - done - if [ "$preferred_found" = "1" ]; then - for node in "${NODES[@]:1}"; do - if [ "$node" != "$PREFERRED_TRAIN_NODE" ]; then - reordered_nodes+=("$node") - fi - done - NODES=("${reordered_nodes[@]}") - fi -fi - -# Keep a suspect-but-usable node in the rollout pool. vLLM health and API -# checks validate it before training, while FSDP remains on known-good nodes. -if [ -n "$AVOID_TRAIN_NODE" ]; then - reordered_nodes=() - deferred_nodes=() - for node in "${NODES[@]}"; do - if [ "$node" = "$AVOID_TRAIN_NODE" ]; then - deferred_nodes+=("$node") - else - reordered_nodes+=("$node") - fi - done - NODES=("${reordered_nodes[@]}" "${deferred_nodes[@]}") -fi - -if [ $((TRAIN_GPUS % GPUS_PER_NODE)) -ne 0 ]; then - echo "ERROR: TRAIN_GPUS must be a multiple of ${GPUS_PER_NODE}; got ${TRAIN_GPUS}" >&2 - exit 2 -fi -TRAIN_NODE_COUNT=$((TRAIN_GPUS / GPUS_PER_NODE)) -if [ "$TRAIN_NODE_COUNT" -lt 1 ] || [ "$TRAIN_NODE_COUNT" -ge "${#NODES[@]}" ]; then - echo "ERROR: TRAIN_GPUS=${TRAIN_GPUS} leaves no rollout node in ${#NODES[@]} allocated nodes" >&2 - exit 2 -fi -TRAIN_MODEL_PARALLEL_SIZE=$((TRAIN_TP_SIZE * TRAIN_PP_SIZE * TRAIN_CP_SIZE)) -if [ $((TRAIN_GPUS % TRAIN_MODEL_PARALLEL_SIZE)) -ne 0 ]; then - echo "ERROR: TRAIN_GPUS must be divisible by TP*PP*CP: ${TRAIN_GPUS} vs ${TRAIN_MODEL_PARALLEL_SIZE}" >&2 - exit 2 -fi -TRAIN_DP_SIZE=$((TRAIN_GPUS / TRAIN_MODEL_PARALLEL_SIZE)) -if [ $((TRAIN_BATCH_SIZE % (TRAIN_DP_SIZE * TRAIN_MICRO_BATCH_SIZE))) -ne 0 ]; then - echo "ERROR: TRAIN_BATCH_SIZE must be divisible by DP * TRAIN_MICRO_BATCH_SIZE: ${TRAIN_BATCH_SIZE} vs ${TRAIN_DP_SIZE}*${TRAIN_MICRO_BATCH_SIZE}" >&2 - exit 2 -fi -LOCAL_BATCH_SIZE=$((TRAIN_BATCH_SIZE / TRAIN_DP_SIZE)) -if [ $((LOCAL_BATCH_SIZE % N_SAMPLES)) -ne 0 ]; then - echo "ERROR: local batch per DP replica must be divisible by N_SAMPLES: local_batch_size=${LOCAL_BATCH_SIZE}, N_SAMPLES=${N_SAMPLES}" >&2 - exit 2 -fi -TRAIN_NODES=("${NODES[@]:0:$TRAIN_NODE_COUNT}") -ROLLOUT_NODES=("${NODES[@]:$TRAIN_NODE_COUNT}") -ROLLOUT_GPUS=$((${#ROLLOUT_NODES[@]} * GPUS_PER_NODE)) -TOTAL_GPUS=$((TRAIN_GPUS + ROLLOUT_GPUS)) -MASTER_ADDR="${TRAIN_NODES[0]}" -export MASTER_ADDR -RUNTIME_CONFIG="$PROJECT_DIR/configs/.r2e_gym_cmlfq_24gpu_${JOB_ID}.yaml" -PLAN_ENV="$JOB_LOG_DIR/planned_rollout.env" - -echo "============================================================" -echo "R2E-Gym full RL post-training with C-MLFQ, Qwen3-30B-A3B, ${TOTAL_GPUS} GPUs" -echo "============================================================" -echo "Job: $JOB_ID" -echo "Model: $MODEL_PATH" -echo "Model arch config: $MODEL_ARCH_CONFIG" -echo "Train backend: $TRAIN_BACKEND" -echo "Train topology: TP=$TRAIN_TP_SIZE PP=$TRAIN_PP_SIZE CP=$TRAIN_CP_SIZE EP=$TRAIN_EP_SIZE" -echo "Megatron CPU initialization: $MEGATRON_USE_CPU_INITIALIZATION" -echo "Megatron grouped GEMM: ${MCORE_MOE_GROUPED_GEMM:-1}" -echo "Train nodes: ${TRAIN_NODES[*]} (${TRAIN_GPUS} GPUs)" -echo "Rollout nodes: ${ROLLOUT_NODES[*]} (GlobalResourcePlanner decides TP layout)" -echo "Total GPUs: $TOTAL_GPUS (train=${TRAIN_GPUS}, rollout=${ROLLOUT_GPUS})" -echo "Total steps: $TOTAL_STEPS" -echo "Max model len: $MAX_MODEL_LEN" -echo "Max new tokens: $MAX_NEW_TOKENS" -echo "Train batch size: $TRAIN_BATCH_SIZE" -echo "Local batch per DP replica: $LOCAL_BATCH_SIZE" -echo "N samples: $N_SAMPLES" -echo "Max concurrent rollouts: $MAX_CONCURRENT_ROLLOUTS" -echo "Queue size: $QUEUE_SIZE" -echo "R2E max turns: $R2E_MAX_TURNS" -echo "R2E max prompt tokens: $R2E_MAX_PROMPT_TOKENS" -echo "Eval samples: $EVAL_MAX_SAMPLES ($R2E_EVAL_STRATEGY)" -echo "Long-context TP first: $LONG_CONTEXT_TP_FIRST" -echo "vLLM read timeout: $VLLM_READ_TIMEOUT" -echo "vLLM NCCL_P2P_DISABLE: $VLLM_NCCL_P2P_DISABLE" -echo "Train NCCL_P2P_DISABLE: $NCCL_P2P_DISABLE" -echo "Train NCCL_IB_DISABLE: $NCCL_IB_DISABLE" -echo "Logs: $JOB_LOG_DIR" -python3 -c 'import torch, transformers, vllm; print("torch", torch.__version__, "transformers", transformers.__version__, "vllm", vllm.__version__)' - -VLLM_STEP_PIDS=() -declare -A VLLM_PID_BY_NAME=() -ROLLOUT_NODE_LIST=() -ROLLOUT_TP_LIST=() -ROLLOUT_PORT_LIST=() -ROLLOUT_NAME_LIST=() -ROLLOUT_GPU_LIST=() - -cleanup() { - local exit_code=$? - trap - EXIT INT TERM - echo "[cleanup] stopping vLLM processes..." - for pid in "${VLLM_STEP_PIDS[@]:-}"; do - kill "$pid" 2>/dev/null || true - done - for i in "${!ROLLOUT_NODE_LIST[@]}"; do - local node="${ROLLOUT_NODE_LIST[$i]}" - local port="${ROLLOUT_PORT_LIST[$i]}" - srun --overlap --nodes=1 --ntasks=1 --nodelist="$node" \ - bash -lc "pkill -f 'vllm.entrypoints.openai.api_server.*--port ${port}' 2>/dev/null || true" \ - >/dev/null 2>&1 || true - done - python3 "$PROJECT_DIR/scripts/merge_cmlfq_prefix_trees.py" \ - --output "$CMLFQ_TREE_PATH" || true - echo "[cleanup] complete, exit=$exit_code" - exit "$exit_code" -} -trap cleanup EXIT INT TERM - -echo "[1/6] Running GlobalResourcePlanner preflight for ${TOTAL_GPUS}-GPU runtime config" -export PROJECT_DIR MODEL_PATH MODEL_ARCH_CONFIG TOTAL_STEPS MAX_MODEL_LEN MAX_NEW_TOKENS EVAL_INTERVAL MAX_WAIT SYNC_INTERVAL ROLLOUT_SYNC_DRAIN_LEAD_STEPS RL_TRAIN_PHASE_TRACE NCCL_RELOAD_PORT -export TRAIN_BATCH_SIZE TRAIN_MICRO_BATCH_SIZE N_SAMPLES MAX_CONCURRENT_ROLLOUTS QUEUE_SIZE VLLM_BASE_PORT GPU_MEMORY_UTILIZATION JOB_ID -export JOB_LOG_DIR EXPERIMENT_TAG SCHEDULER_TYPE GRP_ENABLED -export LONG_CONTEXT_TP_FIRST VLLM_READ_TIMEOUT VLLM_CONNECT_TIMEOUT VLLM_WRITE_TIMEOUT VLLM_POOL_TIMEOUT -export VLLM_NCCL_P2P_DISABLE VLLM_NCCL_IB_DISABLE VLLM_CUDA_LAUNCH_BLOCKING -export NCCL_P2P_DISABLE NCCL_IB_DISABLE -export TRAIN_GPUS ROLLOUT_GPUS TOTAL_GPUS -export TRAIN_BACKEND TRAIN_TP_SIZE TRAIN_PP_SIZE TRAIN_CP_SIZE TRAIN_EP_SIZE -export EXPERT_TENSOR_PARALLEL_SIZE USE_DISTRIBUTED_OPTIMIZER -export MEGATRON_USE_PRECISION_AWARE_OPTIMIZER MEGATRON_OPTIMIZER_CPU_OFFLOAD -export MEGATRON_OPTIMIZER_OFFLOAD_FRACTION -export RUNTIME_CONFIG PLAN_ENV -export ALLOW_QWEN30_FALLBACK -export GRP_PROFILE_DATASET_JSONL GRP_PROFILE_SAMPLE_SIZE GRP_PROFILE_STRATEGY GRP_PROFILE_SEED GRP_PROFILE_SAMPLES_PER_PROMPT -export CMLFQ_TREE_PATH CMLFQ_SHARED_LOAD_DIR CMLFQ_SHARED_LOAD_TTL CMLFQ_SHARED_LOAD_HEARTBEAT CMLFQ_TREE_PERSIST_INTERVAL -ROLLOUT_NODES_CSV="$(IFS=,; echo "${ROLLOUT_NODES[*]}")" -export ROLLOUT_NODES_CSV -python3 - <<'PY' -import os -import shlex -from pathlib import Path -import yaml - -from transformers import AutoTokenizer - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.cost_model.preflight_planner import PreflightPlanner -from RL_Framework.infra.cost_model.startup_profile import ( - load_jsonl_rows, - load_profile_summary, - profile_jsonl_has_records, - profile_metadata_matches, - startup_profile_metadata, - summarize_length_profile, - write_profile_jsonl, - write_profile_summary, -) -from RL_Framework.workflow.r2e_gym_profile import build_r2e_gym_length_profile - -project = Path(os.environ["PROJECT_DIR"]) -base = project / "configs" / "r2e_gym_qwen3_14b_mcore_gpu_6node48_100step_no_ehp.yaml" -seed_path = project / "configs" / f".r2e_gym_cmlfq_24gpu_seed_{os.environ['JOB_ID']}.yaml" -runtime_path = Path(os.environ["RUNTIME_CONFIG"]) -plan_env = Path(os.environ["PLAN_ENV"]) -job_log_dir = Path(os.environ["JOB_LOG_DIR"]) -rollout_nodes = [n for n in os.environ["ROLLOUT_NODES_CSV"].split(",") if n] -base_port = int(os.environ["VLLM_BASE_PORT"]) -max_model_len = int(os.environ["MAX_MODEL_LEN"]) -max_new_tokens = int(os.environ["MAX_NEW_TOKENS"]) -r2e_max_turns = int(os.environ["R2E_MAX_TURNS"]) -r2e_max_prompt_tokens = int(os.environ.get("R2E_MAX_PROMPT_TOKENS", "0") or "0") -profile_dataset = Path(os.environ["GRP_PROFILE_DATASET_JSONL"]) -profile_cache_dir = project / "logs" / "r2e_gym_cmlfq_24gpu" / "startup_profile_cache" -profile_jsonl = profile_cache_dir / "grp_startup_profile.jsonl" -profile_summary_json = profile_cache_dir / "grp_startup_profile_summary.json" -train_gpus = int(os.environ["TRAIN_GPUS"]) -rollout_gpus = int(os.environ["ROLLOUT_GPUS"]) -total_gpus = int(os.environ["TOTAL_GPUS"]) -train_tp = int(os.environ["TRAIN_TP_SIZE"]) -train_pp = int(os.environ["TRAIN_PP_SIZE"]) -train_cp = int(os.environ["TRAIN_CP_SIZE"]) -train_dp = train_gpus // (train_tp * train_pp * train_cp) - -seed = { - "base_config": str(base), - "model_arch_config": os.environ["MODEL_ARCH_CONFIG"], - "model_path": os.environ["MODEL_PATH"], - "tokenizer_path": os.environ["MODEL_PATH"], - "train_gpus": train_gpus, - "rollout_gpus": rollout_gpus, - "n_total_gpus": total_gpus, - "train_backend": os.environ["TRAIN_BACKEND"], - "train_tp_size": train_tp, - "train_pp_size": train_pp, - "train_cp_size": train_cp, - "train_ep_size": int(os.environ["TRAIN_EP_SIZE"]), - "expert_tensor_parallel_size": int(os.environ["EXPERT_TENSOR_PARALLEL_SIZE"]), - "train_dp_size": train_dp, - "use_distributed_optimizer": os.environ["USE_DISTRIBUTED_OPTIMIZER"] == "1", - "megatron_grad_reduce_in_fp32": ( - os.environ.get("MEGATRON_GRAD_REDUCE_IN_FP32", "0") == "1" - ), - "megatron_use_precision_aware_optimizer": ( - os.environ.get("MEGATRON_USE_PRECISION_AWARE_OPTIMIZER", "0") == "1" - ), - "megatron_optimizer_cpu_offload": ( - os.environ.get("MEGATRON_OPTIMIZER_CPU_OFFLOAD", "0") == "1" - ), - "megatron_optimizer_offload_fraction": float( - os.environ.get("MEGATRON_OPTIMIZER_OFFLOAD_FRACTION", "0.0") - ), - "megatron_optimizer_pin_cpu_grads": ( - os.environ.get("MEGATRON_OPTIMIZER_PIN_CPU_GRADS", "1") == "1" - ), - "megatron_optimizer_pin_cpu_params": ( - os.environ.get("MEGATRON_OPTIMIZER_PIN_CPU_PARAMS", "1") == "1" - ), - "megatron_checkpoint_format": "torch_dist", - "megatron_fully_parallel_save": True, - "megatron_async_save": False, - "megatron_streaming_export": os.environ.get("MEGATRON_STREAMING_EXPORT", "1") == "1", - "megatron_use_transformer_engine": False, - "megatron_use_cpu_initialization": ( - os.environ.get("MEGATRON_USE_CPU_INITIALIZATION", "0") == "1" - ), - "megatron_recompute_num_layers": 1, - "batch_size": int(os.environ["TRAIN_BATCH_SIZE"]), - "micro_batch_size": int(os.environ["TRAIN_MICRO_BATCH_SIZE"]), - "n_samples": int(os.environ["N_SAMPLES"]), - "total_steps": int(os.environ["TOTAL_STEPS"]), - "sync_interval": int(os.environ["SYNC_INTERVAL"]), - "rollout_sync_drain_lead_steps": int(os.environ["ROLLOUT_SYNC_DRAIN_LEAD_STEPS"]), - "eval_interval": int(os.environ["EVAL_INTERVAL"]), - "max_new_tokens": int(os.environ["MAX_NEW_TOKENS"]), - "max_seq_length": int(os.environ["MAX_MODEL_LEN"]), - "r2e_max_turns": r2e_max_turns, - "r2e_max_prompt_tokens": r2e_max_prompt_tokens, - "max_concurrent_rollouts": int(os.environ["MAX_CONCURRENT_ROLLOUTS"]), - "queue_size": int(os.environ["QUEUE_SIZE"]), - "sync_path": str(project / "logs" / "r2e_gym_cmlfq_24gpu" / f"weights_{os.environ['JOB_ID']}"), - "rollout_weight_sync_mode": os.environ["ROLLOUT_WEIGHT_SYNC_MODE"], - "weight_sync_mode": "nccl", - "rollout_weight_sync_control_dir": str(project / "logs" / "r2e_gym_cmlfq_24gpu" / f"job_{os.environ['JOB_ID']}" / "rollout_weight_sync"), - "rollout_weight_sync_timeout_s": int(os.environ["MAX_WAIT"]), - "rollout_nccl_host": os.environ["MASTER_ADDR"], - "rollout_nccl_port": int(os.environ.get("NCCL_RELOAD_PORT", "29620")), - "rollout_nccl_chunk_mb": 256, - "rollout_weight_sync_poll_interval_s": 0.05, - "rollout_weight_sync_export_only": os.environ.get("ROLLOUT_WEIGHT_SYNC_EXPORT_ONLY", "1") == "1", - "require_rollout_weight_sync": os.environ.get("REQUIRE_ROLLOUT_WEIGHT_SYNC", "1") == "1", - "log_dir": str(project / "logs" / "r2e_gym_cmlfq_24gpu"), - "wandb_run_name": f"{os.environ['EXPERIMENT_TAG']}-{os.environ['JOB_ID']}", - "enable_history_collection": True, - "history_output_dir": str(Path(os.environ["JOB_LOG_DIR"]) / "history"), - "history_save_raw_lengths": True, - "history_flush_interval": 1, - "history_experiment_name": os.environ["EXPERIMENT_TAG"], - "heterogeneous_rollout": { - "enabled": True, - "total_gpus": rollout_gpus, - "available_gpus": list(range(train_gpus, total_gpus)), - "vllm_base_port": int(os.environ["VLLM_BASE_PORT"]), - "max_model_len": int(os.environ["MAX_MODEL_LEN"]), - "gpu_memory_utilization": float(os.environ["GPU_MEMORY_UTILIZATION"]), - "instances": [], - "scheduling": { - "scheduler_type": os.environ["SCHEDULER_TYPE"], - "load_balance_strategy": "least_connections", - "max_queue_length": int(os.environ["QUEUE_SIZE"]), - "enable_fallback": True, - "cmlfq_tree_path": os.environ["CMLFQ_TREE_PATH"], - "cmlfq_tree_persist_interval": int(os.environ["CMLFQ_TREE_PERSIST_INTERVAL"]), - "cmlfq_shared_load_dir": os.environ["CMLFQ_SHARED_LOAD_DIR"], - "cmlfq_shared_load_ttl_s": float(os.environ["CMLFQ_SHARED_LOAD_TTL"]), - "cmlfq_shared_load_heartbeat_s": float(os.environ["CMLFQ_SHARED_LOAD_HEARTBEAT"]), - "cmlfq_buckets": { - "short": { - "tp_degrees": [2], - "max_tokens": 3000, - }, - "medium": { - "tp_degrees": [2], - "max_tokens": 6000, - }, - "long": {"tp_degrees": [4, 2], "max_tokens": max_model_len}, - }, - }, - }, - "global_resource_planner": { - "enabled": os.environ["GRP_ENABLED"] == "1", - "train_backend": "analytic", - "rollout_backend": "analytic", - "plan_interval": int(os.environ["GRP_INTERVAL"]), - "warmup_steps": int(os.environ["GRP_WARMUP_STEPS"]), - "min_history_size": int(os.environ["GRP_MIN_HISTORY"]), - "min_gain_ratio": float(os.environ["GRP_MIN_GAIN_RATIO"]), - "reconfiguration_cost_s": 15.0, - "allowed_rollout_tp": [2, 4], - "require_heterogeneous_rollout_tp": ( - os.environ["GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP"] == "1" - ), - "allowed_train_tp": [train_tp], - "allowed_train_pp": [train_pp], - "fixed_train_gpus": train_gpus, - "micro_batch_sizes": [1], - "startup_profile_enabled": True, - "startup_profile_sample_size": int(os.environ["GRP_PROFILE_SAMPLE_SIZE"]), - "startup_profile_strategy": os.environ["GRP_PROFILE_STRATEGY"], - "startup_profile_seed": int(os.environ["GRP_PROFILE_SEED"]), - "startup_profile_samples_per_prompt": int(os.environ["GRP_PROFILE_SAMPLES_PER_PROMPT"]), - "startup_profile_dataset_jsonl": str(profile_dataset), - "startup_profile_history_jsonl": str(profile_jsonl), - "startup_profile_summary_json": str(profile_summary_json), - "runtime_length_profile_enabled": True, - "runtime_length_profile_jsonl": str(job_log_dir / "runtime_length_profile.jsonl"), - "apply_to_runtime": True, - "verbose": True, - "runtime_async_planning": os.environ["GRP_RUNTIME_ASYNC_PLANNING"] == "1", - "runtime_max_pending_plans": 1, - "runtime_dynamic_reconfiguration_enabled": os.environ["GRP_DYNAMIC_RECONFIG_ENABLED"] == "1", - "runtime_online_replanning": os.environ["GRP_ONLINE_REPLANNING"] == "1", - "runtime_replan_cooldown_steps": int(os.environ["GRP_REPLAN_COOLDOWN_STEPS"]), - "runtime_queue_pressure_threshold": float(os.environ["GRP_QUEUE_PRESSURE_THRESHOLD"]), - "runtime_active_rollout_pressure_threshold": float(os.environ["GRP_ACTIVE_ROLLOUT_PRESSURE_THRESHOLD"]), - "runtime_rejected_rollout_delta_threshold": int(os.environ["GRP_REJECTED_ROLLOUT_DELTA_THRESHOLD"]), - "runtime_rollout_train_imbalance_threshold": float(os.environ["GRP_ROLLOUT_TRAIN_IMBALANCE_THRESHOLD"]), - "runtime_manage_rollout_processes": os.environ["GRP_MANAGE_ROLLOUT_PROCESSES"] == "1", - "runtime_reconfigure_training": os.environ["GRP_RECONFIGURE_TRAINING"] == "1", - "runtime_training_pool_only": os.environ["GRP_TRAINING_POOL_ONLY"] == "1", - "runtime_training_pool_target_gpus": int(os.environ["GRP_TRAINING_POOL_TARGET_GPUS"]), - "runtime_training_pool_plan_only": os.environ["GRP_TRAINING_POOL_PLAN_ONLY"] == "1", - "runtime_cluster_swap_enabled": os.environ["GRP_CLUSTER_SWAP_ENABLED"] == "1", - "hybrid_worker_launch_enabled": os.environ["GRP_HYBRID_WORKER_LAUNCH_ENABLED"] == "1", - "hybrid_training_prewarm_enabled": os.environ["GRP_HYBRID_TRAINING_PREWARM_ENABLED"] == "1", - "hybrid_training_prewarm_count": int(os.environ["GRP_HYBRID_TRAINING_PREWARM_COUNT"]), - "hybrid_training_prewarm_worker_ids": [ - item.strip() - for item in os.environ["GRP_HYBRID_TRAINING_PREWARM_WORKER_IDS"].split(",") - if item.strip() - ], - "hybrid_worker_task_dir": os.environ["GRP_HYBRID_WORKER_TASK_DIR"], - "hybrid_worker_command_template": os.environ["GRP_HYBRID_WORKER_COMMAND_TEMPLATE"], - "hybrid_worker_ready_timeout_s": float(os.environ["GRP_HYBRID_WORKER_READY_TIMEOUT_S"]), - "gradient_transport_backend": os.environ["GRP_GRADIENT_TRANSPORT_BACKEND"], - "decouple_communication_domains": os.environ["GRP_DECOUPLE_COMMUNICATION_DOMAINS"] == "1", - "gradient_server_host": os.environ["GRP_GRADIENT_SERVER_HOST"], - "gradient_server_public_host": os.environ["GRP_GRADIENT_SERVER_PUBLIC_HOST"], - "gradient_server_port": int(os.environ["GRP_GRADIENT_SERVER_PORT"]), - "gradient_server_authkey": os.environ["GRP_GRADIENT_SERVER_AUTHKEY"], - "runtime_rollout_reconfigure_strategy": os.environ["GRP_ROLLOUT_RECONFIGURE_STRATEGY"], - "runtime_prewarm_no_spare_fallback_strategy": os.environ["GRP_PREWARM_NO_SPARE_FALLBACK_STRATEGY"], - "runtime_drain_before_reconfigure": os.environ["GRP_DRAIN_BEFORE_RECONFIGURE"] == "1", - "runtime_peer_request_wait_s": float(os.environ["GRP_RUNTIME_PEER_REQUEST_WAIT_S"]), - "runtime_batch_collection_timeout_s": float(os.environ["GRP_BATCH_COLLECTION_TIMEOUT_S"]), - "runtime_batch_collection_max_retries": int(os.environ["GRP_BATCH_COLLECTION_MAX_RETRIES"]), - "runtime_use_nccl_barrier_after_rollout": os.environ["GRP_USE_NCCL_BARRIER_AFTER_ROLLOUT"] == "1", - "runtime_use_nccl_barrier_before_weight_sync": os.environ["GRP_USE_NCCL_BARRIER_BEFORE_WEIGHT_SYNC"] == "1", - "runtime_rollout_manifest_path": os.environ["GRP_ROLLOUT_MANIFEST_PATH"], - "runtime_rollout_pid_registry_path": os.environ["GRP_ROLLOUT_PID_REGISTRY_PATH"], - "runtime_wait_rollout_process_start_ready": os.environ["GRP_WAIT_ROLLOUT_PROCESS_START_READY"] == "1", - "runtime_post_rollout_stop_grace_s": float(os.environ["GRP_POST_ROLLOUT_STOP_GRACE_S"]), - "runtime_rollout_log_dir": str(project / "logs" / "r2e_gym_cmlfq_24gpu" / f"job_{os.environ['JOB_ID']}" / "runtime_rollout"), - "vllm_ready_timeout_s": float(os.environ["GRP_VLLM_READY_TIMEOUT_S"]), - "vllm_launch_command_template": os.environ["GRP_VLLM_LAUNCH_COMMAND_TEMPLATE"], - "vllm_stop_command_template": os.environ["GRP_VLLM_STOP_COMMAND_TEMPLATE"], - "simulator_allow_fallback": True, - "simulator_timeout_s": 240.0, - }, -} -seed_path.write_text(yaml.safe_dump(seed, sort_keys=False), encoding="utf-8") - -cfg = AsyncRLConfig.from_yaml(str(seed_path)) -profile_metadata = startup_profile_metadata( - dataset_jsonl=profile_dataset, - model_path=cfg.model_path, - tokenizer_path=cfg.tokenizer_path if cfg.tokenizer_path else cfg.model_path, - sample_size=int(os.environ["GRP_PROFILE_SAMPLE_SIZE"]), - strategy=os.environ["GRP_PROFILE_STRATEGY"], - seed=int(os.environ["GRP_PROFILE_SEED"]), - samples_per_prompt=int(os.environ["GRP_PROFILE_SAMPLES_PER_PROMPT"]), - max_new_tokens=max_new_tokens, - max_seq_length=max_model_len, - r2e_max_turns=r2e_max_turns, - r2e_max_prompt_tokens=r2e_max_prompt_tokens, -) -history = None -summary = None -if profile_jsonl_has_records(profile_jsonl): - existing_summary = load_profile_summary(profile_summary_json) - if ( - existing_summary is None - or profile_metadata_matches(existing_summary, profile_metadata) - ): - history = load_jsonl_rows(profile_jsonl) - if not history: - raise RuntimeError(f"startup profile JSONL is empty: {profile_jsonl}") - summary = summarize_length_profile(history) - summary.update(profile_metadata) - summary["reused"] = True - write_profile_summary(summary, profile_summary_json) -if history is None: - rows = load_jsonl_rows(profile_dataset) - if not rows: - raise RuntimeError(f"GRP startup profile dataset is empty: {profile_dataset}") - tokenizer = AutoTokenizer.from_pretrained( - cfg.tokenizer_path if cfg.tokenizer_path else cfg.model_path, - trust_remote_code=True, - ) - if tokenizer.pad_token is None: - tokenizer.pad_token = tokenizer.eos_token - history = build_r2e_gym_length_profile( - rows, - tokenizer=tokenizer, - sample_size=int(os.environ["GRP_PROFILE_SAMPLE_SIZE"]), - strategy=os.environ["GRP_PROFILE_STRATEGY"], - seed=int(os.environ["GRP_PROFILE_SEED"]), - samples_per_prompt=int(os.environ["GRP_PROFILE_SAMPLES_PER_PROMPT"]), - max_turns=r2e_max_turns, - max_new_tokens=max_new_tokens, - max_seq_length=max_model_len, - max_prompt_tokens=r2e_max_prompt_tokens or None, - ) - summary = summarize_length_profile(history) - summary.update(profile_metadata) - write_profile_jsonl(history, profile_jsonl) - write_profile_summary(summary, profile_summary_json) -result = PreflightPlanner(cfg, apply_best_candidate=True).run(history) -planned = result.planned_config -planned.train_backend = os.environ["TRAIN_BACKEND"] -planned.train_tp_size = train_tp -planned.tp_size = train_tp -planned.train_pp_size = train_pp -planned.train_cp_size = train_cp -planned.train_ep_size = int(os.environ["TRAIN_EP_SIZE"]) -planned.expert_tensor_parallel_size = int( - os.environ["EXPERT_TENSOR_PARALLEL_SIZE"] -) -planned.train_dp_size = train_dp -planned.use_distributed_optimizer = ( - os.environ["USE_DISTRIBUTED_OPTIMIZER"] == "1" -) -planned.megatron_grad_reduce_in_fp32 = ( - os.environ.get("MEGATRON_GRAD_REDUCE_IN_FP32", "0") == "1" -) -planned.megatron_use_precision_aware_optimizer = ( - os.environ.get("MEGATRON_USE_PRECISION_AWARE_OPTIMIZER", "0") == "1" -) -planned.megatron_optimizer_cpu_offload = ( - os.environ.get("MEGATRON_OPTIMIZER_CPU_OFFLOAD", "0") == "1" -) -planned.megatron_optimizer_offload_fraction = float( - os.environ.get("MEGATRON_OPTIMIZER_OFFLOAD_FRACTION", "0.0") -) -planned.megatron_optimizer_pin_cpu_grads = ( - os.environ.get("MEGATRON_OPTIMIZER_PIN_CPU_GRADS", "1") == "1" -) -planned.megatron_optimizer_pin_cpu_params = ( - os.environ.get("MEGATRON_OPTIMIZER_PIN_CPU_PARAMS", "1") == "1" -) -planned.megatron_use_cpu_initialization = ( - os.environ.get("MEGATRON_USE_CPU_INITIALIZATION", "0") == "1" -) - -if not planned.heterogeneous_rollout.instances: - if os.environ.get("ALLOW_QWEN30_FALLBACK", "0") != "1": - raise RuntimeError( - "GlobalResourcePlanner produced no feasible candidate. " - "Refusing Qwen30 fallback because it can hide train-memory OOM. " - "Set ALLOW_QWEN30_FALLBACK=1 only for diagnostic rollout runs." - ) - fallback_layout_by_gpus = { - 4: [2, 2], - 8: [4, 2, 2], - 12: [4, 4, 2, 2], - 20: [4, 4, 4, 4, 2, 2], - } - fallback_tp_layout = fallback_layout_by_gpus.get(rollout_gpus) - if fallback_tp_layout is None: - fallback_tp_layout = [] - remaining_gpus_for_layout = rollout_gpus - while remaining_gpus_for_layout >= 4: - fallback_tp_layout.append(4) - remaining_gpus_for_layout -= 4 - if remaining_gpus_for_layout == 2: - fallback_tp_layout.append(2) - elif remaining_gpus_for_layout: - raise RuntimeError(f"Cannot create Qwen30 fallback TP layout for rollout_gpus={rollout_gpus}") - print( - "GlobalResourcePlanner produced no feasible rollout candidate; " - f"using Qwen30 fallback TP layout {fallback_tp_layout}" - ) - planned.train_gpus = train_gpus - planned.rollout_gpus = rollout_gpus - planned.n_total_gpus = total_gpus - planned.train_tp_size = train_tp - planned.tp_size = train_tp - planned.train_pp_size = train_pp - planned.train_cp_size = train_cp - planned.train_dp_size = train_dp - planned.heterogeneous_rollout.enabled = True - planned.heterogeneous_rollout.total_gpus = rollout_gpus - planned.heterogeneous_rollout.instances = [] - from RL_Framework.config import HeterogeneousInstanceConfig - for idx, tp in enumerate(fallback_tp_layout): - planned.heterogeneous_rollout.instances.append( - HeterogeneousInstanceConfig( - instance_id=f"qwen30_fallback_tp{tp}_{idx}", - tp=tp, - gpus=list(range(tp)), - host=planned.heterogeneous_rollout.vllm_host, - description="qwen30_fallback_after_no_feasible_grp_candidate", - ) - ) -if os.environ.get("GRP_INITIAL_ROLLOUT_TP_LIST", "").strip(): - from RL_Framework.config import HeterogeneousInstanceConfig - override_tps = [ - int(item.strip()) - for item in os.environ["GRP_INITIAL_ROLLOUT_TP_LIST"].replace(";", ":").replace(",", ":").split(":") - if item.strip() - ] - if sum(override_tps) != rollout_gpus: - raise RuntimeError( - "GRP_INITIAL_ROLLOUT_TP_LIST must sum to rollout_gpus=" - f"{rollout_gpus}, got {override_tps} sum={sum(override_tps)}" - ) - planned.heterogeneous_rollout.instances = [ - HeterogeneousInstanceConfig( - instance_id=f"initial_override_tp{tp}_{idx}", - tp=tp, - gpus=[], - host=planned.heterogeneous_rollout.vllm_host, - description="initial_rollout_layout_override_for_online_replanning", - ) - for idx, tp in enumerate(override_tps) - ] - planned.train_gpus = train_gpus - planned.rollout_gpus = rollout_gpus - planned.n_total_gpus = total_gpus - planned.train_tp_size = train_tp - planned.train_pp_size = train_pp - planned.train_dp_size = train_dp - print(f"Using initial rollout TP override: {override_tps}") -tp_list = [int(inst.tp) for inst in planned.heterogeneous_rollout.instances] -require_heterogeneous_rollout_tp = ( - os.environ.get("GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP", "1") == "1" -) -if ( - require_heterogeneous_rollout_tp - and len(set(tp_list)) <= 1 - and not os.environ.get("GRP_INITIAL_ROLLOUT_TP_LIST", "").strip() -): - raise RuntimeError(f"GlobalResourcePlanner/fallback did not produce heterogeneous TP degrees: {tp_list}") -if sum(tp_list) != rollout_gpus: - raise RuntimeError(f"GlobalResourcePlanner/fallback rollout GPUs must sum to {rollout_gpus}, got {sum(tp_list)} from {tp_list}") -if planned.train_gpus != train_gpus: - raise RuntimeError(f"GlobalResourcePlanner/fallback must keep train_gpus={train_gpus}, got {planned.train_gpus}") - -remaining = {node: 4 for node in rollout_nodes} -next_gpu = {node: 0 for node in rollout_nodes} -assigned_nodes: list[str] = [] -assigned_tps: list[int] = [] -assigned_ports: list[int] = [] -assigned_names: list[str] = [] -assigned_gpus: list[str] = [] - -for idx, inst in enumerate(planned.heterogeneous_rollout.instances): - tp = int(inst.tp) - node = next((candidate for candidate in rollout_nodes if remaining[candidate] >= tp), None) - if node is None: - raise RuntimeError(f"Cannot pack planned TP list {tp_list} onto nodes {rollout_nodes}") - start_gpu = next_gpu[node] - inst.gpus = list(range(start_gpu, start_gpu + tp)) - inst.host = node - if not inst.instance_id: - inst.instance_id = f"grp_tp{tp}_{idx}" - remaining[node] -= tp - next_gpu[node] += tp - assigned_nodes.append(node) - assigned_tps.append(tp) - assigned_ports.append(base_port + idx) - assigned_names.append(inst.instance_id) - assigned_gpus.append(",".join(str(gpu) for gpu in inst.gpus)) - -planned.vllm_port = base_port -planned.vllm_num_instances = len(assigned_tps) -planned.rollout_gpus = sum(assigned_tps) -planned.n_total_gpus = planned.train_gpus + planned.rollout_gpus -planned.max_concurrent_rollouts = int(os.environ["MAX_CONCURRENT_ROLLOUTS"]) -planned.queue_size = int(os.environ["QUEUE_SIZE"]) -planned.heterogeneous_rollout.vllm_base_port = base_port -planned.heterogeneous_rollout.total_gpus = planned.rollout_gpus - -grp = planned.global_resource_planner -grp.train_backend = "sailor" -grp.rollout_backend = "vidur" -grp.runtime_async_planning = os.environ["GRP_RUNTIME_ASYNC_PLANNING"] == "1" -grp.runtime_max_pending_plans = 1 -grp.simulator_allow_fallback = True -grp.simulator_timeout_s = 240.0 -grp.allowed_rollout_tp = [2, 4] -grp.require_heterogeneous_rollout_tp = ( - os.environ["GRP_REQUIRE_HETEROGENEOUS_ROLLOUT_TP"] == "1" -) -grp.allowed_train_tp = [train_tp] -grp.allowed_train_pp = [train_pp] -grp.fixed_train_gpus = train_gpus -grp.micro_batch_sizes = [1] - -planned.to_yaml(str(runtime_path)) - -def bash_array(values): - return "(" + " ".join(shlex.quote(str(v)) for v in values) + ")" - -plan_env.write_text( - "\n".join( - [ - f"ROLLOUT_COUNT={len(assigned_tps)}", - f"ROLLOUT_NODE_LIST={bash_array(assigned_nodes)}", - f"ROLLOUT_TP_LIST={bash_array(assigned_tps)}", - f"ROLLOUT_PORT_LIST={bash_array(assigned_ports)}", - f"ROLLOUT_NAME_LIST={bash_array(assigned_names)}", - f"ROLLOUT_GPU_LIST={bash_array(assigned_gpus)}", - f"HETERO_INSTANCE_HOSTS={shlex.quote(','.join(assigned_nodes))}", - f"PLANNED_ROLLOUT_TP_LIST={shlex.quote(','.join(str(v) for v in assigned_tps))}", - f"PLANNED_RUNTIME_CONFIG={shlex.quote(str(runtime_path))}", - ] - ) - + "\n", - encoding="utf-8", -) -print(f"seed_config={seed_path}") -print(f"runtime_config={runtime_path}") -print(f"profile_jsonl={profile_jsonl}") -print(f"profile_summary={summary}") -print(f"decision={result.decision.to_dict()}") -print(f"planned_rollout_tp={assigned_tps}") -print(f"planned_rollout_nodes={assigned_nodes}") -PY - -source "$PLAN_ENV" -echo "GlobalResourcePlanner rollout TP list: ${PLANNED_ROLLOUT_TP_LIST}" -echo "GlobalResourcePlanner rollout nodes: ${ROLLOUT_NODE_LIST[*]}" -TRAIN_NODE_LIST_CSV="$(IFS=,; echo "${TRAIN_NODES[*]}")" - -if [ "$RUN_NCCL_PREFLIGHT" = "1" ]; then - echo "[2/7] Running cross-node NCCL all-gather preflight" - PREFLIGHT_PORT=$((MASTER_PORT + 1)) - PREFLIGHT_STATUS=0 - timeout "$((NCCL_PREFLIGHT_WALLTIME + 30))" srun --overlap \ - --nodes="$TRAIN_NODE_COUNT" \ - --ntasks="$TRAIN_NODE_COUNT" \ - --ntasks-per-node=1 \ - --nodelist="$TRAIN_NODE_LIST_CSV" \ - --gpus-per-task=4 \ - --cpus-per-task=8 \ - bash -lc " - source '$VENV_PATH' - cd '$PROJECT_DIR' - node_rank=\"\${SLURM_PROCID:-0}\" - preflight_log='$JOB_LOG_DIR/nccl_preflight_rank'\${node_rank}'_'\${HOSTNAME}'.log' - { - export PYTHONPATH='$(dirname "$PROJECT_DIR")':\${PYTHONPATH:-} - export MASTER_ADDR='$MASTER_ADDR' - export MASTER_PORT='$PREFLIGHT_PORT' - export CUDA_VISIBLE_DEVICES=0,1,2,3 - echo \"[NCCL preflight launcher] node_rank=\${node_rank} host=\${HOSTNAME} cuda_visible_devices=\${CUDA_VISIBLE_DEVICES}\" - export NCCL_PREFLIGHT_ELEMENTS='$NCCL_PREFLIGHT_ELEMENTS' - export NCCL_PREFLIGHT_ITERATIONS='$NCCL_PREFLIGHT_ITERATIONS' - export NCCL_PREFLIGHT_TIMEOUT='$NCCL_PREFLIGHT_WALLTIME' - export NCCL_P2P_DISABLE='$NCCL_P2P_DISABLE' - export NCCL_IB_DISABLE='$NCCL_IB_DISABLE' - export TORCH_NCCL_ASYNC_ERROR_HANDLING='$TORCH_NCCL_ASYNC_ERROR_HANDLING' - export TORCH_NCCL_TRACE_BUFFER_SIZE='$TORCH_NCCL_TRACE_BUFFER_SIZE' - timeout '$NCCL_PREFLIGHT_WALLTIME' torchrun \ - --nnodes='$TRAIN_NODE_COUNT' \ - --nproc_per_node="$GPUS_PER_NODE" \ - --node_rank=\"\${node_rank}\" \ - --master_addr='$MASTER_ADDR' \ - --master_port='$PREFLIGHT_PORT' \ - scripts/nccl_allgather_preflight.py - } >\"\$preflight_log\" 2>&1 - " || PREFLIGHT_STATUS=$? - if compgen -G "$JOB_LOG_DIR/nccl_preflight_rank*.log" >/dev/null; then - cat "$JOB_LOG_DIR"/nccl_preflight_rank*.log - fi - if [ "$PREFLIGHT_STATUS" -ne 0 ]; then - if [ "$NCCL_PREFLIGHT_REQUIRED" = "1" ]; then - echo "ERROR: NCCL preflight failed with status ${PREFLIGHT_STATUS}" >&2 - exit "$PREFLIGHT_STATUS" - fi - echo "WARNING: NCCL preflight failed with status ${PREFLIGHT_STATUS}; continuing because NCCL_PREFLIGHT_REQUIRED=0" >&2 - fi -fi - -start_vllm() { - local node="$1" - local tp="$2" - local port="$3" - local name="$4" - local gpu_list="$5" - local log_file="$JOB_LOG_DIR/vllm_${name}.log" - echo "Starting $name on $node TP=$tp planned_GPUs=$gpu_list port=$port" - srun --exclusive \ - --nodes=1 --ntasks=1 --nodelist="$node" \ - --gpus="$tp" \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - export TOKENIZERS_PARALLELISM=false - export PLANNED_CUDA_VISIBLE_DEVICES='$gpu_list' - if [ -z \"\${CUDA_VISIBLE_DEVICES:-}\" ]; then - export CUDA_VISIBLE_DEVICES=\"\$PLANNED_CUDA_VISIBLE_DEVICES\" - fi - echo \"CUDA_VISIBLE_DEVICES=\${CUDA_VISIBLE_DEVICES} planned=\${PLANNED_CUDA_VISIBLE_DEVICES}\" - export MASTER_ADDR=127.0.0.1 - export MASTER_PORT=$((20000 + port)) - export NCCL_P2P_DISABLE='$VLLM_NCCL_P2P_DISABLE' - export NCCL_IB_DISABLE='$VLLM_NCCL_IB_DISABLE' - export CUDA_LAUNCH_BLOCKING='$VLLM_CUDA_LAUNCH_BLOCKING' - python3 '$PROJECT_DIR/scripts/restartable_vllm_server.py' \ - --instance-id '$name' \ - --control-dir '$ROLLOUT_SYNC_DIR' \ - --health-url 'http://127.0.0.1:$port/health' \ - --initial-model '$MODEL_PATH' \ - --ready-timeout '$MAX_WAIT' \ - -- python3 '$PROJECT_DIR/scripts/vllm_hot_reload_api_server.py' \ - --worker-extension-cls RL_Framework.vllm_hot_reload.InplaceReloadWorkerExtension \ - --model '__MODEL_PATH__' \ - --served-model-name '$MODEL_PATH' \ - --host 0.0.0.0 \ - --port '$port' \ - --tensor-parallel-size '$tp' \ - --max-model-len '$MAX_MODEL_LEN' \ - --dtype bfloat16 \ - --gpu-memory-utilization '$GPU_MEMORY_UTILIZATION' \ - --trust-remote-code \ - --enforce-eager \ - $VLLM_CUSTOM_ALL_REDUCE_FLAG - " >"$log_file" 2>&1 & - VLLM_STEP_PIDS+=("$!") - VLLM_PID_BY_NAME["$name"]="$!" - python3 - </dev/null 2>&1; then - echo "READY: $name at $host:$port (${elapsed}s)" - return 0 - fi - if ! kill -0 "$pid" 2>/dev/null; then - echo "ERROR: $name exited before ready" >&2 - tail -120 "$JOB_LOG_DIR/vllm_${name}.log" || true - return 1 - fi - sleep 5 - elapsed=$((elapsed + 5)) - done - echo "ERROR: $name not ready after ${MAX_WAIT}s" >&2 - tail -120 "$JOB_LOG_DIR/vllm_${name}.log" || true - return 1 -} - -echo "[3/7] Starting GlobalResourcePlanner rollout vLLM instances" -PRIMARY_INDICES=() -DEFERRED_INDICES=() -declare -A NODE_HAS_PRIMARY=() -for i in "${!ROLLOUT_NODE_LIST[@]}"; do - node="${ROLLOUT_NODE_LIST[$i]}" - if [ -z "${NODE_HAS_PRIMARY[$node]:-}" ]; then - NODE_HAS_PRIMARY["$node"]=1 - PRIMARY_INDICES+=("$i") - else - DEFERRED_INDICES+=("$i") - fi -done - -for i in "${PRIMARY_INDICES[@]}"; do - start_vllm \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_TP_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" \ - "${ROLLOUT_GPU_LIST[$i]}" -done - -echo "[4/7] Waiting for primary rollout services" -for i in "${PRIMARY_INDICES[@]}"; do - wait_for_health \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" -done - -if [ "${#DEFERRED_INDICES[@]}" -gt 0 ]; then - echo "[3b/6] Starting deferred same-node rollout services" - for i in "${DEFERRED_INDICES[@]}"; do - start_vllm \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_TP_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" \ - "${ROLLOUT_GPU_LIST[$i]}" - wait_for_health \ - "${ROLLOUT_NODE_LIST[$i]}" \ - "${ROLLOUT_PORT_LIST[$i]}" \ - "${ROLLOUT_NAME_LIST[$i]}" - done -fi - -echo "[5/7] Checking R2E-Gym data and C-MLFQ flow" -python3 examples/test_r2e_gym.py -python3 examples/test_r2e_cmlfq_flow.py - -echo "[6/7] OpenAI-compatible API check" -curl -fsS "http://${ROLLOUT_NODE_LIST[0]}:${ROLLOUT_PORT_LIST[0]}/v1/completions" \ - -H "Content-Type: application/json" \ - -d "{\"model\":\"$MODEL_PATH\",\"prompt\":\"Write one short sentence.\",\"max_tokens\":8,\"temperature\":0}" \ - | python3 -m json.tool - -export HETERO_INSTANCE_HOSTS -export R2E_GYM_INDEX="${PROJECT_DIR}/data/r2e_gym_v1/index.jsonl" -export R2E_MAX_TURNS -export R2E_MAX_PROMPT_TOKENS -export R2E_EVAL_MAX_SAMPLES="$EVAL_MAX_SAMPLES" -export R2E_EVAL_CONCURRENCY="$EVAL_CONCURRENCY" -export R2E_EVAL_MAX_NEW_TOKENS="$EVAL_MAX_NEW_TOKENS" -export R2E_EVAL_MULTI_TURN -export R2E_EVAL_RECORD_SAMPLES -export R2E_EVAL_STRATEGY -export VLLM_READ_TIMEOUT -export VLLM_CONNECT_TIMEOUT -export VLLM_WRITE_TIMEOUT -export VLLM_POOL_TIMEOUT -export TORCH_DISTRIBUTED_TIMEOUT -export FSDP_ALIGN_SEQUENCE_LENGTHS -export FSDP_LOCKSTEP_BARRIERS -export FSDP_GRADIENT_CHECKPOINTING -export FSDP_ACTIVATION_CHECKPOINTING -export PYTORCH_CUDA_ALLOC_CONF="${PYTORCH_CUDA_ALLOC_CONF:-expandable_segments:True}" - -echo "[7/7] Starting full R2E-Gym AsyncRLTrainer run on ${TOTAL_GPUS} GPUs" -TRAIN_STEP_PIDS=() -for node_rank in "${!TRAIN_NODES[@]}"; do - node="${TRAIN_NODES[$node_rank]}" - train_log="$JOB_LOG_DIR/training_rank${node_rank}_${node}.log" - echo "Starting training rank $node_rank on $node" - srun --exclusive \ - --nodes=1 \ - --ntasks=1 \ - --nodelist="$node" \ - --gpus="$GPUS_PER_NODE" \ - --cpus-per-task=16 \ - bash -lc " - source '$VENV_PATH' - cd '$PROJECT_DIR' - export PYTHONPATH='$(dirname "$PROJECT_DIR")':\${PYTHONPATH:-} - export HETERO_INSTANCE_HOSTS='$HETERO_INSTANCE_HOSTS' - export R2E_GYM_INDEX='$R2E_GYM_INDEX' - export R2E_MAX_TURNS='$R2E_MAX_TURNS' - export R2E_MAX_PROMPT_TOKENS='$R2E_MAX_PROMPT_TOKENS' - export R2E_EVAL_MAX_SAMPLES='$R2E_EVAL_MAX_SAMPLES' - export R2E_EVAL_CONCURRENCY='$R2E_EVAL_CONCURRENCY' - export R2E_EVAL_MAX_NEW_TOKENS='$R2E_EVAL_MAX_NEW_TOKENS' - export R2E_EVAL_MULTI_TURN='$R2E_EVAL_MULTI_TURN' - export R2E_EVAL_RECORD_SAMPLES='$R2E_EVAL_RECORD_SAMPLES' - export R2E_EVAL_STRATEGY='$R2E_EVAL_STRATEGY' - export VLLM_READ_TIMEOUT='$VLLM_READ_TIMEOUT' - export VLLM_CONNECT_TIMEOUT='$VLLM_CONNECT_TIMEOUT' - export VLLM_WRITE_TIMEOUT='$VLLM_WRITE_TIMEOUT' - export VLLM_POOL_TIMEOUT='$VLLM_POOL_TIMEOUT' - export TORCH_DISTRIBUTED_TIMEOUT='$TORCH_DISTRIBUTED_TIMEOUT' - export FSDP_ALIGN_SEQUENCE_LENGTHS='$FSDP_ALIGN_SEQUENCE_LENGTHS' - export FSDP_LOCKSTEP_BARRIERS='$FSDP_LOCKSTEP_BARRIERS' - export FSDP_GRADIENT_CHECKPOINTING='$FSDP_GRADIENT_CHECKPOINTING' - export FSDP_ACTIVATION_CHECKPOINTING='$FSDP_ACTIVATION_CHECKPOINTING' - export PYTORCH_CUDA_ALLOC_CONF='$PYTORCH_CUDA_ALLOC_CONF' - export MCORE_MOE_GROUPED_GEMM='$MCORE_MOE_GROUPED_GEMM' - export FSDP_PROGRESS_DIR='$JOB_LOG_DIR/fsdp_progress' - export TORCH_NCCL_ASYNC_ERROR_HANDLING='$TORCH_NCCL_ASYNC_ERROR_HANDLING' - export TORCH_NCCL_TRACE_BUFFER_SIZE='$TORCH_NCCL_TRACE_BUFFER_SIZE' - export TORCH_NCCL_DUMP_ON_TIMEOUT='$TORCH_NCCL_DUMP_ON_TIMEOUT' - export TORCH_NCCL_DESYNC_DEBUG='$TORCH_NCCL_DESYNC_DEBUG' - export TORCH_NCCL_ENABLE_MONITORING='$TORCH_NCCL_ENABLE_MONITORING' - export TORCH_NCCL_ENABLE_TIMING='$TORCH_NCCL_ENABLE_TIMING' - export TORCH_NCCL_HIGH_PRIORITY='$TORCH_NCCL_HIGH_PRIORITY' - export NCCL_DEBUG='$NCCL_DEBUG' - export NCCL_P2P_DISABLE='$NCCL_P2P_DISABLE' - export NCCL_IB_DISABLE='$NCCL_IB_DISABLE' - export PYTHONUNBUFFERED=1 - export MASTER_ADDR='$MASTER_ADDR' - export MASTER_PORT='$MASTER_PORT' - export TOKENIZERS_PARALLELISM=false - export WANDB_MODE='$WANDB_MODE' - export WANDB_DIR='$WANDB_DIR' - torchrun \ - --nnodes='$TRAIN_NODE_COUNT' \ - --nproc_per_node="$GPUS_PER_NODE" \ - --node_rank='$node_rank' \ - --master_addr='$MASTER_ADDR' \ - --master_port='$MASTER_PORT' \ - examples/r2e_gym_async_rl.py \ - --config '$RUNTIME_CONFIG' - " >"$train_log" 2>&1 & - TRAIN_STEP_PIDS+=("$!") -done - -train_exit=0 -for pid in "${TRAIN_STEP_PIDS[@]}"; do - if ! wait "$pid"; then - train_exit=1 - fi -done -cat "$JOB_LOG_DIR"/training_rank*.log > "$JOB_LOG_DIR/training.log" 2>/dev/null || true -if [ "$train_exit" -ne 0 ]; then - echo "ERROR: one or more training ranks failed" >&2 - exit "$train_exit" -fi - -echo "============================================================" -echo "R2E-Gym C-MLFQ ${TOTAL_GPUS}-GPU training completed" -echo "Logs: $JOB_LOG_DIR" -echo "C-MLFQ tree: $CMLFQ_TREE_PATH" -echo "History: $PROJECT_DIR/logs/r2e_gym_cmlfq/history and logs/r2e_gym_cmlfq_24gpu" -echo "============================================================" diff --git a/scripts/submit_search_r1_searxng_train.slurm b/scripts/submit_search_r1_searxng_train.slurm deleted file mode 100755 index d9c74d4..0000000 --- a/scripts/submit_search_r1_searxng_train.slurm +++ /dev/null @@ -1,130 +0,0 @@ -#!/bin/bash -# ============================================================================= -# Search-R1 + Qwen3-14B + SearXNG production training -# -# Topology: -# node 0: 4-GPU FSDP training -# node 1: 4-GPU TP=4 rollout -# node 2: two 2-GPU TP=2 rollout instances -# -# This wrapper reuses the validated C-MLFQ launcher. Before allocating model -# memory it verifies the official Search-R1 data and requires SearXNG to return -# at least one real web result. -# -# Submit: -# MODEL_PATH=/path/to/Qwen3-14B \ -# sbatch --export=ALL,MODEL_PATH scripts/submit_search_r1_searxng_train.slurm -# -# Common overrides: -# TOTAL_STEPS=5000 TRAIN_BATCH_SIZE=8 MAX_NEW_TOKENS=1024 \ -# SEARXNG_URL=http://192.0.2.30:18080 \ -# sbatch --export=ALL,MODEL_PATH,TOTAL_STEPS,TRAIN_BATCH_SIZE,MAX_NEW_TOKENS,SEARXNG_URL \ -# scripts/submit_search_r1_searxng_train.slurm -# ============================================================================= - -#SBATCH -J search_r1_searxng -#SBATCH -o logs/search_r1_searxng_%j.out -#SBATCH -e logs/search_r1_searxng_%j.err -#SBATCH -N 3 -#SBATCH -G 12 -#SBATCH --ntasks-per-node=2 -#SBATCH --cpus-per-task=16 -#SBATCH -p gpu -#SBATCH --time=7-00:00:00 -#SBATCH --exclude=gn019 - -set -euo pipefail - -PROJECT_DIR="${PROJECT_DIR:-/path/to/RL_Framework}" -MODEL_PATH="${MODEL_PATH:-/path/to/Qwen3-14B}" -SEARXNG_URL="${SEARXNG_URL:-http://192.0.2.30:18080}" -SEARCH_R1_DATA="${SEARCH_R1_DATA:-$PROJECT_DIR/data/search_r1_train.jsonl}" -SEARCH_PREFLIGHT_QUERY="${SEARCH_PREFLIGHT_QUERY:-PyTorch distributed training}" - -export SEARCH_BACKEND=searxng -export SEARXNG_URL -export MODEL_PATH -export TOTAL_STEPS="${TOTAL_STEPS:-1000}" -export TRAIN_BATCH_SIZE="${TRAIN_BATCH_SIZE:-8}" -export TRAIN_MICRO_BATCH_SIZE="${TRAIN_MICRO_BATCH_SIZE:-1}" -export TRAIN_MAX_SEQ_LENGTH="${TRAIN_MAX_SEQ_LENGTH:-40960}" -export MAX_NEW_TOKENS="${MAX_NEW_TOKENS:-1024}" -export MAX_MODEL_LEN="${MAX_MODEL_LEN:-40960}" -export GPU_MEMORY_UTILIZATION="${GPU_MEMORY_UTILIZATION:-0.90}" -export MAX_WAIT="${MAX_WAIT:-1200}" - -cd "$PROJECT_DIR" -mkdir -p logs - -echo "============================================================" -echo "Search-R1 + SearXNG production training preflight" -echo "============================================================" -echo "Job: ${SLURM_JOB_ID}" -echo "Model: $MODEL_PATH" -echo "Dataset: $SEARCH_R1_DATA" -echo "SearXNG: $SEARXNG_URL" -echo "Steps: $TOTAL_STEPS" -echo "Batch size: $TRAIN_BATCH_SIZE" -echo "Max sequence length: $TRAIN_MAX_SEQ_LENGTH" -echo "Max new tokens per turn: $MAX_NEW_TOKENS" - -if [ ! -d "$MODEL_PATH" ]; then - echo "ERROR: model path does not exist: $MODEL_PATH" >&2 - exit 2 -fi - -python3 - "$SEARCH_R1_DATA" <<'PY' -import json -import sys -from collections import Counter -from pathlib import Path - -path = Path(sys.argv[1]) -if not path.is_file(): - raise SystemExit(f"ERROR: Search-R1 dataset does not exist: {path}") - -counts = Counter() -rows = 0 -with path.open(encoding="utf-8") as source: - for line in source: - row = json.loads(line) - counts[row["data_source"]] += 1 - rows += 1 - -expected = {"nq", "hotpotqa"} -if set(counts) != expected: - raise SystemExit( - f"ERROR: expected Search-R1 sources {sorted(expected)}, got {dict(counts)}" - ) -if rows != 169615: - raise SystemExit(f"ERROR: expected 169615 Search-R1 rows, got {rows}") -print(f"Search-R1 data OK: {rows} rows, sources={dict(sorted(counts.items()))}") -PY - -curl -fsS --max-time 10 "$SEARXNG_URL/healthz" >/dev/null -python3 - "$SEARXNG_URL" "$SEARCH_PREFLIGHT_QUERY" <<'PY' -import json -import sys -import urllib.parse -import urllib.request - -base_url, query = sys.argv[1:] -url = base_url.rstrip("/") + "/search?" + urllib.parse.urlencode( - {"q": query, "format": "json", "language": "en-US"} -) -with urllib.request.urlopen(url, timeout=45) as response: - payload = json.load(response) - -results = payload.get("results", []) -if not results: - engines = payload.get("unresponsive_engines", []) - raise SystemExit( - "ERROR: SearXNG returned zero results. Real Search-R1 training is " - f"blocked; check the server's outbound proxy. Unresponsive={engines}" - ) -print(f"SearXNG real-search OK: query={query!r}, results={len(results)}") -print(f"First result: {results[0].get('title', '')}") -PY - -echo "Preflight passed. Starting the validated three-node training launcher." -exec bash "$PROJECT_DIR/scripts/submit_qwen3_cmlfq_train.slurm" diff --git a/scripts/submit_slurm.slurm b/scripts/submit_slurm.slurm deleted file mode 100644 index bd1bbc2..0000000 --- a/scripts/submit_slurm.slurm +++ /dev/null @@ -1,114 +0,0 @@ -#!/bin/bash -# ============================================================================= - -# - -# sbatch submit_slurm.slurm -# - - - - -# ============================================================================= - - - - - - - - - -#SBATCH --mail-type=BEGIN,END,FAIL -#SBATCH --mail-user=your_email@example.com - -# ============================================================================= - -# ============================================================================= -echo "==========================================" -echo "Job information" -echo "==========================================" -echo "Job started at: $(date)" -echo "Running on host: $(hostname)" -echo "SLURM_JOBID: $SLURM_JOBID" -echo "SLURM_NODELIST: $SLURM_NODELIST" -echo "SLURM_NNODES: $SLURM_NNODES" -echo "SLURM_NTASKS: $SLURM_NTASKS" -echo "SLURM_GPUS: $SLURM_GPUS" -echo "" - - -scontrol show hostnames "$SLURM_NODELIST" - -# ============================================================================= - -# ============================================================================= -echo "Activating virtual environment..." -source ~/rl_framework_env/bin/activate - -echo "Python: $(which python3)" -echo "Python version: $(python3 --version 2>&1)" - - -PROJECT_DIR="/path/to/RL_Framework" -cd "$PROJECT_DIR" - -export NO_PROXY="localhost,127.0.0.1" -export PYTHONPATH="${PWD}:${PYTHONPATH}" - - -mkdir -p logs - -# ============================================================================= - -# ============================================================================= - - -export MODEL_PATH="/path/to/Qwen3-4B/1cfa9a7208912126459214e8b04321603b3df60c" - - -export TRAIN_SCRIPT="examples/gsm8k_async_rl.py" - - -export CONFIG_FILE="configs/gsm8k_slurm.yaml" - - - -export GPUS_PER_NODE=4 -export TRAIN_GPUS_PER_NODE=2 -export ROLLOUT_GPUS_PER_NODE=2 - - -export VLLM_TP_SIZE=1 -export VLLM_BASE_PORT=8000 -export MAX_MODEL_LEN=2048 - - -export MASTER_PORT=29500 - - -export LOG_DIR="./logs" - - -export MAX_WAIT=600 - -# ============================================================================= - -# ============================================================================= -echo "" -echo "==========================================" -echo "Starting multi-node asynchronous RL training" -echo "==========================================" -echo " Model: ${MODEL_PATH}" -echo " Training script: ${TRAIN_SCRIPT}" -echo " Configuration file: ${CONFIG_FILE:-none}" -echo " Nodes: ${SLURM_NNODES}" -echo " GPUs per node: ${GPUS_PER_NODE} (Training=${TRAIN_GPUS_PER_NODE}, Rollout=${ROLLOUT_GPUS_PER_NODE})" -echo " vLLM TP: ${VLLM_TP_SIZE}" -echo "" - - -bash scripts/run_slurm_distributed.sh - -echo "" -echo "Job finished at: $(date)" diff --git a/scripts/test_cpu_ci.sh b/scripts/test_cpu_ci.sh old mode 100644 new mode 100755 index 88df08a..32f338d --- a/scripts/test_cpu_ci.sh +++ b/scripts/test_cpu_ci.sh @@ -1,78 +1,4 @@ #!/usr/bin/env bash set -euo pipefail cd "$(dirname "$0")/.." -python -m pytest -v -o faulthandler_timeout=60 --strict-markers --junitxml=reports/cpu-tests.xml \ - tests/test_config_parsing.py \ - tests/test_qwen3_config.py \ - tests/test_planner_global_batch_workload.py \ - tests/test_global_resource_planner_simulators.py \ - tests/test_elastic_cost_horizon.py \ - tests/test_finite_rollout_cost.py \ - tests/test_r2e_cluster_placement.py \ - tests/test_async_task_runner.py \ - tests/test_async_rl_trainer_weight_sync.py \ - tests/test_sync_drain_prefetch.py \ - tests/test_rollout_credit.py \ - tests/test_phase_tracer.py \ - tests/test_restartable_vllm_server.py \ - tests/test_checked_prefix_cache_reset.py \ - tests/test_nccl_store_lifecycle.py \ - tests/test_nccl_store_timeout.py \ - tests/test_nccl_weight_sync.py \ - tests/test_publication_sessions.py \ - tests/test_serving_protocol.py \ - tests/test_serving_behavior_sampling.py \ - tests/test_behavior_capture_v2.py \ - tests/test_collective_weight_export.py \ - tests/test_cmlfq_scheduler.py \ - tests/test_cmlfq_cost_scheduler.py \ - tests/test_cmlfq_kv_cost_scheduler.py \ - tests/test_cost_model_units.py \ - tests/test_cmlfq_rebind_state.py \ - tests/test_hetero_cmlfq_integration.py \ - tests/test_rollout_engine.py \ - tests/test_r2e_rollout_sampling.py \ - tests/test_cpu_offload_backend.py \ - tests/test_r2e_patch_harness.py \ - tests/test_r2e_gym_workflow.py \ - tests/test_decoupled_workflow_v2.py \ - tests/test_decoupled_grpo_v2.py \ - tests/test_r2e_1938329_entrypoint.py \ - tests/test_optimizer_state.py \ - tests/test_elastic_optimizer_state.py \ - tests/test_ehp_dp_resharding.py \ - tests/test_ehp_batch_partition.py \ - tests/test_fixed_batch_gradients.py \ - tests/test_grpo_sample_mean.py \ - tests/test_hybrid_sample_statistics_data.py \ - tests/test_elastic_gradient_idle_path.py \ - tests/test_hybrid_optimizer_cuda_cache.py \ - tests/test_torch_optimizer_memory.py \ - tests/test_megatron_core_train_engine.py \ - tests/test_hybrid_worker_batch_protocol.py \ - tests/test_core_reconfiguration_protocol.py \ - tests/test_core_subset_publication.py \ - tests/test_ehp_membership_release.py \ - tests/test_ehp_readiness_stop.py \ - tests/test_hybrid_join_readiness_budget.py \ - tests/test_hybrid_boundary_activation.py \ - tests/test_hybrid_sample_statistics.py \ - tests/test_hybrid_task_lifecycle.py \ - tests/test_elastic_hybrid_pool.py \ - tests/test_grp_decision_gates.py \ - tests/test_rollout_lending.py \ - tests/test_rollout_lifecycle.py \ - tests/test_rollout_process.py \ - tests/test_rollout_supply.py \ - tests/test_runtime_boundary_integration.py \ - tests/test_runtime_boundary.py \ - tests/test_runtime_core_capabilities.py \ - tests/test_runtime_elastic_executor.py \ - tests/test_runtime_blue_green_gpu_ownership.py \ - tests/test_runtime_repartition_eligibility.py \ - tests/test_runtime_executor_shutdown.py \ - tests/test_runtime_rollout_ownership.py \ - tests/test_runtime_failed_snapshot_cleanup.py \ - tests/test_scheduling_audit.py \ - tests/test_publication_preserves_hybrids.py \ - tests/test_grpo_grouping.py +python -m pytest -q --strict-markers --junitxml=reports/cpu-tests.xml tests/ diff --git a/scripts/validate_cpu_offload.slurm b/scripts/validate_cpu_offload.slurm deleted file mode 100644 index aee5278..0000000 --- a/scripts/validate_cpu_offload.slurm +++ /dev/null @@ -1,62 +0,0 @@ -#!/bin/bash -#SBATCH --job-name=libra_cpu_offload -#SBATCH --partition=gpu -#SBATCH --nodes=1 -#SBATCH --gpus=3 -#SBATCH --ntasks=1 -#SBATCH --cpus-per-task=12 -#SBATCH --mem=72G -#SBATCH --time=00:35:00 - -# Three disjoint GPUs: source TP1 and target TP2. Set SOURCE_TP=2 TARGET_TP=1 -# to check the reverse resharding direction. No training jobs are modified. -set -euo pipefail -PROJECT_DIR="${PROJECT_DIR:-$PWD}" -PYTHON="${PYTHON:-$HOME/rl_framework_env/bin/python3}" -: "${MODEL_PATH:?Set MODEL_PATH to a local Qwen3 model directory}" -SOURCE_TP="${SOURCE_TP:-1}" -TARGET_TP="${TARGET_TP:-2}" -RUN_DIR="${RUN_DIR:-$PROJECT_DIR/logs/cmlfq_offload/${SLURM_JOB_ID}}" -mkdir -p "$RUN_DIR" -cd "$PROJECT_DIR" -export PYTHONPATH="$(dirname "$PROJECT_DIR"):${PYTHONPATH:-}" -export VLLM_USE_V1=1 VLLM_ATTENTION_BACKEND=FLASH_ATTN OMP_NUM_THREADS=4 -export LIBRA_KV_STORAGE_PATH="/dev/shm/libra-kv-${SLURM_JOB_ID}" -mkdir -p "$LIBRA_KV_STORAGE_PATH" -IFS=, read -ra GPUS <<< "$CUDA_VISIBLE_DEVICES" -if (( ${#GPUS[@]} < SOURCE_TP + TARGET_TP )); then - echo "Need disjoint GPUs for source TP${SOURCE_TP} and target TP${TARGET_TP}" >&2 - exit 2 -fi -SOURCE_GPUS=$(IFS=,; echo "${GPUS[*]:0:SOURCE_TP}") -TARGET_GPUS=$(IFS=,; echo "${GPUS[*]:SOURCE_TP:TARGET_TP}") -KV="{\"kv_connector\":\"LibraCPUOffloadConnector\",\"kv_role\":\"kv_both\",\"kv_connector_module_path\":\"RL_Framework.infra.scheduling.vllm_cpu_offload\",\"kv_connector_extra_config\":{\"storage_path\":\"$LIBRA_KV_STORAGE_PATH\"}}" -PIDS=() -cleanup() { - for pid in "${PIDS[@]}"; do kill "$pid" 2>/dev/null || true; done - wait || true - rm -rf -- "$LIBRA_KV_STORAGE_PATH" -} -trap cleanup EXIT INT TERM -"$PYTHON" -c 'import torch,vllm,json,socket;print(json.dumps({"host":socket.gethostname(),"torch":torch.__version__,"vllm":vllm.__version__,"cuda":torch.version.cuda,"gpus":[torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())]}))' > "$RUN_DIR/environment.json" -CUDA_VISIBLE_DEVICES="$SOURCE_GPUS" "$PYTHON" scripts/vllm_hot_reload_api_server.py \ - --model "$MODEL_PATH" --host 127.0.0.1 --port 18910 --tensor-parallel-size "$SOURCE_TP" \ - --dtype bfloat16 --max-model-len 10000 --gpu-memory-utilization 0.50 \ - --max-num-seqs 4 --enforce-eager --disable-log-requests --no-enable-prefix-caching --kv-transfer-config "$KV" \ - > "$RUN_DIR/source.log" 2>&1 & -PIDS+=("$!") -CUDA_VISIBLE_DEVICES="$TARGET_GPUS" "$PYTHON" scripts/vllm_hot_reload_api_server.py \ - --model "$MODEL_PATH" --host 127.0.0.1 --port 18911 --tensor-parallel-size "$TARGET_TP" \ - --dtype bfloat16 --max-model-len 10000 --gpu-memory-utilization 0.50 \ - --max-num-seqs 4 --enforce-eager --disable-log-requests --no-enable-prefix-caching --kv-transfer-config "$KV" \ - > "$RUN_DIR/target.log" 2>&1 & -PIDS+=("$!") -"$PYTHON" -m pytest -q tests/test_cmlfq_cost_scheduler.py tests/test_cmlfq_scheduler.py \ - tests/test_hetero_cmlfq_integration.py tests/test_rollout_engine.py \ - tests/test_cpu_offload_backend.py tests/test_vllm_cpu_offload.py \ - > "$RUN_DIR/tests.log" 2>&1 -"$PYTHON" scripts/benchmark_cpu_offload.py --model "$MODEL_PATH" \ - --source-tp "$SOURCE_TP" --target-tp "$TARGET_TP" \ - --words ${BENCH_WORDS:-64 256 1024} --tool-ms ${TOOL_MS:-0 100 500} \ - --trials "${TRIALS:-3}" --output "$RUN_DIR/results.json" \ - > "$RUN_DIR/benchmark.log" 2>&1 diff --git a/scripts/validate_ehp_ab_config.py b/scripts/validate_ehp_ab_config.py deleted file mode 100644 index ecd0763..0000000 --- a/scripts/validate_ehp_ab_config.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env python3 -"""Validate that a production EHP A/B pair differs only in EHP controls.""" - -from __future__ import annotations - -import argparse -from pathlib import Path -from typing import Any - -try: - from materialize_6node48_config import load_inherited_config -except ModuleNotFoundError: # Imported as scripts.validate_ehp_ab_config in tests. - from scripts.materialize_6node48_config import load_inherited_config - - -ALLOWED_DIFFERENCES = { - "wandb_run_name", - "history_experiment_name", - "global_resource_planner.elastic_hybrid_planning_enabled", - "global_resource_planner.runtime_online_replanning", - "global_resource_planner.runtime_dynamic_reconfiguration_enabled", - "global_resource_planner.runtime_reconfigure_training", - "global_resource_planner.hybrid_worker_launch_enabled", - "global_resource_planner.hybrid_worker_remote_control_enabled", - "global_resource_planner.elastic_hybrid_require_isolated_ccl", -} - -EHP_RUNTIME_CONTROLS = { - "elastic_hybrid_planning_enabled": True, - "runtime_online_replanning": True, - "runtime_dynamic_reconfiguration_enabled": True, - "runtime_reconfigure_training": True, - "hybrid_worker_launch_enabled": True, - "hybrid_worker_remote_control_enabled": True, - "elastic_hybrid_require_isolated_ccl": True, -} - - -def _flatten(value: Any, prefix: str = "") -> dict[str, Any]: - if not isinstance(value, dict): - return {prefix: value} - flattened: dict[str, Any] = {} - for key, item in value.items(): - path = f"{prefix}.{key}" if prefix else str(key) - flattened.update(_flatten(item, path)) - return flattened - - -def validate(no_ehp_path: Path, ehp_path: Path) -> list[str]: - no_ehp = load_inherited_config(no_ehp_path) - ehp = load_inherited_config(ehp_path) - left = _flatten(no_ehp) - right = _flatten(ehp) - differences = sorted( - key for key in set(left) | set(right) if left.get(key) != right.get(key) - ) - unexpected = [key for key in differences if key not in ALLOWED_DIFFERENCES] - if unexpected: - details = "\n".join( - f" {key}: no-EHP={left.get(key)!r}, EHP={right.get(key)!r}" - for key in unexpected - ) - raise ValueError(f"non-EHP variables differ:\n{details}") - - required = ALLOWED_DIFFERENCES - {"wandb_run_name", "history_experiment_name"} - missing = sorted(required - set(differences)) - if missing: - raise ValueError(f"expected EHP controls do not differ: {missing}") - - for name, ehp_expected in EHP_RUNTIME_CONTROLS.items(): - no_ehp_expected = not ehp_expected - no_ehp_actual = bool(no_ehp["global_resource_planner"].get(name, False)) - ehp_actual = bool(ehp["global_resource_planner"].get(name, False)) - if (no_ehp_actual, ehp_actual) != (no_ehp_expected, ehp_expected): - raise ValueError( - f"invalid runtime control {name}: " - f"no-EHP={no_ehp_actual}, EHP={ehp_actual}" - ) - - for label, config in (("no-EHP", no_ehp), ("EHP", ehp)): - if int(config["total_steps"]) != 200: - raise ValueError(f"{label} total_steps must be 200") - if int(config["sync_interval"]) != 5: - raise ValueError(f"{label} sync_interval must be 5") - planner = config["global_resource_planner"] - if str(planner.get("initial_allocation_strategy")) != "grp": - raise ValueError(f"{label} initial allocation must be owned by GRP") - if int(planner.get("fixed_train_gpus", -1)) != 0: - raise ValueError(f"{label} fixed_train_gpus must be zero") - - batch_size = int(no_ehp["batch_size"]) - dp_size = int(no_ehp["train_dp_size"]) - n_samples = int(no_ehp["n_samples"]) - if batch_size % dp_size: - raise ValueError("batch_size must be divisible by train_dp_size") - local_batch = batch_size // dp_size - if local_batch % n_samples: - raise ValueError("local batch per DP replica must contain complete GRPO groups") - - print("EHP A/B config validation passed") - print("steps/arm=200, rollout-training sync interval=5") - print("initial allocation=GRP for both arms") - print("runtime allocation=no-EHP fixed, EHP planner-elastic") - print(f"global trajectories/step={batch_size}") - print(f"prompt groups/step={batch_size // n_samples}") - print(f"local trajectories/DP={local_batch}") - print(f"local prompt groups/DP={local_batch // n_samples}") - print("differences:") - for key in differences: - print(f" {key}: no-EHP={left.get(key)!r}, EHP={right.get(key)!r}") - return differences - - -def main() -> None: - project = Path(__file__).resolve().parents[1] - parser = argparse.ArgumentParser() - parser.add_argument( - "--no-ehp", - type=Path, - default=project - / "configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_no_ehp.yaml", - ) - parser.add_argument( - "--ehp", - type=Path, - default=project - / "configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_ehp.yaml", - ) - args = parser.parse_args() - validate(args.no_ehp, args.ehp) - - -if __name__ == "__main__": - main() diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..c246721 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,22 @@ +"""Pytest bootstrap to keep RL_Framework importable across environments.""" + +from __future__ import annotations + +import importlib.util +import sys +from pathlib import Path + + +def pytest_configure() -> None: + """Register RL_Framework from repo root if editableFinder is hidden/missing.""" + if importlib.util.find_spec("RL_Framework") is None: + repo_root = Path(__file__).resolve().parents[1] + spec = importlib.util.spec_from_file_location( + "RL_Framework", + repo_root / "__init__.py", + submodule_search_locations=[str(repo_root)], + ) + if spec is not None and spec.loader is not None: + module = importlib.util.module_from_spec(spec) + sys.modules["RL_Framework"] = module + spec.loader.exec_module(module) diff --git a/tests/hybrid_statistics_helpers.py b/tests/hybrid_statistics_helpers.py deleted file mode 100644 index 19fed15..0000000 --- a/tests/hybrid_statistics_helpers.py +++ /dev/null @@ -1,77 +0,0 @@ -"""Small CPU model fixture shared by payload-data and activation-integration tests.""" -import sys -import threading -from types import SimpleNamespace as NS - -import torch - -from RL_Framework.engine import megatron_core_train_engine as module -from RL_Framework.engine.megatron_core_train_engine import MegatronCoreTrainEngine as Engine -from RL_Framework.infra.elastic.hybrid_pool import InterReplicaGradientDomain - - -def rows(start, count, zero_mask=False): - return [dict(input_ids=torch.zeros(1, 2+i%3, dtype=torch.long), - logprobs=torch.full((1,2+i%3), -.7), - loss_mask=torch.zeros(1,2+i%3) if zero_mask else torch.ones(1,2+i%3), - rewards=torch.tensor([float(i)]), advantages=torch.tensor([1.+i/5]), - feature=float(i)/3) - for i in range(start,start+count)] - - -def engine(monkeypatch, lane=0, width=1): - # Only MCore finalization is replaced: the loss, microbatching, payload - # compute, enqueue, gradient reduction and statistics methods are real. - monkeypatch.setitem(sys.modules, 'megatron.core.distributed', - NS(finalize_model_grads=lambda model: None)) - ex=Engine.__new__(Engine) - parameter=torch.tensor(.1,requires_grad=True) - ex.train_tp_size=1 - ex.micro_batch_size=3 - ex.tokenizer=NS(pad_token_id=0) - ex.clip_epsilon=.2 - ex.kl_coef=.1 - ex.optimizer_revision=2 - ex.current_version=2 - ex.model=[] - ex._device=lambda:'cpu' - ex._zero_grad=lambda:setattr(parameter,'grad',torch.zeros_like(parameter)) - ex._set_train_mode=lambda enabled:None - def forward(batch): - features=torch.tensor([r['feature'] for r in batch['trajectories']])[:,None] - values=(parameter+features).expand_as(batch['input_ids']) - return torch.stack((values,torch.zeros_like(values)),dim=-1) - ex._forward=forward - ex._model_main_gradients=lambda:[parameter.grad] - ex.use_distributed_optimizer=False - ex.get_data_parallel_rank=lambda:0 - ex.get_data_parallel_world_size=lambda:1 - ex._parallel_state=lambda:NS(get_data_parallel_group=lambda **kw:'dp-lane-'+str(lane)) - monkeypatch.setattr(module.dist,'all_reduce',lambda values,**kw:None) - steps=[] - ex.optimizer=NS(scale_loss=lambda loss:loss, - step=lambda:(steps.append(True) or True,7.,0)) - ex._pending_hybrid_gradients=[] - ex._hybrid_gradient_condition=threading.Condition() - ex._elastic_seen_payloads=set() - ex._elastic_active_gradient_timeout_s=0 - ex._elastic_training_step=3 - ex._elastic_expected_state_version=2 - ex._elastic_gradient_update_callback=None - domain=InterReplicaGradientDomain(core_replica_ids=['dp0'], - replica_world_size=width,local_replica_rank=lane) - domain.request_join('hybrid','dp0',membership_epoch=4) - domain.mark_active('hybrid',membership_epoch=4) - ex.elastic_gradient_domain=domain - ex._elastic_step_hybrid_workers=('hybrid',) - return ex,steps - - -def compute(monkeypatch, subset, lane=0, width=1): - worker,_=engine(monkeypatch,lane,width) - monkeypatch.setenv('RANK',str(lane)) - monkeypatch.setenv('WORLD_SIZE',str(width)) - payload=worker.compute_elastic_gradient_payload(subset,worker_id='hybrid', - target_core_id='dp0',step=3,state_version=2,membership_epoch=4, - global_sample_count=12) - return worker,payload diff --git a/tests/test_async_rl_trainer_weight_sync.py b/tests/test_async_rl_trainer_weight_sync.py deleted file mode 100644 index aec0e30..0000000 --- a/tests/test_async_rl_trainer_weight_sync.py +++ /dev/null @@ -1,335 +0,0 @@ -import json -from types import SimpleNamespace - -import pytest - -from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - - -def test_runtime_topology_refreshes_tp_even_if_endpoint_is_unchanged(): - trainer = object.__new__(AsyncRLTrainer) - trainer.config = SimpleNamespace(heterogeneous_rollout=SimpleNamespace( - instances=[SimpleNamespace(instance_id="rollout", host="node", port=8000, tp=1, gpus=[0])], - )) - trainer.rollout_engine = SimpleNamespace(instance_urls=["http://node:8000"]) - rebound = [] - trainer._rebind_rollout_engine_from_config = lambda **kwargs: rebound.append(True) - trainer._apply_runtime_reconfiguration_state({"instances": [ - {"instance_id": "rollout", "host": "node", "port": 8000, "tp": 2, "gpus": [0, 1]}, - ]}) - instance = trainer.config.heterogeneous_rollout.instances[0] - assert (instance.tp, instance.gpus) == (2, [0, 1]) - assert rebound == [True] - - -def _last_update_trainer(leader): - import torch - from RL_Framework.config import AsyncRLConfig - config = AsyncRLConfig(model_path="/unused", train_gpus=2, rollout_gpus=2, - n_total_gpus=4, train_tp_size=2, batch_size=4, n_samples=4, micro_batch_size=1, - total_steps=1, sync_interval=1, save_interval=0, - recompute_logprobs=False, rollout_weight_sync_mode="restart", - require_rollout_weight_sync=True) - trainer = AsyncRLTrainer(config) - trainer._bounded_rollout_production = True - trainer.is_main_process = leader - events = [] - revision = {"optimizer": 0, "published": 0} - batch = [ - {"grpo_group_id": "a", "rewards": torch.tensor([float(i)]), - "input_len": 3, "output_len": 2 + i, "input_ids": torch.zeros((1, 5 + i)), - "total_output_tokens": str(7 + i)} - for i in range(4) - ] - - def update(*args, **kwargs): - revision["optimizer"] = 1 - trainer.train_engine.optimizer_revision = 1 - events.append("update") - return {} - - trainer.train_engine = SimpleNamespace( - optimizer_revision=0, grpo_update=update, - get_version=lambda: revision["published"], - set_version=lambda version: revision.__setitem__("published", version), - ) - trainer.dispatcher = SimpleNamespace( - retire_batch=lambda rows, version: events.append("retire"), - destroy=lambda: events.append("stop_production"), - on_publication=lambda version: events.append("new_window"), - ) - trainer._source_training_batch = batch - trainer.setup = lambda workflow: None - trainer._create_data_generator = lambda *args: iter(()) - trainer._source_batch_sample_count = lambda: 4 - trainer._prepare_elastic_training_step = lambda step: [] - trainer._collect_fixed_global_batch = lambda *args: (batch, ["dp0"]) - trainer._assign_fixed_global_batch = lambda step, rows, participants: rows - trainer._runtime_reconfiguration_boundary = lambda step, point: events.append(point) - trainer._run_global_resource_planner_at_boundary = lambda *args: events.append("post") - trainer._sync_weights = lambda **kwargs: events.append("publication") - trainer._wait_for_all_ranks_before_weight_sync = lambda step: None - trainer._log_to_wandb = lambda *args: None - trainer._run_periodic_evaluation = lambda *args: events.append("evaluation") - trainer._cleanup = lambda **kwargs: None - return trainer, events, revision - - -@pytest.mark.parametrize("leader", [True, False]) -def test_last_update_runs_post_then_publication_and_stops_production(leader): - trainer, events, revision = _last_update_trainer(leader) - trainer.train(None, dataset=[{}]) - assert events == ["pre", "update", "retire", "stop_production", "post", "publication", "evaluation"] - assert revision["published"] == 1 - - -def test_bounded_history_exports_profile_before_post_and_records_publication_time(tmp_path, monkeypatch): - from RL_Framework.infra.observability.history_collector import HistoryDataCollector, ResourceConfig - from RL_Framework.trainer import async_rl_trainer - - trainer, _, _ = _last_update_trainer(True) - profile = tmp_path / "lengths.jsonl" - collector = trainer.history_collector = HistoryDataCollector( - str(tmp_path), flush_interval=1, length_profile_path=str(profile), - ) - trainer._resource_config_snapshot = ResourceConfig(rollout_gpus=2) - clock = SimpleNamespace(now=100.0) - monkeypatch.setattr(async_rl_trainer, "time", SimpleNamespace(time=lambda: clock.now)) - - def post(step, batch, stats): - rows = [json.loads(line) for line in profile.read_text().splitlines()] - assert [row["output_len"] for row in rows] == [2, 3, 4, 5] - assert [row["total_output_tokens"] for row in rows] == [7, 8, 9, 10] - assert collector.get_records() == [] - trainer._resource_config_snapshot = ResourceConfig(rollout_gpus=1) - clock.now += 1.0 - - def publish(**kwargs): - clock.now += 2.5 - - trainer._run_global_resource_planner_at_boundary = post - trainer._sync_weights = publish - try: - trainer.train(None, dataset=[{}]) - records = [json.loads(line) for line in next(tmp_path.glob("history_*.jsonl")).read_text().splitlines()] - assert len(records) == 1 - assert records[0]["timing"]["weight_sync_time"] == 2.5 - assert records[0]["timing"]["step_total_time"] == 3.5 - assert collector.get_records()[0].resource_config.rollout_gpus == 2 - assert collector.get_records()[0].pipeline_stats.model_version == 1 - assert len(profile.read_text().splitlines()) == 4 - finally: - collector.finalize() - - -@pytest.mark.parametrize("install_outcome", ["ack", "error", "no_targets"]) -def test_periodic_publication_preserves_work_and_opens_window_only_after_ack(install_outcome): - trainer = object.__new__(AsyncRLTrainer) - trainer._bounded_rollout_production = True - trainer.staleness_manager = SimpleNamespace(group_reservations_enabled=True) - trainer.config = SimpleNamespace(weight_sync_mode="nccl", rollout_weight_sync_mode="nccl", - enable_rollout_tracing=False) - events = [] - trainer.dispatcher = SimpleNamespace( - on_publication=lambda revision: events.append(("window", revision)), - pause=lambda: pytest.fail("periodic publication must preserve live group production"), - ) - trainer.train_engine = SimpleNamespace(set_version=lambda revision: events.append(("version", revision))) - trainer.is_main_process = True - trainer._trace_train_phase = lambda *args, **kwargs: None - trainer._wait_for_all_ranks_before_weight_sync = lambda step: events.append(("ranks", step)) - trainer._restored_rollouts_pending_publication = set() - - def install(target_version): - events.append(("install", target_version)) - if install_outcome == "error": - raise RuntimeError("install failed") - if install_outcome == "no_targets": - return None - events.append(("all_ack", target_version)) - return {"optimizer_revision": target_version, "acknowledgements": ["rollout"]} - - def publish(*, target_version, reopen_restored): - assert not reopen_restored - return AsyncRLTrainer._sync_weights(trainer, target_version, reopen_restored=reopen_restored) - - trainer._sync_weights_nccl = install - trainer._sync_weights = publish - if install_outcome == "error": - with pytest.raises(RuntimeError, match="install failed"): - trainer._periodic_weight_sync(2) - assert events == [("ranks", 2), ("install", 3)] - elif install_outcome == "ack": - trainer._periodic_weight_sync(2) - assert events == [("ranks", 2), ("install", 3), ("all_ack", 3), ("version", 3), ("window", 3)] - else: - trainer._periodic_weight_sync(2) - assert events == [("ranks", 2), ("install", 3)] - - -def test_rollout_reload_requests_batch_and_reports_slowest_instance( - tmp_path, - monkeypatch, - capsys, -): - checkpoint_path = tmp_path / "checkpoint" - checkpoint_path.mkdir() - control_dir = tmp_path / "control" - trainer = object.__new__(AsyncRLTrainer) - trainer.config = SimpleNamespace( - rollout_weight_sync_mode="restart", - require_rollout_weight_sync=True, - rollout_weight_sync_control_dir=str(control_dir), - rollout_weight_sync_timeout_s=5.0, - rollout_weight_reload_method="inplace", - rollout_weight_reload_strategy="parallel", - vllm_endpoints="127.0.0.1:8000,127.0.0.1:8001", - vllm_tp_size=1, - ) - trainer._use_heterogeneous = False - trainer.rollout_engine = SimpleNamespace(num_instances=2) - responded = False - - def respond_to_batch(_seconds): - nonlocal responded - request_path = control_dir / "reload_request.json" - if responded or not request_path.exists(): - return - request = json.loads(request_path.read_text(encoding="utf-8")) - for instance_id, total_seconds in zip( - request["instance_ids"], - (1.25, 2.5), - ): - (control_dir / f"ack_{instance_id}_7.json").write_text( - json.dumps( - { - "instance_id": instance_id, - "version": 7, - "checkpoint_path": str(checkpoint_path), - "reload_method": "inplace", - "reload_strategy": "parallel", - "total_seconds": total_seconds, - } - ), - encoding="utf-8", - ) - responded = True - - monkeypatch.setattr( - "RL_Framework.trainer.async_rl_trainer.time.sleep", - respond_to_batch, - ) - - trainer._reload_rollout_from_checkpoint(str(checkpoint_path), 7) - - request = json.loads( - (control_dir / "reload_request.json").read_text(encoding="utf-8") - ) - assert request["reload_method"] == "inplace" - assert request["reload_strategy"] == "parallel" - assert request["instance_ids"] == ["instance_0", "instance_1"] - output = capsys.readouterr().out - assert "method=inplace" in output - assert "slowest_reload=2.50s" in output - - -@pytest.mark.parametrize('rollback', [True, False], ids=['rollback', 'periodic']) -def test_disk_publication_exports_only_its_targets_without_releasing_loan(tmp_path, monkeypatch, rollback): - from RL_Framework.infra.elastic.core_reconfiguration import _run_operation - - trainer = object.__new__(AsyncRLTrainer) - trainer.is_main_process = True - trainer.global_step = 6 - trainer.config = SimpleNamespace(weight_sync_mode='disk', rollout_weight_sync_mode='restart', - rollout_weight_sync_control_dir=str(tmp_path), rollout_weight_reload_method='inplace', - rollout_weight_sync_timeout_s=1, sync_path=str(tmp_path), vllm_endpoints='a:8000,b:8000', - vllm_tp_size=1) - published = [] - def save(path, version): - assert version == 6 - (tmp_path / 'v6').mkdir(exist_ok=True) - trainer.train_engine = SimpleNamespace(train_backend='megatron_core', optimizer_revision=7, - save_weights=save) - trainer._cleanup_old_weights = lambda: None - trainer._restore_lent_rollouts_for_publication = lambda: pytest.fail('rollback released old Hybrid') - trainer._sync_weights_nccl = lambda *args, **kwargs: pytest.fail('checkpoint path entered NCCL') - trainer._reopen_restored_rollouts = lambda: pytest.fail('publisher opened routing before caller') - unavailable = {'instance_0', 'instance_1'} if rollback else {'instance_1'} - trainer._rollout_unavailable_ids = unavailable - target = 'instance_1' if rollback else 'instance_0' - - def finish_reload(_seconds): - request = json.loads((tmp_path / 'reload_request.json').read_text()) - assert request['instance_ids'] == [target] - assert request['version'] == 7 and request['checkpoint_path'] == str(tmp_path / 'v6') - if published: - trainer._write_json_atomic(tmp_path / f'error_{target}_7.json', - dict(request, instance_id=target, snapshot_id=published[-1], error='previous attempt')) - trainer._write_json_atomic(tmp_path / f'ack_{target}_7.json', dict(request, instance_id=target)) - published.append(request['snapshot_id']) - monkeypatch.setattr('RL_Framework.trainer.async_rl_trainer.time.sleep', finish_reload) - command = dict(operation='publish', target=dict(scope='returned_subset', - instances=[dict(instance_id='instance_1')])) - - for _ in range(2): - if rollback: - result = _run_operation(trainer.train_engine, command, trainer) - assert result == {'optimizer_revision': 7, 'acknowledged': True} - else: - trainer._sync_weights(7, reopen_restored=False) - - assert len(published) == len(set(published)) == 2 - assert trainer._rollout_unavailable_ids == unavailable - - -def test_serial_reload_strategy_is_preserved_in_batch_request( - tmp_path, - monkeypatch, -): - checkpoint_path = tmp_path / "checkpoint" - checkpoint_path.mkdir() - control_dir = tmp_path / "control" - trainer = object.__new__(AsyncRLTrainer) - trainer.config = SimpleNamespace( - rollout_weight_sync_mode="restart", - require_rollout_weight_sync=True, - rollout_weight_sync_control_dir=str(control_dir), - rollout_weight_sync_timeout_s=5.0, - rollout_weight_reload_method="restart", - rollout_weight_reload_strategy="serial", - vllm_endpoints="127.0.0.1:8000", - vllm_tp_size=1, - ) - trainer._use_heterogeneous = False - trainer.rollout_engine = SimpleNamespace(num_instances=1) - - def respond_to_batch(_seconds): - request = json.loads( - (control_dir / "reload_request.json").read_text(encoding="utf-8") - ) - (control_dir / "ack_instance_0_3.json").write_text( - json.dumps( - { - "instance_id": "instance_0", - "version": 3, - "checkpoint_path": str(checkpoint_path), - "reload_method": "restart", - "reload_strategy": request["reload_strategy"], - "total_seconds": 1.0, - } - ), - encoding="utf-8", - ) - - monkeypatch.setattr( - "RL_Framework.trainer.async_rl_trainer.time.sleep", - respond_to_batch, - ) - - trainer._reload_rollout_from_checkpoint(str(checkpoint_path), 3) - - request = json.loads( - (control_dir / "reload_request.json").read_text(encoding="utf-8") - ) - assert request["reload_method"] == "restart" - assert request["reload_strategy"] == "serial" diff --git a/tests/test_checked_prefix_cache_reset.py b/tests/test_checked_prefix_cache_reset.py deleted file mode 100644 index 5ca224e..0000000 --- a/tests/test_checked_prefix_cache_reset.py +++ /dev/null @@ -1,52 +0,0 @@ -"""A failed or missing V1 utility cannot produce a cache-clear ACK.""" - -import asyncio -from types import SimpleNamespace - -import pytest - -from RL_Framework.infra.sync.prefix_cache_reset import ( - install_checked_prefix_cache_reset, reset_prefix_cache_verified, -) - - -@pytest.mark.parametrize('success', [True, False]) -def test_checked_core_utility_preserves_scheduler_outcome(success): - class Core: - def reset_prefix_cache(self): - # Mirrors vLLM 0.9.2's original wrapper, which discards the bool. - self.scheduler.reset_prefix_cache() - - original = Core.reset_prefix_cache - install_checked_prefix_cache_reset(Core) - core = Core() - core.scheduler = SimpleNamespace(reset_prefix_cache=lambda: success) - assert Core.reset_prefix_cache is original - if success: - assert core.libra_reset_prefix_cache() is True - else: - with pytest.raises(RuntimeError, match='active KV blocks'): - core.libra_reset_prefix_cache() - - -@pytest.mark.parametrize('outcome', [True, False, 'missing']) -def test_verified_reset_accepts_only_the_real_utility_success(outcome): - async def utility(name): - assert name == 'libra_reset_prefix_cache' - if outcome == 'missing': - raise AttributeError('Unknown utility method') - return outcome - - client = SimpleNamespace(engine_core=SimpleNamespace(call_utility_async=utility)) - if outcome is True: - assert asyncio.run(reset_prefix_cache_verified(client, require_verified=True)) is True - else: - with pytest.raises((RuntimeError, AttributeError)): - asyncio.run(reset_prefix_cache_verified(client, require_verified=True)) - - -def test_legacy_none_return_is_preserved_without_claiming_verified_reset(): - async def reset(): - return None - - assert asyncio.run(reset_prefix_cache_verified(SimpleNamespace(reset_prefix_cache=reset))) is None diff --git a/tests/test_checkpoint_snapshot.py b/tests/test_checkpoint_snapshot.py deleted file mode 100644 index d4af6e4..0000000 --- a/tests/test_checkpoint_snapshot.py +++ /dev/null @@ -1,93 +0,0 @@ -import io -import os -from unittest.mock import patch - -import torch - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.cost_model.global_resource_planner import GlobalResourcePlanner -from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - - -def _max_container_depth(value): - if isinstance(value, dict): - return 1 + max((_max_container_depth(item) for item in value.values()), default=0) - if isinstance(value, (list, tuple)): - return 1 + max((_max_container_depth(item) for item in value), default=0) - return 0 - - -def test_planner_runtime_stats_do_not_feed_previous_decisions_back_in(): - config = AsyncRLConfig( - model_path="/tmp/fake-model", - train_gpus=2, - rollout_gpus=2, - train_dp_size=2, - batch_size=8, - n_total_gpus=4, - ) - config.global_resource_planner.enabled = True - planner = GlobalResourcePlanner.from_config(config) - stats = {} - - for step in range(200): - planner_stats = AsyncRLTrainer._planner_step_stats(stats) - metrics = planner.observe_runtime( - step=step, - dispatcher_metrics={"runner_max_queue_size": 16}, - step_stats={ - **planner_stats, - "rollout_time": 20.0, - "train_time": 5.0, - "step_time": 30.0, - "max_concurrent_rollouts": 8, - }, - ) - stats["global_resource_planner"] = { - "step": step, - "runtime_metrics": metrics.to_dict(), - } - - raw_step_stats = stats["global_resource_planner"]["runtime_metrics"]["raw"]["step_stats"] - assert "global_resource_planner" not in raw_step_stats - assert "global_resource_planner_runtime" not in raw_step_stats - assert _max_container_depth(stats) < 10 - - buffer = io.BytesIO() - torch.save( - {"stats": AsyncRLTrainer._checkpoint_safe_value(stats)}, - buffer, - ) - assert buffer.tell() > 0 - - -def test_checkpoint_snapshot_breaks_cycles_and_limits_depth(): - recursive = {"reward": 0.5} - recursive["self"] = recursive - nested = current = {} - for index in range(100): - current["next"] = {} - current = current["next"] - current["index"] = index - - snapshot = AsyncRLTrainer._checkpoint_safe_value( - {"recursive": recursive, "nested": nested} - ) - - assert snapshot["recursive"]["self"] == "" - assert _max_container_depth(snapshot) <= 34 - buffer = io.BytesIO() - torch.save(snapshot, buffer) - assert buffer.tell() > 0 - - -def test_resume_step_and_model_version_are_read_from_environment(): - config = AsyncRLConfig(model_path="/tmp/fake-model", total_steps=1000) - with patch.dict( - os.environ, - {"RL_TRAIN_START_STEP": "151", "RL_INITIAL_MODEL_VERSION": "151"}, - ): - trainer = AsyncRLTrainer(config) - - assert trainer.start_step == 151 - assert trainer.initial_model_version == 151 diff --git a/tests/test_cmlfq_rebind_state.py b/tests/test_cmlfq_rebind_state.py deleted file mode 100644 index c143e2b..0000000 --- a/tests/test_cmlfq_rebind_state.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Online CMLFQ evidence survives the engine lifecycle used by weight sync.""" - -from unittest.mock import patch - -import pytest - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.engine.heterogeneous_engine import HeterogeneousRolloutEngine -from RL_Framework.infra.scheduling.cmlfq_prefix_tree import CausalPrefixTree, Trajectory -from RL_Framework.infra.scheduling.cmlfq_scheduler import CMLFQScheduler -from RL_Framework.infra.scheduling.cmlfq_tool_state import DefaultToolStateExtractor - - -EVENT = {"tool_type": "search", "output": "ok", "payload_tokens": 2} -STATE = DefaultToolStateExtractor().extract(EVENT) - - -def config_for(kind, tree_path=""): - config = AsyncRLConfig(model_path="not-loaded") - config.heterogeneous_rollout.instances = [] - sched = config.heterogeneous_rollout.scheduling - sched.scheduler_type = kind - sched.cmlfq_buckets = { - "short": {"tp_degrees": [1], "max_tokens": 5000}, - "long": {"tp_degrees": [4], "max_tokens": 50000}, - } - sched.cmlfq_tree_path = tree_path - sched.cmlfq_tree_persist_interval = 3 - sched.cmlfq_rebuild_interval = 4 - return config - - -@pytest.mark.parametrize("kind", ["cmlfq", "cmlfq_cost"]) -@pytest.mark.parametrize("persist", [False, True]) -@pytest.mark.parametrize("lifecycle", ["from_config", "reconfigure"]) -def test_online_window_and_rebuild_follow_real_engine_rebind(kind, persist, lifecycle, tmp_path): - config = config_for(kind, str(tmp_path / "tree.json") if persist else "") - engine = HeterogeneousRolloutEngine.from_config(config) - # Offline evidence must survive rebind but should be retired at the first - # periodic rebuild, which intentionally uses only the online window. - unit = "model_generated_tokens" if kind == "cmlfq_cost" else "context_tokens" - engine.scheduler.prefix_tree.insert(Trajectory("offline", [STATE], [2000], remaining_unit=unit)) - rebuilt = [] - original = CausalPrefixTree.rebuild - - def observe(tree, trajectories): - rebuilt.append([trajectory.prompt_id for trajectory in trajectories]) - return original(tree, trajectories) - - with patch.object(CausalPrefixTree, "rebuild", observe): - for step in range(9): - engine.scheduler.register_instance(0, "short", 1) - engine.notify_epoch_start(step) - request = engine.begin_cmlfq_request(f"p-{step}", 100) - # R2E supplies both lengths to both schedulers. Each retains the - # same units as its existing offline tree across online updates. - engine.route_cmlfq_tool_return(request, dict(EVENT, generated_token_position=100), 102) - engine.finish_cmlfq_request(request, 1102 + step, generated_tokens=1000 + step) - old = engine.scheduler - if lifecycle == "from_config": - engine = HeterogeneousRolloutEngine.from_config( - config, carry_scheduler_state_from=old, - ) - else: - engine.reconfigure_from_plan(None, config) - current = engine.scheduler - assert current._current_epoch == step - assert current._tree_update_count == step + 1 - assert current._tool_return_count == step + 1 - assert len(current._recent_trajectories) == step + 1 - assert current.prefix_tree is not old.prefix_tree - assert current._recent_trajectories is not old._recent_trajectories - assert current.prefix_tree.lookup(f"p-{step}", [STATE]) is not None - expected_length = (900 if kind == "cmlfq_cost" else 1000) + step - assert current.prefix_tree.lookup(f"p-{step}", [STATE]).remaining_lengths == [expected_length] - if step < 4: - assert current.prefix_tree.lookup("offline", [STATE]) is not None - engine.notify_epoch_end(step) - - assert rebuilt == [[f"p-{n}" for n in range(5)], [f"p-{n}" for n in range(9)]] - assert engine.scheduler.prefix_tree.lookup("offline", [STATE]) is None - assert engine.scheduler.prefix_tree.get_stats()["total_insertions"] == 9 - - -def test_export_and_repeated_import_do_not_alias_or_round_evidence(): - scheduler = CMLFQScheduler(max_recent_trajectories=3) - scheduler.prefix_tree.insert(Trajectory("precise", [STATE], [1 / 3])) - scheduler._recent_trajectories = [Trajectory(str(i), [STATE], [i]) for i in range(3)] - state = scheduler.export_learned_state() - scheduler._recent_trajectories[0].total_remaining_lengths[0] = 999 - scheduler.prefix_tree.lookup("precise", [STATE]).remaining_lengths.append(999) - - restored = CMLFQScheduler(max_recent_trajectories=2) - restored.import_learned_state(state) - other = CMLFQScheduler() - other.import_learned_state(state) - assert [traj.prompt_id for traj in restored._recent_trajectories] == ["1", "2"] - assert restored.prefix_tree.lookup("precise", [STATE]).mean_remaining_length == 1 / 3 - assert restored.prefix_tree.lookup("precise", [STATE]).remaining_lengths == [1 / 3] - restored._recent_trajectories[0].total_remaining_lengths[0] = -1 - restored.prefix_tree.lookup("precise", [STATE]).remaining_lengths.append(-1) - assert other._recent_trajectories[1].total_remaining_lengths == [1] - assert other.prefix_tree.lookup("precise", [STATE]).remaining_lengths == [1 / 3] - - -def test_non_cmlfq_state_keeps_preloaded_tree(): - scheduler = CMLFQScheduler() - scheduler.prefix_tree.insert(Trajectory("offline", [STATE], [100])) - scheduler.import_learned_state({"output_ema": {"short": 42}}) - assert scheduler.prefix_tree.lookup("offline", [STATE]) is not None - assert scheduler._output_ema["short"] == 42 diff --git a/tests/test_collective_weight_export.py b/tests/test_collective_weight_export.py deleted file mode 100644 index bab7cc3..0000000 --- a/tests/test_collective_weight_export.py +++ /dev/null @@ -1,128 +0,0 @@ -"""Transport failures must not abandon peers inside the next TP export.""" - -import json -from datetime import timedelta -from pathlib import Path -from types import SimpleNamespace -from unittest.mock import patch - -import torch -import torch.distributed as dist -import torch.multiprocessing as mp - - -def _worker(rank, rendezvous, directory): - torch.set_num_threads(1) - dist.init_process_group("gloo", init_method=f"file://{rendezvous}", rank=rank, world_size=2, - timeout=timedelta(seconds=12)) - control = dist.new_group(backend="gloo", timeout=timedelta(seconds=12)) - try: - from RL_Framework.infra.sync.collective_export import stream_export_with_consensus - from RL_Framework.infra.sync import nccl_weight_sync, publication_session - from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - for entrypoint in ("helper", "native"): - for failure in ("before-first", "after-first", "iterator", "prepare", "request"): - if failure == "prepare" and entrypoint != "helper": - continue - if failure == "request" and entrypoint == "helper": - continue - exported, sent = [], [] - - def weights(): - for index in range(3): - # Real inter-rank compute/export synchronization. - dist.barrier() - if failure == "iterator" and rank == 1 and index == 1: - raise RuntimeError("iterator failed on rank 1") - exported.append(index) - yield f"weight-{index}", torch.ones(2) * index - - def prepare(item): - if failure == "prepare" and rank == 0 and item[0] == "weight-1": - raise RuntimeError("tensor preparation failed") - return item - - def send(items, *args, **kwargs): - if failure == "before-first": - raise RuntimeError("transport bootstrap failed") - for item in items: - sent.append(item[0]) - if failure == "after-first": - raise RuntimeError("transport failed after first tensor") - - folder = Path(directory) / entrypoint / failure - config = SimpleNamespace( - rollout_weight_sync_control_dir=str(folder), rollout_nccl_host="127.0.0.1", - rollout_nccl_port=29620, rollout_nccl_chunk_mb=1, - rollout_nccl_rate_limit_gbps=0, rollout_weight_sync_timeout_s=2, - rollout_weight_sync_poll_interval_s=0.001, - heterogeneous_rollout=SimpleNamespace(enabled=True, instances=[ - SimpleNamespace(instance_id="engine", host="127.0.0.1", port=8000, tp=2), - ]), - ) - - def command(value): - packet = [value] - dist.broadcast_object_list(packet, src=0, group=control) - if packet[0].get("error"): - raise RuntimeError(packet[0]["error"]) - return packet[0] - - def write_request(path, value): - if failure == "request": - raise OSError("control request write failed") - path.write_text(json.dumps(value)) - - trainer = SimpleNamespace( - config=config, is_main_process=rank == 0, control=control, - train_engine=SimpleNamespace(train_backend="megatron_core", optimizer_revision=23, - stream_rollout_weights=weights), - optimizer_revision=23, service_generations={}, - events=SimpleNamespace(emit=lambda *args, **kwargs: None), command=command, - _nccl_rollout_topology=lambda: (3, {"engine": 0}), - _write_json_atomic=write_request, - ) - caught = "" - with patch.object(nccl_weight_sync, "send_weights", send), \ - patch.object(publication_session, "live_publication_state", - lambda endpoint: dict(server_instance_id="live-service", - server_generation=0, server_generation_verified=True, tp_size=2)), \ - patch.object(torch.cuda, "current_device", lambda: "cpu"), \ - patch.object(torch.cuda, "current_stream", lambda: SimpleNamespace(synchronize=lambda: None)): - try: - if entrypoint == "helper": - stream_export_with_consensus(weights, is_sender=rank == 0, send=send, - group=control, prepare=prepare) - elif entrypoint == "native": - AsyncRLTrainer._sync_weights_nccl(trainer, 23) - except RuntimeError as exc: - caught = str(exc) - if failure == "request": - assert "control request write failed" in caught, caught - assert exported == [] - else: - assert "collective weight publication failed" in caught, caught - errors = [None, None] - dist.all_gather_object(errors, caught, group=control) - assert all(errors) - if failure in ("before-first", "after-first"): - assert exported == [0, 1, 2] - assert sent == (["weight-0"] if rank == 0 and failure == "after-first" else []) - elif failure in ("iterator", "prepare"): - assert 2 not in exported # nobody enters another export collective - # A matching barrier proves the failed publication left no rank - # waiting in an orphaned export iteration. - dist.barrier() - - captured = [] - stream_export_with_consensus(lambda: iter([("ok", torch.ones(1))]), - is_sender=rank == 0, - send=lambda items: captured.extend(items), group=control) - assert len(captured) == (1 if rank == 0 else 0) - finally: - dist.destroy_process_group() - - -def test_two_rank_stream_failures_drain_then_fail_all_entrypoints(tmp_path): - mp.start_processes(_worker, args=(str(tmp_path / "rendezvous"), str(tmp_path)), - nprocs=2, join=True, start_method="spawn") diff --git a/tests/test_compare_dynarl_libra.py b/tests/test_compare_dynarl_libra.py deleted file mode 100644 index ae0c383..0000000 --- a/tests/test_compare_dynarl_libra.py +++ /dev/null @@ -1,68 +0,0 @@ -from __future__ import annotations - -import importlib.util -import json -from pathlib import Path - -import pytest - - -SCRIPT_PATH = Path(__file__).parents[1] / "scripts" / "compare_dynarl_libra.py" -SPEC = importlib.util.spec_from_file_location("compare_dynarl_libra", SCRIPT_PATH) -assert SPEC is not None and SPEC.loader is not None -MODULE = importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(MODULE) - - -def test_parse_rlinf_log_supports_scientific_notation(tmp_path: Path) -> None: - log_path = tmp_path / "main.log" - log_path.write_text( - "\n".join( - [ - "Global Step: 1/3 [step_time=24.5, sync_weights_time=8.69, " - "variance_of_response_length=3.17e+3, actor/lr=2e-6]", - "Global Step: 2/3 [step_time=12.9, sync_weights_time=2.85, " - "advantages_mean=-1.07e-8]", - "[ElasticMegatron-Perf] : nccl_build_cost=1.2e+0ms, " - "transfer_cost=3.85e+2ms, update_model_cost=1e-2ms, " - "transfer_bytes=4.97GB, bandwidth=1.29e+1 GB/s", - ] - ), - encoding="utf-8", - ) - - result = MODULE.parse_rlinf_log(log_path) - - assert result["num_steps"] == 2 - assert result["steps"][0]["variance_of_response_length"] == 3170.0 - assert result["steps"][0]["actor/lr"] == 2e-6 - assert result["steps"][1]["advantages_mean"] == -1.07e-8 - assert result["warm_step_time_mean_s"] == 12.9 - assert result["warm_sync_time_mean_s"] == 2.85 - assert result["migrations"][0]["transfer_ms"] == 385.0 - assert result["migrations"][0]["bandwidth_gbps"] == 12.9 - - -def test_parse_libra_result_uses_last_round_as_steady_state( - tmp_path: Path, -) -> None: - result_path = tmp_path / "result.json" - result_path.write_text( - json.dumps( - { - "model": "Qwen/Qwen3-4B", - "outputs_stable": True, - "rounds": [ - {"send_seconds": 20.84, "payload_gib_per_second": 0.77}, - {"send_seconds": 0.19, "payload_gib_per_second": 17.6}, - ], - } - ), - encoding="utf-8", - ) - - result = MODULE.parse_libra_result(result_path) - - assert result["cold_reload_s"] == pytest.approx(20.84) - assert result["steady_reload_s"] == pytest.approx(0.19) - assert result["steady_payload_gib_per_second"] == pytest.approx(17.6) diff --git a/tests/test_config_parsing.py b/tests/test_config_parsing.py index 1b2433f..f78e844 100644 --- a/tests/test_config_parsing.py +++ b/tests/test_config_parsing.py @@ -1,4 +1,14 @@ -from RL_Framework.config import HardwareConfig +from pathlib import Path + +from RL_Framework.config import ( + HardwareConfig, + ModelArchConfig, + ProfilingConfig, +) +from RL_Framework.infra.cost_model.model import CostModel + + +CONFIG_DIR = Path(__file__).parents[1] / "configs" / "model_arch_config" def test_from_dict_parses_numeric_strings_and_ignores_unknown_keys(): @@ -20,6 +30,43 @@ def test_from_dict_parses_numeric_strings_and_ignores_unknown_keys(): assert not hasattr(config, "unknown_key") +def test_qwen3_14b_architecture_config(): + model = ModelArchConfig.from_file( + str(CONFIG_DIR / "qwen3-14b.yaml") + ) + assert model.num_params == 14e9 + assert model.d_model == 5120 + assert model.n_layers == 40 + assert model.intermediate_size == 17408 + assert model.vocab_size == 151936 + assert not model.is_moe + + +def test_qwen3_30b_a3b_moe_config_and_memory(): + model = ModelArchConfig.from_file( + str(CONFIG_DIR / "qwen3-30b-a3b.yaml") + ) + assert model.is_moe + assert model.d_model == 2048 + assert model.n_layers == 48 + assert model.num_experts == 128 + assert model.num_activated_experts == 8 + assert model.expert_intermediate_size == 768 + assert model.effective_num_params == 3e9 + + cost = CostModel( + hardware=HardwareConfig(), + model_arch=model, + profiling=ProfilingConfig(), + ) + expected = ( + 8 * cost.hw.mem_capacity + - model.num_params * model.dtype_bytes + - cost.rollout_model.act_workspace + ) + assert cost.rollout_model.compute_kv_pool(8) == expected + + def test_decoupled_configuration_round_trips_to_megatron_engine(tmp_path, monkeypatch): from RL_Framework.config import AsyncRLConfig from RL_Framework.engine.train_factory import create_train_engine diff --git a/tests/test_core_reconfiguration_protocol.py b/tests/test_core_reconfiguration_protocol.py deleted file mode 100644 index 44ab4f9..0000000 --- a/tests/test_core_reconfiguration_protocol.py +++ /dev/null @@ -1,223 +0,0 @@ -"""Every parked training rank must execute fixed-topology live-state commands.""" - -import threading -import time -from concurrent.futures import ThreadPoolExecutor -from types import SimpleNamespace - -import pytest - -from RL_Framework.infra.elastic import core_reconfiguration as protocol -from RL_Framework.infra.elastic.runtime_boundary import read_record, write_record - - -class Engine: - def __init__(self, rank, calls, barrier=None, failing_rank=None): - self.rank, self.world_size = rank, 2 - self.calls, self.barrier, self.failing_rank = calls, barrier, failing_rank - - def capture_elastic_state_snapshot(self, worker, target): - self.calls.append((self.rank, "capture", worker, target)) - if self.barrier: - self.barrier.wait(timeout=3) - if self.rank == self.failing_rank: - raise RuntimeError("rank-local capture failed") - return 17 - - def get_elastic_state_snapshot_path(self, revision): - return f"ehp://rank-{self.rank}/revision-{revision}" - - def get_elastic_lane_state(self): - return {"global_rank": self.rank, "tensor_parallel_rank": self.rank, - "data_parallel_rank": 0} - - def release_elastic_state_snapshot(self, revision): - self.calls.append((self.rank, "release", revision)) - - - -class Trainer: - def __init__(self, engine, calls): - self.train_engine = engine - self.calls = calls - self.config = SimpleNamespace(train_tp_size=2, train_dp_size=1, tp_size=2) - self._elastic_gradient_server = SimpleNamespace( - close=lambda: calls.append((engine.rank, "close-gradient-server"))) - - def _runtime_state_is_current(self, command): - return command.get("run_id") == "run-current" - - def _initialize_elastic_communication_domains(self): - self.calls.append((self.train_engine.rank, "new-comm-domain")) - - def _init_nonblocking_elastic_core(self): - self.calls.append((self.train_engine.rank, "new-gradient-server")) - - def _on_train_engine_reconfigured(self): - self.calls.append((self.train_engine.rank, "new-topology-hook")) - - -def executor(directory, engine, trainer=None, timeout=1): - return SimpleNamespace( - train_engine=engine, trainer=trainer, - _coordination_dir=lambda: directory, _active_runtime_coord_id="coord-current", - runtime_run_id="run-current", _closing=threading.Event(), - config=SimpleNamespace(global_resource_planner=SimpleNamespace(runtime_drain_timeout_s=timeout)), - ) - - -def follow_one(trainer, directory): - deadline = time.monotonic() + 4 - while time.monotonic() < deadline: - if read_record(directory / "core_command.json").get("command_id"): - protocol.follow_core_command(trainer, directory, "coord-current") - return - time.sleep(0.001) - raise AssertionError("leader did not publish command") - - -@pytest.mark.parametrize("operation", ["capture", "release"]) -def test_every_training_rank_executes_command(tmp_path, operation): - calls = [] - barrier = threading.Barrier(2) if operation != "release" else None - engines = [Engine(rank, calls, barrier) for rank in range(2)] - trainers = [Trainer(engine, calls) for engine in engines] - with ThreadPoolExecutor(max_workers=1) as pool: - peer = pool.submit(follow_one, trainers[1], tmp_path) - receipts = protocol.dispatch_core_command( - executor(tmp_path, engines[0], trainers[0]), operation, - target={"train_tp_size": 1, "train_dp_size": 2}, revisions=(16, 17), - ) - peer.result(timeout=4) - assert {item["rank"] for item in receipts} == {0, 1} - assert all(item["status"] == "success" for item in receipts) - assert len({item["command_id"] for item in receipts}) == 1 - if operation == "capture": - assert {item["snapshot_uri"] for item in receipts} == { - "ehp://rank-0/revision-17", "ehp://rank-1/revision-17"} - assert all(item["optimizer_revision"] == 17 for item in receipts) - elif operation == "release": - assert {(item[0], item[2]) for item in calls if item[1] == "release"} == { - (0, 16), (0, 17), (1, 16), (1, 17)} - - -def test_one_rank_failure_reaches_dispatch_and_follower(tmp_path): - calls, barrier = [], threading.Barrier(2) - engines = [Engine(rank, calls, barrier, failing_rank=1) for rank in range(2)] - trainers = [Trainer(engine, calls) for engine in engines] - with ThreadPoolExecutor(max_workers=1) as pool: - peer = pool.submit(follow_one, trainers[1], tmp_path) - with pytest.raises(RuntimeError, match="collective core capture failed"): - protocol.dispatch_core_command(executor(tmp_path, engines[0], trainers[0]), "capture", - target={"train_tp_size": 1, "train_dp_size": 2}) - with pytest.raises(RuntimeError, match="rank-local capture failed"): - peer.result(timeout=4) - failed = read_record(tmp_path / "core_receipts" / "rank_1.json") - assert failed["status"] == "failed" - assert trainers[1].config.train_tp_size == 2 - - -def test_repartition_weights_publish_before_binding_new_endpoint(): - from RL_Framework.config import HeterogeneousInstanceConfig, HeterogeneousRolloutConfig - from RL_Framework.infra.sync.publication_session import publication_inventory - from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - trainer = object.__new__(AsyncRLTrainer) - trainer.config = SimpleNamespace(heterogeneous_rollout=HeterogeneousRolloutConfig(enabled=True, instances=[ - HeterogeneousInstanceConfig(instance_id='old', host='node', port=8001, tp=1), - ])) - trainer.rollout_engine = SimpleNamespace(instance_urls=['http://node:8001']) - trainer.runtime_elastic_executor = SimpleNamespace(_lent_rollout=None) - expected = [{'instance_id': 'new', 'endpoint': 'node:8002', 'tp_size': 2}] - operations = [] - - def publish(target_version, *, reopen_restored): - assert target_version == 17 - assert not reopen_restored - assert publication_inventory(trainer)['targets'] == expected - assert trainer._rollout_unavailable_ids == {'new'} - operations.append('publish') - - def rebind(reason): - assert operations == ['publish'] - operations.append('rebind') - - trainer._sync_weights = publish - trainer._rebind_rollout_engine_from_config = rebind - engine = SimpleNamespace(optimizer_revision=17, set_version=lambda revision: None) - result = protocol._run_operation(engine, {'operation': 'publish', 'target': { - 'instances': [{'instance_id': 'new', 'host': 'node', 'port': 8002, 'tp': 2}], - }}, trainer) - - assert result['acknowledged'] and operations == ['publish', 'rebind'] - assert not trainer._rollout_unavailable_ids - - -def test_followers_ignore_stale_or_repeated_commands(tmp_path): - calls = [] - trainer = Trainer(Engine(1, calls), calls) - command = {"command_id": "release-once", "coord_id": "coord-current", - "run_id": "run-stale", "operation": "release", "revisions": [17]} - write_record(tmp_path / "core_command.json", command) - protocol.follow_core_command(trainer, tmp_path, "coord-current") - assert calls == [] - command["run_id"] = "run-current" - write_record(tmp_path / "core_command.json", command) - protocol.follow_core_command(trainer, tmp_path, "wrong-coord") - assert calls == [] - protocol.follow_core_command(trainer, tmp_path, "coord-current") - protocol.follow_core_command(trainer, tmp_path, "coord-current") - assert calls == [(1, "release", 17)] - - -@pytest.mark.parametrize("wrong", [{"coord_id": "coord-stale"}, {"rank": 0}, {"run_id": "run-stale"}]) -def test_rank_coverage_requires_current_coord_and_exact_rank(tmp_path, monkeypatch, wrong): - original = protocol.execute_core_command - - def local_and_invalid_peer(engine, command, directory, trainer): - receipt = original(engine, command, directory, trainer) - stale = dict(receipt, rank=1) - stale.update(wrong) - write_record(directory / "core_receipts" / "rank_1.json", stale) - return receipt - - monkeypatch.setattr(protocol, "execute_core_command", local_and_invalid_peer) - with pytest.raises(TimeoutError, match="missing rank receipts"): - protocol.dispatch_core_command(executor(tmp_path, Engine(0, []), timeout=0.02), "release") - - -def test_zero_timeout_waits_for_delayed_rank(tmp_path, monkeypatch): - original = protocol.execute_core_command - peer_thread = [] - - def delayed_peer(engine, command, directory, trainer): - receipt = original(engine, command, directory, trainer) - - def publish(): - time.sleep(0.05) - write_record(directory / "core_receipts" / "rank_1.json", dict(receipt, rank=1)) - - thread = threading.Thread(target=publish) - thread.start() - peer_thread.append(thread) - return receipt - - monkeypatch.setattr(protocol, "execute_core_command", delayed_peer) - receipts = protocol.dispatch_core_command(executor(tmp_path, Engine(0, []), timeout=0), "release") - assert len(receipts) == 2 - peer_thread[0].join(timeout=1) - - -def test_closing_executor_does_not_report_partial_success(tmp_path): - instance = executor(tmp_path, Engine(0, [])) - instance._closing.set() - with pytest.raises(RuntimeError, match="executor closed"): - protocol.dispatch_core_command(instance, "release") - - -def test_topology_rebuild_is_outside_fixed_core_protocol(tmp_path): - receipt = protocol.execute_core_command(Engine(0, []), { - "command_id": "unsupported", "coord_id": "coord-current", - "run_id": "run-current", "operation": "rebuild", - }, tmp_path) - assert receipt["status"] == "failed" - assert "unknown collective core operation: rebuild" in receipt["error"] diff --git a/tests/test_core_subset_publication.py b/tests/test_core_subset_publication.py deleted file mode 100644 index 96d178a..0000000 --- a/tests/test_core_subset_publication.py +++ /dev/null @@ -1,64 +0,0 @@ -"""Rollback publication targets only newly restored services, preserving loans.""" -from types import SimpleNamespace as NS - -import pytest - -from RL_Framework.infra.elastic.core_reconfiguration import _run_operation -from RL_Framework.infra.elastic.runtime_executor import RuntimeElasticExecutor - - -@pytest.mark.parametrize('fail', [False, True]) -@pytest.mark.parametrize('preexisting', [False, True]) -def test_subset_publication_keeps_old_loan_and_pending_scope(fail, preexisting): - borrowed = {'old-hybrid-engine'} - unavailable = borrowed | {'returned-engine'} - topology = object() - engine = NS(optimizer_revision=7) - trainer = NS(config=topology, _rollout_unavailable_ids=unavailable, - rollout_engine=NS(scheduler=NS(_instances=[]))) - previous_targets, previous_pending = {'previous-target'}, {'previous-pending'} - if preexisting: - trainer._publication_target_ids = previous_targets - trainer._restored_rollouts_pending_publication = previous_pending - observed = [] - - def sync(*, target_version, instance_ids, reopen_restored): - observed.append((target_version, set(instance_ids), reopen_restored)) - if fail: - raise RuntimeError('receiver failed') - - trainer._sync_weights = sync - command = dict(operation='publish', target=dict(scope='returned_subset', - instances=[dict(instance_id='returned-engine')])) - if fail: - with pytest.raises(RuntimeError, match='receiver failed'): - _run_operation(engine, command, trainer) - else: - assert _run_operation(engine, command, trainer)['acknowledged'] - assert observed == [(7, {'returned-engine'}, False)] - assert trainer.config is topology - assert trainer._rollout_unavailable_ids is unavailable - if preexisting: - assert trainer._publication_target_ids is previous_targets - assert trainer._restored_rollouts_pending_publication is previous_pending - else: - assert not hasattr(trainer, '_publication_target_ids') - assert not hasattr(trainer, '_restored_rollouts_pending_publication') - - -def test_runtime_subset_targets_are_selected_from_current_configuration(monkeypatch): - from RL_Framework.infra.elastic import core_reconfiguration as commands - runtime = object.__new__(RuntimeElasticExecutor) - instances = [NS(instance_id=name, tp=1, gpus=[index], host='node', port=8000+index) - for index, name in enumerate(('old-hybrid-engine', 'returned-engine', 'unaffected-engine'))] - runtime.config = NS(heterogeneous_rollout=NS(instances=instances)) - calls = [] - monkeypatch.setattr(commands, 'dispatch_core_command', - lambda *args, **kwargs: calls.append((args, kwargs))) - runtime._publish_current_rollout_weights(instance_ids=['returned-engine']) - target = calls[0][1]['target'] - assert target['scope'] == 'returned_subset' - assert [entry['instance_id'] for entry in target['instances']] == ['returned-engine'] - with pytest.raises(ValueError, match='unknown instances'): - runtime._publish_current_rollout_weights(instance_ids=['no-longer-configured']) - assert len(calls) == 1 diff --git a/tests/test_cpu_offload_backend.py b/tests/test_cpu_offload_backend.py deleted file mode 100644 index c7dbc7e..0000000 --- a/tests/test_cpu_offload_backend.py +++ /dev/null @@ -1,67 +0,0 @@ -import asyncio -import unittest - -from RL_Framework.engine.cmlfq_backend import CMLFQGenerationBackend - - -class FakeCPUBackend: - def __init__(self): - self.calls = [] - self.released = [] - self.ready = asyncio.Event() - - async def generate(self, prompt, kv_transfer_params, **kwargs): - self.calls.append(kv_transfer_params) - return {"text": "answer", "kv_transfer_params": { - "libra_offload_key": kv_transfer_params["libra_offload_key"], - "source_tp": 1, "cached_tokens": 128, - "libra_imported_tokens": 128 if "libra_load_key" in kv_transfer_params else 0, - }} - - async def wait_for_cpu_offload(self, key, source_tp): - await self.ready.wait() - return {"ready": True} - - async def release_cpu_offload(self, key): - self.released.append(key) - - -class TestCPUOffloadBackend(unittest.IsolatedAsyncioTestCase): - async def test_first_completion_does_not_wait_for_offload_and_next_reuses_cache(self): - src, dst = FakeCPUBackend(), FakeCPUBackend() - backend = CMLFQGenerationBackend("cpu_offload", [(1, 1)]) - first = await asyncio.wait_for(backend.generate(src, src, "prompt", "stay", "r"), 1) - self.assertFalse(src.ready.is_set()) - key = first.output["kv_transfer_params"]["libra_offload_key"] - resumed = asyncio.create_task(backend.generate(src, dst, "prompt+tool", "transfer", "r")) - await asyncio.sleep(0) - self.assertFalse(resumed.done()) - src.ready.set() - result = await resumed - self.assertEqual(dst.calls[0]["libra_load_key"], key) - self.assertEqual(result.path, "cpu_reload") - self.assertEqual(result.output["_cpu_offload_info"]["imported_tokens"], 128) - await backend.close() - self.assertEqual(len(src.released), 1) - self.assertEqual(len(dst.released), 1) - - async def test_recompute_path_does_not_wait_or_load_prior_cache(self): - src, dst = FakeCPUBackend(), FakeCPUBackend() - backend = CMLFQGenerationBackend("cpu_offload") - await backend.generate(src, src, "prompt", "stay", "r") - result = await asyncio.wait_for(backend.generate(src, dst, "next", "recompute", "r"), 1) - self.assertEqual(result.path, "recompute") - self.assertNotIn("libra_load_key", dst.calls[0]) - await backend.close() - - async def test_cache_failure_recomputes_and_cleans_up(self): - class FailedCache(FakeCPUBackend): - async def wait_for_cpu_offload(self, key, source_tp): - raise TimeoutError("offload failed") - src, dst = FailedCache(), FakeCPUBackend() - backend = CMLFQGenerationBackend("cpu_offload") - await backend.generate(src, src, "prompt", "stay", "r") - result = await backend.generate(src, dst, "next", "transfer", "r") - self.assertEqual(result.fallback_reason, "TimeoutError") - self.assertNotIn("libra_load_key", dst.calls[0]) - await backend.close() diff --git a/tests/test_ehp_batch_partition.py b/tests/test_ehp_batch_partition.py index 2c4a602..609b7b2 100644 --- a/tests/test_ehp_batch_partition.py +++ b/tests/test_ehp_batch_partition.py @@ -9,6 +9,7 @@ import torch.distributed as dist import torch.multiprocessing as mp +from RL_Framework.config import AsyncRLConfig, GlobalResourcePlannerConfig from RL_Framework.infra.elastic.batch_partition import ( complete_group_sample_counts, partition_complete_grpo_groups, ) @@ -71,21 +72,33 @@ def make_trainer(tmp_path, rank=0, dp_size=1, dp_rank=0, source=True, hybrids=() trainer = object.__new__(AsyncRLTrainer) trainer.rank, trainer.local_rank = rank, rank trainer.world_size, trainer.is_main_process = dp_size, rank == 0 - trainer.config = SimpleNamespace( + trainer.config = AsyncRLConfig( + model_path="/tmp/fake-model", batch_size=16, n_samples=4, total_steps=2, micro_batch_size=1, ppo_epochs=1, recompute_logprobs=False, sync_interval=0, save_interval=0, log_dir=str(tmp_path), enable_rollout_tracing=False, - heterogeneous_rollout=SimpleNamespace(instances=[]), - global_resource_planner=SimpleNamespace(hybrid_worker_task_dir=str(tmp_path), - hybrid_lockstep_gradient_sync=True), + train_gpus=dp_size, train_dp_size=dp_size, rollout_gpus=1, + global_resource_planner=GlobalResourcePlannerConfig( + hybrid_worker_task_dir=str(tmp_path), + hybrid_lockstep_gradient_sync=True, + ), ) trainer.train_engine = Engine(dp_rank, dp_size, source) trainer.start_step = 0 + trainer.global_step = 0 + trainer.control = None trainer.runtime_elastic_executor = None trainer._use_heterogeneous = False trainer._bounded_rollout_production = False trainer.staleness_manager = None trainer._pending_hybrid_training_batches = {} + trainer._consumed_grpo_group_ids = set() + trainer._advantage_stats = {} + trainer._rollout_unavailable_ids = set() + trainer._restored_rollouts_pending_publication = set() + trainer._publication_target_ids = None + trainer._rollout_source_rank = None + trainer._rollout_source_world_size = None trainer._elastic_membership_run_id = "fixed-b-test" trainer.setup = lambda workflow: None trainer._create_data_generator = lambda dataset, workflow: iter(()) diff --git a/tests/test_ehp_dp_resharding.py b/tests/test_ehp_dp_resharding.py deleted file mode 100644 index c728d93..0000000 --- a/tests/test_ehp_dp_resharding.py +++ /dev/null @@ -1,117 +0,0 @@ -"""Native MCore Adam resharding from two Core DP replicas to one Hybrid. - -Each test isolates one model-parallel lane: real Gloo gathers the Core shards, -then a separately initialized DP1 group restores the native DP-zero payload. -The small optimizer fixture follows test_ehp_correctness.py and needs no CUDA. -""" -from pathlib import Path -from types import SimpleNamespace -from datetime import timedelta -import torch -import torch.distributed as dist -import torch.multiprocessing as mp -import pytest - -from RL_Framework.engine.megatron_core_train_engine import MegatronCoreTrainEngine - - -def _engine(module, rank, world, values, padded_extra=0): - full = torch.tensor(values, dtype=torch.float32) - padded_numel = len(values) + padded_extra - width = padded_numel // world - start, end = rank * width, min((rank + 1) * width, len(values)) - master = torch.nn.Parameter(full[start:end].clone(), requires_grad=False) - model = torch.nn.Parameter(full.bfloat16().clone()) - inner = torch.optim.AdamW([{'params': [master], 'wd_mult': 1., 'lr_mult': 1., - 'is_expert_parallel': False, 'is_decoupled_lr': False}], - lr=.01, betas=(.9, .95)) - optimizer = module.DistributedOptimizer.__new__(module.DistributedOptimizer) - optimizer.optimizer = inner - optimizer.ddp_config = SimpleNamespace(use_megatron_fsdp=False) - optimizer.config = SimpleNamespace(exp_avg_dtype=torch.float32, exp_avg_sq_dtype=torch.float32, - use_precision_aware_optimizer_no_fp8_or_ds_fp8=False, fp16=False) - optimizer.grad_scaler = None - optimizer.data_parallel_group_gloo = dist.group.WORLD - optimizer.model_param_group_index_map = {model: (0, 0)} - dtype = (torch.bfloat16, torch.bfloat16) - optimizer.gbuf_ranges = [{dtype: [{'param_map': {model: { - 'gbuf_world': module.Range(start, end), 'param': module.Range(start, end), - 'gbuf_local': module.Range(0, end - start)}}}]}] - optimizer.buffers = [SimpleNamespace(numel_unpadded=len(values), params=[model], - buckets=[SimpleNamespace(grad_data=torch.zeros(padded_numel), numel_unpadded=len(values))])] - chunk = torch.nn.Module() - chunk.register_parameter('weight', model) - engine = MegatronCoreTrainEngine.__new__(MegatronCoreTrainEngine) - engine.model, engine.optimizer = [chunk], optimizer - engine.optimizer_revision, engine.current_version = 3, 0 - engine.get_parallel_state = lambda: dict(train_tp=1, train_dp=world) - return engine, master, model - - -def _capture_core_shards(rank, rendezvous, directory, padded_extra): - from megatron.core.optimizer import distrib_optimizer as module - module.HAVE_APEX_OR_TE = False - torch.cuda.current_device = lambda: 'cpu' - dist.init_process_group('gloo', init_method=f'file://{rendezvous}', rank=rank, world_size=2, - timeout=timedelta(seconds=30)) - try: - engine, master, model = _engine(module, rank, 2, [1., 2., 3., 4.], padded_extra) - gradient = torch.tensor([.1, -.2, .3, -.4]) - width = (4 + padded_extra) // 2 - for _ in range(3): - master.grad = gradient[rank * width:rank * width + master.numel()].clone() - engine.optimizer.optimizer.step() - local = torch.zeros(width) - local[:master.numel()].copy_(master.detach()) - shards = [torch.empty_like(local) for _ in range(2)] - dist.all_gather(shards, local) - with torch.no_grad(): - model.copy_(torch.cat(shards)[:4]) - snapshot = engine.capture_elastic_state() - if rank == 0: - torch.save(snapshot, Path(directory) / 'core-dp0.pt') - else: - # MCore returns empty per-bucket metadata on followers, not full - # Adam/master tensors. Production canonicalizes all targets to dp0. - state = snapshot['distributed_optimizer']['state'] - assert not state[0][(torch.bfloat16, torch.bfloat16)] - finally: - dist.destroy_process_group() - - -@pytest.mark.parametrize('source_padding', [0, 2]) -def test_native_mcore_dp2_to_dp1_restores_full_master_moments_step_and_next_update(tmp_path, monkeypatch, source_padding): - module = pytest.importorskip( - 'megatron.core.optimizer.distrib_optimizer', - reason='native DP-zero resharding requires the pinned Megatron-Core source', - ) - monkeypatch.setattr(module, 'HAVE_APEX_OR_TE', False) - monkeypatch.setattr(torch.cuda, 'current_device', lambda: 'cpu') - mp.spawn(_capture_core_shards, args=(str(tmp_path / 'source-rendezvous'), str(tmp_path), source_padding), nprocs=2, join=True) - snapshot = torch.load(tmp_path / 'core-dp0.pt', weights_only=False) - dist.init_process_group('gloo', init_method=f'file://{tmp_path / "target-rendezvous"}', - rank=0, world_size=1, timeout=timedelta(seconds=30)) - try: - target, master, model = _engine(module, 0, 1, [-9.] * 4) - receipt = target.restore_elastic_state(snapshot) - assert receipt['acknowledged'] and receipt['optimizer_revision'] == 3 - reference = torch.nn.Parameter(torch.tensor([1., 2., 3., 4.])) - adam = torch.optim.AdamW([reference], lr=.01, betas=(.9, .95)) - for _ in range(3): - reference.grad = torch.tensor([.1, -.2, .3, -.4]) - adam.step() - torch.testing.assert_close(master, reference, rtol=0, atol=0) - torch.testing.assert_close(model, reference.bfloat16(), rtol=0, atol=0) - for key in ('step', 'exp_avg', 'exp_avg_sq'): - torch.testing.assert_close(target.optimizer.optimizer.state[master][key], - adam.state[reference][key], rtol=0, atol=0) - master.grad = torch.tensor([-.7, .4, .2, -.1]) - reference.grad = master.grad.clone() - target.optimizer.optimizer.step() - adam.step() - torch.testing.assert_close(master, reference, rtol=0, atol=0) - for key in ('step', 'exp_avg', 'exp_avg_sq'): - torch.testing.assert_close(target.optimizer.optimizer.state[master][key], - adam.state[reference][key], rtol=0, atol=0) - finally: - dist.destroy_process_group() diff --git a/tests/test_ehp_membership_release.py b/tests/test_ehp_membership_release.py deleted file mode 100644 index 7dffae0..0000000 --- a/tests/test_ehp_membership_release.py +++ /dev/null @@ -1,431 +0,0 @@ -"""CPU-only publication -> peer refresh -> training-source regression tests.""" - -import json -import threading -import time -from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout -from dataclasses import replace -from types import SimpleNamespace - -import pytest -import torch - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.engine.megatron_core_train_engine import MegatronCoreTrainEngine -from RL_Framework.infra.elastic.hybrid_pool import ( - ElasticHybridPool, - GradientPayload, - InterReplicaGradientDomain, - JoinCancelledError, -) -from RL_Framework.infra.elastic.runtime_executor import ( - RuntimeElasticExecutor, - RuntimeReconfigurationResult, -) -from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer -from RL_Framework.trainer import async_rl_trainer as trainer_module - - -@pytest.fixture -def make_harness(tmp_path): - pools = [] - - def make(run_id="run-a"): - config = AsyncRLConfig( - model_path="/unused", train_gpus=1, rollout_gpus=2, n_total_gpus=3, - train_tp_size=1, train_dp_size=1, batch_size=1, n_samples=1, - micro_batch_size=1, log_dir=str(tmp_path), - ) - cfg = config.global_resource_planner - cfg.enabled = True - cfg.hybrid_worker_task_dir = str(tmp_path / "tasks") - cfg.elastic_hybrid_min_rollout_gpus = 0 - pool = ElasticHybridPool( - core_train_workers=["dp0"], core_rollout_workers=["rollout0", "rollout1"], - zero_sync_steps=0, - ) - pools.append(pool) - executor = RuntimeElasticExecutor( - config=config, elastic_pool=pool, membership_run_id=run_id, - planner=SimpleNamespace(latest_runtime_metrics=SimpleNamespace(step=2)), - ) - engine = object.__new__(MegatronCoreTrainEngine) - engine.elastic_gradient_domain = InterReplicaGradientDomain(core_replica_ids=["dp0"]) - engine.get_data_parallel_rank = lambda: 0 - engine._pending_hybrid_gradients = [] - engine._hybrid_gradient_condition = threading.Condition() - engine._elastic_active_gradient_timeout_s = 0.05 - engine._elastic_step_hybrid_workers = () - engine.optimizer_revision = 0 - engine.current_version = 0 - engine._elastic_seen_payloads = set() - engine._elastic_batch_partition = None - engine._elastic_gradient_update_callback = None - engine._model_main_gradients = lambda: [torch.zeros(1)] - peer = object.__new__(AsyncRLTrainer) - peer.config = config - peer.train_engine = engine - peer._elastic_membership_run_id = run_id - peer._elastic_membership_epochs = {} - directory = tmp_path / "tasks" / "membership" - return SimpleNamespace( - config=config, pool=pool, executor=executor, peer=peer, engine=engine, - directory=directory, - ) - - yield make - for pool in pools: - pool.close() - - -def _installed(*args): - # No real model/worker in these membership-ordering tests. Simulate the - # successful installation receipt; the readiness suite verifies real files. - return {"acknowledged": True, "state_version": 0, "optimizer_revision": 0} - - -def activate(harness, replica="replica0", worker="rollout0"): - harness.pool.join_replica(replica, [worker], "dp0", replica_activation_barrier=_installed).result(timeout=3) - harness.executor.hybrid_runtime_state() - harness.peer._prepare_elastic_training_step(0) - - -def record(harness, replica="replica0"): - return json.loads((harness.directory / f"{replica}.json").read_text()) - - -def release(harness): - # Release-only maintenance: no PlannerDecision or runtime transaction. - harness.executor.accept_planner_signal({"step": 2, "desired_replicas": 0}) - - -def test_m1_release_publishes_exit_without_a_runtime_transaction(make_harness): - h = make_harness() - activate(h) - previous = record(h) - assert h.engine._elastic_step_hybrid_workers == ("replica0",) - - release(h) - # Do not call hybrid_runtime_state: release itself must publish the exit. - exited = record(h) - assert h.pool.gradient_domain.active_hybrid_ids() == () - assert exited["role"] == "hybrid_rollout" - assert exited["membership_epoch"] > previous["membership_epoch"] - assert exited["run_id"] == "run-a" - h.peer._refresh_nonblocking_elastic_membership() - assert h.engine.elastic_gradient_domain.active_hybrid_ids() == () - assert not (h.executor._coordination_dir() / "request.json").exists() - - -def test_m2_stale_training_record_cannot_undo_consumed_exit(make_harness): - h = make_harness() - activate(h) - stale = record(h) - release(h) - h.peer._prepare_elastic_training_step(1) - exit_epoch = h.peer._elastic_membership_epochs["replica0"] - - (h.directory / "replica0.json").write_text(json.dumps(stale)) - assert h.peer._prepare_elastic_training_step(2) == [] - assert h.peer._elastic_membership_epochs["replica0"] == exit_epoch - h.executor.hybrid_runtime_state() - assert record(h)["role"] == "hybrid_rollout" - - -def test_m3_pre_refresh_precedes_freezing_gradient_sources(make_harness, monkeypatch): - h = make_harness() - activate(h) - release(h) - frozen = [] - original = h.engine.set_elastic_training_step - - def set_step(step, sources): - assert h.engine.elastic_gradient_domain.active_hybrid_ids() == () - frozen.append((step, tuple(sources))) - original(step, sources) - - monkeypatch.setattr(h.engine, "set_elastic_training_step", set_step) - assert h.peer._prepare_elastic_training_step(1) == [] - assert frozen == [(1, ())] - - -def test_m4_original_probe_no_longer_waits_for_released_gradient(make_harness): - h = make_harness() - activate(h) - # The real wait path would reject the still-active source without a payload. - with pytest.raises(TimeoutError, match="missing=.*replica0"): - h.engine._apply_elastic_inter_replica_gradients() - release(h) - assert h.peer._prepare_elastic_training_step(1) == [] - h.engine._apply_elastic_inter_replica_gradients() - - -@pytest.mark.parametrize("replica", [True, False], ids=["replica", "singleton"]) -@pytest.mark.parametrize("rejoin", [False, True], ids=["released", "new-generation"]) -def test_m5_cancelled_join_cannot_republish_active_membership(make_harness, replica, rejoin): - h = make_harness() - entered, resume = threading.Event(), threading.Event() - - def activating(*args): - entered.set() - assert resume.wait(3), "test did not release activation" - - worker = "replica0" if replica else "rollout0" - if replica: - handle = h.pool.join_replica( - worker, ["rollout0"], "dp0", replica_activation_barrier=activating, - ) - else: - handle = h.pool.join_training("rollout0", "dp0", activation_barrier=activating) - try: - assert entered.wait(3) - h.executor._pending_hybrid_joins[worker] = handle - h.executor._pending_hybrid_join_started_at[worker] = time.time() - h.executor.hybrid_runtime_state() - release(h) - assert h.pool.snapshot()["rollout0"].transition_generation == handle.generation + 1 - exit_record = record(h, worker) - if rejoin: - if replica: - newer = h.pool.join_replica(worker, ["rollout0"], "dp0", replica_activation_barrier=_installed) - else: - newer = h.pool.join_training(worker, "dp0", activation_barrier=_installed) - newer.result(timeout=3) - h.executor.hybrid_runtime_state() - expected_record = record(h, worker) - assert expected_record["membership_epoch"] > exit_record["membership_epoch"] - else: - expected_record = exit_record - resume.set() - with pytest.raises(JoinCancelledError): - handle.result(timeout=3) - h.executor.hybrid_runtime_state() - assert record(h, worker) == expected_record - assert h.pool.gradient_domain.attached_hybrid_ids() == ((worker,) if rejoin else ()) - assert h.peer._prepare_elastic_training_step(1) == ([worker] if rejoin else []) - finally: - resume.set() - try: - handle.result(timeout=3) - except JoinCancelledError: - pass - - -@pytest.mark.parametrize("replica", [True, False], ids=["replica", "singleton"]) -def test_activation_and_release_commit_membership_and_role_atomically(make_harness, monkeypatch, replica): - h = make_harness() - marked, resume = threading.Event(), threading.Event() - mark_active = h.pool.gradient_domain.mark_active - - def pause_after_domain_activation(worker): - mark_active(worker) - marked.set() - assert resume.wait(3) - - monkeypatch.setattr(h.pool.gradient_domain, "mark_active", pause_after_domain_activation) - worker = "replica0" if replica else "rollout0" - if replica: - handle = h.pool.join_replica(worker, ["rollout0"], "dp0", replica_activation_barrier=_installed) - else: - handle = h.pool.join_training(worker, "dp0", activation_barrier=_installed) - h.executor._pending_hybrid_joins[worker] = handle - h.executor._pending_hybrid_join_started_at[worker] = time.time() - with ThreadPoolExecutor(max_workers=1) as workers: - try: - assert marked.wait(3) - releasing = workers.submit(release, h) - # Cancellation must not split domain activation from the matching - # worker-role update. With the old gap it completed in this window. - try: - releasing.result(timeout=0.1) - except FutureTimeout: - pass - finally: - resume.set() - handle.result(timeout=3) - releasing.result(timeout=3) - assert h.pool.snapshot()["rollout0"].role.value == "hybrid_rollout" - assert h.pool.gradient_domain.active_hybrid_ids() == () - assert h.peer._prepare_elastic_training_step(1) == [] - - -def test_m6_repeated_release_is_idempotent(make_harness): - h = make_harness() - activate(h) - release(h) - first = record(h) - release(h) - h.executor.hybrid_runtime_state() - assert record(h) == first - assert h.peer._prepare_elastic_training_step(1) == [] - - -@pytest.mark.parametrize("legacy", [False, True], ids=["old-run", "unversioned-run"]) -def test_m7_old_run_files_do_not_pollute_reused_directory(make_harness, legacy): - old = make_harness("old-run") - activate(old) - if legacy: - state = record(old) - state.pop("run_id") - (old.directory / "replica0.json").write_text(json.dumps(state)) - new = make_harness("new-run") - assert new.peer._prepare_elastic_training_step(0) == [] - activate(new) - assert new.engine._elastic_step_hybrid_workers == ("replica0",) - assert record(new)["run_id"] == "new-run" - - -def test_m8_publication_failure_is_fatal(make_harness, monkeypatch): - h = make_harness() - activate(h) - - def fail(*args): - raise OSError("simulated shared filesystem failure") - - monkeypatch.setattr(h.executor, "_write_json_atomic", fail) - with pytest.raises(RuntimeError, match="failed to publish EHP membership for replica0"): - release(h) - assert h.pool.gradient_domain.active_hybrid_ids() == () - # The error cannot be swallowed: peers would otherwise retain this state. - assert record(h)["role"] == "hybrid_training" - - -def test_m9_active_replica_retains_its_membership_epoch(make_harness): - h = make_harness() - activate(h) - original = record(h) - h.executor.accept_planner_signal({"step": 2, "desired_replicas": 1}) - h.executor.hybrid_runtime_state() - assert h.peer._prepare_elastic_training_step(1) == ["replica0"] - assert record(h) == original - assert h.engine.elastic_gradient_domain.membership_state()["membership_epochs"]["replica0"] == original["membership_epoch"] - - -def test_1913443_reapplied_runtime_state_restores_step10_gradient_epochs(make_harness, monkeypatch): - h = make_harness("13f79e4cac264319b6f1897c204e5e9a") - epochs = {"ehp_replica_rollout2": 4, "ehp_replica_rollout4": 3} - h.directory.mkdir(parents=True, exist_ok=True) - for replica, epoch in epochs.items(): - (h.directory / f"{replica}.json").write_text(json.dumps(dict( - worker_id=replica, target_core_id="dp0", role="hybrid_training", - membership_epoch=epoch, run_id=h.peer._elastic_membership_run_id))) - h.engine.rank, h.engine.train_tp_size = 1, 2 - h.engine.train_pp_size = h.engine.train_cp_size = 1 - # Keep the real domain construction; this CPU reproduction has no NCCL group. - monkeypatch.setattr(h.engine, "initialize_elastic_communication_domain", lambda: None) - monkeypatch.setattr(h.engine, "_elastic_communication_domains", lambda: None) - h.engine.optimizer_revision = 9 - h.peer._prepare_elastic_training_step(9) - assert h.peer._elastic_membership_epochs == epochs - - # Consumed fields from job 1913443 applied coord b52a821b43da4ede8df73729a93a78bb. - h.peer._apply_training_reconfiguration_state(dict( - enabled=True, plan_only=False, core_replica_ids=["dp0"], - hybrid_targets={replica: "dp0" for replica in epochs}, - active_hybrid_ids=list(epochs), activate_hybrids=True)) - h.engine.optimizer_revision = 10 - h.peer._prepare_elastic_training_step(10) - h.engine.set_elastic_batch_partition(8, 16, {replica: 4 for replica in epochs}) - - assert h.engine.elastic_gradient_domain.membership_state()["membership_epochs"] == epochs - payloads = [GradientPayload( - replica_id=replica, target_core_id="dp0", tensors=(torch.ones(1),), - replica_rank=1, replica_world_size=2, step=10, state_version=10, - membership_epoch=epoch, sample_count=4, global_sample_count=16) - for replica, epoch in epochs.items()] - with pytest.raises(ValueError, match="membership epoch"): - h.engine.enqueue_hybrid_gradient_payload(replace(payloads[0], membership_epoch=2)) - for payload in payloads: - h.engine.enqueue_hybrid_gradient_payload(payload) - assert {payload.replica_id for payload in h.engine._pending_hybrid_gradients} == set(epochs) - - -def test_m10_partial_release_preserves_other_replica(make_harness, monkeypatch): - h = make_harness() - activate(h) - activate(h, "replica1", "rollout1") - preserved = record(h, "replica1") - h.executor._active_elastic_signal = {"step": 2, "desired_replicas": 1} - monkeypatch.setattr(h.executor, "_training_reconfiguration_targets", - lambda *args: (["dp0"], "dp0", ["rollout0", "rollout1"])) - h.executor._reconfigure_training_pool( - 1, SimpleNamespace(train_gpus=2), RuntimeReconfigurationResult(False, "test"), - ) - assert record(h)["role"] == "hybrid_rollout" - assert record(h, "replica1") == preserved - assert h.peer._prepare_elastic_training_step(1) == ["replica1"] - - -def test_release_serializes_with_delayed_membership_publication(make_harness, monkeypatch): - h = make_harness() - activate(h) - publishing, detached, resume = threading.Event(), threading.Event(), threading.Event() - write = h.executor._write_json_atomic - detach = h.pool.release_replica_to_rollout - - def delayed_write(path, payload): - if payload["role"] == "hybrid_training": - publishing.set() - assert resume.wait(3) - write(path, payload) - - def release_replica(replica_id): - detach(replica_id) - detached.set() - - monkeypatch.setattr(h.executor, "_write_json_atomic", delayed_write) - monkeypatch.setattr(h.pool, "release_replica_to_rollout", release_replica) - with ThreadPoolExecutor(max_workers=2) as workers: - try: - observer = workers.submit(h.executor._publish_hybrid_membership) - assert publishing.wait(3) - releasing = workers.submit(release, h) - assert detached.wait(3) - finally: - resume.set() - observer.result(timeout=3) - releasing.result(timeout=3) - assert record(h)["role"] == "hybrid_rollout" - assert h.peer._prepare_elastic_training_step(1) == [] - - -def test_setup_reuses_existing_barrier_for_fresh_membership_session(make_harness, monkeypatch): - leader = make_harness().peer - peer = make_harness().peer - barrier = threading.Barrier(2, timeout=3) - barrier_calls = [] - - class Server: - def __init__(self, **kwargs): - pass - - def start(self): - return SimpleNamespace(to_dict=lambda: {"host": "fake", "port": 1}) - - def synchronize(): - barrier_calls.append(1) - barrier.wait() - - monkeypatch.setattr(trainer_module, "ElasticGradientServer", Server) - monkeypatch.setattr(trainer_module.dist, "is_initialized", lambda: True) - monkeypatch.setattr(trainer_module.dist, "barrier", synchronize) - for rank, trainer in enumerate((leader, peer)): - trainer.rank = rank - trainer.is_main_process = rank == 0 - trainer.runtime_elastic_executor = None - trainer.config.global_resource_planner.hybrid_worker_launch_enabled = True - engine = trainer.train_engine - engine.configure_elastic_training = lambda *a, _engine=engine, **kw: _engine.elastic_gradient_domain - engine.get_elastic_core_replica_ids = lambda: ["dp0"] - engine.get_elastic_lane_state = lambda: {} - - identities = [] - with ThreadPoolExecutor(max_workers=2) as workers: - for _ in range(2): - tasks = [workers.submit(t._init_nonblocking_elastic_core) for t in (leader, peer)] - for task in tasks: - task.result(timeout=4) - assert leader._elastic_membership_run_id == peer._elastic_membership_run_id - identities.append(leader._elastic_membership_run_id) - assert identities[0] != identities[1] - assert len(barrier_calls) == 4 # One existing setup barrier per rank per run. diff --git a/tests/test_ehp_readiness_stop.py b/tests/test_ehp_readiness_stop.py deleted file mode 100644 index 7269308..0000000 --- a/tests/test_ehp_readiness_stop.py +++ /dev/null @@ -1,257 +0,0 @@ -from contextlib import nullcontext -import json -from pathlib import Path -from types import SimpleNamespace -import subprocess -import threading -import time - -import pytest - -from RL_Framework.infra.elastic.readiness import clear_ready_receipts, read_ready_receipts, snapshot_contract -from RL_Framework.infra.elastic.runtime_executor import ( - ManagedHybridWorkerProcess, ManagedRolloutProcess, RuntimeElasticExecutor, -) - - -def _executor(tmp_path, **options): - engine = RuntimeElasticExecutor.__new__(RuntimeElasticExecutor) - cfg = dict(hybrid_worker_task_dir=str(tmp_path), hybrid_worker_remote_control_dir=str(tmp_path), - hybrid_worker_ready_timeout_s=.15, hybrid_worker_stop_timeout_s=.15, - hybrid_worker_remote_control_enabled=False, vllm_stop_timeout_s=.1, - vllm_stop_command_template='stop {instance_id}') - cfg.update(options) - engine.config = SimpleNamespace(global_resource_planner=SimpleNamespace(**cfg)) - engine._hybrid_worker_meta = {} - engine._hybrid_worker_processes = {} - engine._hybrid_task_contexts = {} - engine._closing = threading.Event() - engine._lifecycle_lock = threading.RLock() - engine._hybrid_resource_guard = lambda *args, **kwargs: nullcontext() - return engine - - -def _manifest(tmp_path): - path = tmp_path / 'snapshot.json' - path.write_text(json.dumps({'format': 'libra-ehp-lanes-v1', 'optimizer_revision': 9, - 'snapshot_id': 'actual-boundary', 'lanes': {'dp1': {'0': 'ehp://a', '1': 'ehp://b'}}})) - return str(path) - - -def _ready(tmp_path, snapshot, lane_rank, **overrides): - fields = dict(snapshot=snapshot, snapshot_id='actual-boundary', lane_snapshot_id=f'lane-{lane_rank}', - acknowledged='True', state_version=9, optimizer_revision=9, target_core_id='dp1', - rank=lane_rank, pid=123 + lane_rank, source_uri='ehp://a' if lane_rank == 0 else 'ehp://b') - fields.update(overrides) - (tmp_path / f'h.rank_{lane_rank}.ready').write_text(''.join(f'{key}={value}\n' for key, value in fields.items())) - - -def test_requires_every_model_lane_and_rejects_generic_virtual_ready(tmp_path): - snapshot = _manifest(tmp_path) - engine = _executor(tmp_path) - (tmp_path / 'h.ready').write_text('ready') - _ready(tmp_path, snapshot, 0) - with pytest.raises(TimeoutError, match='all 2 lanes'): - engine._wait_hybrid_worker_ready('h', state_version=9, replica_world_size=2, - snapshot_path=snapshot, target_core_id='dp1') - _ready(tmp_path, snapshot, 1) - receipt = engine._wait_hybrid_worker_ready('h', state_version=9, replica_world_size=2, - snapshot_path=snapshot, target_core_id='dp1') - assert receipt['acknowledged'] and len(receipt['rank_receipts']) == 2 - - -@pytest.mark.parametrize('change', [dict(snapshot_id='previous-boundary'), dict(optimizer_revision=8), - dict(state_version=8), dict(rank=5), dict(acknowledged='False'), - dict(target_core_id='dp0'), dict(lane_snapshot_id=''), - dict(source_uri='ehp://wrong-lane'), dict(pid=123)]) -def test_stale_or_wrong_lane_receipt_cannot_release_activation(tmp_path, change): - snapshot = _manifest(tmp_path) - contract = snapshot_contract(snapshot, state_version=9, target_core_id='dp1') - _ready(tmp_path, snapshot, 0) - _ready(tmp_path, snapshot, 1, **change) - assert read_ready_receipts(tmp_path, 'h', 2, contract) is None - - -def test_timeout_zero_waits_for_actual_replacement_ack(tmp_path): - snapshot = _manifest(tmp_path) - engine = _executor(tmp_path, hybrid_worker_ready_timeout_s=0) - _ready(tmp_path, snapshot, 0, snapshot_id='old') - result = [] - worker = threading.Thread(target=lambda: result.append(engine._wait_hybrid_worker_ready( - 'h', state_version=9, replica_world_size=1, snapshot_path=snapshot, target_core_id='dp1'))) - worker.start() - time.sleep(.06) - assert worker.is_alive() and not result - _ready(tmp_path, snapshot, 0) - worker.join(2) - assert not worker.is_alive() - assert result[0]['optimizer_revision'] == 9 - - -def test_clear_ready_before_restart_removes_same_snapshot_files(tmp_path): - snapshot = _manifest(tmp_path) - _ready(tmp_path, snapshot, 0) - (tmp_path / 'h.ready').write_text('old') - clear_ready_receipts(tmp_path, 'h') - assert not list(tmp_path.glob('*.ready')) - - -def test_singleton_activation_returns_boundary_approved_receipt(tmp_path): - engine = _executor(tmp_path) - snapshot = _manifest(tmp_path) - engine._snapshot_path_for_version = lambda version: snapshot - engine._cluster_swap_training_slot = lambda worker: {} - engine._is_hybrid_worker_running = lambda worker: True - engine._hybrid_worker_meta['h'] = ManagedHybridWorkerProcess('h', 'dp1', 'existing', 1, snapshot, replica_id='h') - initial = {'acknowledged': True, 'optimizer_revision': 9, 'state_version': 9} - approved = dict(initial, optimizer_revision=10, state_version=10) - engine._wait_hybrid_worker_ready = lambda *args, **kwargs: initial - queued = [] - engine._queue_activation = lambda replica, receipt: queued.append((replica, receipt)) or approved - result = engine._activate_hybrid_worker('h', 'dp1', 9) - assert result is approved and queued == [('h', initial)] - - -def test_remote_stop_retains_ownership_until_matching_exit_ack_and_ignores_stale_done(tmp_path): - engine = _executor(tmp_path, hybrid_worker_remote_control_enabled=True, hybrid_worker_stop_timeout_s=0) - meta = ManagedHybridWorkerProcess('h', 'dp1', 'remote', 1234, 'state', host='node') - engine._hybrid_worker_meta = {'h': meta, 'member': meta} - (tmp_path / '.stop_h.done').write_text(json.dumps({'request_id': 'stale', 'worker_id': 'h', 'exited': True})) - observed = [] - def controller(): - deadline = time.monotonic() + 2 - while not (tmp_path / '.stop_h.json').exists() and time.monotonic() < deadline: - time.sleep(.01) - request = json.loads((tmp_path / '.stop_h.json').read_text()) - observed.append(request) - assert engine._hybrid_worker_meta['h'] is meta - time.sleep(.05) - (tmp_path / '.stop_h.done').write_text(json.dumps(dict(request, exited=True))) - thread = threading.Thread(target=controller) - thread.start() - engine._stop_hybrid_worker_process('member') - thread.join(2) - assert observed[0]['request_id'] != 'stale' - assert not engine._hybrid_worker_meta - - -def test_stop_timeout_keeps_ownership_and_retry_uses_same_request(tmp_path): - engine = _executor(tmp_path, hybrid_worker_remote_control_enabled=True) - meta = ManagedHybridWorkerProcess('h', 'dp1', 'remote', 1234, 'state', host='node') - engine._hybrid_worker_meta['h'] = meta - with pytest.raises(TimeoutError): - engine._stop_hybrid_worker_process('h') - assert engine._hybrid_worker_meta['h'] is meta - request = json.loads((tmp_path / '.stop_h.json').read_text()) - (tmp_path / '.stop_h.done').write_text(json.dumps(dict(request, exited=True))) - engine._stop_hybrid_worker_process('h') - assert meta.stop_request_id == request['request_id'] - assert not engine._hybrid_worker_meta - - -@pytest.mark.parametrize('timeout', [False, True]) -def test_external_rollout_stop_failure_propagates(tmp_path, monkeypatch, timeout): - engine = _executor(tmp_path, vllm_stop_timeout_s=0) - meta = ManagedRolloutProcess('engine', 'command', 1, [0], 8000, log_path=str(tmp_path / 'stop.log')) - def run(*args, **kwargs): - assert kwargs['timeout'] is None - if timeout: - raise subprocess.TimeoutExpired('stop', 1) - return SimpleNamespace(returncode=17) - monkeypatch.setattr(subprocess, 'run', run) - with pytest.raises(TimeoutError if timeout else RuntimeError): - engine._run_external_stop(meta) - - -def test_local_stop_waits_for_launcher_and_child_processes(): - import sys - from RL_Framework.infra.elastic.process_lifecycle import _live_group_members, stop_local_worker - script = "import subprocess,sys,time; child=subprocess.Popen([sys.executable,'-c','import time;time.sleep(60)']); print(child.pid,flush=True); time.sleep(60)" - proc = subprocess.Popen([sys.executable, '-c', script], stdout=subprocess.PIPE, text=True, start_new_session=True) - try: - child_pid = int(proc.stdout.readline()) - assert child_pid in _live_group_members(proc.pid) - stop_local_worker(proc, timeout=1) - assert proc.poll() is not None - assert _live_group_members(proc.pid) == [] - finally: - if proc.poll() is None: - proc.kill() - proc.wait() - - -def test_hybrid_factory_installs_the_shared_bounded_tp_logprob_kernel(monkeypatch): - import torch - from RL_Framework.config import AsyncRLConfig - from RL_Framework.engine import train_factory - from RL_Framework.engine import logprob_compat - from RL_Framework.scripts.elastic_hybrid_worker import _initialize_megatron_worker - calls = [] - config = SimpleNamespace(train_backend='megatron_core', max_seq_length=32768, - global_resource_planner=SimpleNamespace(hybrid_lockstep_gradient_sync=True)) - engine = SimpleNamespace(initialize=lambda **kwargs: calls.append(('initialize', kwargs)), - prepare_elastic_gradient_communication=lambda: calls.append('prepare'), - world_size=1, get_parallel_state=lambda: dict(train_tp=1, train_pp=1, train_cp=1, train_ep=1, train_dp=1)) - monkeypatch.setattr(AsyncRLConfig, 'from_yaml', lambda path: config) - monkeypatch.setattr(train_factory, 'create_train_engine', lambda cfg: engine) - monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) - monkeypatch.setattr(torch.cuda, 'set_device', lambda device: None) - monkeypatch.setattr(logprob_compat, 'install', lambda target: calls.append(('bounded_logprob', target))) - result = _initialize_megatron_worker(SimpleNamespace(config='current-config.yaml', initialize_only=True)) - assert result is engine - assert calls == [('initialize', {'max_seq_length': 32768}), ('bounded_logprob', engine), 'prepare'] - - -def test_hybrid_factory_partitions_core_dp2_into_one_complete_model_replica(monkeypatch): - import torch - from RL_Framework.config import AsyncRLConfig - from RL_Framework.engine import train_factory - from RL_Framework.engine import logprob_compat - from RL_Framework.scripts.elastic_hybrid_worker import _initialize_megatron_worker - config = SimpleNamespace(train_backend='megatron_core', max_seq_length=32768, - train_tp_size=2, train_pp_size=1, train_cp_size=1, train_ep_size=1, - train_dp_size=2, train_gpus=4, micro_batch_size=1, learning_rate=1e-6, - global_resource_planner=SimpleNamespace(hybrid_lockstep_gradient_sync=True)) - observed = [] - engine = SimpleNamespace(initialize=lambda **kwargs: None, world_size=2, - prepare_elastic_gradient_communication=lambda: 1, - get_parallel_state=lambda: dict(train_tp=2, train_pp=1, train_cp=1, train_ep=1, train_dp=1)) - def factory(cfg): - observed.append((cfg.train_tp_size, cfg.train_dp_size, cfg.train_gpus, cfg.learning_rate)) - return engine - monkeypatch.setattr(AsyncRLConfig, 'from_yaml', lambda path: config) - monkeypatch.setattr(train_factory, 'create_train_engine', factory) - monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) - monkeypatch.setattr(torch.cuda, 'set_device', lambda device: None) - monkeypatch.setattr(logprob_compat, 'install', lambda target: None) - monkeypatch.setenv('WORLD_SIZE', '2') - result = _initialize_megatron_worker(SimpleNamespace(config='current-core-config.yaml', initialize_only=True)) - assert result is engine - assert observed == [(2, 1, 2, 1e-6)] - monkeypatch.setenv('WORLD_SIZE', '4') - with pytest.raises(ValueError, match='one complete model replica'): - _initialize_megatron_worker(SimpleNamespace(config='current-core-config.yaml', initialize_only=True)) - - -def test_remote_member_alias_stops_actual_replica_controller_key(tmp_path, monkeypatch): - from RL_Framework.infra.elastic import rollout_lending - engine = _executor(tmp_path, hybrid_worker_remote_control_enabled=True) - canonical = ManagedHybridWorkerProcess('replica0', 'dp1', 'remote group', 1234, 'state', host='node') - engine._hybrid_worker_meta['replica0'] = canonical - for rank in range(2): - worker = f'rollout{rank}' - engine._hybrid_worker_meta[worker] = ManagedHybridWorkerProcess( - worker, 'dp1', 'remote group', -1, 'state', host='node', replica_id='replica0', replica_rank=rank, - replica_world_size=2, - ) - stopped = [] - def acknowledge(executor, worker, request_id=None): - stopped.append(worker) - assert len(executor._hybrid_worker_meta) == 3 - return {'worker_id': worker, 'request_id': request_id, 'exited': True} - monkeypatch.setattr(rollout_lending, 'wait_hybrid_stopped', acknowledge) - engine._stop_hybrid_worker_process('rollout1') - assert stopped == ['replica0'] - assert (tmp_path / '.stop_replica0.json').exists() - assert not (tmp_path / '.stop_rollout1.json').exists() - assert not engine._hybrid_worker_meta diff --git a/tests/test_elastic_cross_process_worker.py b/tests/test_elastic_cross_process_worker.py deleted file mode 100644 index b58929c..0000000 --- a/tests/test_elastic_cross_process_worker.py +++ /dev/null @@ -1,81 +0,0 @@ -import subprocess -import sys -import time -from pathlib import Path - -import torch - -from RL_Framework.engine.train_engine import FSDPTrainEngine -from RL_Framework.infra.elastic.gradient_ipc import ElasticGradientServer - - -def test_cross_process_hybrid_worker_sends_gradient_payload(tmp_path, monkeypatch): - monkeypatch.setenv("ELASTIC_TRAINING_STATE_DIR", str(tmp_path / "state")) - engine = FSDPTrainEngine(model_path="unused") - engine.model = torch.nn.Linear(2, 1) - engine.optimizer = torch.optim.SGD(engine.model.parameters(), lr=0.1) - engine.world_size = 1 - engine.rank = 0 - engine.current_version = 5 - domain = engine.configure_elastic_training(["dp0"]) - domain.request_join("hybrid0", "dp0") - domain.mark_active("hybrid0") - - snapshot_version = engine.capture_elastic_state_snapshot("hybrid0", "dp0") - snapshot_path = engine.get_elastic_state_snapshot_path(snapshot_version) - payload_file = tmp_path / "payload.pt" - params = list(engine.model.parameters()) - torch.save( - { - "replica_id": "hybrid0", - "target_core_id": "dp0", - "tensors": tuple(torch.full_like(p, 2.0) for p in params), - }, - payload_file, - ) - - server = ElasticGradientServer( - host="127.0.0.1", - port=0, - authkey="secret", - on_payload=engine.enqueue_hybrid_gradient_payload, - ) - endpoint = server.start() - try: - script = Path(__file__).resolve().parents[1] / "scripts" / "elastic_hybrid_worker.py" - subprocess.run( - [ - sys.executable, - str(script), - "--worker-id", - "hybrid0", - "--target-core-id", - "dp0", - "--snapshot-path", - snapshot_path, - "--gradient-host", - endpoint.host, - "--gradient-port", - str(endpoint.port), - "--authkey", - endpoint.authkey, - "--payload-file", - str(payload_file), - ], - check=True, - cwd=str(Path(__file__).resolve().parents[1]), - ) - - deadline = time.time() + 5 - while server.received_count < 1 and time.time() < deadline: - time.sleep(0.05) - - for param in params: - param.grad = torch.ones_like(param) - engine._apply_elastic_inter_replica_gradients() - - assert server.received_count == 1 - for param in params: - assert torch.allclose(param.grad, torch.full_like(param.grad, 3.0)) - finally: - server.close() diff --git a/tests/test_elastic_gradient_idle_path.py b/tests/test_elastic_gradient_idle_path.py deleted file mode 100644 index ca345c7..0000000 --- a/tests/test_elastic_gradient_idle_path.py +++ /dev/null @@ -1,81 +0,0 @@ -from types import SimpleNamespace -import threading - -import torch - -from RL_Framework.engine.megatron_core_train_engine import MegatronCoreTrainEngine -from RL_Framework.engine.megatron_train_engine import Megatron3DTrainEngine -from RL_Framework.engine.train_engine import FSDPTrainEngine -from RL_Framework.infra.elastic.hybrid_pool import GradientPayload, InterReplicaGradientDomain - - -class _UnexpectedReduce: - def reduce_core_gradients(self, **_kwargs): - raise AssertionError("elastic reduce must not run without a hybrid payload") - - -def test_mcore_skips_elastic_collective_when_domain_is_not_configured(): - engine = object.__new__(MegatronCoreTrainEngine) - engine.elastic_gradient_domain = None - engine._pending_hybrid_gradients = [] - - engine._apply_elastic_inter_replica_gradients() - - -def test_mcore_dp1_reuses_main_gradient_for_weighted_hybrid_update(): - domain = InterReplicaGradientDomain(core_replica_ids=['dp0']) - domain.request_join('hybrid', 'dp0', membership_epoch=1) - domain.mark_active('hybrid', membership_epoch=1) - engine = object.__new__(MegatronCoreTrainEngine) - engine.elastic_gradient_domain = domain - engine._pending_hybrid_gradients = [GradientPayload( - 'hybrid', 'dp0', (torch.full((73,), 7.),), - step=3, state_version=2, membership_epoch=1, - sample_count=2, global_sample_count=4, - )] - engine._elastic_step_hybrid_workers = ('hybrid',) - engine._elastic_active_gradient_timeout_s = 0 - engine._hybrid_gradient_condition = threading.Condition() - engine._elastic_batch_partition = (2, 4, {'hybrid': 2}) - engine._elastic_training_step = 3 - engine._elastic_expected_state_version = 2 - # This is the already weighted, finalized Core contribution. Passing it - # through an out-of-place divide-by-one would waste a full model buffer. - grad = torch.full((73,), 3.) - engine._model_main_gradients = lambda: [grad] - engine.get_data_parallel_rank = lambda: 0 - reduce = domain.reduce_core_gradients - - def checked_reduce(**kwargs): - assert kwargs['in_place'] is True - assert kwargs['core_gradients']['dp0'][0].data_ptr() == grad.data_ptr() - return reduce(**kwargs) - - domain.reduce_core_gradients = checked_reduce - acknowledgements = [] - engine._elastic_gradient_update_callback = acknowledgements.append - engine._apply_elastic_inter_replica_gradients() - assert torch.equal(grad, torch.full((73,), 6.5)) - assert not engine._pending_hybrid_gradients - assert len(acknowledgements) == 1 - assert acknowledgements[0].tensors[0].data_ptr() != grad.data_ptr() - assert acknowledgements[0].state_version == 3 - grad.zero_() - assert torch.equal(acknowledgements[0].tensors[0], torch.full((73,), 6.5)) - - -def test_megatron3d_skips_elastic_collective_without_hybrid_payload(): - engine = object.__new__(Megatron3DTrainEngine) - engine.elastic_gradient_domain = _UnexpectedReduce() - engine.runtime = SimpleNamespace() - engine._pending_hybrid_gradients = [] - - engine._apply_elastic_inter_replica_gradients() - - -def test_fsdp_skips_elastic_collective_without_hybrid_payload(): - engine = object.__new__(FSDPTrainEngine) - engine.elastic_gradient_domain = _UnexpectedReduce() - engine._pending_hybrid_gradients = [] - - engine._apply_elastic_inter_replica_gradients() diff --git a/tests/test_elastic_optimizer_state.py b/tests/test_elastic_optimizer_state.py deleted file mode 100644 index 8c7a689..0000000 --- a/tests/test_elastic_optimizer_state.py +++ /dev/null @@ -1,132 +0,0 @@ -"""Native master/moment/step restoration at an elastic boundary.""" -import pytest -import torch -import torch.distributed as dist -from RL_Framework.engine.megatron_core_train_engine import MegatronCoreTrainEngine - - -def test_chained_distributed_optimizer_snapshot_includes_actual_master_and_adam_tensors(): - from types import SimpleNamespace - class DistributedChild: - data_parallel_group_gloo = object() - def __init__(self, value): - self.state = {'param': torch.tensor([value]), 'exp_avg': torch.tensor([value + 1]), - 'exp_avg_sq': torch.tensor([value + 2]), 'step': torch.tensor(9)} - def get_parameter_state_dp_zero(self): - return self.state - def load_parameter_state_from_dp_zero(self, state): - self.state = state - source = SimpleNamespace(chained_optimizers=[DistributedChild(1.), DistributedChild(3.)]) - target = SimpleNamespace(chained_optimizers=[DistributedChild(0.), DistributedChild(0.)]) - payload = MegatronCoreTrainEngine._clone_cpu_state(MegatronCoreTrainEngine._capture_optimizer_parameter_state(source)) - source.chained_optimizers[0].state['param'].add_(100) - MegatronCoreTrainEngine._restore_optimizer_parameter_state(target, payload) - assert target.chained_optimizers[0].state['param'].item() == 1. - assert target.chained_optimizers[1].state['exp_avg_sq'].item() == 5. - assert target.chained_optimizers[1].state['step'].item() == 9 - - - -def test_receiving_dp_root_rejects_nonroot_source_missing_adam_and_accepts_canonical_dp0(): - from types import SimpleNamespace - loaded = [] - target = SimpleNamespace(data_parallel_group_gloo=SimpleNamespace(rank=lambda: 0), - load_parameter_state_from_dp_zero=loaded.append) - with pytest.raises(ValueError, match='master parameters and Adam'): - MegatronCoreTrainEngine._restore_optimizer_parameter_state(target, {'kind': 'dp_zero', 'state': None}) - assert not loaded - canonical = {'param': torch.tensor([2.]), 'exp_avg': torch.tensor([.2]), 'exp_avg_sq': torch.tensor([.02])} - MegatronCoreTrainEngine._restore_optimizer_parameter_state(target, {'kind': 'dp_zero', 'state': canonical}) - assert loaded == [canonical] - - - -def test_actual_mcore_dp_zero_restore_preserves_step_master_moments_and_removes_adapter(tmp_path, monkeypatch): - from types import SimpleNamespace - module = pytest.importorskip('megatron.core.optimizer.distrib_optimizer') - monkeypatch.setattr(module, 'HAVE_APEX_OR_TE', False) - monkeypatch.setattr(torch.cuda, 'current_device', lambda: 'cpu') - # The production initialization may already have installed its global - # ordinary-checkpoint compatibility wrapper. Isolate the real native setter - # for the negative reproduction, then restore that wrapper before the EHP - # installation to verify that the scoped context can coexist with it. - existing_setter = module.DistributedOptimizer._set_main_param_and_optimizer_states - native_setter = existing_setter - if getattr(native_setter, '_rl_framework_step_compat', False): - closure = dict(zip(native_setter.__code__.co_freevars, - (cell.cell_contents for cell in native_setter.__closure__))) - native_setter = closure['original_set_state'] - monkeypatch.setattr(module.DistributedOptimizer, '_set_main_param_and_optimizer_states', native_setter) - assert not dist.is_initialized() - dist.init_process_group('gloo', init_method=f'file://{tmp_path / "dp-zero-rendezvous"}', rank=0, world_size=1) - try: - def engine(values): - master = torch.nn.Parameter(torch.tensor(values, dtype=torch.float32), requires_grad=False) - model = torch.nn.Parameter(master.detach().bfloat16().clone()) - inner = torch.optim.AdamW([{ - 'params': [master], 'wd_mult': 1., 'lr_mult': 1., - 'is_expert_parallel': False, 'is_decoupled_lr': False, - }], lr=.01, betas=(.9, .95)) - optimizer = module.DistributedOptimizer.__new__(module.DistributedOptimizer) - optimizer.optimizer = inner - optimizer.ddp_config = SimpleNamespace(use_megatron_fsdp=False) - optimizer.config = SimpleNamespace( - exp_avg_dtype=torch.float32, exp_avg_sq_dtype=torch.float32, - use_precision_aware_optimizer_no_fp8_or_ds_fp8=False, fp16=False, - ) - optimizer.grad_scaler = None - optimizer.data_parallel_group_gloo = dist.group.WORLD - optimizer.model_param_group_index_map = {model: (0, 0)} - dtype = (torch.bfloat16, torch.float32) - optimizer.gbuf_ranges = [{dtype: [{'param_map': { - model: {'gbuf_world': module.Range(0, 2), 'param': module.Range(0, 2), - 'gbuf_local': module.Range(0, 2)}, - }}]}] - optimizer.buffers = [SimpleNamespace( - numel_unpadded=2, params=[model], - buckets=[SimpleNamespace(grad_data=torch.zeros(2), numel_unpadded=2)], - )] - chunk = torch.nn.Module() - chunk.register_parameter('weight', model) - result = MegatronCoreTrainEngine.__new__(MegatronCoreTrainEngine) - result.model, result.optimizer = [chunk], optimizer - result.optimizer_revision, result.current_version = 3, 0 - result.get_parallel_state = lambda: dict(train_tp=1, train_dp=1) - return result, master, model - - source, source_master, source_model = engine([1., 2.]) - for _ in range(3): - source_master.grad = torch.tensor([.1, -.2]) - source.optimizer.optimizer.step() - with torch.no_grad(): - source_model.copy_(source_master) - snapshot = source.capture_elastic_state() - target, target_master, target_model = engine([-9., -9.]) - # Actual pinned DP-zero gather/scatter excludes scalar step from tensor - # transfers, while its native setter iterates the destination step key. - target.optimizer.load_state_dict(snapshot['optimizer']) - with pytest.raises(KeyError, match='step'): - target.optimizer.load_parameter_state_from_dp_zero(snapshot['distributed_optimizer']['state']) - monkeypatch.setattr(module.DistributedOptimizer, '_set_main_param_and_optimizer_states', existing_setter) - receipt = target.restore_elastic_state(snapshot) - assert receipt['acknowledged'] and receipt['optimizer_revision'] == 3 - assert '_set_main_param_and_optimizer_states' not in vars(target.optimizer) - assert module.DistributedOptimizer._set_main_param_and_optimizer_states is existing_setter - torch.testing.assert_close(target_master, source_master, rtol=0, atol=0) - torch.testing.assert_close(target_model, source_model, rtol=0, atol=0) - for key in ('step', 'exp_avg', 'exp_avg_sq'): - torch.testing.assert_close(target.optimizer.optimizer.state[target_master][key], - source.optimizer.optimizer.state[source_master][key], rtol=0, atol=0) - for adapter, parameter in ((source, source_master), (target, target_master)): - parameter.grad = torch.tensor([-.3, .4]) - adapter.optimizer.optimizer.step() - torch.testing.assert_close(target_master, source_master, rtol=0, atol=0) - incomplete = MegatronCoreTrainEngine._clone_cpu_state(snapshot) - dtype = (torch.bfloat16, torch.float32) - del incomplete['distributed_optimizer']['state'][0][dtype]['exp_avg'] - with pytest.raises(KeyError, match='exp_avg'): - target.restore_elastic_state(incomplete) - assert '_set_main_param_and_optimizer_states' not in vars(target.optimizer) - assert module.DistributedOptimizer._set_main_param_and_optimizer_states is existing_setter - finally: - dist.destroy_process_group() diff --git a/tests/test_elastic_rdma_distributed.py b/tests/test_elastic_rdma_distributed.py deleted file mode 100644 index 76a87a0..0000000 --- a/tests/test_elastic_rdma_distributed.py +++ /dev/null @@ -1,32 +0,0 @@ -import os - -import torch -import torch.distributed as dist - -from RL_Framework.infra.elastic import InterReplicaGradientDomain - - -def test_chunked_inter_replica_all_reduce_with_torchrun(): - if "RANK" not in os.environ or "WORLD_SIZE" not in os.environ: - return - - dist.init_process_group(backend="gloo") - try: - rank = dist.get_rank() - world_size = dist.get_world_size() - core_ids = [f"dp{i}" for i in range(world_size)] - domain = InterReplicaGradientDomain( - core_replica_ids=core_ids, - process_group=dist.group.WORLD, - ) - - local_core_id = f"dp{rank}" - local = torch.full((8192,), float(rank + 1), dtype=torch.float32) - reduced = domain.reduce_core_gradients( - core_gradients={local_core_id: (local,)}, - ) - - expected = torch.full_like(local, (world_size + 1) / 2.0) - assert torch.allclose(reduced[local_core_id][0], expected) - finally: - dist.destroy_process_group() diff --git a/tests/test_elastic_train_engine_hooks.py b/tests/test_elastic_train_engine_hooks.py deleted file mode 100644 index 6043194..0000000 --- a/tests/test_elastic_train_engine_hooks.py +++ /dev/null @@ -1,58 +0,0 @@ -import os - -import torch - -from RL_Framework.engine.train_engine import FSDPTrainEngine -from RL_Framework.infra.elastic import GradientPayload - - -def test_fsdp_engine_merges_active_hybrid_gradients_before_step(): - engine = FSDPTrainEngine(model_path="unused") - engine.model = torch.nn.Linear(2, 1) - engine.optimizer = torch.optim.SGD(engine.model.parameters(), lr=0.1) - engine.world_size = 1 - engine.rank = 0 - domain = engine.configure_elastic_training(["dp0"]) - domain.request_join("hybrid0", "dp0") - domain.mark_active("hybrid0") - - params = list(engine.model.parameters()) - for param in params: - param.grad = torch.ones_like(param) - payload = GradientPayload( - replica_id="hybrid0", - target_core_id="dp0", - tensors=tuple(torch.full_like(param.grad, 2.0) for param in params), - ) - engine.enqueue_hybrid_gradient_payload(payload) - - engine._apply_elastic_inter_replica_gradients() - - for param in params: - assert torch.allclose(param.grad, torch.full_like(param.grad, 3.0)) - - -def test_fsdp_engine_captures_and_loads_elastic_snapshot(tmp_path, monkeypatch): - monkeypatch.setenv("ELASTIC_TRAINING_STATE_DIR", str(tmp_path)) - engine = FSDPTrainEngine(model_path="unused") - engine.model = torch.nn.Linear(2, 1) - engine.optimizer = torch.optim.SGD(engine.model.parameters(), lr=0.1) - engine.world_size = 1 - engine.rank = 0 - engine.current_version = 3 - - version = engine.capture_elastic_state_snapshot("rollout0", "dp0") - snapshot = tmp_path / "v3" / "rank_0.pt" - - assert version == 3 - assert snapshot.exists() - - with torch.no_grad(): - for param in engine.model.parameters(): - param.add_(10.0) - - engine.load_elastic_state_snapshot(str(snapshot)) - - payload = torch.load(snapshot, map_location="cpu", weights_only=False) - for name, tensor in engine.model.state_dict().items(): - assert torch.allclose(tensor, payload["model"][name]) diff --git a/tests/test_fixed_batch_gradients.py b/tests/test_fixed_batch_gradients.py deleted file mode 100644 index bfd2dfa..0000000 --- a/tests/test_fixed_batch_gradients.py +++ /dev/null @@ -1,312 +0,0 @@ -"""Fixed-batch gradient weighting, delivery identity and CPU reduction.""" -from dataclasses import replace -import threading -import pytest -import torch -import torch.distributed as dist -import torch.multiprocessing as mp -from RL_Framework.engine.megatron_core_train_engine import MegatronCoreTrainEngine -from RL_Framework.infra.elastic.hybrid_pool import GradientPayload, InterReplicaGradientDomain, ReplicaRole -from RL_Framework.infra.elastic.gradient_ipc import ElasticGradientClient, ElasticGradientServer - -def _domain(): - domain = InterReplicaGradientDomain(core_replica_ids=['dp0', 'dp1']) - domain.request_join('hybrid', 'dp0', membership_epoch=7) - domain.mark_active('hybrid', membership_epoch=7) - return domain - - - -def _payload(**changes): - return replace(GradientPayload('hybrid', 'dp0', (torch.tensor([9.]),), - step=3, state_version=2, membership_epoch=7, - sample_count=2, global_sample_count=8), **changes) - - - -def test_uneven_partitions_match_full_batch_gradient_and_adam_update(): - # Core means 1 (four samples) and 5 (two); Hybrid mean 9 (two). - result = _domain().reduce_core_gradients( - core_gradients={'dp0': (torch.tensor([1.]),), 'dp1': (torch.tensor([5.]),)}, - core_sample_counts={'dp0': 4, 'dp1': 2}, global_sample_count=8, - hybrid_payloads=[_payload()], step=3, state_version=2, - ) - expected = torch.tensor([(4 + 10 + 18) / 8]) - for gradients in result.values(): - torch.testing.assert_close(gradients[0], expected) - full = torch.nn.Parameter(torch.tensor([2.])) - split = torch.nn.Parameter(full.detach().clone()) - reference = torch.optim.Adam([full], lr=.1) - elastic = torch.optim.Adam([split], lr=.1) - full.grad, split.grad = expected.clone(), result['dp0'][0].clone() - reference.step() - elastic.step() - torch.testing.assert_close(full, split) - torch.testing.assert_close(reference.state[full]['exp_avg'], elastic.state[split]['exp_avg']) - - - - - - - - - -def _gloo_worker(rank, rendezvous, output, in_place=False): - dist.init_process_group('gloo', init_method=f'file://{rendezvous}', rank=rank, world_size=2) - isolated = dist.new_group([0, 1], backend='gloo') - domain = _domain() - domain.bind_hybrid_process_group(isolated) - result = domain.reduce_core_gradients( - core_gradients={f'dp{rank}': (torch.tensor([1. if rank == 0 else 5.]),)}, - core_sample_counts={f'dp{rank}': 4 if rank == 0 else 2}, - global_sample_count=8, hybrid_payloads=[_payload()] if rank == 0 else [], - step=3, state_version=2, - in_place=in_place, - ) - output[rank] = float(result[f'dp{rank}'][0].item()) - dist.destroy_process_group() - - - -@pytest.mark.parametrize('in_place', [False, True]) -def test_real_gloo_lane_without_hybrid_still_participates(tmp_path, in_place): - context = mp.get_context('spawn') - with context.Manager() as manager: - results = manager.dict() - processes = [context.Process(target=_gloo_worker, args=(rank, str(tmp_path / 'rendezvous'), results, in_place)) for rank in range(2)] - for process in processes: - process.start() - for process in processes: - process.join(30) - try: - assert [process.exitcode for process in processes] == [0, 0] - assert dict(results) == {0: 4., 1: 4.} - finally: - for process in processes: - if process.is_alive(): - process.terminate() - process.join() - - - - - - - - - - - - - - - -def test_tcp_preserves_batch_weighting_metadata(): - received = [] - server = ElasticGradientServer(on_payload=received.append) - endpoint = server.start() - try: - ElasticGradientClient(endpoint).send(_payload()) - assert received[0].sample_count == 2 - assert received[0].global_sample_count == 8 - assert received[0].state_version == 2 - finally: - server.close() - - - - - - -def test_empty_core_lane_enters_elastic_reduce_without_pending_or_expected_hybrids(): - engine = MegatronCoreTrainEngine.__new__(MegatronCoreTrainEngine) - engine.elastic_gradient_domain = _domain() - engine._pending_hybrid_gradients = [] - engine._elastic_step_hybrid_workers = () - engine._elastic_active_gradient_timeout_s = 0 - engine._hybrid_gradient_condition = threading.Condition() - engine._elastic_batch_partition = (0, 8, {'hybrid': 4}) - engine._elastic_training_step = 3 - engine._elastic_expected_state_version = 2 - engine._elastic_gradient_update_callback = None - grad = torch.zeros(1) - engine._model_main_gradients = lambda: [grad] - engine.get_data_parallel_rank = lambda: 1 - entered = [] - def reduce(**kwargs): - entered.append(kwargs) - return {'dp1': (torch.tensor([7.]),)} - engine.elastic_gradient_domain.reduce_core_gradients = reduce - engine._apply_elastic_inter_replica_gradients() - assert len(entered) == 1 - assert entered[0]['in_place'] is True - assert entered[0]['core_gradients']['dp1'][0].data_ptr() == grad.data_ptr() - torch.testing.assert_close(grad, torch.tensor([7.])) - - - -def test_native_dp_without_hybrid_domain_keeps_loss_scale_one(): - engine = MegatronCoreTrainEngine.__new__(MegatronCoreTrainEngine) - engine.elastic_gradient_domain = None - engine.get_data_parallel_world_size = lambda: 2 - engine.set_elastic_batch_partition(8, 16, {}) - assert engine._elastic_core_loss_scale() == 1. - - - -class _GradientModel(torch.nn.Module): - def __init__(self): - super().__init__() - self.weight = torch.nn.Parameter(torch.tensor([2.])) - self.weight.main_grad = torch.zeros(1) - self.weight.register_hook(self._accumulate) - - def _accumulate(self, gradient): - self.weight.main_grad.add_(gradient) - return gradient - - def zero_grad_buffer(self): - self.weight.main_grad.zero_() - - - -class _AdamAdapter: - def __init__(self, model): - self.model = model - self.inner = torch.optim.Adam(model.parameters(), lr=.01) - - def zero_grad(self): - self.inner.zero_grad() - - def scale_loss(self, loss): - return loss - - def step(self): - self.model.weight.grad = self.model.weight.main_grad.clone() - self.inner.step() - return True, self.model.weight.main_grad.norm(), 0 - - - -def _gloo_engine_worker(rank, rendezvous, output): - import sys - import types - dist.init_process_group('gloo', init_method=f'file://{rendezvous}', rank=rank, world_size=2) - isolated = dist.new_group([0, 1], backend='gloo') - def finalize(models): - for model in models: - dist.all_reduce(model.weight.main_grad) - model.weight.main_grad.div_(2) - sys.modules['megatron.core.distributed'] = types.SimpleNamespace(finalize_model_grads=finalize) - engine = MegatronCoreTrainEngine.__new__(MegatronCoreTrainEngine) - model = _GradientModel() - engine.model = [model] - engine.optimizer = _AdamAdapter(model) - engine.optimizer_revision = 0 - engine.current_version = 0 - engine.elastic_gradient_domain = _domain() - engine.elastic_gradient_domain.bind_hybrid_process_group(isolated) - engine.get_data_parallel_world_size = lambda: 2 - engine.get_data_parallel_rank = lambda: rank - engine._hybrid_gradient_condition = threading.Condition() - engine._elastic_active_gradient_timeout_s = 10 - engine._elastic_gradient_update_callback = None - engine._elastic_seen_payloads = set() - engine._pending_hybrid_gradients = [] - engine.set_elastic_training_step(0, ['hybrid'] if rank == 0 else []) - engine.set_elastic_batch_partition(4 if rank == 0 else 0, 8, {'hybrid': 4}) - if rank == 0: - engine.enqueue_hybrid_gradient_payload(_payload(tensors=(torch.tensor([-7.]),), step=0, - state_version=0, sample_count=4)) - engine._iter_micro_batches = lambda rows: ({'trajectories': rows[start:start + 3]} for start in range(0, len(rows), 3)) - engine._forward = lambda batch: (model.weight - torch.tensor(batch['trajectories'])).square().mean() - engine._loss = lambda batch, loss: (loss, {'loss': float(loss.detach()), 'pg_loss': float(loss.detach()), - 'kl': 0., 'reward_sum': 0., 'n_samples': len(batch['trajectories']), 'n_updates': 1}) - engine._reduce_stats = lambda stats: stats - engine.grpo_update([0., 1., 2., 3.] if rank == 0 else []) - optimizer_state = engine.optimizer.inner.state[model.weight] - # Simulate a real RS buffer: only this rank's shard contains finalized - # gradients; the other shard still has stale local values. - bucket_data = torch.tensor([1., 2., 999., 999.]) if rank == 0 else torch.tensor([-999., -999., 3., 4.]) - model.bucket_groups = [types.SimpleNamespace( - intra_distributed_optimizer_instance_group=dist.group.WORLD, - buckets=[types.SimpleNamespace(grad_data=bucket_data)], - )] - engine.use_distributed_optimizer = True - engine._materialize_elastic_core_gradients() - output[rank] = (float(model.weight.detach()), float(optimizer_state['exp_avg']), - float(optimizer_state['exp_avg_sq']), engine.optimizer_revision, bucket_data.tolist()) - dist.destroy_process_group() - - - -def test_full_engine_gloo_prescale_finalize_elastic_sum_matches_full_batch_with_empty_core(tmp_path): - context = mp.get_context('spawn') - with context.Manager() as manager: - results = manager.dict() - processes = [context.Process(target=_gloo_engine_worker, args=(rank, str(tmp_path / 'rendezvous'), results)) for rank in range(2)] - for process in processes: - process.start() - for process in processes: - process.join(30) - try: - assert [process.exitcode for process in processes] == [0, 0] - expected = torch.nn.Parameter(torch.tensor([2.])) - optimizer = torch.optim.Adam([expected], lr=.01) - (expected - torch.arange(8)).square().mean().backward() - optimizer.step() - for result in results.values(): - assert result[0] == pytest.approx(float(expected)) - assert result[1] == pytest.approx(float(optimizer.state[expected]['exp_avg'])) - assert result[2] == pytest.approx(float(optimizer.state[expected]['exp_avg_sq'])) - assert result[3] == 1 - assert result[4] == [1., 2., 3., 4.] - finally: - for process in processes: - if process.is_alive(): - process.terminate() - process.join() - - -@pytest.mark.parametrize('change,message', [ - ({'step': -1}, 'step'), ({'state_version': -1}, 'revision'), - ({'membership_epoch': 6}, 'epoch'), ({'global_sample_count': 16}, 'batch size'), - ({'zero_placeholder': True}, 'placeholder'), -]) -def test_rejects_stale_or_incomplete_gradient_identity(change, message): - with pytest.raises(ValueError, match=message): - _domain().reduce_core_gradients( - core_gradients={'dp0': (torch.ones(1),), 'dp1': (torch.ones(1),)}, - core_sample_counts={'dp0': 4, 'dp1': 2}, global_sample_count=8, - hybrid_payloads=[_payload(**change)], step=3, state_version=2, - ) - - - -def test_rejects_duplicate_payload_before_double_counting(): - domain = _domain() - kwargs = dict(core_gradients={'dp0': (torch.ones(1),), 'dp1': (torch.ones(1),)}, - hybrid_payloads=[_payload(), _payload()], step=3, state_version=2) - with pytest.raises(ValueError, match='duplicate'): - domain.reduce_core_gradients(**kwargs) - - - -def test_engine_ingress_rejects_unknown_revision_and_duplicate_without_waking_waiters(): - engine = MegatronCoreTrainEngine.__new__(MegatronCoreTrainEngine) - engine.elastic_gradient_domain = _domain() - engine.optimizer_revision = 2 - engine._elastic_seen_payloads = set() - engine._pending_hybrid_gradients = [] - engine._hybrid_gradient_condition = threading.Condition() - engine.set_elastic_training_step(3, ['hybrid']) - engine.set_elastic_batch_partition(4, 8, {'hybrid': 2}) - for bad in (_payload(state_version=-1), _payload(step=-1), _payload(membership_epoch=6)): - with pytest.raises(ValueError): - engine.enqueue_hybrid_gradient_payload(bad) - assert not engine._pending_hybrid_gradients - engine.enqueue_hybrid_gradient_payload(_payload()) - with pytest.raises(ValueError, match='duplicate'): - engine.enqueue_hybrid_gradient_payload(_payload()) - assert len(engine._pending_hybrid_gradients) == 1 diff --git a/tests/test_fsdp_sequence_alignment.py b/tests/test_fsdp_sequence_alignment.py deleted file mode 100644 index e928261..0000000 --- a/tests/test_fsdp_sequence_alignment.py +++ /dev/null @@ -1,82 +0,0 @@ -from types import SimpleNamespace - -import torch - -from RL_Framework.engine.train_engine import FSDPTrainEngine - - -def _trajectory(length: int) -> dict: - return { - "input_ids": torch.arange(length).unsqueeze(0), - "attention_mask": torch.ones((1, length), dtype=torch.long), - "logprobs": torch.zeros((1, length), dtype=torch.float32), - "loss_mask": torch.ones((1, length), dtype=torch.long), - } - - -def test_alignment_pads_effective_work_but_masks_loss(monkeypatch): - engine = FSDPTrainEngine.__new__(FSDPTrainEngine) - engine.is_distributed = True - engine.world_size = 2 - engine.rank = 0 - engine.local_rank = 0 - engine.model = torch.nn.Linear(1, 1) - engine.tokenizer = SimpleNamespace(pad_token_id=0) - - call_count = 0 - - def fake_all_reduce(tensor, op=None): - nonlocal call_count - call_count += 1 - if tensor.numel() == 2: - tensor.copy_(torch.tensor([8, 6], dtype=tensor.dtype)) - - monkeypatch.setattr(torch.distributed, "all_reduce", fake_all_reduce) - aligned = engine.align_distributed_trajectories( - [_trajectory(4), _trajectory(7)] - ) - - assert call_count == 3 - assert [traj["_original_seq_len"] for traj in aligned] == [7, 4] - assert [traj["_padded_seq_len"] for traj in aligned] == [8, 6] - assert aligned[0]["attention_mask"].tolist()[0][-1] == 1 - assert aligned[0]["loss_mask"].tolist()[0][-1] == 0 - assert aligned[1]["attention_mask"].tolist()[0][-2:] == [1, 1] - assert aligned[1]["loss_mask"].tolist()[0][-2:] == [0, 0] - - -def test_recompute_logprobs_locksteps_each_microbatch(): - class TinyModel(torch.nn.Module): - def __init__(self): - super().__init__() - self.anchor = torch.nn.Parameter(torch.zeros(())) - - def forward(self, input_ids, attention_mask, use_cache=False): - del attention_mask, use_cache - vocab_size = 16 - logits = torch.zeros( - (*input_ids.shape, vocab_size), - device=input_ids.device, - ) - return SimpleNamespace(logits=logits + self.anchor) - - engine = FSDPTrainEngine.__new__(FSDPTrainEngine) - engine.model = TinyModel() - engine._fsdp_update_index = 3 - phases = [] - engine._fsdp_lockstep = ( - lambda update, micro, phase, length: - phases.append((update, micro, phase, length)) - ) - - trajectories = [_trajectory(4), _trajectory(6)] - engine.recompute_logprobs(trajectories) - - assert phases == [ - (3, 0, "recompute_before_forward", 4), - (3, 0, "recompute_after_forward", 4), - (3, 0, "recompute_after_logprobs", 4), - (3, 1, "recompute_before_forward", 6), - (3, 1, "recompute_after_forward", 6), - (3, 1, "recompute_after_logprobs", 6), - ] diff --git a/tests/test_global_resource_planner_forced_runtime.py b/tests/test_global_resource_planner_forced_runtime.py deleted file mode 100644 index a99be43..0000000 --- a/tests/test_global_resource_planner_forced_runtime.py +++ /dev/null @@ -1,37 +0,0 @@ -import unittest - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.cost_model.global_resource_planner import GlobalResourcePlanner - - -class TestForcedRuntimePlanner(unittest.TestCase): - def test_forced_runtime_plan_survives_optimizer_no_candidate(self): - config = AsyncRLConfig(model_path="/tmp/test-model") - config.n_total_gpus = 12 - config.train_gpus = 8 - config.rollout_gpus = 4 - config.batch_size = 8 - config.max_seq_length = 32768 - config.global_resource_planner.enabled = True - config.global_resource_planner.min_history_size = 1 - config.global_resource_planner.warmup_steps = 0 - config.global_resource_planner.plan_interval = 1 - config.global_resource_planner.fixed_train_gpus = 8 - config.global_resource_planner.allowed_train_tp = [4] - config.global_resource_planner.allowed_train_pp = [1] - config.global_resource_planner.allowed_rollout_tp = [2, 4] - config.global_resource_planner.require_heterogeneous_rollout_tp = True - - config.global_resource_planner.runtime_forced_train_gpus = 4 - config.global_resource_planner.runtime_forced_rollout_tp_list = [4, 2, 2] - planner = GlobalResourcePlanner.from_config(config) - history = [{"input_len": 2048, "output_len": 30000}] - decision = planner.plan_if_needed(1, config, batch=history) - - self.assertTrue(decision.should_reconfigure) - self.assertEqual(decision.reason, "forced_reconfigure") - self.assertEqual(decision.candidate_plan.rollout_tp_list, [4, 2, 2]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_global_resource_planner_simulators.py b/tests/test_global_resource_planner_simulators.py index afbdc25..8bd420a 100644 --- a/tests/test_global_resource_planner_simulators.py +++ b/tests/test_global_resource_planner_simulators.py @@ -1,4 +1,5 @@ import json +import shlex import sys import tempfile import unittest @@ -63,7 +64,7 @@ def test_sailor_command_backend_is_used(self): cfg.global_resource_planner.train_backend = "sailor" cfg.global_resource_planner.sailor_path = str(sailor) cfg.global_resource_planner.sailor_train_command = ( - f"{sys.executable} {script} {{input_json}} {{output_json}}" + f"{shlex.quote(sys.executable)} {shlex.quote(str(script))} {{input_json}} {{output_json}}" ) evaluator = HybridSimulatorCostModel(cfg) @@ -96,7 +97,7 @@ def test_vidur_command_backend_is_used(self): cfg.global_resource_planner.rollout_backend = "vidur" cfg.global_resource_planner.vidur_path = str(vidur) cfg.global_resource_planner.vidur_rollout_command = ( - f"{sys.executable} {script} {{trace_csv}} {{output_json}}" + f"{shlex.quote(sys.executable)} {shlex.quote(str(script))} {{trace_csv}} {{output_json}}" ) evaluator = HybridSimulatorCostModel(cfg) @@ -173,10 +174,10 @@ def test_planner_runs_with_hybrid_backends(self): cfg.global_resource_planner.sailor_path = str(sailor) cfg.global_resource_planner.vidur_path = str(vidur) cfg.global_resource_planner.sailor_train_command = ( - f"{sys.executable} {sailor_script} {{input_json}} {{output_json}}" + f"{shlex.quote(sys.executable)} {shlex.quote(str(sailor_script))} {{input_json}} {{output_json}}" ) cfg.global_resource_planner.vidur_rollout_command = ( - f"{sys.executable} {vidur_script} {{trace_csv}} {{output_json}} {{tp_list}}" + f"{shlex.quote(sys.executable)} {shlex.quote(str(vidur_script))} {{trace_csv}} {{output_json}} {{tp_list}}" ) planner = GlobalResourcePlanner.from_config(cfg) diff --git a/tests/test_grp_decision_gates.py b/tests/test_grp_decision_gates.py deleted file mode 100644 index 994aced..0000000 --- a/tests/test_grp_decision_gates.py +++ /dev/null @@ -1,137 +0,0 @@ -"""EHP demand cannot authorize a rejected full resource repartition.""" - -from unittest.mock import Mock - -import pytest - -from RL_Framework.config import AsyncRLConfig, HeterogeneousInstanceConfig -from RL_Framework.infra.cost_model.global_resource_planner import ( - CoreRuntimeCapabilities, - GlobalResourcePlan, - GlobalResourcePlanner, - PlannerDecision, -) -from RL_Framework.infra.cost_model.model import RolloutClusterConfig, TrainParallelConfig -from RL_Framework.infra.cost_model.optimizer import OptimizationResult - - -def planner_fixture(monkeypatch, reconfiguration_cost, *, training_bound=False): - for variable in ("GRP_FORCE_RUNTIME_RECONFIGURE", "GRP_FORCE_ROLLOUT_TP_LIST", "GRP_FORCE_TRAIN_GPUS"): - monkeypatch.delenv(variable, raising=False) - config = AsyncRLConfig( - model_path="not-loaded", train_gpus=2, rollout_gpus=2, - train_tp_size=1, train_dp_size=2, micro_batch_size=1, - batch_size=24, n_total_gpus=4, - ) - cfg = config.global_resource_planner - cfg.enabled = True - cfg.train_backend = cfg.rollout_backend = "analytic" - cfg.plan_interval = 1 - cfg.warmup_steps = 0 - cfg.min_history_size = 1 - cfg.reconfiguration_cost_s = reconfiguration_cost - cfg.elastic_hybrid_planning_enabled = True - cfg.elastic_hybrid_min_rollout_gpus = 1 - config.heterogeneous_rollout.enabled = True - config.heterogeneous_rollout.instances = [ - HeterogeneousInstanceConfig(instance_id="service-a", tp=1, gpus=[0]), - HeterogeneousInstanceConfig(instance_id="service-b", tp=1, gpus=[1]), - ] - config.profiling.calibration = { - "training": {"compute_scale": 1000 if training_bound else 0.0001, "anchor_scale": 0}, - "rollout": {"1": { - "prefill_scale": 0.0001 if training_bound else 1000, - "decode_scale": 0.0001 if training_bound else 1000, - }}, - "horizon_updates": 4, - } - planner = GlobalResourcePlanner.from_config(config) - train = TrainParallelConfig(tp=1, dp=2, b_micro=1) - current = GlobalResourcePlan( - train_config=train, rollout_config=RolloutClusterConfig([1, 1]), - t_train=100, t_rollout=90, t_global=100, - n_total_gpus=4, max_concurrent_rollouts=16, - ) - planner._build_current_plan = Mock(return_value=current) - # Freeze the optimizer result so these tests exercise the real decision - # gates and EHP policy independently of the search's selected candidate. - planner.optimizer.optimize = Mock(return_value=OptimizationResult( - train_config=train, rollout_config=RolloutClusterConfig([2]), - t_train=80, t_rollout=70, t_global=80, - )) - return config, planner, current - - -@pytest.mark.parametrize("resource_allowed,cost", [(False, 1e9), (True, 0)]) -@pytest.mark.parametrize("elastic_adjust", [False, True]) -def test_full_repartition_and_ehp_have_independent_gates( - monkeypatch, resource_allowed, cost, elastic_adjust, -): - config, planner, current = planner_fixture(monkeypatch, cost, training_bound=elastic_adjust) - metrics = planner.observe_runtime( - step=1, dispatcher_metrics={}, - step_stats={"remaining_updates": 4}, - ) - decision = planner.plan_if_needed( - 1, config, batch=[{"input_len": 128, "output_len": 4096}], - runtime_metrics=metrics, - ) - assert decision.resource_should_reconfigure is resource_allowed - assert decision.elastic_hybrid_signal.should_adjust is elastic_adjust - assert decision.should_reconfigure is (resource_allowed or elastic_adjust) - assert decision.candidate_plan.rollout_tp_list == [2] - assert decision.current_plan.rollout_tp_list == [1, 1] - assert decision.candidate_plan.expected_gain_s == 20 - cost - assert planner.active_plan is (decision.candidate_plan if resource_allowed else current) - wire = decision.to_dict() - assert wire["resource_should_reconfigure"] is resource_allowed - assert wire["elastic_should_adjust"] is elastic_adjust - assert wire["elastic_hybrid_signal"]["desired_workers"] == (1 if elastic_adjust else 0) - assert len(wire["elastic_hybrid_signal"]["loan_instance_ids"]) == int(elastic_adjust) - assert config.train_dp_size == 2 - assert config.rollout_gpus == 2 - - -def test_release_also_leaves_rejected_full_candidate_inactive(monkeypatch): - config, planner, current = planner_fixture(monkeypatch, 1e9) - metrics = planner.observe_runtime( - step=1, dispatcher_metrics={}, - step_stats={ - "remaining_updates": 4, - "active_hybrid_replicas": 1, - "loan_instance_ids": ["service-a"], - }, - ) - decision = planner.plan_if_needed( - 1, config, batch=[{"input_len": 128, "output_len": 4096}], runtime_metrics=metrics, - ) - assert decision.should_reconfigure - assert decision.resource_should_reconfigure is False - assert decision.elastic_hybrid_signal.action == "release" - assert planner.active_plan is current - - -def test_explicit_rollout_repartition_reaches_the_full_gate_with_live_elastic_core(monkeypatch): - config, planner, current = planner_fixture(monkeypatch, 1e9) - planner.runtime_capabilities = CoreRuntimeCapabilities( - world_size=2, tp=1, pp=1, cp=1, ep=1, dp=2, - ) - monkeypatch.setenv("GRP_FORCE_ROLLOUT_TP_LIST", "2") - decision = planner.plan_if_needed( - 1, config, batch=[{"input_len": 128, "output_len": 4096}], - ) - assert decision.current_plan is current - assert decision.candidate_plan.rollout_tp_list == [2] - assert decision.resource_should_reconfigure - - -def test_skipped_real_decision_and_legacy_manual_decision_are_distinguishable(monkeypatch): - config, planner, _ = planner_fixture(monkeypatch, 0) - planner.warmup_steps = 2 - decision = planner.plan_if_needed(1, config) - assert decision.resource_should_reconfigure is False - assert not decision.should_reconfigure - assert decision.to_dict()["elastic_should_adjust"] is False - manual = PlannerDecision(step=1, should_reconfigure=True, reason="legacy") - assert manual.resource_should_reconfigure is None - assert manual.to_dict()["resource_should_reconfigure"] is None diff --git a/tests/test_grpo_grouping.py b/tests/test_grpo_grouping.py index d3a1bee..30fc6d7 100644 --- a/tests/test_grpo_grouping.py +++ b/tests/test_grpo_grouping.py @@ -7,6 +7,7 @@ import pytest import torch +from RL_Framework.config import AsyncRLConfig from RL_Framework.infra.execution.async_runner import AsyncTaskRunner, TaskResult from RL_Framework.infra.execution.batch_dispatcher import BatchTaskDispatcher, TaskInput from RL_Framework.infra.sync.staleness import StalenessManager @@ -26,9 +27,14 @@ def get_version(self): def _trainer(n_samples=4): trainer = object.__new__(AsyncRLTrainer) - trainer.config = SimpleNamespace(n_samples=n_samples) + trainer.config = AsyncRLConfig(model_path="/tmp/fake-model", n_samples=n_samples) trainer.train_engine = _FakeTrainEngine() + trainer.is_main_process = True trainer._task_counter = 0 + trainer._consumed_grpo_group_ids = set() + trainer._advantage_stats = {} + trainer._rollout_source_rank = None + trainer._rollout_source_world_size = None return trainer diff --git a/tests/test_grpo_sample_mean.py b/tests/test_grpo_sample_mean.py deleted file mode 100644 index 537ea81..0000000 --- a/tests/test_grpo_sample_mean.py +++ /dev/null @@ -1,95 +0,0 @@ -"""Trajectory weights remain fixed across uneven elastic microbatches.""" -from types import SimpleNamespace - -import pytest -import torch - -from RL_Framework.engine import megatron_core_train_engine as engine_module -from RL_Framework.engine.megatron_core_train_engine import MegatronCoreTrainEngine -from RL_Framework.infra.elastic.batch_partition import partition_complete_grpo_groups -from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - - -def _engine(): - engine = MegatronCoreTrainEngine.__new__(MegatronCoreTrainEngine) - engine.train_tp_size = 1 - engine.clip_epsilon, engine.kl_coef = .2, .1 - return engine - - -def test_b12_n4_mb3_gradient_matches_each_trajectory_reference_with_or_without_hybrid(): - rows = [dict(grpo_group_id=str(i // 4), rollout_index=i % 4, index=i, - rewards=torch.tensor([float(i == 8)])) for i in range(12)] - AsyncRLTrainer.__new__(AsyncRLTrainer)._compute_advantages(rows) - engine = _engine() - - def gradient(participants, microbatch_size): - parameter = torch.tensor(.1, requires_grad=True) - assignments = partition_complete_grpo_groups(rows, 4, participants) - for subset in assignments.values(): - for start in range(0, len(subset), microbatch_size): - part = subset[start:start + microbatch_size] - count = len(part) - mask = torch.zeros(count, 11) - mask[:, 1] = 1 - for index, row in enumerate(part): - if row['index'] in (6, 8): - mask[index, 1:] = 1 - # Distinct row features keep the reference gradient nonzero. - features = torch.tensor([1 + row['index'] / 20 for row in part])[:, None] - logits = torch.stack([(parameter * features).expand(count, 11), - torch.zeros(count, 11)], -1) - batch = dict(input_ids=torch.zeros(count, 11, dtype=torch.long), - old_logprobs=torch.full((count, 11), -torch.log(torch.tensor(2.))), - loss_mask=mask, advantages=torch.cat([row['advantages'] for row in part]), - rewards=torch.cat([row['rewards'] for row in part])) - loss, _ = engine._loss(batch, logits) - (loss * count / len(rows)).backward() - return parameter.grad - - reference = gradient(['dp0'], 1) - assert reference.abs() > 1e-4 - torch.testing.assert_close(gradient(['dp0'], 3), reference) - torch.testing.assert_close(gradient(['dp0', 'hybrid'], 3), reference) - - -def test_masked_sample_losses_and_statistics_match_single_trajectory_reference(monkeypatch): - engine = _engine() - values = torch.tensor([.1, -.3, .8], requires_grad=True) - logits = torch.stack([values[:, None].expand(3, 4), torch.zeros(3, 4)], -1) - batch = dict(input_ids=torch.zeros(3, 4, dtype=torch.long), - old_logprobs=torch.full((3, 4), -.7), - loss_mask=torch.tensor([[0., 1., 0., 0.], [0., 1., 1., 1.], [0., 0., 0., 0.]]), - advantages=torch.tensor([.7, -.4, 1.]), rewards=torch.tensor([1., 2., 3.])) - - def subset(start, stop): - return {key: value[start:stop] for key, value in batch.items()} - - singles = [engine._loss(subset(i, i + 1), logits[i:i + 1]) for i in range(3)] - reference_loss = torch.stack([loss for loss, _ in singles]).mean() - actual_loss, actual_stats = engine._loss(batch, logits) - torch.testing.assert_close(actual_loss, reference_loss) - actual_gradient, = torch.autograd.grad(actual_loss, values, retain_graph=True) - reference_gradient, = torch.autograd.grad(reference_loss, values, retain_graph=True) - torch.testing.assert_close(actual_gradient, reference_gradient) - assert actual_gradient[2] == 0 - assert singles[2][0] == 0 and singles[2][1]['n_samples'] == 1 - - left = engine._loss(subset(0, 2), logits[:2])[1] - right = singles[2][1] - merged = engine._merge_stats([left, right]) - for key in ('loss', 'pg_loss', 'kl'): - assert merged[key] == pytest.approx(actual_stats[key]) - assert merged['n_samples'] == 3 and merged['n_updates'] == 2 - - # Exercise the real DP-stat encoder and decoder with a captured peer vector. - engine._device = lambda: 'cpu' - engine._parallel_state = lambda: SimpleNamespace(get_data_parallel_group=lambda **_: None) - peer = [] - monkeypatch.setattr(engine_module.dist, 'all_reduce', lambda values, **_: peer.append(values.clone())) - engine._reduce_stats(right) - monkeypatch.setattr(engine_module.dist, 'all_reduce', lambda values, **_: values.add_(peer[0])) - reduced = engine._reduce_stats(left) - for key in ('loss', 'pg_loss', 'kl'): - assert reduced[key] == pytest.approx(actual_stats[key]) - assert reduced['n_samples'] == 3 and reduced['n_updates'] == 2 diff --git a/tests/test_homogeneous_rollout_baseline.py b/tests/test_homogeneous_rollout_baseline.py deleted file mode 100644 index 3a57e59..0000000 --- a/tests/test_homogeneous_rollout_baseline.py +++ /dev/null @@ -1,109 +0,0 @@ -from pathlib import Path - -import yaml - -from RL_Framework.infra.scheduling.load_balance import LoadBalanceScheduler -from scripts.materialize_6node48_config import load_inherited_config, materialize - - -PROJECT = Path(__file__).resolve().parents[1] -HETERO = PROJECT / "configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_100step.yaml" -HOMOGENEOUS = ( - PROJECT - / "configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_100step_homogeneous_lb.yaml" -) - - -def test_homogeneous_baseline_changes_only_rollout_policy_fields(): - hetero = load_inherited_config(HETERO) - homogeneous = load_inherited_config(HOMOGENEOUS) - - for key in ( - "model_path", - "train_backend", - "train_gpus", - "rollout_gpus", - "batch_size", - "micro_batch_size", - "n_samples", - "total_steps", - "max_seq_length", - "max_new_tokens", - "sync_interval", - "seed", - ): - assert homogeneous.get(key) == hetero.get(key) - - homogeneous_rollout = homogeneous["heterogeneous_rollout"] - assert homogeneous_rollout["scheduling"]["scheduler_type"] == "load_balance" - assert [instance["tp"] for instance in homogeneous_rollout["instances"]] == [2] * 8 - planner = homogeneous["global_resource_planner"] - assert planner["rollout_node_tp_pattern"] == [2, 2, 2, 2] - assert planner["allowed_rollout_tp"] == [2] - assert planner["require_heterogeneous_rollout_tp"] is False - - -def test_materialize_homogeneous_tp2_layout(tmp_path: Path): - output = tmp_path / "effective.yaml" - materialize( - template=HOMOGENEOUS, - output=output, - master_addr="192.0.2.10", - master_port=29901, - rollout_hosts=["192.0.2.20", "192.0.2.21"], - run_root=tmp_path / "run", - gradient_port=29902, - ) - config = yaml.safe_load(output.read_text(encoding="utf-8")) - instances = config["heterogeneous_rollout"]["instances"] - assert len(instances) == 8 - - for host_index, host in enumerate(("192.0.2.20", "192.0.2.21")): - host_instances = instances[host_index * 4:(host_index + 1) * 4] - assert [instance["host"] for instance in host_instances] == [host] * 4 - assert [instance["tp"] for instance in host_instances] == [2] * 4 - assert [instance["gpus"] for instance in host_instances] == [ - [0, 1], - [2, 3], - [4, 5], - [6, 7], - ] - assert [instance["port"] for instance in host_instances] == [8000, 8001, 8002, 8003] - assert [instance["instance_id"] for instance in host_instances] == [ - f"n{host.rsplit('.', 1)[-1]}_tp2_0", - f"n{host.rsplit('.', 1)[-1]}_tp2_1", - f"n{host.rsplit('.', 1)[-1]}_tp2_2", - f"n{host.rsplit('.', 1)[-1]}_tp2_3", - ] - - -def test_least_connections_rotates_equal_load_endpoints(): - scheduler = LoadBalanceScheduler(load_balance_strategy="least_connections") - for index in range(8): - scheduler.register_instance(index, f"tp2_{index}", 2) - - routed = [] - for request_index in range(16): - result = scheduler.schedule(512, prompt_id=str(request_index)) - routed.append(result.instance_index) - # Model a low-concurrency multi-turn workload: the request finishes - # before the next turn is scheduled, so all endpoints tie at zero. - scheduler.on_request_done(result.instance_index) - - assert routed[:8] == list(range(8)) - assert routed[8:] == list(range(8)) - - -def test_least_connections_does_not_skip_endpoints_across_concurrent_waves(): - scheduler = LoadBalanceScheduler(load_balance_strategy="least_connections") - for index in range(8): - scheduler.register_instance(index, f"tp2_{index}", 2) - - waves = [] - for _ in range(2): - wave = [scheduler.schedule(512).instance_index for _ in range(4)] - waves.append(wave) - for instance_index in wave: - scheduler.on_request_done(instance_index) - - assert waves == [list(range(4)), list(range(4, 8))] diff --git a/tests/test_hybrid_boundary_activation.py b/tests/test_hybrid_boundary_activation.py deleted file mode 100644 index 71fa2f4..0000000 --- a/tests/test_hybrid_boundary_activation.py +++ /dev/null @@ -1,225 +0,0 @@ -"""Ready joins wait for Core boundaries; installation keeps its ACK deadline.""" -from concurrent.futures import TimeoutError as FutureTimeout -import json -import queue -import threading -from types import SimpleNamespace as NS - -import pytest - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.elastic import hybrid_pool as pool_module -from RL_Framework.infra.elastic import runtime_executor as runtime_module -from RL_Framework.infra.elastic.hybrid_pool import ElasticHybridPool -from RL_Framework.infra.elastic.runtime_executor import RuntimeElasticExecutor - - -@pytest.fixture -def boundary_join(tmp_path, monkeypatch): - clock = NS(now=0.0) - timing = NS(monotonic=lambda: clock.now, time=lambda: clock.now) - monkeypatch.setattr(runtime_module, "time", timing) - monkeypatch.setattr(pool_module, "time", timing) - config = AsyncRLConfig(model_path="/not-loaded", train_gpus=1, rollout_gpus=1, - n_total_gpus=2, train_tp_size=1, train_dp_size=1) - cfg = config.global_resource_planner - cfg.elastic_hybrid_join_timeout_s = 180 - cfg.hybrid_worker_ready_timeout_s = 60 - cfg.hybrid_worker_task_dir = str(tmp_path) - pool = ElasticHybridPool(core_train_workers=["dp0"], - core_rollout_workers=["rollout0"], snapshot_fetcher=lambda *_: 0) - runtime = RuntimeElasticExecutor(config=config, planner=NS(), elastic_pool=pool, - train_engine=NS(optimizer_revision=14)) - checkpoints = queue.Queue() - requests = [] - - class ControlledEvent: - """Expose each real queue poll without relying on thread scheduling.""" - def __init__(self): - self.condition = threading.Condition() - self.ready = False - self.polls = 0 - requests.append(self) - - def set(self): - with self.condition: - self.ready = True - self.condition.notify_all() - - def wait(self, _timeout): - with self.condition: - if not self.ready: - checkpoints.put("waiting") - assert self.condition.wait_for( - lambda: self.ready or self.polls, timeout=3), "test did not release the queue poll" - if self.polls: - self.polls -= 1 - return self.ready - - def poll(self): - with self.condition: - self.polls += 1 - self.condition.notify_all() - - # Runtime locks and pool futures retain real threading primitives. Only - # the request Event created inside _queue_activation is controlled. - monkeypatch.setattr(runtime_module, "threading", NS(Event=ControlledEvent)) - closing = threading.Event() - state = NS(capture_seconds=0, install_seconds=0, checkpoint=None) - manifest = tmp_path / "state14.json" - manifest.write_text(json.dumps({"format": "libra-ehp-lanes-v1", - "snapshot_id": "capture14", "optimizer_revision": 14, - "lanes": {"dp0": {"0": "ehp://source/lane14"}}})) - - def advance(seconds): - clock.now += seconds - requests[0].poll() - state.checkpoint = checkpoints.get(timeout=3) - - def acknowledge(): - receipt = dict(snapshot=str(manifest), rank=0, pid=123, acknowledged=True, - snapshot_id="capture14", optimizer_revision=14, state_version=14, - lane_snapshot_id="lane14", target_core_id="dp0", source_uri="ehp://source/lane14") - (tmp_path / "replica.rank_0.ready").write_text( - "".join(f"{key}={value}\n" for key, value in receipt.items())) - - def capture(): - if state.capture_seconds: - advance(state.capture_seconds) - return str(manifest) - - def install(_seconds): - advance(state.install_seconds) - acknowledge() - return closing.is_set() - - runtime._closing = NS(is_set=closing.is_set, set=closing.set, wait=install) - monkeypatch.setattr(runtime, "_capture_core_snapshot", capture) - monkeypatch.setattr(runtime, "_publish_hybrid_membership", lambda: None) - monkeypatch.setattr(runtime, "_stop_managed_rollout_processes", lambda: None) - - def activate(replica_id, members, target_core_id, version): - return runtime._queue_activation(replica_id, - dict(acknowledged=True, state_version=version, optimizer_revision=version)) - - handle = pool.join_replica("replica", ["rollout0"], "dp0", - replica_activation_barrier=activate, timeout_s=180) - handle.future.add_done_callback(lambda future: checkpoints.put("finished")) - runtime._pending_hybrid_joins["replica"] = handle - runtime._pending_hybrid_join_started_at["replica"] = 0 - assert checkpoints.get(timeout=3) == "waiting" - assert runtime.has_pending_activations() and not handle.done() - - def finish(): - if not state.install_seconds: - acknowledge() - runtime._finish_pending_activations() - return handle.result(timeout=3) - - h = NS(runtime=runtime, pool=pool, clock=clock, state=state, - advance=advance, finish=finish, handle=handle) - try: - yield h - finally: - closing.set() - for event in requests: - event.set() - pool.close() - try: - handle.result(timeout=3) - except FutureTimeout: - if not handle.done(): - raise - except RuntimeError: - pass - - -def test_ready_join_waits_past_180_seconds_until_a_core_boundary(boundary_join): - h = boundary_join - h.advance(181) - workers = h.finish() - assert h.clock.now == 181 - assert all(worker.join_state.value == "active" and worker.state_version == 14 - for worker in workers) - - -def test_capture_and_ack_can_cross_the_old_queue_deadline(boundary_join): - h = boundary_join - h.advance(50) - h.state.capture_seconds = 96 - h.state.install_seconds = 50 - workers = h.finish() - assert h.clock.now == 196 - assert all(worker.join_state.value == "active" and worker.state_version == 14 - for worker in workers) - assert h.pool.snapshot()["rollout0"].state_version == 14 - - -@pytest.mark.parametrize("action", ["cancel", "close"]) -def test_cancel_and_cleanup_still_wake_ready_join(boundary_join, action): - h = boundary_join - if action == "cancel": - h.runtime._release_all_hybrid_workers(reason="test cancellation") - else: - h.runtime.close() - h.advance(1) # the production Event's next 50ms poll observes closing - with pytest.raises(RuntimeError, match="cancelled"): - h.handle.result(timeout=3) - worker = h.pool.snapshot()["rollout0"] - assert worker.join_state.value == "cancelled" - assert worker.role.value != "hybrid_training" - - -@pytest.mark.parametrize("cold,seconds", [(True, 180), (False, 60)]) -def test_worker_installation_ack_still_has_its_existing_deadline( - tmp_path, monkeypatch, cold, seconds): - clock = NS(now=0.0) - monkeypatch.setattr(runtime_module, "time", NS(monotonic=lambda: clock.now)) - config = AsyncRLConfig(model_path="/not-loaded", train_gpus=1, rollout_gpus=1, - n_total_gpus=2, train_tp_size=1, train_dp_size=1) - config.global_resource_planner.hybrid_worker_task_dir = str(tmp_path) - config.global_resource_planner.hybrid_worker_ready_timeout_s = 60 - runtime = RuntimeElasticExecutor(config=config, planner=NS()) - manifest = tmp_path / "manifest.json" - manifest.write_text(json.dumps({"format": "libra-ehp-lanes-v1", - "snapshot_id": "state", "optimizer_revision": 2, - "lanes": {"dp0": {"0": "ehp://source/lane0"}}})) - - def advance(_seconds): - clock.now += 1 - return False - - runtime._closing = NS(is_set=lambda: False, wait=advance) - with pytest.raises(TimeoutError, match=f"after {seconds}s"): - runtime._wait_hybrid_worker_ready("replica", state_version=2, - replica_world_size=1, snapshot_path=str(manifest), target_core_id="dp0", - **({"timeout_s": 180} if cold else {})) - assert clock.now == seconds - - -def test_planner_sees_the_number_of_ready_replicas_among_pending_joins(): - config = AsyncRLConfig(model_path='/not-loaded', train_gpus=2, rollout_gpus=4, - n_total_gpus=6, train_tp_size=2, train_dp_size=1) - runtime = RuntimeElasticExecutor(config=config, planner=NS()) - runtime._pending_hybrid_joins = { - 'ready-one':NS(done=lambda:False), 'still-loading':NS(done=lambda:False)} - runtime._pending_activations = {'ready-one':{}} - state = runtime.hybrid_runtime_state() - assert state['pending_hybrid_replica_joins'] == 2 - assert state['activation_ready_replicas'] == 1 - - -def test_runtime_exposes_current_generates_separately_from_trace_load(): - from RL_Framework.infra.scheduling.cmlfq_cost_scheduler import CMLFQCostScheduler - - scheduler = CMLFQCostScheduler() - scheduler.register_instance(0, 'a', 1) - scheduler.register_instance(1, 'b', 1) - generating = scheduler.schedule(100, 'p').request_id - scheduler.schedule(100, 'tool-wait') - scheduler.reserve_generation(generating) - config = AsyncRLConfig(model_path='/not-loaded', train_gpus=2, rollout_gpus=2, - n_total_gpus=4, train_tp_size=2, train_dp_size=1) - executor = RuntimeElasticExecutor(config=config, planner=NS(), rollout_engine=NS(scheduler=scheduler)) - - assert executor.hybrid_runtime_state()['generate_reservations_by_instance'] == {'a': 1, 'b': 0} diff --git a/tests/test_hybrid_join_readiness_budget.py b/tests/test_hybrid_join_readiness_budget.py deleted file mode 100644 index ee7bdf2..0000000 --- a/tests/test_hybrid_join_readiness_budget.py +++ /dev/null @@ -1,223 +0,0 @@ -"""Cold startup shares the join budget; live state catch-up keeps its ACK budget.""" - -import json -import threading -from types import SimpleNamespace - -import pytest - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.elastic import hybrid_pool as pool_module -from RL_Framework.infra.elastic import runtime_executor as runtime_module -from RL_Framework.infra.elastic.hybrid_pool import ElasticHybridPool -from RL_Framework.infra.elastic.runtime_executor import ( - RuntimeElasticExecutor, - RuntimeReconfigurationResult, -) - - -@pytest.fixture -def bootstrap(tmp_path, monkeypatch): - clock = SimpleNamespace(now=0.0) - timing = SimpleNamespace(monotonic=lambda: clock.now, time=lambda: clock.now) - monkeypatch.setattr(runtime_module, "time", timing) - monkeypatch.setattr(pool_module, "time", timing) - config = AsyncRLConfig(model_path="/not-loaded", train_gpus=1, rollout_gpus=1, - n_total_gpus=2, train_tp_size=1, train_dp_size=1) - cfg = config.global_resource_planner - cfg.hybrid_worker_task_dir = str(tmp_path) - cfg.hybrid_worker_launch_enabled = True - cfg.hybrid_worker_remote_control_enabled = True - cfg.elastic_hybrid_join_timeout_s = 180 - cfg.hybrid_worker_ready_timeout_s = 60 - pool = ElasticHybridPool(core_train_workers=["dp0"], - core_rollout_workers=["rollout0"], snapshot_fetcher=lambda *args: 0) - executor = RuntimeElasticExecutor(config=config, planner=SimpleNamespace(), elastic_pool=pool) - manifest = tmp_path / "snapshot.json" - manifest.write_text(json.dumps({"format": "libra-ehp-lanes-v1", - "optimizer_revision": 0, "snapshot_id": "capture0", - "lanes": {"dp0": {"0": "ehp://source/lane0"}}})) - executor._snapshot_manifests[0] = str(manifest) - monkeypatch.setattr(executor, "_capture_core_snapshot", lambda: str(manifest)) - monkeypatch.setattr(executor, "_build_hybrid_worker_command", lambda **kw: "not executed") - monkeypatch.setattr(executor, "_cluster_swap_training_slot", - lambda *args: {"host": "allocated-node", "gpus": [1]}) - monkeypatch.setattr(executor, "_desired_hybrid_workers", lambda *args: 1) - monkeypatch.setattr(executor, "_training_reconfiguration_targets", - lambda *args: (["dp0"], "dp0", ["rollout0"])) - # The loader's initial installation is the subject here, before the real - # activation queue hands control back to a Core training boundary. - monkeypatch.setattr(executor, "_queue_activation", lambda identity, receipt: receipt) - ready_at = 70.0 - identity = SimpleNamespace(worker="ehp_replica_rollout0") - - def advance(_seconds): - clock.now += 1 - if clock.now >= ready_at: - receipt = dict(snapshot=str(manifest), rank=0, pid=123, acknowledged=True, - snapshot_id="capture0", optimizer_revision=0, state_version=0, - lane_snapshot_id="lane0", target_core_id="dp0", source_uri="ehp://source/lane0") - receipt.update(executor.hybrid_task_identity(identity.worker)) - (tmp_path / f"{identity.worker}.rank_0.ready").write_text( - "".join(f"{key}={value}\n" for key, value in receipt.items())) - return False - - executor._closing = SimpleNamespace(is_set=lambda: False, wait=advance) - yield SimpleNamespace(executor=executor, pool=pool, clock=clock, - manifest=manifest, identity=identity) - pool.close() - - -@pytest.mark.parametrize("replica", [True, False], ids=["replica", "singleton"]) -def test_initial_installation_can_be_ready_after_seventy_seconds(bootstrap, replica): - h = bootstrap - if replica: - h.executor._reconfigure_training_pool(1, SimpleNamespace(), - RuntimeReconfigurationResult(False, "test")) - handle = h.executor._pending_hybrid_joins["ehp_replica_rollout0"] - else: - h.identity.worker = "rollout0" - handle = h.pool.join_training("rollout0", "dp0", timeout_s=180, - activation_barrier=h.executor._activate_hybrid_worker) - handle.result(timeout=3) - assert h.clock.now == 70 - assert h.pool.snapshot()["rollout0"].role.value == "hybrid_training" - - -def test_live_state_catchup_still_times_out_after_sixty_seconds(bootstrap): - h = bootstrap - with pytest.raises(TimeoutError, match="after 60s"): - h.executor._wait_hybrid_worker_ready(h.identity.worker, state_version=0, - replica_world_size=1, snapshot_path=str(h.manifest), target_core_id="dp0") - assert h.clock.now == 60 - - -@pytest.mark.parametrize("preparation_seconds", [0, 20]) -def test_initial_installation_does_not_extend_the_overall_join_deadline( - bootstrap, monkeypatch, preparation_seconds): - h = bootstrap - h.executor.config.global_resource_planner.elastic_hybrid_join_timeout_s = 65 - - def prepare(**kwargs): - h.clock.now += preparation_seconds - return "not executed" - - monkeypatch.setattr(h.executor, "_build_hybrid_worker_command", prepare) - h.executor._reconfigure_training_pool(1, SimpleNamespace(), - RuntimeReconfigurationResult(False, "test")) - handle = h.executor._pending_hybrid_joins["ehp_replica_rollout0"] - with pytest.raises(TimeoutError): - handle.result(timeout=3) - # The pool checks its original deadline on every poll; preparation cannot - # restart it. The clock advances in one-second increments in this fixture. - assert h.clock.now <= 66 - - -@pytest.fixture -def queued_activation(bootstrap, monkeypatch): - h = bootstrap - executor = h.executor - monkeypatch.setattr(executor, "_queue_activation", - RuntimeElasticExecutor._queue_activation.__get__(executor)) - monkeypatch.setattr(executor, "_publish_hybrid_membership", lambda: None) - monkeypatch.setattr(executor, "_stop_hybrid_worker_process", lambda *args: None) - monkeypatch.setattr(executor, "_stop_managed_rollout_processes", lambda: None) - from RL_Framework.infra.elastic import core_reconfiguration - monkeypatch.setattr(core_reconfiguration, "dispatch_core_command", lambda *args, **kwargs: []) - closing = threading.Event() - cold_wait = executor._closing.wait - state = SimpleNamespace(catching_up=False, ack_at=0, capture_seconds=0) - latest = h.manifest.with_name("snapshot14.json") - latest.write_text(json.dumps({"format": "libra-ehp-lanes-v1", - "optimizer_revision": 14, "snapshot_id": "capture14", - "lanes": {"dp0": {"0": "ehp://source/lane14"}}})) - - def acknowledge(): - receipt = dict(snapshot=str(latest), rank=0, pid=123, acknowledged=True, - snapshot_id="capture14", optimizer_revision=14, state_version=14, - lane_snapshot_id="lane14", target_core_id="dp0", source_uri="ehp://source/lane14") - receipt.update(executor.hybrid_task_identity(h.identity.worker)) - (latest.parent / f"{h.identity.worker}.rank_0.ready").write_text( - "".join(f"{key}={value}\n" for key, value in receipt.items())) - - def advance(seconds): - if not state.catching_up: - return cold_wait(seconds) - h.clock.now += 1 - if h.clock.now >= state.ack_at: - acknowledge() - return closing.is_set() - - def capture(): - h.clock.now += state.capture_seconds - return str(latest) - - executor._closing = SimpleNamespace(is_set=closing.is_set, set=closing.set, wait=advance) - executor._reconfigure_training_pool(1, SimpleNamespace(), - RuntimeReconfigurationResult(False, "test")) - handle = executor._pending_hybrid_joins[h.identity.worker] - for _ in range(200): - if executor.has_pending_activations(): - break - threading.Event().wait(.01) - assert executor.has_pending_activations() - assert h.clock.now == 70 - assert not handle.done() - # Submission occurred at t=0, before the fake clock's cold-start polls. - executor._pending_hybrid_join_started_at[h.identity.worker] = 0 - executor.train_engine = SimpleNamespace(optimizer_revision=14) - monkeypatch.setattr(executor, "_capture_core_snapshot", capture) - state.catching_up = True - h.handle, h.catchup, h.acknowledge = handle, state, acknowledge - try: - yield h - finally: - closing.set() - with executor._pending_activation_lock: - for request in executor._pending_activations.values(): - request["error"] = "test cleanup" - request["event"].set() - - -@pytest.mark.parametrize("boundary_at,capture_seconds", [(140, 0), (70, 90)], - ids=["ack-at-190", "cold70-capture90-install50"]) -def test_activation_queue_can_finish_after_cold_deadline( - queued_activation, boundary_at, capture_seconds): - h = queued_activation - h.clock.now = boundary_at - h.catchup.capture_seconds = capture_seconds - h.catchup.ack_at = boundary_at + capture_seconds + 50 - h.executor._finish_pending_activations() - workers = h.handle.result(timeout=3) - assert h.clock.now == h.catchup.ack_at - assert all(worker.join_state.value == "active" and worker.state_version == 14 - for worker in workers) - assert h.pool.snapshot()["rollout0"].state_version == 14 - - -def test_reconcile_does_not_cancel_a_join_waiting_in_activation_queue(queued_activation): - h = queued_activation - h.clock.now = 190 - h.executor._reconcile_pending_hybrid_joins() - assert h.executor._pending_hybrid_joins[h.identity.worker] is h.handle - assert not h.handle.done() - assert h.pool.snapshot()["rollout0"].join_state.value == "activating" - - -@pytest.mark.parametrize("action", ["cancel", "close"]) -def test_queued_activation_late_ack_cannot_activate_cancelled_join(queued_activation, action): - h = queued_activation - if action == "cancel": - h.handle.cancel() - else: - h.executor.close() - h.clock.now = 90 - h.catchup.ack_at = 90 - h.acknowledge() - with pytest.raises(RuntimeError): - h.executor._finish_pending_activations() - with pytest.raises(RuntimeError): - h.handle.result(timeout=3) - worker = h.pool.snapshot()["rollout0"] - assert worker.join_state.value == "cancelled" - assert worker.role.value != "hybrid_training" diff --git a/tests/test_hybrid_optimizer_cuda_cache.py b/tests/test_hybrid_optimizer_cuda_cache.py deleted file mode 100644 index 0ec61ad..0000000 --- a/tests/test_hybrid_optimizer_cuda_cache.py +++ /dev/null @@ -1,125 +0,0 @@ -"""Hybrid cache release happens once, without changing gradient/update semantics.""" - -from contextlib import contextmanager -from types import SimpleNamespace - -import pytest -import torch - -from RL_Framework.engine.megatron_core_train_engine import MegatronCoreTrainEngine - - -class DeviceGradient: - def __init__(self, calls): - self.calls = calls - self.device = torch.device('cuda:1') - self.dtype = torch.bfloat16 - self.tensor = torch.zeros(2, dtype=self.dtype) - - def copy_(self, value): - self.calls.append('copy') - self.tensor.copy_(value) - - -class Source: - def __init__(self, value): - self.tensor = torch.tensor(value, dtype=torch.float32) - - def to(self, *, device, dtype): - assert device == torch.device('cuda:1') - return self.tensor.to(dtype=dtype) - - -def cuda_engine(monkeypatch): - calls = [] - gradients = [DeviceGradient(calls), DeviceGradient(calls)] - engine = MegatronCoreTrainEngine.__new__(MegatronCoreTrainEngine) - engine.rank, engine.optimizer_revision = 0, 1 - engine._model_main_gradients = lambda: gradients - engine.optimizer = SimpleNamespace(step=lambda: (calls.append('step') or (True, 0., 0))) - monkeypatch.setattr(torch.cuda, 'is_available', lambda: True) - - @contextmanager - def device_context(device): - assert device == torch.device('cuda:1') - calls.append('enter') - yield - calls.append('exit') - - monkeypatch.setattr(torch.cuda, 'device', device_context) - monkeypatch.setattr(torch.cuda, 'empty_cache', lambda: calls.append('empty')) - return engine, gradients, calls - - -def test_first_cuda_hybrid_update_releases_after_copy_and_before_step(monkeypatch, capsys): - engine, gradients, calls = cuda_engine(monkeypatch) - sources = (Source([1.25, 2.5]), Source([3., 4.])) - engine.apply_elastic_gradient_update(sources, state_version=2) - assert calls == ['copy', 'copy', 'enter', 'empty', 'exit', 'step'] - assert engine.optimizer_revision == 2 and engine._hybrid_optimizer_cuda_cache_released - for gradient, source in zip(gradients, sources): - assert torch.equal(gradient.tensor, source.tensor.bfloat16()) - assert not capsys.readouterr().out - calls.clear() - engine.apply_elastic_gradient_update(sources, state_version=3) - assert calls == ['copy', 'copy', 'step'] and engine.optimizer_revision == 3 - assert not capsys.readouterr().out - - -def test_optimizer_exception_is_preserved_and_cache_release_can_retry(monkeypatch): - engine, _gradients, calls = cuda_engine(monkeypatch) - failure = RuntimeError('original NCCL failure') - - def failed_step(): - calls.append('step') - raise failure - - engine.optimizer.step = failed_step - with pytest.raises(RuntimeError) as error: - engine.apply_elastic_gradient_update((Source([1., 2.]), Source([3., 4.])), state_version=2) - assert error.value is failure and engine.optimizer_revision == 1 - assert not getattr(engine, '_hybrid_optimizer_cuda_cache_released', False) - engine.optimizer.step = lambda: (True, 0., 0) - engine.apply_elastic_gradient_update((Source([1., 2.]), Source([3., 4.])), state_version=2) - assert calls.count('empty') == 2 and engine.optimizer_revision == 2 - - -def test_rejected_optimizer_update_does_not_mark_cache_or_revision_complete(monkeypatch): - engine, _gradients, calls = cuda_engine(monkeypatch) - engine.optimizer.step = lambda: (False, 0., 0) - with pytest.raises(FloatingPointError, match='rejected the update'): - engine.apply_elastic_gradient_update((Source([1., 2.]), Source([3., 4.])), state_version=2) - assert calls.count('empty') == 1 and engine.optimizer_revision == 1 - assert not getattr(engine, '_hybrid_optimizer_cuda_cache_released', False) - - -@pytest.mark.parametrize('cuda_available', [False, True]) -def test_cpu_gradients_keep_original_copy_dtype_and_optimizer_update(monkeypatch, cuda_available): - engine = MegatronCoreTrainEngine.__new__(MegatronCoreTrainEngine) - gradient = torch.zeros(2, dtype=torch.bfloat16) - source = torch.tensor([1.25, -2.5], dtype=torch.float32) - source_before = source.clone() - weight = torch.tensor([10., 20.]) - engine.optimizer_revision = 1 - engine._model_main_gradients = lambda: [gradient] - monkeypatch.setattr(torch.cuda, 'is_available', lambda: cuda_available) - monkeypatch.setattr(torch.cuda, 'empty_cache', lambda: pytest.fail('CPU path released CUDA cache')) - - def step(): - weight.sub_(gradient.float(), alpha=.1) - return True, 0., 0 - - engine.optimizer = SimpleNamespace(step=step) - engine.apply_elastic_gradient_update((source,), state_version=2) - assert torch.equal(source, source_before) - assert torch.equal(gradient, source.bfloat16()) - assert torch.equal(weight, torch.tensor([10., 20.]) - source.bfloat16().float() * .1) - assert engine.optimizer_revision == 2 - assert not getattr(engine, '_hybrid_optimizer_cuda_cache_released', False) - - -def test_tensor_count_failure_happens_before_copy_or_cache_release(monkeypatch): - engine, _gradients, calls = cuda_engine(monkeypatch) - with pytest.raises(ValueError, match='tensor count mismatch'): - engine.apply_elastic_gradient_update((Source([1., 2.]),), state_version=2) - assert calls == [] and engine.optimizer_revision == 1 diff --git a/tests/test_hybrid_sample_statistics.py b/tests/test_hybrid_sample_statistics.py deleted file mode 100644 index 88c2ea4..0000000 --- a/tests/test_hybrid_sample_statistics.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Core reports the full batch only after the activation protocol accepts gradients.""" -from dataclasses import replace - -import pytest - -from hybrid_statistics_helpers import compute, engine, rows - - -@pytest.mark.parametrize('core_count,zero_mask',[(8,False),(8,True),(0,False)]) -def test_real_payload_and_grpo_report_all_samples_without_counting_extra_core_updates( - monkeypatch,core_count,zero_mask): - core_rows=rows(0,core_count) - hybrid_count=4 if core_count else 12 - hybrid_rows=rows(8,hybrid_count,zero_mask=zero_mask) - _,payload=compute(monkeypatch,hybrid_rows) - core,steps=engine(monkeypatch) - core.set_elastic_batch_partition(core_count,12,{'hybrid':hybrid_count}) - core.enqueue_hybrid_gradient_payload(payload) - reference=core._merge_stats([core._loss(batch,core._forward(batch))[1] - for batch in core._iter_micro_batches(core_rows+hybrid_rows)]) - result=core.grpo_update(core_rows) - assert result['n_samples']==12 - assert result['reward_sum']==reference['reward_sum'] - for key in ('loss','pg_loss','kl','reward_mean'): - assert result[key]==pytest.approx(reference[key],abs=1e-6) - assert result['n_updates']==(core_count+2)//3 - if core_count: - assert result['grad_norm']==7. - assert len(steps)==1 and core.optimizer_revision==3 - - -def test_only_this_reduction_matching_lane_and_target_statistics_are_used(monkeypatch): - _,payload=compute(monkeypatch,rows(8,4),lane=1,width=2) - core,_=engine(monkeypatch,lane=1,width=2) - core.set_elastic_batch_partition(8,12,{'hybrid':4}) - core.enqueue_hybrid_gradient_payload(payload) - assert hasattr(payload,'stats'), 'Hybrid compute discarded the loss statistics' - ignored=replace(payload,replica_rank=0,stats=dict(payload.stats,n_samples=999.)) - stale=replace(payload,replica_id='old',step=2,stats=dict(payload.stats,n_samples=888.)) - prior=(stale.replica_id,stale.replica_rank,stale.step,stale.state_version,stale.membership_epoch) - core.elastic_gradient_domain._consumed_payloads.add(prior) - core._pending_hybrid_gradients.extend([ignored,stale]) - result=core.grpo_update(rows(0,8)) - assert result['n_samples']==12 and result['n_updates']==3 diff --git a/tests/test_hybrid_sample_statistics_data.py b/tests/test_hybrid_sample_statistics_data.py deleted file mode 100644 index a222739..0000000 --- a/tests/test_hybrid_sample_statistics_data.py +++ /dev/null @@ -1,53 +0,0 @@ -"""Hybrid loss statistics are sample means carried by the existing transports.""" -import shutil - -import pytest - -from hybrid_statistics_helpers import compute, rows -from RL_Framework.infra.elastic.gradient_ipc import ElasticGradientClient, ElasticGradientServer -from RL_Framework.infra.elastic.native_rdma import NativeRDMAGradientClient, NativeRDMAGradientServer - - -@pytest.mark.parametrize('zero_mask',[False,True]) -def test_payload_statistics_match_single_sample_means(monkeypatch,zero_mask): - samples=rows(8,4,zero_mask=zero_mask) - worker,payload=compute(monkeypatch,samples) - per_sample=[] - for row in samples: - batch=worker._pad_micro_batch([row]) - per_sample.append(worker._loss(batch,worker._forward(batch))[1]) - reference=worker._merge_stats(per_sample) - for key in ('loss','pg_loss','kl','reward_sum','reward_mean','n_samples'): - assert payload.stats[key]==pytest.approx(reference[key],abs=1e-6) - assert payload.stats['n_samples']==4 and payload.stats['n_updates']==2 - - -def test_tcp_transports_statistics_from_real_hybrid_compute(monkeypatch): - _,payload=compute(monkeypatch,rows(8,4)) - assert hasattr(payload,'stats'), 'Hybrid compute discarded the loss statistics' - received=[] - server=ElasticGradientServer(on_payload=received.append) - endpoint=server.start() - try: - ElasticGradientClient(endpoint).send(payload) - assert received[0].stats==payload.stats - finally: - server.close() - - -def test_native_metadata_transports_statistics_without_requiring_rdma_hardware(tmp_path,monkeypatch): - _,payload=compute(monkeypatch,rows(8,4)) - assert hasattr(payload,'stats'), 'Hybrid compute discarded the loss statistics' - received=[] - server=NativeRDMAGradientServer(on_payload=received.append,work_dir=tmp_path/'server') - staged=tmp_path/'wire.pt' - client=NativeRDMAGradientClient(server.endpoint) - client.transfer.send_file_once=lambda input_path,**kw:shutil.copyfile(input_path,staged) - client.send(payload) - def transfer(output_path,**kw): - shutil.copyfile(staged,output_path) - server._stop.set() - server.transfer.receive_file_once=transfer - server._serve() - assert server.last_error is None - assert received[0].stats==payload.stats diff --git a/tests/test_hybrid_task_lifecycle.py b/tests/test_hybrid_task_lifecycle.py deleted file mode 100644 index fcd2762..0000000 --- a/tests/test_hybrid_task_lifecycle.py +++ /dev/null @@ -1,132 +0,0 @@ -"""Hybrid completion receipts fence normal return; exit fences cancellation.""" -import threading -from types import SimpleNamespace - -import pytest - -from RL_Framework.infra.elastic.runtime_executor import ManagedHybridWorkerProcess, RuntimeElasticExecutor - - -def _executor(tmp_path): - executor = RuntimeElasticExecutor.__new__(RuntimeElasticExecutor) - executor.config = SimpleNamespace(global_resource_planner=SimpleNamespace( - hybrid_worker_task_dir=str(tmp_path), hybrid_worker_remote_control_dir=str(tmp_path), - hybrid_worker_remote_control_enabled=True, hybrid_update_timeout_s=.3, - hybrid_worker_stop_timeout_s=.1)) - executor._lifecycle_lock = threading.RLock() - executor._hybrid_worker_processes = {} - executor._hybrid_task_contexts = {} - canonical = ManagedHybridWorkerProcess('h', 'dp0', 'worker', 123, 'snapshot', host='node') - member = ManagedHybridWorkerProcess('member', 'dp0', 'worker', -1, 'snapshot', host='node', replica_id='h') - canonical.launch_owner = member.launch_owner = 'current-launch' - executor._hybrid_worker_meta = {'h': canonical, 'member': member} - return executor - - -def test_normal_return_waits_for_actual_task_completion_before_detach(tmp_path): - executor = _executor(tmp_path) - executor._snapshot_cleanup_requested = False - executor._pending_activation_lock = threading.RLock() - executor._pending_activations = {} - executor._pending_hybrid_join_lock = threading.RLock() - executor._pending_hybrid_joins = {} - executor._pending_hybrid_join_started_at = {} - executor._retired_hybrid_joins = [] - executor._publish_hybrid_membership = lambda: None - worker = SimpleNamespace(worker_id='member', role='hybrid_training') - detached = [] - executor.elastic_pool = SimpleNamespace(replica_snapshot=lambda: {'h': (worker,)}, - release_replica_to_rollout=lambda replica: detached.append(replica)) - executor._stop_snapshot_loader = lambda *_: None - task = tmp_path / 'h.step_14.pt' - task.write_text('already consumed by Core, still applying on Hybrid') - executor.record_hybrid_task_assignment('h', dict(launch_owner='current-launch', step=14), task) - finished = threading.Event() - thread = threading.Thread(target=lambda: (executor._release_all_hybrid_workers(reason='planner'), finished.set())) - thread.start() - try: - assert not finished.wait(.08) - assert not detached - task.rename(str(task) + '.done') - assert finished.wait(2) - assert detached == ['h'] - finally: - task.rename(str(task) + '.done') if task.exists() else None - thread.join(2) - - -def test_failed_or_missing_completion_is_not_success(tmp_path): - executor = _executor(tmp_path) - executor.config.global_resource_planner.hybrid_update_timeout_s = .05 - task = tmp_path / 'h.step_14.pt'; task.touch() - executor.record_hybrid_task_assignment('h', dict(launch_owner='current-launch', step=14), task) - with pytest.raises(TimeoutError, match='completion'): - executor.wait_for_hybrid_training_tasks('member') - assert task.exists() and not (tmp_path / 'h.step_14.pt.done').exists() - - -def test_worker_failure_while_waiting_propagates_without_completion(tmp_path): - executor = _executor(tmp_path) - task = tmp_path / 'h.step_14.pt'; task.touch() - executor.record_hybrid_task_assignment('h', dict(launch_owner='current-launch', step=14), task) - worker = threading.Timer(.02, lambda: task.rename(str(task) + '.failed')) - worker.start() - try: - with pytest.raises(RuntimeError, match='failed before completion'): - executor.wait_for_hybrid_training_tasks('member') - finally: - worker.join(2) - assert not (tmp_path / 'h.step_14.pt.done').exists() - - -def test_confirmed_exit_retires_only_old_owner_tasks_without_faking_done(tmp_path, monkeypatch): - from RL_Framework.infra.elastic import rollout_lending - executor = _executor(tmp_path) - task = tmp_path / 'h.step_14.pt'; task.write_text('membership_epoch=7;state_version=14') - executor.record_hybrid_task_assignment('h', dict(launch_owner='current-launch', step=14), task) - other = tmp_path / 'other.step_14.pt'; other.touch() - (tmp_path / 'h.step_13.pt.done').touch() - observed = [] - def acknowledge(executor, worker, request_id=None): - observed.append(worker) - assert task.exists() and 'h' in executor._hybrid_worker_meta - return dict(worker_id=worker, request_id=request_id, exited=True) - monkeypatch.setattr(rollout_lending, 'wait_hybrid_stopped', acknowledge) - executor._stop_hybrid_worker_process('member') - assert observed == ['h'] - assert not task.exists() and not (tmp_path / 'h.step_14.pt.done').exists() - assert (tmp_path / 'h.step_14.pt.cancelled').read_text() == 'membership_epoch=7;state_version=14' - assert other.exists() and (tmp_path / 'h.step_13.pt.done').exists() - assert not executor._hybrid_worker_meta - - -def test_failed_stop_retains_pending_task_for_owned_retry(tmp_path, monkeypatch): - from RL_Framework.infra.elastic import rollout_lending - executor = _executor(tmp_path) - task = tmp_path / 'h.step_14.pt'; task.touch() - executor.record_hybrid_task_assignment('h', dict(launch_owner='current-launch', step=14), task) - def fail(*args, **kwargs): - raise TimeoutError('old process has not exited') - monkeypatch.setattr(rollout_lending, 'wait_hybrid_stopped', fail) - with pytest.raises(TimeoutError): - executor._stop_hybrid_worker_process('member') - assert task.exists() and executor._hybrid_worker_meta - assert not (tmp_path / 'h.step_14.pt.cancelled').exists() - - -def test_local_exit_also_retires_unfinished_task(tmp_path, monkeypatch): - from RL_Framework.infra.elastic import process_lifecycle - executor = _executor(tmp_path) - proc = object() - executor._hybrid_worker_processes = {'h': proc, 'member': proc} - task = tmp_path / 'h.step_14.pt'; task.touch() - executor.record_hybrid_task_assignment('h', dict(launch_owner='current-launch', step=14), task) - exited = [] - def stop(owned, timeout): - assert owned is proc and task.exists() - exited.append(True) - monkeypatch.setattr(process_lifecycle, 'stop_local_worker', stop) - executor._stop_hybrid_worker_process('member') - assert exited and not task.exists() - assert (tmp_path / 'h.step_14.pt.cancelled').exists() - assert not executor._hybrid_worker_processes and not executor._hybrid_worker_meta diff --git a/tests/test_hybrid_worker_batch_protocol.py b/tests/test_hybrid_worker_batch_protocol.py deleted file mode 100644 index 76c25f0..0000000 --- a/tests/test_hybrid_worker_batch_protocol.py +++ /dev/null @@ -1,61 +0,0 @@ -"""The worker forwards fixed-batch counts through its actual task loop.""" -import importlib.util -from pathlib import Path -from types import SimpleNamespace - -import torch - -from RL_Framework.infra.elastic.hybrid_pool import GradientPayload - - -def _worker(): - path = Path(__file__).parents[1] / 'scripts' / 'elastic_hybrid_worker.py' - spec = importlib.util.spec_from_file_location('hybrid_batch_worker', path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -def test_payload_file_retains_local_and_global_sample_counts(tmp_path): - worker = _worker() - path = tmp_path / 'payload.pt' - torch.save(dict(tensors=[torch.ones(1)], sample_count=4, global_sample_count=12), path) - args = SimpleNamespace(replica_id='h', replica_rank=0, replica_world_size=1) - payload = worker._load_payload_file(path, worker_id='h', target_core_id='dp0', args=args) - assert payload.sample_count == 4 and payload.global_sample_count == 12 - - -def test_training_task_passes_global_count_to_engine_and_gradient_client(tmp_path, monkeypatch): - worker = _worker() - snapshot = tmp_path / 'snapshot.pt' - snapshot.touch() - args = SimpleNamespace(snapshot_path=str(snapshot), initialize_only=False, - worker_mode='megatron_core', gradient_host='localhost', gradient_port=1, - authkey='', gradient_transport='tcp', payload_file='', idle=False, - task_dir=str(tmp_path), worker_id='h', replica_id='h', target_core_id='dp0') - received, sent = [], [] - - def compute(trajectories, **metadata): - received.append(metadata) - return GradientPayload('h', 'dp0', (torch.ones(1),), - step=metadata['step'], state_version=metadata['state_version'], - membership_epoch=metadata['membership_epoch'], sample_count=len(trajectories), - global_sample_count=metadata['global_sample_count']) - - engine = SimpleNamespace(hybrid_lockstep_gradient_sync=False, recompute_logprobs=lambda _: None, - compute_elastic_gradient_payload=compute) - monkeypatch.setattr(worker, 'parse_args', lambda: args) - monkeypatch.setattr(worker, '_initialize_megatron_worker', lambda _: engine) - monkeypatch.setattr(worker, '_endpoint_for_lane', lambda *_: {}) - monkeypatch.setattr(worker, '_gradient_client', lambda *_: - SimpleNamespace(send=lambda payload, **_: sent.append(payload))) - monkeypatch.setattr(worker.torch.distributed, 'is_initialized', lambda: False) - monkeypatch.setenv('RANK', '0') - torch.save(dict(trajectories=[{}] * 4, step=3, state_version=2, - membership_epoch=7, sample_count=4, global_sample_count=12), tmp_path / 'h.0.pt') - torch.save(dict(shutdown=True), tmp_path / 'h.1.pt') - worker.main() - assert received[0]['global_sample_count'] == 12 - assert received[0]['state_version'] == 2 - assert len(sent) == 1 and sent[0].sample_count == 4 and sent[0].global_sample_count == 12 - assert (tmp_path / 'h.0.pt.done').exists() diff --git a/tests/test_megatron_core_attention.py b/tests/test_megatron_core_attention.py deleted file mode 100644 index 9a4fefe..0000000 --- a/tests/test_megatron_core_attention.py +++ /dev/null @@ -1,20 +0,0 @@ -from types import SimpleNamespace - -from RL_Framework.engine.megatron_core_attention import ( - TorchSequenceParallelNorm, -) - - -def test_torch_norm_marks_replicated_parameters_for_sequence_parallel(): - config = SimpleNamespace( - normalization="RMSNorm", - sequence_parallel=True, - layernorm_zero_centered_gamma=False, - persist_layer_norm=False, - memory_efficient_layer_norm=False, - ) - - norm = TorchSequenceParallelNorm(config, hidden_size=16, eps=1e-6) - - assert norm.weight.shape == (16,) - assert norm.weight.sequence_parallel is True diff --git a/tests/test_megatron_core_checkpointing.py b/tests/test_megatron_core_checkpointing.py deleted file mode 100644 index 36e45e7..0000000 --- a/tests/test_megatron_core_checkpointing.py +++ /dev/null @@ -1,147 +0,0 @@ -import json - -from RL_Framework.engine.megatron_core_checkpointing import ( - MegatronDistributedCheckpointManager, -) - - -class FakeModel: - def __init__(self): - self.loaded = None - - def sharded_state_dict(self): - return {"weight": "local-shard"} - - def load_state_dict(self, state): - self.loaded = state - - -class FakeOptimizer: - def __init__(self): - self.loaded = None - - def sharded_state_dict(self, model_state, is_loading=False): - assert "model" in model_state - suffix = "load-template" if is_loading else "optimizer-shard" - return {"state": suffix} - - def load_state_dict(self, state): - self.loaded = state - - -class FakeDistCheckpointing: - def __init__(self): - self.saved = None - - def save( - self, - *, - sharded_state_dict, - checkpoint_dir, - sharded_strategy, - async_sharded_save, - ): - self.saved = { - "state": sharded_state_dict, - "checkpoint_dir": checkpoint_dir, - "strategy": sharded_strategy, - "async": async_sharded_save, - } - return None - - def load(self, *, sharded_state_dict, checkpoint_dir, sharded_strategy): - assert "model" in sharded_state_dict - assert checkpoint_dir.endswith("megatron_dist") - assert sharded_strategy is None - return { - "model": {"weight": "restored-shard"}, - "optimizer": {"state": "restored-optimizer-shard"}, - } - - -class FakeBridge: - def __init__(self): - self.calls = [] - - def save_hf_pretrained(self, model, path, show_progress): - self.calls.append((model, path, show_progress)) - (path / "model-00001-of-00002.safetensors").write_bytes(b"shard") - (path / "model.safetensors.index.json").write_text( - json.dumps({"weight_map": {"weight": "model-00001-of-00002.safetensors"}}), - encoding="utf-8", - ) - - -def test_distributed_checkpoint_and_streaming_export(tmp_path, monkeypatch): - manager = MegatronDistributedCheckpointManager( - sync_path=str(tmp_path), - fully_parallel_save=False, - ) - dist_checkpointing = FakeDistCheckpointing() - monkeypatch.setattr( - manager, - "_dist_checkpointing", - lambda: dist_checkpointing, - ) - model = [FakeModel()] - optimizer = FakeOptimizer() - bridge = FakeBridge() - - version_dir = manager.save( - model=model, - optimizer=optimizer, - bridge=bridge, - version=5, - topology={ - "train_tp": 1, - "train_pp": 1, - "train_cp": 1, - "train_ep": 8, - "train_dp": 8, - }, - ) - - assert dist_checkpointing.saved["state"]["model"] == { - "weight": "local-shard" - } - assert bridge.calls == [(model, version_dir, True)] - manifest = json.loads( - (version_dir / "megatron_checkpoint_manifest.json").read_text( - encoding="utf-8" - ) - ) - assert manifest["checkpoint_format"] == "torch_dist" - assert manifest["expert_parallel_size"] == 8 - assert manifest["includes_optimizer"] is True - progress = json.loads( - (version_dir / "sync_progress" / "rank_0.json").read_text( - encoding="utf-8" - ) - ) - assert progress["phase"] == "complete" - - -def test_load_uses_sharded_templates(tmp_path, monkeypatch): - manager = MegatronDistributedCheckpointManager( - sync_path=str(tmp_path), - fully_parallel_save=False, - ) - dist_checkpointing = FakeDistCheckpointing() - monkeypatch.setattr( - manager, - "_dist_checkpointing", - lambda: dist_checkpointing, - ) - version_dir = tmp_path / "v3" - (version_dir / "megatron_dist").mkdir(parents=True) - (version_dir / "megatron_checkpoint_manifest.json").write_text( - "{}", - encoding="utf-8", - ) - model = [FakeModel()] - optimizer = FakeOptimizer() - - manager.load(model=model, optimizer=optimizer, version=3) - - assert model[0].loaded == {"weight": "restored-shard"} - assert optimizer.loaded == {"state": "restored-optimizer-shard"} diff --git a/tests/test_megatron_core_moe_mapping.py b/tests/test_megatron_core_moe_mapping.py deleted file mode 100644 index 6792324..0000000 --- a/tests/test_megatron_core_moe_mapping.py +++ /dev/null @@ -1,40 +0,0 @@ -import torch - -from RL_Framework.engine.megatron_core_moe_mapping import ( - pack_grouped_weight1, - pack_grouped_weight2, -) - - -def test_pack_grouped_weight1_preserves_expert_major_layout(): - gate0 = torch.arange(24).reshape(6, 4) - up0 = gate0 + 100 - gate1 = gate0 + 200 - up1 = gate0 + 300 - - packed = pack_grouped_weight1( - [(gate0, up0), (gate1, up1)], - etp_rank=1, - etp_size=2, - ) - blocks = packed.view(2, 4, 6) - - assert torch.equal(blocks[0, :, :3], gate0[3:].t()) - assert torch.equal(blocks[0, :, 3:], up0[3:].t()) - assert torch.equal(blocks[1, :, :3], gate1[3:].t()) - assert torch.equal(blocks[1, :, 3:], up1[3:].t()) - - -def test_pack_grouped_weight2_preserves_expert_major_layout(): - down0 = torch.arange(24).reshape(4, 6) - down1 = down0 + 100 - - packed = pack_grouped_weight2( - [down0, down1], - etp_rank=0, - etp_size=2, - ) - blocks = packed.view(2, 3, 4) - - assert torch.equal(blocks[0], down0[:, :3].t()) - assert torch.equal(blocks[1], down1[:, :3].t()) diff --git a/tests/test_memory_budget.py b/tests/test_memory_budget.py deleted file mode 100644 index b798e7a..0000000 --- a/tests/test_memory_budget.py +++ /dev/null @@ -1,54 +0,0 @@ -from RL_Framework.config import AsyncRLConfig, HardwareConfig, ModelArchConfig -from RL_Framework.infra.cost_model.memory_budget import ( - estimate_recompute_logprobs_memory, -) -from RL_Framework.infra.cost_model.model import CostModel, TrainParallelConfig - - -def test_recompute_memory_uses_local_vocab_and_fp32_workspace(): - estimate = estimate_recompute_logprobs_memory( - batch_size=2, - sequence_length=1024, - vocab_size=1000, - tensor_parallel_size=4, - logits_dtype_bytes=4, - workspace_factor=1.5, - ) - - assert estimate.local_vocab_size == 250 - assert estimate.logits_bytes == 2 * 1023 * 250 * 4 - assert estimate.total_bytes == int(estimate.logits_bytes * 1.5) - - -def test_train_oom_budget_uses_max_sequence_length_for_recompute(): - config = AsyncRLConfig( - model_path="/tmp/model", - train_gpus=1, - rollout_gpus=1, - train_tp_size=1, - train_dp_size=1, - batch_size=1, - micro_batch_size=1, - max_seq_length=4096, - recompute_logprobs=True, - hardware=HardwareConfig(mem_capacity=2.0e9), - model_arch=ModelArchConfig( - num_params=1.0e8, - d_model=128, - n_layers=2, - vocab_size=10000, - ), - ) - model = CostModel( - hardware=config.hardware, - model_arch=config.model_arch, - profiling=config.profiling, - max_seq_length=config.max_seq_length, - recompute_logprobs=True, - ) - - assert model.check_train_oom( - TrainParallelConfig(tp=1, pp=1, dp=1, b_micro=1), - B_global=1, - L=128, - ) diff --git a/tests/test_native_rdma_backend.py b/tests/test_native_rdma_backend.py deleted file mode 100644 index 1e048a2..0000000 --- a/tests/test_native_rdma_backend.py +++ /dev/null @@ -1,162 +0,0 @@ -import os -import subprocess -import sys -from pathlib import Path - -import pytest -import torch - -from RL_Framework.infra.elastic.native_rdma import ( - NativeRDMAConfig, - NativeRDMAFileTransfer, - NativeRDMAGradientClient, - NativeRDMAGradientServer, -) -from RL_Framework.infra.elastic.gradient_ipc import GradientEndpoint -from RL_Framework.infra.elastic.hybrid_pool import GradientPayload - - -def test_native_rdma_helper_builds(): - if not NativeRDMAFileTransfer.is_system_available(): - pytest.skip("native RDMA build prerequisites are not available") - transfer = NativeRDMAFileTransfer(NativeRDMAConfig()) - helper = transfer.build_helper(force=True) - assert helper.exists() - assert os.access(helper, os.X_OK) - - -def test_native_rdma_loopback_file_transfer(tmp_path: Path): - if not NativeRDMAFileTransfer.is_system_available(): - pytest.skip("native RDMA build prerequisites are not available") - payload = bytes((i % 251 for i in range(256 * 1024))) - src = tmp_path / "payload.bin" - dst = tmp_path / "received.bin" - src.write_bytes(payload) - - transfer = NativeRDMAFileTransfer( - NativeRDMAConfig( - device=os.environ.get("NATIVE_RDMA_DEVICE", "mlx5_0"), - gid_index=int(os.environ.get("NATIVE_RDMA_GID_INDEX", "0")), - ib_port=int(os.environ.get("NATIVE_RDMA_IB_PORT", "1")), - max_bytes=1024 * 1024, - ) - ) - transfer.transfer_file(input_path=src, output_path=dst) - - assert dst.read_bytes() == payload - - -def test_native_rdma_gradient_payload_transfer(tmp_path: Path): - if not NativeRDMAFileTransfer.is_system_available(): - pytest.skip("native RDMA build prerequisites are not available") - received = [] - config = NativeRDMAConfig( - device=os.environ.get("NATIVE_RDMA_DEVICE", "mlx5_0"), - gid_index=int(os.environ.get("NATIVE_RDMA_GID_INDEX", "0")), - ib_port=int(os.environ.get("NATIVE_RDMA_IB_PORT", "1")), - max_bytes=1024 * 1024, - ) - server = NativeRDMAGradientServer( - host="127.0.0.1", - port=0, - authkey="rdma-secret", - on_payload=received.append, - rdma_config=config, - work_dir=tmp_path, - ) - endpoint = server.start() - try: - client = NativeRDMAGradientClient(endpoint, rdma_config=config) - client.send( - GradientPayload( - replica_id="hybrid0", - target_core_id="dp0", - tensors=(torch.tensor([1.0, 2.0]),), - ) - ) - import time - - deadline = time.time() + 10 - while not received and time.time() < deadline: - time.sleep(0.05) - assert len(received) == 1 - assert received[0].replica_id == "hybrid0" - assert received[0].target_core_id == "dp0" - finally: - server.close() - - -def test_elastic_hybrid_worker_cli_uses_native_rdma(tmp_path: Path): - if not NativeRDMAFileTransfer.is_system_available(): - pytest.skip("native RDMA build prerequisites are not available") - received = [] - config = NativeRDMAConfig( - device=os.environ.get("NATIVE_RDMA_DEVICE", "mlx5_0"), - gid_index=int(os.environ.get("NATIVE_RDMA_GID_INDEX", "0")), - ib_port=int(os.environ.get("NATIVE_RDMA_IB_PORT", "1")), - max_bytes=1024 * 1024, - ) - server = NativeRDMAGradientServer( - host="127.0.0.1", - port=0, - authkey="rdma-secret", - on_payload=received.append, - rdma_config=config, - work_dir=tmp_path / "server", - ) - endpoint = server.start() - snapshot = tmp_path / "snapshot.pt" - payload_file = tmp_path / "payload.pt" - torch.save({"version": 1, "model": {}, "optimizer": None}, snapshot) - torch.save( - { - "replica_id": "hybrid_cli", - "target_core_id": "dp0", - "tensors": (torch.tensor([3.0]),), - }, - payload_file, - ) - try: - script = Path(__file__).resolve().parents[1] / "scripts" / "elastic_hybrid_worker.py" - subprocess.run( - [ - sys.executable, - str(script), - "--worker-id", - "hybrid_cli", - "--target-core-id", - "dp0", - "--snapshot-path", - str(snapshot), - "--gradient-host", - endpoint.host, - "--gradient-port", - str(endpoint.port), - "--authkey", - endpoint.authkey, - "--payload-file", - str(payload_file), - "--gradient-transport", - "native_rdma", - "--native-rdma-device", - config.device, - "--native-rdma-gid-index", - str(config.gid_index), - "--native-rdma-ib-port", - str(config.ib_port), - "--native-rdma-max-bytes", - str(config.max_bytes), - ], - cwd=str(Path(__file__).resolve().parents[1]), - check=True, - ) - import time - - deadline = time.time() + 10 - while not received and time.time() < deadline: - time.sleep(0.05) - assert len(received) == 1 - assert received[0].replica_id == "hybrid_cli" - assert torch.equal(received[0].tensors[0], torch.tensor([3.0])) - finally: - server.close() diff --git a/tests/test_nccl_store_lifecycle.py b/tests/test_nccl_store_lifecycle.py deleted file mode 100644 index 1116c7e..0000000 --- a/tests/test_nccl_store_lifecycle.py +++ /dev/null @@ -1,147 +0,0 @@ -"""The stateless rendezvous transfers its listening FD to the real TCPStore.""" -import os -from pathlib import Path -import subprocess -import sys -import textwrap -from types import ModuleType, SimpleNamespace - -import pytest - -from RL_Framework.infra.sync import nccl_weight_sync -from RL_Framework.infra.sync.nccl_weight_sync import NcclReloadSpec - - -@pytest.mark.parametrize("rank", [0, 1]) -def test_only_master_transfers_listening_socket_ownership(monkeypatch, rank): - detached = [] - group = SimpleNamespace(socket=SimpleNamespace(detach=lambda: detached.append(True))) - utils = ModuleType("vllm.distributed.utils") - utils.StatelessProcessGroup = SimpleNamespace(create=lambda **_kwargs: group) - monkeypatch.setitem(sys.modules, "vllm.distributed.utils", utils) - - assert nccl_weight_sync._group(NcclReloadSpec("127.0.0.1", 12345, 2, rank, "cpu")) is group - assert detached == ([True] if rank == 0 else []) - - -def test_real_tcp_store_survives_python_socket_cleanup_and_cache_eviction(): - # A subprocess is essential: closing a socket that still owns TCPStore's FD - # triggers SIGABRT in a C++ daemon, bypassing Python exception handling. Use - # real CPU PyTorch but reproduce vLLM's small create() without importing GPU - # dependencies. Multiple groups also exercise independent cache lifetimes. - script = textwrap.dedent(""" - import gc - import socket - import sys - from datetime import timedelta - from types import ModuleType, SimpleNamespace - import torch.distributed as dist - from RL_Framework.infra.sync import nccl_weight_sync - - def create(host, port, rank, world_size, store_timeout): - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.bind((host, port)) - sock.listen() - port = sock.getsockname()[1] - store = dist.TCPStore(host, port, world_size, True, - timeout=timedelta(seconds=store_timeout), use_libuv=False, - master_listen_fd=sock.fileno()) - return SimpleNamespace(socket=sock, store=store) - - utils = ModuleType('vllm.distributed.utils') - utils.StatelessProcessGroup = SimpleNamespace(create=create) - sys.modules['vllm.distributed.utils'] = utils - for index in range(3): - spec = nccl_weight_sync.NcclReloadSpec('127.0.0.1', 0, 1, 0, 'cpu', timeout_s=2) - group = nccl_weight_sync._group(spec) - assert group.socket.fileno() == -1 - group.socket.close() - group.store.set('working', b'yes') - assert group.store.get('working') == b'yes' - nccl_weight_sync._COMMUNICATOR_CACHE[('test', index)] = SimpleNamespace(group=group) - del group - nccl_weight_sync.clear_communicator_cache() - gc.collect() - print('ORDERLY_TCPSTORE_EXIT', flush=True) - """) - root = Path(nccl_weight_sync.__file__).resolve().parents[2] - # Preserve the package alias provided by the ordinary project test runner. - environment = dict(os.environ) - completed = subprocess.run([sys.executable, "-B", "-c", script], cwd=root, - env=environment, capture_output=True, text=True, timeout=30) - assert completed.returncode == 0, completed.stdout + completed.stderr - assert "ORDERLY_TCPSTORE_EXIT" in completed.stdout - assert "TCPStoreMasterDaemon::run() failed" not in completed.stderr - - -def test_real_namespaced_store_reuses_listener_and_reconnects_new_member(): - # Keep TCPStore lifetime errors isolated in a real subprocess, as above. - # Only vLLM's dataclass container is stubbed; all stores/connections are real. - script = textwrap.dedent(''' - import gc - import os - import subprocess - import sys - import textwrap - from types import ModuleType, SimpleNamespace - from RL_Framework.infra.sync import nccl_weight_sync as transport - - utils = ModuleType('vllm.distributed.utils') - utils.StatelessProcessGroup = lambda **kwargs: SimpleNamespace(**kwargs) - sys.modules[utils.__name__] = utils - sender = transport.NcclReloadSpec('127.0.0.1', 0, 2, 0, 'cpu', timeout_s=2, session_id='old') - old_sender = transport._group(sender) - port = transport._BASE_STORE_CACHE[('127.0.0.1', 0, True)].port - receiver = transport.NcclReloadSpec('127.0.0.1', port, 2, 1, 'cpu', timeout_s=2, session_id='old') - old_receiver = transport._group(receiver) - old_sender.store.set('broadcast_from/0/0', b'old-nccl-id') - assert old_receiver.store.get('broadcast_from/0/0') == b'old-nccl-id' - - from dataclasses import replace - new_sender = transport._group(replace(sender, session_id='new')) - new_receiver = transport._group(replace(receiver, session_id='new')) - assert len(transport._BASE_STORE_CACHE) == 2 - assert transport._BASE_STORE_CACHE[('127.0.0.1', 0, True)].port == port - assert not new_receiver.store.check(['broadcast_from/0/0']) - new_sender.store.set('broadcast_from/0/0', b'new-nccl-id') - assert new_receiver.store.get('broadcast_from/0/0') == b'new-nccl-id' - assert old_receiver.store.get('broadcast_from/0/0') == b'old-nccl-id' - assert all(group.socket is None for group in (old_sender, old_receiver, new_sender, new_receiver)) - - client = textwrap.dedent(""" - import sys - from types import ModuleType, SimpleNamespace - from RL_Framework.infra.sync import nccl_weight_sync as transport - utils = ModuleType('vllm.distributed.utils') - utils.StatelessProcessGroup = lambda **kwargs: SimpleNamespace(**kwargs) - sys.modules[utils.__name__] = utils - group = transport._group(transport.NcclReloadSpec('127.0.0.1', int(sys.argv[1]), - 2, 1, 'cpu', timeout_s=2, session_id='new')) - assert group.store.get('broadcast_from/0/0') == b'new-nccl-id' - group.store.set('reconnected', b'yes') - del group - transport.clear_communicator_cache() - """) - result = subprocess.run([sys.executable, '-B', '-c', client, str(port)], - env=dict(os.environ), capture_output=True, text=True, timeout=15) - assert result.returncode == 0, result.stdout + result.stderr - assert new_sender.store.get('reconnected') == b'yes' - - del old_sender, old_receiver, new_sender, new_receiver - transport.clear_communicator_cache() - gc.collect() - assert not transport._BASE_STORE_CACHE - # After whole cleanup, the actual port can be bound by a fresh master. - fresh = transport._group(replace(sender, port=port, session_id='fresh')) - fresh.store.set('healthy', b'yes') - assert fresh.store.get('healthy') == b'yes' - del fresh - transport.clear_communicator_cache() - gc.collect() - print('NAMESPACED_STORE_RECONNECT_AND_CLEANUP_OK', flush=True) - ''') - root = Path(nccl_weight_sync.__file__).resolve().parents[2] - completed = subprocess.run([sys.executable, '-B', '-c', script], cwd=root, - env=dict(os.environ), capture_output=True, text=True, timeout=40) - assert completed.returncode == 0, completed.stdout + completed.stderr - assert 'NAMESPACED_STORE_RECONNECT_AND_CLEANUP_OK' in completed.stdout diff --git a/tests/test_nccl_store_timeout.py b/tests/test_nccl_store_timeout.py deleted file mode 100644 index 3e7cc32..0000000 --- a/tests/test_nccl_store_timeout.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Shared rendezvous waits preserve application timeout=0 and subsecond limits.""" -from datetime import timedelta -import sys -from types import ModuleType, SimpleNamespace - -import pytest -import torch.distributed as dist - -from RL_Framework.infra.sync import nccl_weight_sync -from RL_Framework.infra.sync.nccl_weight_sync import NcclReloadSpec - - -@pytest.fixture -def create_group(monkeypatch): - calls = [] - utils = ModuleType('vllm.distributed.utils') - utils.StatelessProcessGroup = SimpleNamespace(create=lambda **kwargs: calls.append(kwargs) or kwargs) - for name in ('vllm', 'vllm.distributed'): - package = ModuleType(name) - package.__path__ = [] - monkeypatch.setitem(sys.modules, name, package) - monkeypatch.setitem(sys.modules, 'vllm.distributed.utils', utils) - return calls - - -@pytest.mark.parametrize('timeout', [0.125, 1, 29.5, 1200]) -def test_positive_nccl_store_timeout_preserves_seconds_without_minimum_or_truncation(create_group, timeout): - nccl_weight_sync._group(NcclReloadSpec('127.0.0.1', 12345, 2, 0, 'cpu', timeout_s=timeout)) - assert create_group[0]['store_timeout'] == timeout - - -def test_zero_nccl_store_timeout_uses_safe_unbounded_sentinel(create_group): - nccl_weight_sync._group(NcclReloadSpec('127.0.0.1', 12345, 2, 0, 'cpu', timeout_s=0)) - timeout = create_group[0]['store_timeout'] - assert timeout > 365 * 24 * 60 * 60 - assert timeout * 1_000_000_000 < 2**63 - # Exercise the same timedelta conversion performed by vLLM. - assert timedelta(seconds=timeout).total_seconds() == timeout - - -@pytest.mark.parametrize('timeout', [-1, float('nan'), float('inf')]) -def test_invalid_nccl_store_timeout_fails_before_group_creation(create_group, timeout): - with pytest.raises(ValueError, match='non-negative seconds'): - nccl_weight_sync._group(NcclReloadSpec('127.0.0.1', 12345, 2, 0, 'cpu', timeout_s=timeout)) - assert not create_group - - -def test_unbounded_sentinel_is_accepted_by_real_torch_tcp_store(): - # No peer or wait is needed: this verifies PyTorch's C++ duration conversion - # accepts the sentinel and the resulting store remains functional. - timeout = timedelta(seconds=nccl_weight_sync._UNBOUNDED_STORE_TIMEOUT_S) - store = dist.TCPStore('127.0.0.1', 0, 1, True, timeout=timeout) - store.set('probe', b'ready') - assert store.get('probe') == b'ready' diff --git a/tests/test_optimizer_state.py b/tests/test_optimizer_state.py deleted file mode 100644 index 9b7c9f2..0000000 --- a/tests/test_optimizer_state.py +++ /dev/null @@ -1,52 +0,0 @@ -"""Strict Adam metadata restoration must also preserve the next optimizer step.""" -from types import SimpleNamespace - -import pytest -import torch - -from RL_Framework.engine.optimizer_state import optimizer_state_load_context - - -def test_restored_parameter_steps_do_not_share_mutable_metadata_tensor(): - restored = [torch.nn.Parameter(torch.tensor([1.])), torch.nn.Parameter(torch.tensor([2.]))] - reference = [torch.nn.Parameter(parameter.detach().clone()) for parameter in restored] - actual = torch.optim.AdamW(restored, lr=.01) - expected = torch.optim.AdamW(reference, lr=.01) - shared = torch.tensor(3.) - for optimizer, parameters in [(actual, restored), (expected, reference)]: - for parameter in parameters: - optimizer.state[parameter] = { - 'step': shared if optimizer is actual else shared.clone(), - 'exp_avg': torch.tensor([.1]), 'exp_avg_sq': torch.tensor([.2]), - } - wrapper = SimpleNamespace(optimizer=actual, model_param_group_index_map={ - parameter: (0, index) for index, parameter in enumerate(restored)}) - received = [] - wrapper._set_main_param_and_optimizer_states = lambda parameter, tensors: received.append(tensors) - original = wrapper._set_main_param_and_optimizer_states - with optimizer_state_load_context(wrapper): - wrapper._set_main_param_and_optimizer_states(restored[0], {'exp_avg': torch.tensor([.1])}) - assert received[0]['step'].item() == 3 - assert wrapper._set_main_param_and_optimizer_states is original - assert actual.state[restored[0]]['step'] is not actual.state[restored[1]]['step'] - for optimizer, parameters in [(actual, restored), (expected, reference)]: - for parameter in parameters: - parameter.grad = torch.tensor([.3]) - optimizer.step() - for actual_parameter, expected_parameter in zip(restored, reference): - torch.testing.assert_close(actual_parameter, expected_parameter, rtol=0, atol=0) - assert actual.state[actual_parameter]['step'].item() == 4 - - -def test_missing_master_or_moment_state_is_not_invented(): - parameter = torch.nn.Parameter(torch.tensor([1.])) - optimizer = torch.optim.AdamW([parameter]) - optimizer.state[parameter]['step'] = torch.tensor(3.) - def strict_setter(parameter, tensors): - return tensors['exp_avg'] - wrapper = SimpleNamespace(optimizer=optimizer, model_param_group_index_map={parameter: (0, 0)}, - _set_main_param_and_optimizer_states=strict_setter) - with pytest.raises(KeyError, match='exp_avg'): - with optimizer_state_load_context(wrapper): - wrapper._set_main_param_and_optimizer_states(parameter, {}) - assert wrapper._set_main_param_and_optimizer_states is strict_setter diff --git a/tests/test_phase_tracer.py b/tests/test_phase_tracer.py deleted file mode 100644 index afd9b1f..0000000 --- a/tests/test_phase_tracer.py +++ /dev/null @@ -1,18 +0,0 @@ -import json - -from RL_Framework.infra.observability.phase_tracer import PhaseTracer - - -def test_phase_tracer_writes_spans_and_preserves_details(tmp_path): - path = tmp_path / "phase_trace_rank0.jsonl" - tracer = PhaseTracer(path, rank=0, world_size=2) - tracer.start(3, "rollout", {"batch_size": 4}) - tracer.end(3, "rollout", {"requests": 4}) - tracer.close() - - records = [json.loads(line) for line in path.read_text().splitlines()] - assert [record["event"] for record in records] == ["phase_start", "phase_span"] - assert records[1]["phase"] == "rollout" - assert records[1]["step"] == 3 - assert records[1]["details"] == {"batch_size": 4, "requests": 4} - assert records[1]["duration_s"] >= 0 diff --git a/tests/test_planner_global_batch_workload.py b/tests/test_planner_global_batch_workload.py deleted file mode 100644 index fe8fe13..0000000 --- a/tests/test_planner_global_batch_workload.py +++ /dev/null @@ -1,132 +0,0 @@ -"""Historical sample count must not change the cost of one fixed global batch.""" - -import pytest - -from RL_Framework.config import AsyncRLConfig, HeterogeneousInstanceConfig -from RL_Framework.infra.cost_model.global_resource_planner import GlobalResourcePlanner -from RL_Framework.infra.cost_model.model import RequestInfo, representative_global_batch - - -ROWS = [ - dict(input_len=1024, output_len=length) - for length in ([128] * 4 + [1024] * 4 + [4096] * 4 + [8192] * 4) -] - - -def planner(): - config = AsyncRLConfig(model_path="not-loaded") - config.n_total_gpus = 12 - config.train_gpus, config.rollout_gpus = 4, 8 - config.train_tp_size, config.train_dp_size = 4, 1 - config.batch_size, config.micro_batch_size, config.n_samples = 16, 1, 4 - config.heterogeneous_rollout.enabled = True - config.heterogeneous_rollout.instances = [ - HeterogeneousInstanceConfig(instance_id=f"rollout-{index}", tp=4) - for index in range(2) - ] - controls = config.global_resource_planner - controls.enabled = True - controls.initial_allocation_strategy = "grp" - controls.fixed_train_gpus = 0 - controls.allowed_train_tp, controls.allowed_train_pp = [1, 2, 4], [1] - controls.allowed_train_ep, controls.allowed_rollout_tp = [1], [1, 2, 4] - controls.micro_batch_sizes = [1] - controls.allocation_granularity_gpus = 4 - controls.min_train_gpus = controls.min_rollout_gpus = 4 - controls.warmup_steps = 0 - controls.plan_interval = controls.min_history_size = 1 - controls.reconfiguration_cost_s = controls.min_gain_ratio = 0 - return config, GlobalResourcePlanner.from_config(config) - - -def costs(plan): - return (plan.t_train, plan.t_rollout, plan.t_global) - - -def layout(plan): - return (plan.train_config, plan.rollout_tp_list) - - -def test_repeating_the_same_history_does_not_inflate_current_assignment_cost(): - config, evaluator = planner() - sample = evaluator._extract_requests([dict(input_len=1024, output_len=2048)] * 16) - original = evaluator._build_current_plan(config, sample) - for repeats in (4, 16): - repeated = evaluator._build_current_plan(config, sample * repeats) - assert costs(repeated) == pytest.approx(costs(original)) - assert layout(repeated) == layout(original) - assert original.metadata["training"]["anchor_s"] > 0 - - -def test_real_candidate_search_is_invariant_to_duplicate_history(): - decisions = [] - for repeats in (1, 4, 16): - config, evaluator = planner() - decisions.append(evaluator.plan_if_needed(step=5, config=config, batch=ROWS * repeats)) - for compared in decisions[1:]: - assert costs(compared.current_plan) == pytest.approx(costs(decisions[0].current_plan)) - assert costs(compared.candidate_plan) == pytest.approx(costs(decisions[0].candidate_plan)) - assert layout(compared.candidate_plan) == layout(decisions[0].candidate_plan) - assert compared.should_reconfigure == decisions[0].should_reconfigure - assert [decision.num_requests for decision in decisions] == [16, 64, 256] - assert [decision.candidate_plan.metadata["workload"]["representative_requests"] - for decision in decisions] == [16, 16, 16] - - -def test_direct_optimizer_call_cannot_price_all_historical_requests_as_one_step(): - _, evaluator = planner() - requests = evaluator._extract_requests(ROWS) - kwargs = dict(n_total_gpus=12, B_global=16, allowed_train_tp=[1, 2, 4], - allowed_train_pp=[1], allowed_train_ep=[1], micro_batch_sizes=[1], - allocation_granularity_gpus=4, min_train_gpus=4, min_rollout_gpus=4, - dp_batch_group_size=4) - base = evaluator.optimizer.optimize(requests=requests, **kwargs) - repeated = evaluator.optimizer.optimize(requests=requests * 16, **kwargs) - assert repeated.train_config == base.train_config - assert repeated.rollout_config == base.rollout_config - assert (repeated.t_train, repeated.t_rollout, repeated.t_global) == pytest.approx( - (base.t_train, base.t_rollout, base.t_global)) - - -def test_forced_rollout_and_training_candidates_use_the_same_global_batch(monkeypatch): - config, evaluator = planner() - monkeypatch.setenv("GRP_FORCE_TRAIN_GPUS", "8") - monkeypatch.setenv("GRP_FORCE_ROLLOUT_TP_LIST", "4") - requests, training = [], [] - original_rollout = evaluator.optimizer.evaluate_fixed_rollout_config - original_training = evaluator.evaluator.evaluate_training - - def rollout(cluster, rows): - requests.append(len(rows)) - return original_rollout(cluster, rows) - - def train(topology, batch_size, lengths): - training.append((batch_size, len(lengths))) - return original_training(topology, batch_size, lengths) - - monkeypatch.setattr(evaluator.optimizer, "evaluate_fixed_rollout_config", rollout) - monkeypatch.setattr(evaluator.evaluator, "evaluate_training", train) - decision = evaluator.plan_if_needed(step=5, config=config, batch=ROWS * 16) - assert decision.candidate_plan.train_gpus == 8 - assert requests and set(requests) == {16} - assert training and set(training) == {(16, 16)} - - -def test_representative_lengths_preserve_oom_tail_and_do_not_modify_history(): - requests = [RequestInfo(prompt_length=1, gen_length=index) for index in range(1, 65)] - original = list(requests) - selected = representative_global_batch(requests, 16) - assert len(selected) == 16 and selected[0] is requests[0] and selected[-1] is requests[-1] - assert requests == original - assert representative_global_batch(requests, 1) == [requests[-1]] - assert representative_global_batch([], 16) == [] - with pytest.raises(ValueError, match="positive"): - representative_global_batch(requests, 0) - - -def test_short_history_is_a_distribution_for_a_full_global_batch(): - requests = [RequestInfo(prompt_length=1024, gen_length=2048)] - assert len(representative_global_batch(requests, 16)) == 16 - config, evaluator = planner() - assert costs(evaluator._build_current_plan(config, requests)) == pytest.approx( - costs(evaluator._build_current_plan(config, requests * 16))) diff --git a/tests/test_preflight_planner.py b/tests/test_preflight_planner.py index 9b9165e..93ea4cf 100644 --- a/tests/test_preflight_planner.py +++ b/tests/test_preflight_planner.py @@ -1,4 +1,5 @@ import json +import shlex import sys import tempfile from pathlib import Path @@ -53,10 +54,10 @@ def _config(tmp_path: Path) -> AsyncRLConfig: cfg.global_resource_planner.sailor_path = str(sailor) cfg.global_resource_planner.vidur_path = str(vidur) cfg.global_resource_planner.sailor_train_command = ( - f"{sys.executable} {sailor_script} {{input_json}} {{output_json}}" + f"{shlex.quote(sys.executable)} {shlex.quote(str(sailor_script))} {{input_json}} {{output_json}}" ) cfg.global_resource_planner.vidur_rollout_command = ( - f"{sys.executable} {vidur_script} {{trace_csv}} {{output_json}} {{tp_list}}" + f"{shlex.quote(sys.executable)} {shlex.quote(str(vidur_script))} {{trace_csv}} {{output_json}} {{tp_list}}" ) cfg.global_resource_planner.allowed_train_tp = [1, 2] cfg.global_resource_planner.allowed_train_pp = [1] diff --git a/tests/test_production_ehp_ab_config.py b/tests/test_production_ehp_ab_config.py deleted file mode 100644 index cafe571..0000000 --- a/tests/test_production_ehp_ab_config.py +++ /dev/null @@ -1,57 +0,0 @@ -from pathlib import Path - -from scripts.materialize_6node48_config import load_inherited_config -from scripts.validate_ehp_ab_config import validate - - -PROJECT = Path(__file__).resolve().parents[1] -NO_EHP = PROJECT / "configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_no_ehp.yaml" -EHP = PROJECT / "configs/r2e_gym_qwen3_14b_mcore_gpu_6node48_production_ehp.yaml" - - -def test_production_ab_diff_is_ehp_only(): - differences = validate(NO_EHP, EHP) - assert "global_resource_planner.elastic_hybrid_planning_enabled" in differences - assert "global_resource_planner.runtime_online_replanning" in differences - assert "global_resource_planner.runtime_dynamic_reconfiguration_enabled" in differences - assert "global_resource_planner.runtime_reconfigure_training" in differences - assert "global_resource_planner.hybrid_worker_launch_enabled" in differences - assert "global_resource_planner.hybrid_worker_remote_control_enabled" in differences - assert "global_resource_planner.elastic_hybrid_require_isolated_ccl" in differences - assert "batch_size" not in differences - assert "n_samples" not in differences - assert "seed" not in differences - - -def test_production_batch_contains_complete_grpo_groups_per_dp_replica(): - config = load_inherited_config(EHP) - local_batch = config["batch_size"] // config["train_dp_size"] - assert config["batch_size"] == 32 - assert config["n_samples"] == 4 - assert local_batch == 8 - assert local_batch % config["n_samples"] == 0 - assert config["total_steps"] == 200 - assert config["sync_interval"] == 5 - - -def test_control_arm_freezes_initial_grp_allocation(): - no_ehp = load_inherited_config(NO_EHP) - ehp = load_inherited_config(EHP) - no_ehp_planner = no_ehp["global_resource_planner"] - ehp_planner = ehp["global_resource_planner"] - - assert no_ehp_planner["initial_allocation_strategy"] == "grp" - assert no_ehp_planner["fixed_train_gpus"] == 0 - assert no_ehp_planner["runtime_online_replanning"] is False - assert no_ehp_planner["runtime_dynamic_reconfiguration_enabled"] is False - assert no_ehp_planner["runtime_reconfigure_training"] is False - assert no_ehp_planner["hybrid_worker_launch_enabled"] is False - assert no_ehp_planner["hybrid_worker_remote_control_enabled"] is False - assert no_ehp_planner["elastic_hybrid_require_isolated_ccl"] is False - - assert ehp_planner["runtime_online_replanning"] is True - assert ehp_planner["runtime_dynamic_reconfiguration_enabled"] is True - assert ehp_planner["runtime_reconfigure_training"] is True - assert ehp_planner["hybrid_worker_launch_enabled"] is True - assert ehp_planner["hybrid_worker_remote_control_enabled"] is True - assert ehp_planner["elastic_hybrid_require_isolated_ccl"] is True diff --git a/tests/test_publication_preserves_hybrids.py b/tests/test_publication_preserves_hybrids.py deleted file mode 100644 index cf9bc4d..0000000 --- a/tests/test_publication_preserves_hybrids.py +++ /dev/null @@ -1,205 +0,0 @@ -"""Routine rollout publication preserves the current Hybrid GPU loan.""" -import io -import json -from types import SimpleNamespace as NS - -import pytest -import torch - -from RL_Framework.infra.sync import nccl_weight_sync, publication_session -from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - - -@pytest.fixture -def publication(tmp_path, monkeypatch): - instances = [NS(instance_id=name, host=name, port=8100 + index, tp=index + 1) - for index, name in enumerate(('a', 'b', 'c'))] - endpoints = {inst.instance_id: f'http://{inst.host}:{inst.port}' for inst in instances} - calls, requests, status_urls, exported = [], [], [], [] - members = ('hybrid-b',) - client = NS(scheduler=NS(_instances=[NS(instance_id=inst.instance_id, is_ready=True) - for inst in instances])) - config = NS(weight_sync_mode='nccl', heterogeneous_rollout=NS(enabled=True, instances=instances), - rollout_weight_sync_control_dir=str(tmp_path), rollout_nccl_host='core', - rollout_nccl_port=29620, rollout_nccl_chunk_mb=1, rollout_nccl_rate_limit_gbps=0, - rollout_weight_sync_timeout_s=2, rollout_weight_sync_poll_interval_s=.001, - enable_rollout_tracing=False) - dispatcher = NS(paused=False) - dispatcher.pause = lambda: setattr(dispatcher, 'paused', True) - dispatcher.resume = lambda: setattr(dispatcher, 'paused', False) - dispatcher.is_paused = lambda: dispatcher.paused - dispatcher.cancel_queued = lambda: dict(dispatcher_queue=0, runner_queue=0) - dispatcher.get_runtime_metrics = lambda: dict(staleness_running=0) - dispatcher.wait_until_idle = lambda **kwargs: None - - def weights(): - exported.append(True) - yield 'weight', torch.ones(2) - - trainer = NS(config=config, is_main_process=True, control=None, dispatcher=dispatcher, - rollout_engine=client, _use_heterogeneous=True, - _rollout_unavailable_ids={'b'}, - runtime_elastic_executor=NS(_lent_rollout={'engines': [instances[1]]}), - train_engine=NS(train_backend='megatron_core', optimizer_revision=7, - _elastic_step_hybrid_workers=members, stream_rollout_weights=weights, - set_version=lambda version: calls.append(('version', version))), - _restore_lent_rollouts_for_publication=lambda: calls.append(('restore',)), - _write_json_atomic=lambda path, value: path.write_text(json.dumps(value)), - _record_rollout_weight_version=lambda **kwargs: None, - _record_weight_sync_phase=lambda phase: None, - _trace_train_phase=lambda *args: None, - _wait_for_all_ranks_before_weight_sync=lambda step: None) - - def rebind(**kwargs): - calls.append(('rebind',)) - trainer.rollout_engine = NS(rebound=True) - - trainer._rebind_rollout_engine_from_config = rebind - for name in ('_nccl_rollout_topology', '_sync_weights_nccl', '_sync_weights', - '_reopen_restored_rollouts', '_resume_rollout_pipeline'): - setattr(trainer, name, getattr(AsyncRLTrainer, name).__get__(trainer)) - h = NS(trainer=trainer, instances=instances, endpoints=endpoints, client=client, - calls=calls, requests=requests, status_urls=status_urls, exported=exported, - expected=['a', 'c'], directory=tmp_path, members=members, stale_receiver=None) - - def status(url, timeout): - status_urls.append(url) - identity = next(identity for identity, endpoint in endpoints.items() - if url == endpoint + '/publication/status') - return io.StringIO(json.dumps(dict(server_instance_id='service-' + identity, - server_generation=0, server_generation_verified=True, - tp_size=next(inst.tp for inst in instances if inst.instance_id == identity)))) - - def send(weights, spec, **kwargs): - tensors = list(weights) - request = json.loads((tmp_path / 'reload_request.json').read_text()) - requests.append(request) - expected_offsets, offset = {}, 0 - for inst in instances: - if inst.instance_id in h.expected: - expected_offsets[inst.instance_id] = offset - offset += inst.tp - assert request['nccl_rank_offsets'] == expected_offsets - assert spec.world_size == request['nccl_world_size'] == 1 + offset - assert spec.session_id == request['nccl_session_id'] - for name, tensor in tensors: - kwargs['on_tensor'](name, tensor.numel() * tensor.element_size()) - for inst in instances: - identity = inst.instance_id - if identity not in expected_offsets: - continue - workers = [dict(rank=rank, nccl_rank=expected_offsets[identity] + rank + 1, - received_tensors=len(tensors), receive_complete=True, loaded_parameters=1, - service_generation=1) for rank in range(inst.tp)] - record = dict(instance_id=identity, version=request['version'], snapshot_id=request['snapshot_id'], - optimizer_revision=request['optimizer_revision'], server_response=dict( - snapshot_id=request['snapshot_id'], optimizer_revision=request['optimizer_revision'], - service_instance_id='retired-service' if identity == h.stale_receiver else 'service-' + identity, - service_generation=1, - prefix_cache_cleared=True, workers=workers)) - (tmp_path / f'ack_{identity}_{request["version"]}.json').write_text(json.dumps(record)) - - monkeypatch.setattr(publication_session.urllib.request, 'urlopen', status) - monkeypatch.setattr(nccl_weight_sync, 'send_weights', send) - monkeypatch.setattr(torch.cuda, 'current_device', lambda: 'cpu') - return h - - -def test_periodic_publication_keeps_hybrid_members_and_existing_rollout_client(publication): - h = publication - # Exercise the real periodic + ordinary publication lifecycle separately - # from the sender's receiver selection, covered below. - def publish(version): - h.calls.append(('publish', version)) - return {'version': version} - h.trainer._sync_weights_nccl = publish - AsyncRLTrainer._periodic_weight_sync(h.trainer, 7) - assert ('publish', 8) in h.calls - assert ('restore',) not in h.calls - assert ('rebind',) not in h.calls - assert h.trainer.rollout_engine is h.client - assert h.trainer.train_engine._elastic_step_hybrid_workers == h.members - assert h.trainer._rollout_unavailable_ids == {'b'} - assert not h.trainer.dispatcher.paused - - -@pytest.mark.parametrize('borrowed,restored', [('a', False), ('b', False), ('b', True)], - ids=['first-lent', 'middle-lent', 'middle-explicitly-returned']) -def test_native_publication_targets_only_live_or_explicitly_returned_receivers( - publication, borrowed, restored): - h = publication - h.trainer._rollout_unavailable_ids = {borrowed} - h.trainer.runtime_elastic_executor._lent_rollout = { - 'engines': [inst for inst in h.instances if inst.instance_id == borrowed] - } - if restored: - h.trainer.runtime_elastic_executor._lent_rollout = None - h.trainer._restored_rollouts_pending_publication = {borrowed} - h.expected = [inst.instance_id for inst in h.instances - if inst.instance_id != borrowed or restored] - h.trainer._sync_weights(8) - assert len(h.requests) == 1 - assert h.status_urls == [h.endpoints[identity] + '/publication/status' for identity in h.expected] - membership, _ = h.trainer._nccl_publication_session - assert [(row[0], row[1], row[2]) for row in membership] == [ - (inst.instance_id, h.endpoints[inst.instance_id].removeprefix('http://'), inst.tp) - for inst in h.instances if inst.instance_id in h.expected] - assert ('restore',) not in h.calls - assert h.trainer.rollout_engine is h.client - assert h.trainer.train_engine._elastic_step_hybrid_workers == h.members - - -@pytest.mark.parametrize('borrowed', ['a', 'b'], ids=['first-lent', 'middle-lent']) -def test_publication_session_resolves_filtered_receivers_by_instance_identity(publication, borrowed): - h = publication - offsets, offset = {}, 0 - for inst in h.instances: - if inst.instance_id != borrowed: - offsets[inst.instance_id] = offset - offset += inst.tp - targets = publication_session.publication_targets(h.trainer.config, instance_ids=offsets) - publication_session.prepare_nccl_session(h.trainer, targets, offsets) - assert h.status_urls == [h.endpoints[identity] + '/publication/status' for identity in offsets] - membership, _ = h.trainer._nccl_publication_session - assert [(row[0], row[1], row[2], row[3]) for row in membership] == [ - (inst.instance_id, h.endpoints[inst.instance_id].removeprefix('http://'), inst.tp, offsets[inst.instance_id]) - for inst in h.instances if inst.instance_id in offsets] - - -def test_publication_with_every_receiver_lent_keeps_admission_paused_without_sender_only_group(publication): - h = publication - h.trainer._rollout_unavailable_ids = set(h.endpoints) - h.trainer.runtime_elastic_executor._lent_rollout = {'engines': h.instances} - h.expected = [] - AsyncRLTrainer._periodic_weight_sync(h.trainer, 7) - assert not h.requests and not h.status_urls and not h.exported - assert not (h.directory / 'reload_request.json').exists() - assert h.trainer.dispatcher.paused - assert h.trainer.rollout_engine is h.client - assert h.trainer.train_engine._elastic_step_hybrid_workers == h.members - assert ('restore',) not in h.calls - - -def test_publication_rejects_acknowledgement_from_replaced_receiver(publication): - h = publication - h.stale_receiver = 'a' - with pytest.raises(RuntimeError, match='Invalid physical-engine ACK identity'): - h.trainer._sync_weights(8) - assert not hasattr(h.trainer, 'last_publication') - assert h.trainer._rollout_unavailable_ids == {'b'} - - -def test_extension_rollback_publishes_only_explicit_receivers(): - trainer = AsyncRLTrainer.__new__(AsyncRLTrainer) - trainer.config = NS(heterogeneous_rollout=NS(enabled=True, instances=[ - NS(instance_id='old-loan', host='a', port=8000, tp=1), - NS(instance_id='returned', host='b', port=8000, tp=2), - NS(instance_id='still-serving', host='c', port=8000, tp=1)])) - trainer.rollout_engine = None - trainer._use_heterogeneous = True - trainer._rollout_unavailable_ids = {'old-loan', 'returned'} - trainer._restored_rollouts_pending_publication = {'returned'} - trainer._publication_target_ids = {'returned'} - assert trainer._nccl_rollout_topology() == (3, {'returned': 0}) - assert trainer._current_rollout_instance_ids() == ['returned'] - assert trainer._rollout_unavailable_ids == {'old-loan', 'returned'} diff --git a/tests/test_publication_sessions.py b/tests/test_publication_sessions.py deleted file mode 100644 index 9779368..0000000 --- a/tests/test_publication_sessions.py +++ /dev/null @@ -1,108 +0,0 @@ -"""The native sender reuses only the current physical receiver membership.""" -import io -import json -from types import SimpleNamespace as NS - -import pytest -import torch - -from RL_Framework.infra.sync import nccl_weight_sync, publication_session -from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - - -@pytest.mark.parametrize('endpoints,environment,expected', [ - ('', '', ['http://127.0.0.1:8000', 'http://127.0.0.1:8001', 'http://127.0.0.1:8002']), - ('', 'remote-a:8100,remote-b:8200', ['http://remote-a:8100', 'http://remote-b:8200']), - ('explicit:8300', 'ignored:8400', ['http://explicit:8300']), -]) -def test_session_reuses_the_existing_homogeneous_endpoint_setup( - monkeypatch, endpoints, environment, expected): - config = NS(rollout_backend='vllm', model_path='/model', vllm_endpoints=endpoints, - heterogeneous_rollout=NS(enabled=False, instances=[NS(instance_id='inactive', host='inactive', port=9999, tp=1)]), - vllm_host='127.0.0.1', vllm_port=8000, vllm_num_instances=0, - rollout_gpus=3, vllm_tp_size=1) - owner = NS(config=config, is_main_process=False) - monkeypatch.setenv('VLLM_ENDPOINTS', environment) - AsyncRLTrainer._setup_homogeneous_engine(owner) - assert [engine.base_url for engine in owner.rollout_engine.engines] == expected - observed = [] - - def status(url, timeout): - observed.append(url) - return io.StringIO(json.dumps(dict(server_instance_id=url, server_generation=0, - server_generation_verified=True, tp_size=1))) - - monkeypatch.setattr(publication_session.urllib.request, 'urlopen', status) - offsets = {f'instance_{index}': index for index in range(owner.rollout_engine.num_instances)} - targets = publication_session.publication_targets(owner.config) - first = publication_session.prepare_nccl_session(owner, targets, offsets) - assert publication_session.prepare_nccl_session(owner, targets, offsets) == first - assert observed == [endpoint + '/publication/status' for endpoint in expected] * 2 - - -def test_native_publication_reuses_membership_and_sends_a_fresh_same_revision_transfer(tmp_path, monkeypatch): - states = dict(a='service-a', b='service-b') - config = NS(heterogeneous_rollout=NS(enabled=True, instances=[ - NS(instance_id=name, host=name, port=8000, tp=1) for name in states]), - rollout_weight_sync_control_dir=str(tmp_path), rollout_nccl_host='core', - rollout_nccl_port=29620, rollout_nccl_chunk_mb=1, rollout_nccl_rate_limit_gbps=0, - rollout_weight_sync_timeout_s=2, rollout_weight_sync_poll_interval_s=.001) - trainer = NS(config=config, is_main_process=True, control=None, - train_engine=NS(train_backend='megatron_core', optimizer_revision=7, - stream_rollout_weights=lambda: iter([('weight', torch.ones(2))])), - _nccl_rollout_topology=lambda: (3, {'a': 0, 'b': 1}), - _write_json_atomic=lambda path, value: path.write_text(json.dumps(value)), - _record_rollout_weight_version=lambda **kwargs: None, - _record_weight_sync_phase=lambda phase: None) - - def status(url, timeout): - host = url.split('://', 1)[1].split(':', 1)[0] - service = states[host] - return io.StringIO(json.dumps(dict(server_instance_id=service, - server_generation=generations.get(service, 0), server_generation_verified=True, tp_size=1))) - - monkeypatch.setattr(publication_session.urllib.request, 'urlopen', status) - monkeypatch.setattr(torch.cuda, 'current_device', lambda: 'cpu') - requests, generations = [], {} - - def send(weights, spec, **kwargs): - tensors = list(weights) - for name, tensor in tensors: - kwargs['on_tensor'](name, tensor.numel() * tensor.element_size()) - request = json.loads((tmp_path / 'reload_request.json').read_text()) - assert spec.session_id == request['nccl_session_id'] - assert request['optimizer_revision'] == trainer.train_engine.optimizer_revision - assert request['expected_service_instance_ids'] == states - requests.append(request) - for identity, offset in request['nccl_rank_offsets'].items(): - service = states[identity] - generations[service] = generations.get(service, 0) + 1 - worker = dict(rank=0, nccl_rank=offset+1, received_tensors=len(tensors), - receive_complete=True, loaded_parameters=1, service_generation=generations[service]) - record = dict(instance_id=identity, version=request['version'], snapshot_id=request['snapshot_id'], - optimizer_revision=request['optimizer_revision'], server_response=dict( - snapshot_id=request['snapshot_id'], optimizer_revision=request['optimizer_revision'], - service_instance_id=service, service_generation=generations[service], - prefix_cache_cleared=True, workers=[worker])) - (tmp_path / f'ack_{identity}_{request["version"]}.json').write_text(json.dumps(record)) - - monkeypatch.setattr(nccl_weight_sync, 'send_weights', send) - receipt = AsyncRLTrainer._sync_weights_nccl(trainer, 1) - assert receipt['target_ids'] == ['a', 'b'] - assert [ack['server_instance_id'] for ack in receipt['acknowledgements']] == ['service-a', 'service-b'] - AsyncRLTrainer._sync_weights_nccl(trainer, 1) - assert requests[0]['snapshot_id'] != requests[1]['snapshot_id'] - assert requests[0]['nccl_session_id'] == requests[1]['nccl_session_id'] - states['a'] = 'returned-service-a' - AsyncRLTrainer._sync_weights_nccl(trainer, 1) - assert requests[2]['nccl_session_id'] != requests[1]['nccl_session_id'] - - -def test_unverified_live_service_cannot_allocate_a_publication_session(): - owner = NS() - targets = [dict(instance_id='a', endpoint='a:8000', tp_size=1)] - state = dict(server_instance_id='a-old', server_generation=2, - server_generation_verified=False, tp_size=1) - with pytest.raises(RuntimeError, match='Unverified current physical service'): - publication_session.prepare_nccl_session(owner, targets, {'a': 0}, read_state=lambda _: state) - assert not hasattr(owner, '_nccl_publication_session') diff --git a/tests/test_qwen3_config.py b/tests/test_qwen3_config.py deleted file mode 100644 index f9919c6..0000000 --- a/tests/test_qwen3_config.py +++ /dev/null @@ -1,48 +0,0 @@ -from pathlib import Path - -from RL_Framework.config import ( - HardwareConfig, - ModelArchConfig, - ProfilingConfig, -) -from RL_Framework.infra.cost_model.model import CostModel - - -CONFIG_DIR = Path(__file__).parents[1] / "configs" / "model_arch_config" - - -def test_qwen3_14b_architecture_config(): - model = ModelArchConfig.from_file( - str(CONFIG_DIR / "qwen3-14b.yaml") - ) - assert model.num_params == 14e9 - assert model.d_model == 5120 - assert model.n_layers == 40 - assert model.intermediate_size == 17408 - assert model.vocab_size == 151936 - assert not model.is_moe - - -def test_qwen3_30b_a3b_moe_config_and_memory(): - model = ModelArchConfig.from_file( - str(CONFIG_DIR / "qwen3-30b-a3b.yaml") - ) - assert model.is_moe - assert model.d_model == 2048 - assert model.n_layers == 48 - assert model.num_experts == 128 - assert model.num_activated_experts == 8 - assert model.expert_intermediate_size == 768 - assert model.effective_num_params == 3e9 - - cost = CostModel( - hardware=HardwareConfig(), - model_arch=model, - profiling=ProfilingConfig(), - ) - expected = ( - 8 * cost.hw.mem_capacity - - model.num_params * model.dtype_bytes - - cost.rollout_model.act_workspace - ) - assert cost.rollout_model.compute_kv_pool(8) == expected diff --git a/tests/test_r2e_patch_harness.py b/tests/test_r2e_patch_harness.py deleted file mode 100644 index 09b26a4..0000000 --- a/tests/test_r2e_patch_harness.py +++ /dev/null @@ -1,34 +0,0 @@ -import subprocess -from pathlib import Path - -from env.r2e_patch_harness import R2EPatchExecutionHarness - - -def test_patch_harness_uses_isolated_checkout_and_docker(tmp_path: Path, monkeypatch): - repo = tmp_path / "source" - repo.mkdir() - subprocess.run(["git", "init", "-q"], cwd=repo, check=True) - (repo / "value.py").write_text("VALUE = 1\n") - subprocess.run(["git", "add", "."], cwd=repo, check=True) - subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "base"], cwd=repo, check=True) - commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip() - (repo / "value.py").write_text("VALUE = 2\n") - patch = subprocess.check_output(["git", "diff", "--", "value.py"], cwd=repo, text=True) - subprocess.run(["git", "checkout", "--", "value.py"], cwd=repo, check=True) - real_run = subprocess.run - calls = 0 - - def run(command, **kwargs): - nonlocal calls - if command[0] == "docker": - calls += 1 - mount = command[command.index("-v") + 1].split(":/workspace")[0] - expected = "VALUE = 1\n" if calls == 1 else "VALUE = 2\n" - assert (Path(mount) / "value.py").read_text() == expected - return subprocess.CompletedProcess(command, 1 if calls == 1 else 0, "", "") - return real_run(command, **kwargs) - - monkeypatch.setattr(subprocess, "run", run) - result = R2EPatchExecutionHarness().execute(patch, repo, ["pytest", "-q"], "example:test", commit) - assert result["patch_applied"] and result["baseline_failed"] and result["tests_passed"] - assert (repo / "value.py").read_text() == "VALUE = 1\n" diff --git a/tests/test_r2e_rollout_sampling.py b/tests/test_r2e_rollout_sampling.py deleted file mode 100644 index cb3541a..0000000 --- a/tests/test_r2e_rollout_sampling.py +++ /dev/null @@ -1,90 +0,0 @@ -from pathlib import Path - -import pytest - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.workflow.r2e_gym import R2EGymWorkflow - - -class _Tokenizer: - pad_token = "" - eos_token = "" - - def encode(self, text, add_special_tokens=False): - del add_special_tokens - return [ord(char) for char in text] - - def decode(self, tokens, skip_special_tokens=True): - del skip_special_tokens - return "".join(chr(token) for token in tokens) - - def apply_chat_template(self, messages, **kwargs): - del kwargs - return "\n".join(message["content"] for message in messages) - - -class _Engine: - def __init__(self): - self.requests = [] - - async def generate(self, **kwargs): - self.requests.append(kwargs) - return {"text": "[ISSUE] sampled [/ISSUE]", "logprobs": []} - - -@pytest.mark.asyncio -async def test_r2e_rollout_index_produces_distinct_reproducible_sampling_seeds(): - workflow = R2EGymWorkflow( - reward_fn=lambda **_: 0.5, - tokenizer=_Tokenizer(), - max_turns=1, - max_new_tokens=32, - max_seq_length=512, - temperature=0.8, - top_p=0.95, - ) - data = {"prompt_id": "sample-42", "task_text": "Describe the failure."} - engine = _Engine() - - await workflow.run_episode(engine, data, version=3, rollout_index=0) - await workflow.run_episode(engine, data, version=3, rollout_index=1) - await workflow.run_episode(engine, data, version=3, rollout_index=0) - - first, second, repeated = [request["seed"] for request in engine.requests] - assert first != second - assert first == repeated - - -def test_r2e_stop_reward_loads_from_production_config(monkeypatch): - monkeypatch.setattr('RL_Framework.config.os.makedirs', lambda *args, **kwargs: None) - config_path = Path(__file__).resolve().parents[1] / "configs" / ( - "r2e_gym_qwen3_14b_mcore_gpu_6node48_production_ehp.yaml" - ) - config = AsyncRLConfig.from_yaml(str(config_path)) - - assert config.r2e_stop_reward == pytest.approx(0.5) - - -@pytest.mark.asyncio -async def test_r2e_stop_reward_ends_multiturn_rollout(monkeypatch): - monkeypatch.setattr( - "RL_Framework.workflow.r2e_gym.evaluate_issue", - lambda **_: {"reward": 0.6}, - ) - workflow = R2EGymWorkflow( - reward_fn=lambda **_: 0.6, - tokenizer=_Tokenizer(), - max_turns=3, - max_new_tokens=32, - max_seq_length=512, - stop_reward=0.5, - ) - engine = _Engine() - - trajectory = await workflow.run_episode( - engine, - {"prompt_id": "stop-threshold", "task_text": "Describe the failure."}, - ) - - assert len(engine.requests) == 1 - assert trajectory["n_turns"] == 1 diff --git a/tests/test_restartable_vllm_server.py b/tests/test_restartable_vllm_server.py deleted file mode 100644 index 9080c2b..0000000 --- a/tests/test_restartable_vllm_server.py +++ /dev/null @@ -1,195 +0,0 @@ -import importlib.util -import json -from pathlib import Path -from types import SimpleNamespace - -import pytest - - -SCRIPT_PATH = Path(__file__).parents[1] / "scripts" / "restartable_vllm_server.py" - - -def _load_module(): - spec = importlib.util.spec_from_file_location( - "restartable_vllm_server", SCRIPT_PATH - ) - module = importlib.util.module_from_spec(spec) - assert spec.loader is not None - spec.loader.exec_module(module) - return module - - -def test_atomic_ack_write_publishes_complete_payload(tmp_path): - module = _load_module() - ack_path = tmp_path / "ack_instance_1.json" - - module.write_json_atomic( - ack_path, - {"version": 1, "reload_strategy": "parallel"}, - ) - - assert json.loads(ack_path.read_text(encoding="utf-8")) == { - "version": 1, - "reload_strategy": "parallel", - } - assert list(tmp_path.iterdir()) == [ack_path] - - -def test_parallel_is_default_reload_strategy(monkeypatch): - module = _load_module() - monkeypatch.setattr( - "sys.argv", - [ - "restartable_vllm_server.py", - "--instance-id", - "instance_0", - "--control-dir", - "/tmp/control", - "--health-url", - "http://127.0.0.1:8000/health", - "--initial-model", - "/tmp/model", - "--", - "python", - "server.py", - ], - ) - - args = module.parse_args() - assert args.reload_method == "restart" - assert args.reload_strategy == "parallel" - - -@pytest.fixture -def supervisor(tmp_path, monkeypatch): - module = _load_module() - args = SimpleNamespace(instance_id='returned', control_dir=str(tmp_path), - health_url='http://service/health', initial_model='/model', ready_timeout=1, - reload_strategy='parallel', reload_method='inplace', poll_interval=.01, - command=['server']) - monkeypatch.setattr(module, 'parse_args', lambda: args) - monkeypatch.setattr(module.subprocess, 'Popen', lambda *args, **kwargs: SimpleNamespace(poll=lambda: None)) - monkeypatch.setattr(module, 'wait_until_ready', lambda *args: None) - monkeypatch.setattr(module, 'stop_process', lambda *args: None) - monkeypatch.setattr(module.signal, 'signal', lambda *args: None) - calls = [] - - def reload(url, payload, timeout): - calls.append(payload) - return dict(service_instance_id='new-service', service_generation=len(calls)) - - def stop(seconds): - raise KeyboardInterrupt() - - monkeypatch.setattr(module, 'reload_nccl', reload) - monkeypatch.setattr(module.time, 'sleep', stop) - request = dict(mode='nccl', version=0, snapshot_id='same-snapshot', optimizer_revision=0, - nccl_host='train', nccl_port=29620, nccl_world_size=2, - nccl_rank_offsets={'returned': 0}, nccl_chunk_bytes=1024) - return SimpleNamespace(module=module, args=args, calls=calls, request=request, - request_path=tmp_path / 'reload_request.json', ack=tmp_path / 'ack_returned_0.json') - - -def test_startup_ignores_old_nccl_but_accepts_atomic_replacement_with_same_identity(supervisor, monkeypatch): - s = supervisor - s.module.write_json_atomic(s.request_path, s.request) - polls = 0 - - def poll(seconds): - nonlocal polls - polls += 1 - if polls == 1: - assert not s.calls and not s.ack.exists() - # Same revision, snapshot and content; a new file is a new transaction. - s.module.write_json_atomic(s.request_path, s.request) - else: - raise KeyboardInterrupt() - - monkeypatch.setattr(s.module.time, 'sleep', poll) - assert s.module.main() == 130 - assert len(s.calls) == 1 - ack = json.loads(s.ack.read_text()) - assert ack['snapshot_id'] == 'same-snapshot' and ack['optimizer_revision'] == 0 - assert ack['server_response'] == dict(service_instance_id='new-service', service_generation=1) - - -@pytest.mark.parametrize('old_request', [False, True]) -def test_new_nccl_request_during_launch_is_not_missed(supervisor, monkeypatch, old_request): - s = supervisor - if old_request: - s.module.write_json_atomic(s.request_path, s.request) - monkeypatch.setattr(s.module, 'wait_until_ready', - lambda *args: s.module.write_json_atomic(s.request_path, s.request)) - assert s.module.main() == 130 - assert len(s.calls) == 1 - assert json.loads(s.ack.read_text())['server_response']['service_generation'] == 1 - - -def test_existing_disk_request_keeps_its_original_reload_behavior(supervisor, tmp_path, monkeypatch): - s = supervisor - checkpoint = tmp_path / 'checkpoint' - checkpoint.mkdir() - s.module.write_json_atomic(s.request_path, - dict(mode='checkpoint', version=1, checkpoint_path=str(checkpoint))) - disk_calls = [] - monkeypatch.setattr(s.module, 'reload_inplace', lambda *args: disk_calls.append(args) or {}) - assert s.module.main() == 130 - assert disk_calls == [(s.args.health_url, str(checkpoint), s.args.ready_timeout)] - assert not s.calls - assert json.loads((tmp_path / 'ack_returned_1.json').read_text())['version'] == 1 - - -def test_checkpoint_subset_skips_survivor_without_advancing_its_revision(supervisor, tmp_path, monkeypatch): - s = supervisor - checkpoint = tmp_path / 'checkpoint' - checkpoint.mkdir() - request = dict(mode='checkpoint', version=2, checkpoint_path=str(checkpoint), - instance_ids=['another-service'], snapshot_id='restore') - s.module.write_json_atomic(s.request_path, request) - calls = [] - monkeypatch.setattr(s.module, 'reload_inplace', lambda *args: calls.append(args) or {}) - - def poll(_seconds): - if s.request_path.exists() and json.loads(s.request_path.read_text())['version'] == 2: - assert not calls - s.module.write_json_atomic(s.request_path, dict(request, version=1, - instance_ids=['returned'], snapshot_id='next-for-survivor')) - else: - raise KeyboardInterrupt() - monkeypatch.setattr(s.module.time, 'sleep', poll) - - assert s.module.main() == 130 - assert len(calls) == 1 - assert not (tmp_path / 'ack_returned_2.json').exists() - assert json.loads((tmp_path / 'ack_returned_1.json').read_text())['snapshot_id'] == 'next-for-survivor' - - -def test_startup_stat_retry_still_ignores_old_request_until_replacement(supervisor, monkeypatch): - s = supervisor - s.module.write_json_atomic(s.request_path, s.request) - original_stat = Path.stat - failed = False - sleeps = 0 - - def transient_error(path, *args, **kwargs): - nonlocal failed - if path == s.request_path and not failed: - failed = True - raise PermissionError('temporarily inaccessible request metadata') - return original_stat(path, *args, **kwargs) - - def poll(seconds): - nonlocal sleeps - sleeps += 1 - if sleeps <= 2: - assert not s.calls and not s.ack.exists() - if sleeps == 2: - s.module.write_json_atomic(s.request_path, s.request) - else: - raise KeyboardInterrupt() - - monkeypatch.setattr(Path, 'stat', transient_error) - monkeypatch.setattr(s.module.time, 'sleep', poll) - assert s.module.main() == 130 - assert failed and sleeps == 3 and len(s.calls) == 1 - assert json.loads(s.ack.read_text())['server_response']['service_generation'] == 1 diff --git a/tests/test_rlvr_workflow_interface.py b/tests/test_rlvr_workflow_interface.py deleted file mode 100644 index b52b768..0000000 --- a/tests/test_rlvr_workflow_interface.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Regression coverage for the async RLVR workflow interface.""" - -import inspect - -from RL_Framework.workflow.rlvr import RLVRWorkflow - - -def test_rlvr_run_episode_accepts_trainer_rollout_index(): - parameters = inspect.signature(RLVRWorkflow.run_episode).parameters - assert "rollout_index" in parameters diff --git a/tests/test_rollout_credit.py b/tests/test_rollout_credit.py deleted file mode 100644 index 417ddb5..0000000 --- a/tests/test_rollout_credit.py +++ /dev/null @@ -1,46 +0,0 @@ -"""A timed-out task releases running credit, never accepted credit.""" -import asyncio -from types import SimpleNamespace - -from RL_Framework.infra.execution.async_runner import AsyncTaskRunner -from RL_Framework.infra.execution.batch_dispatcher import BatchTaskDispatcher, TaskInput -from RL_Framework.infra.sync.staleness import StalenessManager -from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - - -def test_timeout_notification_does_not_consume_successful_result_credit(monkeypatch): - trainer = AsyncRLTrainer.__new__(AsyncRLTrainer) - trainer.config = SimpleNamespace(n_samples=4, max_head_offpolicyness=3, - enable_rollout_tracing=False) - trainer.is_main_process = True - trainer.train_engine = SimpleNamespace(get_version=lambda: 0) - trainer.rollout_engine = object() - trainer._pending_grpo_groups = {} - manager = trainer.staleness_manager = StalenessManager( - trainer.train_engine, max_concurrent_rollouts=8, - consumer_batch_size=4, max_staleness=3) - - async def episode(engine, data, **kwargs): - if data['timeout']: - await asyncio.Future() - return {} - - trainer.workflow = SimpleNamespace(run_episode=episode) - monkeypatch.setenv('ROLLOUT_TASK_TIMEOUT_S', '.001') - - inputs = (TaskInput(index, {'timeout': index == 0}, version=0, - group_id='failed' if index == 0 else 'complete', - rollout_index=max(0, index - 1)) - for index in range(5)) - runner = AsyncTaskRunner(max_queue_size=8) - dispatcher = trainer.dispatcher = BatchTaskDispatcher(runner, manager, trainer._create_rollout_task) - runner.initialize() - dispatcher.initialize() - try: - batch = trainer._collect_complete_grpo_batch(inputs, batch_size=4) - assert [row['grpo_rollout_index'] for row in batch] == [0, 1, 2, 3] - assert (manager.get_stats().accepted, manager.get_stats().running, - manager.get_stats().rejected) == (0, 0, 1) - assert manager.get_capacity() == 8 - finally: - dispatcher.destroy() diff --git a/tests/test_rollout_engine.py b/tests/test_rollout_engine.py deleted file mode 100644 index bdf48f0..0000000 --- a/tests/test_rollout_engine.py +++ /dev/null @@ -1,142 +0,0 @@ -import asyncio -import json - -import httpx -import pytest - -from RL_Framework.engine.rollout_engine import VLLMRolloutEngine -from RL_Framework.workflow.behavior import SamplingEvidenceError - - -def test_parse_response_accepts_missing_logprobs(): - engine = VLLMRolloutEngine() - - parsed = engine._parse_response( - { - "choices": [ - { - "text": "hello", - "logprobs": None, - "finish_reason": "stop", - } - ] - } - ) - - assert parsed == { - "text": "hello", - "tokens": [], - "logprobs": [], - "finish_reason": "stop", - } - - -def test_parse_response_rejects_invalid_choice(): - engine = VLLMRolloutEngine() - - with pytest.raises(ValueError, match="Invalid choice type"): - engine._parse_response({"choices": [None]}) - - -class InterruptedBody(httpx.AsyncByteStream): - async def __aiter__(self): - yield b'{"choices":' - raise httpx.ReadError("completion response interrupted") - - -@pytest.mark.parametrize("initial_failure", ["read_error", "missing_response"]) -def test_http_disconnect_retries_same_nonstreaming_request_once_without_relaxing_evidence(initial_failure): - attempts = [] - - async def handle(request): - payload = json.loads(request.content) - attempts.append((str(request.url), dict(request.headers), payload)) - if len(attempts) == 1: - if initial_failure == "missing_response": - raise httpx.RemoteProtocolError("Server disconnected without sending a response.") - return httpx.Response(200, stream=InterruptedBody()) - trace = dict(logprob_kind="sampler", prompt_token_ids=payload["prompt"], - output_token_ids=[21], logprobs=[-.2], - sampling_parameters={key: payload[key] for key in ("seed", "temperature", "top_p")}) - return httpx.Response(200, headers={"x-libra-optimizer-revision": "24"}, - json={"choices": [{"text": "answer", "libra_behavior": trace}]}) - - async def run(): - engine = VLLMRolloutEngine() - async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client: - engine.http_client = client - engine._http_client_loop = asyncio.get_running_loop() - return await engine.generate("display", prompt_token_ids=[10, 11], - capture_behavior=True, seed=12, temperature=.8, top_p=.95, max_new_tokens=4) - - result = asyncio.run(run()) - assert result["tokens"] == [21] - assert result["logprobs"] == [-.2] - assert result["sample_revision"] == 24 - assert len(attempts) == 2 and attempts[0] == attempts[1] - assert attempts[1][1]["x-libra-capture-behavior"] == "1" - - -@pytest.mark.parametrize(("initial_failure", "second_failure"), [ - ("read_error", "read_error"), - ("read_error", "invalid_evidence"), - ("read_error", "cancelled"), - ("missing_response", "missing_response"), - ("missing_response", "invalid_evidence"), - ("missing_response", "cancelled"), -]) -def test_http_disconnect_retry_keeps_original_failure_and_cancellation_boundaries(initial_failure, second_failure): - attempts = [] - - async def handle(request): - attempts.append(request) - if initial_failure == "missing_response" and ( - len(attempts) == 1 or second_failure == "missing_response" - ): - raise httpx.RemoteProtocolError("Server disconnected without sending a response.") - if len(attempts) == 1 or second_failure == "read_error": - return httpx.Response(200, stream=InterruptedBody()) - if second_failure == "cancelled": - raise asyncio.CancelledError() - return httpx.Response(200, headers={"x-libra-optimizer-revision": "24"}, - json={"choices": [{"text": "answer"}]}) - - async def run(): - engine = VLLMRolloutEngine() - async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client: - engine.http_client = client - engine._http_client_loop = asyncio.get_running_loop() - return await engine.generate("display", prompt_token_ids=[10, 11], - capture_behavior=True, seed=12, temperature=.8, top_p=.95, max_new_tokens=4) - - error = asyncio.CancelledError if second_failure == "cancelled" else SamplingEvidenceError - with pytest.raises(error) as caught: - asyncio.run(run()) - assert len(attempts) == 2 - if second_failure == "read_error": - assert isinstance(caught.value.__cause__, httpx.ReadError) - elif second_failure == "missing_response": - assert isinstance(caught.value.__cause__, httpx.RemoteProtocolError) - elif second_failure == "invalid_evidence": - assert str(caught.value) == "Server omitted sampler token evidence" - - -def test_other_remote_protocol_errors_are_not_retried(): - attempts = [] - - async def handle(request): - attempts.append(request) - raise httpx.RemoteProtocolError("illegal status line: bytearray(b'broken')") - - async def run(): - engine = VLLMRolloutEngine() - async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client: - engine.http_client = client - engine._http_client_loop = asyncio.get_running_loop() - return await engine.generate("display", prompt_token_ids=[10, 11], - capture_behavior=True, seed=12, temperature=.8, top_p=.95, max_new_tokens=4) - - with pytest.raises(SamplingEvidenceError) as caught: - asyncio.run(run()) - assert isinstance(caught.value.__cause__, httpx.RemoteProtocolError) - assert len(attempts) == 1 diff --git a/tests/test_rollout_lending.py b/tests/test_rollout_lending.py deleted file mode 100644 index 3289dd0..0000000 --- a/tests/test_rollout_lending.py +++ /dev/null @@ -1,397 +0,0 @@ -"""Loans grow without disturbing existing Hybrid ownership or exposing unsafe GPUs.""" -from dataclasses import dataclass -from types import SimpleNamespace as NS - -from types import SimpleNamespace -from RL_Framework.infra.elastic.runtime_executor import ManagedRolloutProcess, RuntimeElasticExecutor - -import pytest - -from RL_Framework.infra.elastic.rollout_lending import _choose_engines, lend_rollout, return_rollout -from RL_Framework.infra.elastic.rollout_lifecycle import unavailable_rollouts - - -@dataclass -class Meta: - instance_id: str - command: str - pid: int - gpus: list - port: int - host: str = 'node' - tp: int = 1 - adopted: bool = False - - -def fixture(count=4, reserve=1): - original = [Meta(chr(97+i), 'serve', 10+i, [i], 8000+i) for i in range(count)] - handles = [NS(instance_id=m.instance_id, is_ready=True) for m in original] - events = [] - dispatcher = NS(paused=False) - dispatcher.is_paused = lambda: dispatcher.paused - dispatcher.pause = lambda: setattr(dispatcher, 'paused', True) - dispatcher.resume = lambda: setattr(dispatcher, 'paused', False) - dispatcher.wait_until_idle = lambda **kw: events.append('drained') - cfg = NS(train_tp_size=1, train_ep_size=1, train_pp_size=1, train_cp_size=1, - global_resource_planner=NS(elastic_hybrid_min_rollout_gpus=reserve, - runtime_drain_timeout_s=1)) - ex = NS(config=cfg, dispatcher=dispatcher, _process_meta={m.instance_id:m for m in original}, - _hybrid_worker_meta={}, rollout_engine=NS(scheduler=NS(_instances=handles), - wait_until_idle=lambda **kw: None)) - ex._adopt_existing_rollout_processes = lambda: None - ex._elastic_replica_size_gpus = lambda: cfg.train_tp_size*cfg.train_ep_size*cfg.train_pp_size*cfg.train_cp_size - def stop(identity): - assert not next(h for h in handles if h.instance_id == identity).is_ready - events.append(('stop',identity)) - return [ex._process_meta.pop(identity)] - ex._stop_rollout_process = stop - ex._command_for_instance_id = lambda identity,port: 'restart '+identity - def start(meta): - assert meta.instance_id not in ex._process_meta - events.append(('start',meta.instance_id)) - ex._process_meta[meta.instance_id] = meta - return meta - ex._start_one_rollout_process = start - ex._wait_rollout_process_start_ready = lambda meta: events.append(('ready',meta.instance_id)) - def publish(instance_ids=None): - assert instance_ids is not None - assert all(not h.is_ready for h in handles if h.instance_id in instance_ids) - events.append(('publish',tuple(instance_ids))) - ex._publish_current_rollout_weights = publish - return ex,events,handles - - -def test_grow_total_loan_preserves_existing_slots_generation_and_hybrid(): - ex,events,handles = fixture() - first = lend_rollout(ex,1) - saved = ex._lent_rollout - generation = saved['generation'] - hybrid = NS(host='node',gpus=[0]) - ex._hybrid_worker_meta['old-hybrid'] = hybrid - second = lend_rollout(ex,2) - assert ex._lent_rollout is saved and saved['generation'] == generation - assert first == {'rollout0':{'host':'node','gpus':[0]}} - assert second == {**first,'rollout1':{'host':'node','gpus':[1]}} - assert ex._hybrid_worker_meta == {'old-hybrid':hybrid} - assert [e for e in events if isinstance(e,tuple) and e[0]=='stop'] == [('stop','a'),('stop','b')] - assert not handles[0].is_ready and not handles[1].is_ready - assert lend_rollout(ex,2) == second - - -def test_reserve_counts_only_rollout_gpus_not_existing_loan(): - ex,events,_ = fixture(reserve=2) - first = lend_rollout(ex,1) - second = lend_rollout(ex,2) - assert len(second) == 2 - before = list(events) - assert lend_rollout(ex,3) == second - assert events == before and len(ex._process_meta) == 2 - assert first.items() <= second.items() - - -def test_selection_uses_full_runtime_replica_width(): - ex,_,_ = fixture(count=3,reserve=0) - ex.config.train_ep_size = 2 - for i,meta in enumerate(ex._process_meta.values()): - meta.host = 'node'+str(i) - assert _choose_engines(ex,2) == () - - -def test_failed_expansion_restores_only_new_engines_after_targeted_ack(): - ex,events,handles = fixture(reserve=1) - first = lend_rollout(ex,1) - old = ex._lent_rollout - snapshot = (dict(old['slots']),list(old['engines']),old['generation']) - stop = ex._stop_rollout_process - once = {'fail':True} - def fail_second(identity): - if identity=='c' and once['fail']: - once['fail']=False - raise RuntimeError('unconfirmed stop') - return stop(identity) - ex._stop_rollout_process = fail_second - with pytest.raises(RuntimeError,match='unconfirmed stop'): - lend_rollout(ex,3) - assert ex._lent_rollout is old - assert (old['slots'],old['engines'],old['generation']) == snapshot - assert lend_rollout(ex,1)==first - assert not handles[0].is_ready and all(h.is_ready for h in handles[1:]) - assert ('publish',('b','c')) in events - assert not any(e in [('start','a'),('publish',('a',))] for e in events) - assert getattr(ex,'_rollout_loan_rollback',None) is None - - -def test_failed_rollback_keeps_new_ownership_isolated_and_old_loan_usable(): - ex,events,handles = fixture() - first = lend_rollout(ex,1) - old = ex._lent_rollout - def fail_publish(instance_ids=None): - events.append(('publish-failed',tuple(instance_ids))) - raise RuntimeError('current weights not acknowledged') - ex._publish_current_rollout_weights=fail_publish - stop=ex._stop_rollout_process - once={'fail':True} - def fail_stop(identity): - if identity=='c' and once['fail']: - once['fail']=False - raise RuntimeError('stop lost acknowledgement') - return stop(identity) - ex._stop_rollout_process=fail_stop - with pytest.raises(RuntimeError): - lend_rollout(ex,3) - assert ex._lent_rollout is old and old['slots']==first - assert ex._rollout_loan_rollback - assert set(unavailable_rollouts(ex))=={'a','b','c'} - assert not any(h.is_ready for h in handles[:3]) - assert lend_rollout(ex,1)==first - before=list(events) - with pytest.raises(RuntimeError,match='incomplete'): - lend_rollout(ex,3) - assert events==before - - -def test_rollback_reopens_selected_services_that_were_never_stopped(): - ex,events,handles=fixture(count=6,reserve=1) - lend_rollout(ex,1) - stop=ex._stop_rollout_process - once={'fail':True} - def fail(identity): - if identity=='c' and once['fail']: - once['fail']=False - raise RuntimeError('middle stop failed') - return stop(identity) - ex._stop_rollout_process=fail - with pytest.raises(RuntimeError,match='middle stop failed'): - lend_rollout(ex,4) - assert not handles[0].is_ready - assert all(h.is_ready for h in handles[1:]) - assert ('stop','d') not in events and ('start','d') not in events - assert ('publish',('b','c')) in events - - -def test_return_readiness_retry_keeps_started_process_ownership(tmp_path): - ex,events,_=fixture(count=2,reserve=0) - lend_rollout(ex,1) - ex._hybrid_worker_control_dir=lambda:tmp_path - once={'fail':True} - def wait(meta): - if once['fail']: - once['fail']=False - raise RuntimeError('service still warming') - ex._wait_rollout_process_start_ready=wait - with pytest.raises(RuntimeError,match='still warming'): - return_rollout(ex) - owned=ex._lent_rollout['restored'][0] - assert ex._process_meta['a'] is owned - assert return_rollout(ex)==[owned] - assert events.count(('start','a'))==1 - - -def test_return_restarts_a_dead_restoration_only_after_confirming_exit(tmp_path): - ex, events, _ = fixture(count=2, reserve=0) - lend_rollout(ex, 1) - ex._hybrid_worker_control_dir = lambda: tmp_path - ex._processes = {} - start = ex._start_one_rollout_process - launched = [] - - def tracked_start(meta): - owner = start(meta) - process = NS(returncode=None) - process.poll = lambda: process.returncode - ex._processes[owner.instance_id] = process - launched.append(owner) - return owner - - ex._start_one_rollout_process = tracked_start - - def wait(meta): - if len(launched) == 1: - ex._processes[meta.instance_id].returncode = 1 - raise RuntimeError('new rollout exited') - - ex._wait_rollout_process_start_ready = wait - with pytest.raises(RuntimeError, match='new rollout exited'): - return_rollout(ex) - - assert ex._process_meta['a'] is launched[0] - stop = ex._stop_rollout_process - ex._stop_rollout_process = lambda _: [] - with pytest.raises(RuntimeError, match='cannot confirm exit'): - return_rollout(ex) - assert ex._process_meta['a'] is launched[0] - assert len(launched) == 1 - - ex._stop_rollout_process = stop - restored = return_rollout(ex) - assert len(launched) == 2 - assert restored == [launched[1]] - assert events.count(('start', 'a')) == 2 - assert [event for event in events if isinstance(event, tuple)] == [ - ('stop', 'a'), ('start', 'a'), ('stop', 'a'), ('start', 'a'), - ] - assert launched[0].incarnation_id != launched[1].incarnation_id - - -def test_wide_replica_hands_off_only_after_every_engine_exit_ack(): - ex,events,_=fixture(count=4,reserve=0) - ex.config.train_tp_size=2 - ex.config.train_pp_size=2 - stop=ex._stop_rollout_process - def checked(identity): - assert not getattr(ex,'_lent_rollout',None) - return stop(identity) - ex._stop_rollout_process=checked - slots=lend_rollout(ex,4) - assert len(slots)==4 and not ex._process_meta - assert len([e for e in events if isinstance(e,tuple) and e[0]=='stop'])==4 - - -def test_one_wide_engine_cannot_borrow_through_rollout_reserve(): - ex,events,_=fixture(count=1,reserve=2) - ex.config.train_tp_size=2 - ex._process_meta['a'].gpus=[0,1,2,3] - ex._process_meta['a'].tp=4 - assert lend_rollout(ex,2)=={} - assert events==[] - - -def test_remote_exit_ack_is_bound_to_the_owned_request(tmp_path): - import json - from RL_Framework.infra.elastic.rollout_lending import wait_hybrid_stopped - ex,_,_=fixture() - ex._hybrid_worker_control_dir=lambda:tmp_path - ex.config.global_resource_planner.hybrid_worker_stop_timeout_s=.01 - path=tmp_path/'.stop_worker.done' - path.write_text(json.dumps(dict(worker_id='worker',request_id='old',exited=True))) - with pytest.raises(TimeoutError): - wait_hybrid_stopped(ex,'worker','current') - path.write_text(json.dumps(dict(worker_id='worker',request_id='current',exited=True))) - assert wait_hybrid_stopped(ex,'worker','current')['exited'] - - -def executor_fixture(tmp_path, *, remote=False): - metas = [ManagedRolloutProcess(f"engine{i}", "vllm", i + 10, [2 * i, 2 * i + 1], 8000 + i, - host="rollout-host", tp=2) for i in range(2)] - handles = [SimpleNamespace(instance_id=meta.instance_id, is_ready=True) for meta in metas] - events = [] - dispatcher = SimpleNamespace(paused=False) - dispatcher.is_paused = lambda: dispatcher.paused - def pause(): - dispatcher.paused = True - events.append("pause") - dispatcher.pause = pause - dispatcher.resume = lambda: setattr(dispatcher, "paused", False) - dispatcher.wait_until_idle = lambda timeout: events.append("dispatcher-drained") - scheduler = SimpleNamespace(_instances=handles) - def withdraw(indices): - for index in indices: - handles[index].is_ready = False - events.append(("withdraw", tuple(indices))) - scheduler.withdraw_instances = withdraw - def wait_generations(indices, timeout): - assert all(not handles[index].is_ready for index in indices) - events.append(("generate-complete", tuple(indices))) - scheduler.wait_for_generations = wait_generations - executor = SimpleNamespace( - config=SimpleNamespace(train_tp_size=4, - global_resource_planner=SimpleNamespace(runtime_drain_timeout_s=0, hybrid_worker_stop_timeout_s=.05), - heterogeneous_rollout=SimpleNamespace( - instances=[SimpleNamespace(host=m.host, gpus=m.gpus) for m in metas], - scheduling=SimpleNamespace(scheduler_type="cmlfq_cost", cmlfq_kv_backend="recompute"))), - _process_meta={meta.instance_id: meta for meta in metas}, _hybrid_worker_meta={}, - wait_for_hybrid_training_tasks=lambda worker: events.append(f"task-complete-{worker}"), - _hybrid_worker_remote_control_enabled=remote, dispatcher=dispatcher, - rollout_engine=SimpleNamespace(scheduler=scheduler, - wait_until_idle=lambda timeout: events.append("engine-drained")), - ) - executor._adopt_existing_rollout_processes = lambda: None - executor._elastic_replica_size_gpus = lambda: RuntimeElasticExecutor._elastic_replica_size_gpus(executor) - executor._hybrid_worker_control_dir = lambda: tmp_path - def stop(instance_id): - assert all(not handle.is_ready for handle in handles) - events.append(f"stop-{instance_id}") - return [executor._process_meta.pop(instance_id)] - executor._stop_rollout_process = stop - def start(meta): - assert not executor._hybrid_worker_meta - assert all(not handle.is_ready for handle in handles) - events.append(f"start-{meta.instance_id}") - executor._process_meta[meta.instance_id] = meta - return meta - executor._start_one_rollout_process = start - executor._wait_rollout_process_start_ready = lambda meta: events.append(f"ready-{meta.instance_id}") - executor._command_for_instance_id = lambda instance_id, port: f"restart {instance_id}:{port}" - return executor, events, metas, handles - - -def test_borrow_uses_selected_physical_service_and_keeps_survivor_dispatching(tmp_path): - executor, events, original, handles = executor_fixture(tmp_path) - executor.config.train_tp_size = 2 - executor.config.global_resource_planner.elastic_hybrid_min_rollout_gpus = 2 - executor._stop_rollout_process = lambda name: ( - events.append(f"stop-{name}") or [executor._process_meta.pop(name)]) - slots = lend_rollout(executor, 2, instance_ids=["engine1"]) - assert {gpu for slot in slots.values() for gpu in slot["gpus"]} == {2, 3} - assert events == [("withdraw", (1,)), ("generate-complete", (1,)), "stop-engine1"] - assert handles[0].is_ready and not handles[1].is_ready - assert not executor.dispatcher.paused - - -def test_borrow_does_not_stop_target_if_generate_reservation_does_not_finish(tmp_path): - executor, events, _, handles = executor_fixture(tmp_path) - executor.config.train_tp_size = 2 - def timeout(indices, timeout): - raise TimeoutError("target generate still reserved before HTTP") - executor.rollout_engine.scheduler.wait_for_generations = timeout - with pytest.raises(TimeoutError, match="reserved before HTTP"): - lend_rollout(executor, 2) - assert not any(isinstance(event, str) and event.startswith("stop-") for event in events) - assert not getattr(executor, "_lent_rollout", None) - assert all(handle.is_ready for handle in handles) - - -def test_legacy_lending_drains_before_withdrawing_route(tmp_path): - executor, events, _, _ = executor_fixture(tmp_path) - executor.config.heterogeneous_rollout.scheduling = SimpleNamespace(scheduler_type="length_aware") - lend_rollout(executor, 4) - assert events[:3] == ["pause", "dispatcher-drained", "engine-drained"] - assert events[3:] == ["stop-engine0", "stop-engine1"] - - -def test_reserve_counts_unique_host_gpu_addresses(tmp_path): - executor, _, original, _ = executor_fixture(tmp_path) - executor.config.train_tp_size = 1 - executor.config.global_resource_planner.elastic_hybrid_min_rollout_gpus = 3 - duplicate = ManagedRolloutProcess('alias', 'vllm', 11, [0, 1], 8002, - host='rollout-host', tp=2) - executor._process_meta[duplicate.instance_id] = duplicate - assert _choose_engines(executor, 1) == () - - executor.config.global_resource_planner.elastic_hybrid_min_rollout_gpus = 2 - original[1].host = 'another-host' - original[1].gpus = [0, 1] - assert len(_choose_engines(executor, 1)) == 1 - - -def test_failed_engine_stop_exposes_no_gpu_slots_and_can_recover(tmp_path): - from RL_Framework.infra.elastic.rollout_lifecycle import unavailable_rollouts - executor, events, _, handles = executor_fixture(tmp_path) - stop = executor._stop_rollout_process - def fail_second(instance_id): - if instance_id == "engine1": - raise RuntimeError("still owns CUDA") - return stop(instance_id) - executor._stop_rollout_process = fail_second - with pytest.raises(RuntimeError, match="CUDA"): - lend_rollout(executor, 4) - assert not getattr(executor, "_lent_rollout", None) - assert set(unavailable_rollouts(executor)) == {"engine0", "engine1"} - with pytest.raises(RuntimeError, match="incomplete"): - lend_rollout(executor, 4) - executor._stop_rollout_process = stop - executor._publish_current_rollout_weights = lambda instance_ids: events.append(("install", instance_ids)) - assert return_rollout(executor) == [] - assert ("install", ["engine0", "engine1"]) in events - assert all(handle.is_ready for handle in handles) - assert unavailable_rollouts(executor) == [] diff --git a/tests/test_rollout_lifecycle.py b/tests/test_rollout_lifecycle.py deleted file mode 100644 index c6586ca..0000000 --- a/tests/test_rollout_lifecycle.py +++ /dev/null @@ -1,335 +0,0 @@ -"""Lent GPUs return before supply waits and stay closed until publication.""" - -import copy -import threading -from concurrent.futures import ThreadPoolExecutor -from types import SimpleNamespace - -import pytest - -from RL_Framework.infra.elastic import rollout_lifecycle as lifecycle -from RL_Framework.infra.elastic import rollout_lending - - -class Collectives: - def __init__(self): - self.barrier = threading.Barrier(2) - self.packet = None - self.values = [None, None] - self.calls = [] - - @staticmethod - def is_available(): - return True - - @staticmethod - def is_initialized(): - return True - - @staticmethod - def get_world_size(group=None): - return 2 - - @staticmethod - def get_rank(group=None): - return group.rank if group is not None else 0 - - def broadcast_object_list(self, packet, src, group): - assert src == 0 - self.calls.append((group.rank, "broadcast")) - if group.rank == 0: - self.packet = copy.deepcopy(packet[0]) - self.barrier.wait(timeout=3) - packet[0] = copy.deepcopy(self.packet) - self.barrier.wait(timeout=3) - - def all_gather_object(self, records, value, group): - self.calls.append((group.rank, "gather")) - self.values[group.rank] = value - self.barrier.wait(timeout=3) - records[:] = self.values - self.barrier.wait(timeout=3) - - -def trainer(rank, *, ready_groups=2, loan=True, publish_failure=False): - instances = [SimpleNamespace(instance_id=name) for name in ("engine-a", "engine-b")] - calls = [] - handles = [SimpleNamespace(instance_id=instance.instance_id, is_ready=not loan) - for instance in instances] - executor = SimpleNamespace( - _lent_rollout={"engines": instances} if loan else None, - _release_all_hybrid_workers=lambda **kwargs: calls.append("release-hybrids"), - _rollout_lending_resume_pending=True, - ) - state = SimpleNamespace( - is_main_process=rank == 0, control=SimpleNamespace(rank=rank), - runtime_elastic_executor=executor if rank == 0 else None, - config=SimpleNamespace( - n_samples=4, heterogeneous_rollout=SimpleNamespace(enabled=True, instances=instances), - global_resource_planner=SimpleNamespace( - enabled=True, runtime_reconfigure_training=True, - hybrid_worker_launch_enabled=True, runtime_training_pool_plan_only=False, - ), - ), - rollout_engine=SimpleNamespace(scheduler=SimpleNamespace(_instances=handles)), - dispatcher=SimpleNamespace(peek_ready_data=lambda: [], is_paused=lambda: False), - _pending_grpo_groups={f"group-{i}": [ - {"grpo_group_id": f"group-{i}", "grpo_rollout_index": index} - for index in range(4)] for i in range(ready_groups)}, - _consumed_grpo_group_ids=set(), _source_batch_sample_count=lambda: 8, - _is_rollout_source=lambda: rank == 0, - _pause_rollout_pipeline=lambda: calls.append("pause"), - _resume_rollout_pipeline=lambda: calls.append("resume"), - _refresh_nonblocking_elastic_membership=lambda: calls.append("refresh-membership"), - _rebind_rollout_engine_from_config=lambda **kwargs: calls.append("rebind"), - train_engine=SimpleNamespace( - optimizer_revision=23, _elastic_step_hybrid_workers=("hybrid-old",), - set_version=lambda version: calls.append(("set-version", version)), - ), - calls=calls, handles=handles, - ) - - def publish(*, target_version, reopen_restored): - assert not reopen_restored - assert target_version == 23 - assert all(not handle.is_ready for handle in handles) - assert state._restored_rollouts_pending_publication == {"engine-a", "engine-b"} - calls.append("publish") - if publish_failure: - raise RuntimeError("weight install failed") - - state._sync_weights = publish - return state - - -def run_ranks(function, trainers): - with ThreadPoolExecutor(max_workers=2) as pool: - futures = [pool.submit(function, state) for state in trainers] - results = [] - for future in futures: - try: - results.append(future.result(timeout=5)) - except Exception as exc: - results.append(exc) - return results - - -def install_transport(monkeypatch): - collectives = Collectives() - monkeypatch.setattr(lifecycle, "dist", collectives) - - def return_loan(executor): - executor._lent_rollout = None - return ["new-service-a", "new-service-b"] - - monkeypatch.setattr(rollout_lending, "return_rollout", return_loan) - return collectives - - -def test_keep_whole_pool_lent_while_complete_batch_ready(monkeypatch): - collectives = install_transport(monkeypatch) - ranks = [trainer(rank) for rank in range(2)] - assert run_ranks(lifecycle.ensure_batch_supply, ranks) == [None, None] - assert all(state.calls == [] for state in ranks) - assert ranks[0].runtime_elastic_executor._lent_rollout is not None - assert len([call for call in collectives.calls if call[1] == "gather"]) == 2 - - -def test_return_pool_before_supply_wait_then_publish_before_reopen(monkeypatch): - install_transport(monkeypatch) - ranks = [trainer(rank, ready_groups=1) for rank in range(2)] - assert run_ranks(lifecycle.ensure_batch_supply, ranks) == [None, None] - for state in ranks: - assert state.calls.index("pause") < state.calls.index("publish") - assert state.calls.index("refresh-membership") < state.calls.index("publish") - assert state.calls.index("publish") < state.calls.index("rebind") < state.calls.index("resume") - assert all(handle.is_ready for handle in state.handles) - assert state._restored_rollouts_pending_publication == set() - assert state.train_engine._elastic_step_hybrid_workers == () - assert ("set-version", 23) in state.calls - assert ranks[0].calls.index("release-hybrids") < ranks[0].calls.index("publish") - - -def test_supply_restore_uses_publication_hook_on_every_rank(monkeypatch): - install_transport(monkeypatch) - ranks = [trainer(rank, ready_groups=1) for rank in range(2)] - for state in ranks: - def restore(state=state): - state.calls.append("invalidate-old-publication") - return lifecycle.restore_for_publication(state) - state._restore_lent_rollouts_for_publication = restore - assert run_ranks(lifecycle.ensure_batch_supply, ranks) == [None, None] - for state in ranks: - assert state.calls.index("pause") < state.calls.index("invalidate-old-publication") - assert state.calls.index("invalidate-old-publication") < state.calls.index("publish") - - -def test_restore_failure_is_broadcast_to_every_rank_without_reopen(monkeypatch): - install_transport(monkeypatch) - - def failed_return(executor): - raise RuntimeError("service restart failed") - - monkeypatch.setattr(rollout_lending, "return_rollout", failed_return) - ranks = [trainer(rank, ready_groups=1) for rank in range(2)] - results = run_ranks(lifecycle.ensure_batch_supply, ranks) - assert all(isinstance(result, RuntimeError) and "service restart failed" in str(result) - for result in results) - assert all("publish" not in state.calls and "resume" not in state.calls for state in ranks) - assert all(not handle.is_ready for state in ranks for handle in state.handles) - - -def test_failed_publication_keeps_restored_engines_closed(monkeypatch): - install_transport(monkeypatch) - ranks = [trainer(rank, ready_groups=1, publish_failure=True) for rank in range(2)] - results = run_ranks(lifecycle.ensure_batch_supply, ranks) - assert all(isinstance(result, RuntimeError) and "weight install failed" in str(result) - for result in results) - assert all("resume" not in state.calls and "rebind" not in state.calls for state in ranks) - assert all(not handle.is_ready for state in ranks for handle in state.handles) - - -def test_one_rank_publication_failure_prevents_every_rank_reopening(monkeypatch): - install_transport(monkeypatch) - ranks = [trainer(0, ready_groups=1, publish_failure=True), - trainer(1, ready_groups=1, publish_failure=False)] - results = run_ranks(lifecycle.ensure_batch_supply, ranks) - assert all(isinstance(result, RuntimeError) and "weight install failed" in str(result) - for result in results) - assert all("resume" not in state.calls and "rebind" not in state.calls for state in ranks) - assert all(not handle.is_ready for state in ranks for handle in state.handles) - - -def test_any_dp_source_shortage_returns_pool(monkeypatch): - install_transport(monkeypatch) - ranks = [trainer(0), trainer(1, ready_groups=1)] - ranks[1]._is_rollout_source = lambda: True - assert run_ranks(lifecycle.ensure_batch_supply, ranks) == [None, None] - assert all("publish" in state.calls for state in ranks) - - -def test_partial_loan_keeps_available_rollout_supply_running(monkeypatch): - collectives = install_transport(monkeypatch) - ranks = [trainer(rank, ready_groups=0) for rank in range(2)] - ranks[0].runtime_elastic_executor._lent_rollout["engines"] = [SimpleNamespace(instance_id="engine-a")] - assert run_ranks(lifecycle.ensure_batch_supply, ranks) == [None, None] - assert all(state.calls == [] for state in ranks) - assert not any(call[1] == "gather" for call in collectives.calls) - - -def test_disabled_resource_management_avoids_collectives(monkeypatch): - state = trainer(0, loan=False) - state.config.global_resource_planner.enabled = False - - class ForbiddenCollectives: - def __getattr__(self, name): - raise AssertionError(f"disabled resource management entered dist.{name}") - - monkeypatch.setattr(lifecycle, "dist", ForbiddenCollectives()) - lifecycle.ensure_batch_supply(state) - assert state.calls == [] - - -def test_reopen_without_pending_install_is_noop(): - state = trainer(0) - lifecycle.reopen_after_publication(state) - assert all(not handle.is_ready for handle in state.handles) - - -def test_loan_publication_does_not_reenable_unrelated_unhealthy_engine(): - state = trainer(0) - unhealthy = SimpleNamespace(instance_id="unhealthy-other", is_ready=False) - state.handles.append(unhealthy) - lifecycle.apply_availability(state, ("engine-a", "engine-b")) - state._restored_rollouts_pending_publication = {"engine-a", "engine-b"} - lifecycle.reopen_after_publication(state) - assert all(handle.is_ready for handle in state.handles[:2]) - assert unhealthy.is_ready is False - - -def test_pending_hybrid_activation_gets_post_boundary_catchup_even_without_grp_gain(): - from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - events = [] - current_plan = object() - state = SimpleNamespace( - config=SimpleNamespace(total_steps=11), - runtime_elastic_executor=SimpleNamespace(has_pending_boundary_work=lambda: True), - global_resource_planner=SimpleNamespace( - _history=[], _build_current_plan=lambda config, history: current_plan), - _run_global_resource_planner=lambda *args: events.append("planner"), - _runtime_reconfiguration_boundary=lambda *args: events.append(("noop", args)), - ) - - def apply(step, decision, stats): - events.append((step, decision)) - state._runtime_boundary_published = True - - state._apply_global_resource_planner_decision = apply - AsyncRLTrainer._run_global_resource_planner_at_boundary(state, 9, [], {}) - assert len(events) == 2 and events[0] == "planner" - step, decision = events[1] - assert step == 9 - assert decision.reason == "hybrid_boundary_maintenance" - assert decision.should_reconfigure is True - assert decision.resource_should_reconfigure is False - assert decision.current_plan is decision.candidate_plan is current_plan - assert state._runtime_post_boundary is None - - -def test_no_pending_activation_keeps_normal_grp_post_boundary(): - from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - events = [] - state = SimpleNamespace( - config=SimpleNamespace(total_steps=11), - runtime_elastic_executor=SimpleNamespace(has_pending_boundary_work=lambda: False), - _run_global_resource_planner=lambda *args: events.append("planner"), - _runtime_reconfiguration_boundary=lambda step, point: events.append((step, point)), - ) - AsyncRLTrainer._run_global_resource_planner_at_boundary(state, 9, [], {}) - assert events == ["planner", (9, "post")] - assert state._runtime_post_boundary is None - - -def test_repartition_publication_uses_new_topology_before_client_reopen(): - from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - state = SimpleNamespace( - _use_heterogeneous=True, - rollout_engine=SimpleNamespace(instance_configs=[ - {"instance_id": "old-engine-a", "tp_degree": 2}, - {"instance_id": "old-engine-b", "tp_degree": 2}, - ]), - config=SimpleNamespace(heterogeneous_rollout=SimpleNamespace(enabled=True, instances=[ - SimpleNamespace(instance_id="new-engine", tp=4, host="new", port=8000), - ])), - ) - world_size, offsets = AsyncRLTrainer._nccl_rollout_topology(state) - assert world_size == 5 - assert offsets == {"new-engine": 0} - - -def test_resource_repartition_publishes_current_config_targets(monkeypatch): - from RL_Framework.infra.elastic.runtime_executor import RuntimeElasticExecutor - from RL_Framework.infra.elastic import core_reconfiguration - commands = [] - monkeypatch.setattr(core_reconfiguration, "dispatch_core_command", lambda executor, operation, **kwargs: - commands.append((operation, kwargs))) - state = SimpleNamespace(config=SimpleNamespace(heterogeneous_rollout=SimpleNamespace(enabled=True, instances=[ - SimpleNamespace(instance_id="new-engine", tp=4, gpus=[0, 1, 2, 3], host="rollout-node", port=8200), - ]))) - RuntimeElasticExecutor._publish_current_rollout_weights(state) - assert commands == [("publish", {"target": {"instances": [ - {"instance_id": "new-engine", "tp": 4, "gpus": [0, 1, 2, 3], - "host": "rollout-node", "port": 8200}, - ]}})] - - -def test_subset_publication_leaves_routing_to_rollback_owner(): - state = trainer(0) - lifecycle.apply_availability(state, ('engine-a','engine-b')) - state._publication_target_ids = {'engine-b'} - state._restored_rollouts_pending_publication = {'engine-b'} - lifecycle.reopen_after_publication(state) - assert state._rollout_unavailable_ids == {'engine-a','engine-b'} - assert state._restored_rollouts_pending_publication == {'engine-b'} - assert all(not handle.is_ready for handle in state.handles) - assert state.runtime_elastic_executor._rollout_lending_resume_pending diff --git a/tests/test_rollout_process.py b/tests/test_rollout_process.py deleted file mode 100644 index 2720a3a..0000000 --- a/tests/test_rollout_process.py +++ /dev/null @@ -1,303 +0,0 @@ -"""Placement uses the existing Slurm allocation and precise owned process IDs.""" -import json -import os -from pathlib import Path -import shlex -import signal -import subprocess -import sys -import time -from types import SimpleNamespace as NS - -import pytest - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.elastic import rollout_process as placement -from RL_Framework.infra.elastic.runtime_executor import RuntimeElasticExecutor, ManagedRolloutProcess - - -def test_default_full_launcher_keeps_serving_worker_recompute_and_exact_gpu_contract(monkeypatch): - monkeypatch.delenv('VLLM_SERVER_MODULE', raising=False) - monkeypatch.delenv('LIBRA_KV_STORAGE_PATH', raising=False) - monkeypatch.setenv('LIBRA_CAPTURE_BEHAVIOR', '1') - monkeypatch.setenv('RANK', '2') - monkeypatch.setenv('MASTER_ADDR', 'training-only') - monkeypatch.setenv('TORCHELASTIC_WORKER_GROUP', 'training') - executor = object.__new__(RuntimeElasticExecutor) - executor.config = AsyncRLConfig(model_path='/not-loaded', train_gpus=2, rollout_gpus=2, n_total_gpus=4) - executor.config.heterogeneous_rollout.scheduling.cmlfq_kv_backend = 'recompute' - executor.config.rollout_weight_sync_control_dir = '/fyp/run/control' - instance = NS(instance_id='current', tp=2, host='rollout-node', gpus=[2, 3]) - command = executor._build_vllm_command(instance, 9000) - args = shlex.split(command) - assert args[:2] == ['env', 'CUDA_VISIBLE_DEVICES=2,3'] - assert 'RL_Framework.scripts.restartable_vllm_server' in args - assert 'RL_Framework.scripts.vllm_hot_reload_api_server' in args - assert args[args.index('--worker-extension-cls') + 1] == 'RL_Framework.vllm_hot_reload.InplaceReloadWorkerExtension' - assert args[args.index('--instance-id') + 1] == 'current' - assert '--kv-transfer-config' not in args - meta = ManagedRolloutProcess('current', command, 0, [2, 3], 9000, host='rollout-node', tp=2) - env = executor._rollout_launch_env(meta) - assert env['CUDA_VISIBLE_DEVICES'] == env['PLANNED_CUDA_VISIBLE_DEVICES'] == '2,3' - assert env['LIBRA_CAPTURE_BEHAVIOR'] == '1' and env['LIBRA_EXPECTED_TP_SIZE'] == '2' - assert env['LIBRA_INSTANCE_ID'] == 'current' - assert 'LIBRA_KV_STORAGE_PATH' not in env - assert 'RANK' not in env and 'MASTER_ADDR' not in env and 'TORCHELASTIC_WORKER_GROUP' not in env - - -def test_remote_command_targets_current_allocation_and_preserves_gpu_ids(monkeypatch): - def query(argv, **kwargs): - assert argv == ['scontrol', 'show', 'hostnames', 'node[1-2]'] - return NS(stdout='node1\nnode2\n') - monkeypatch.setattr(placement.subprocess, 'run', query) - env = dict(SLURM_JOB_ID='123', SLURM_JOB_NODELIST='node[1-2]', - SLURMD_NODENAME='node1', SLURM_GPUS_ON_NODE='4') - command = placement.slurm_command('exec python serve.py', 'node2', [2, 3], env, step_name='owned') - args = shlex.split(command) - assert args[args.index('--jobid') + 1] == '123' - assert args[args.index('--nodelist') + 1] == 'node2' - assert '--overlap' in args and '--gres=gpu:4' in args - assert not any(arg.startswith('--gpus=') for arg in args) - assert 'CUDA_VISIBLE_DEVICES=2,3' in args and 'PLANNED_CUDA_VISIBLE_DEVICES=2,3' in args - assert args[-3:] == ['bash', '-c', 'exec python serve.py'] - with pytest.raises(RuntimeError, match='not one unambiguous node'): - placement.slurm_command('serve', 'outside-job', [0], env) - - -def test_remote_host_without_allocation_is_rejected_and_local_stays_local(monkeypatch): - with pytest.raises(RuntimeError, match='current Slurm allocation'): - placement.placement_command('serve', 'remote-node', [0], {}) - assert placement.placement_command('serve', '127.0.0.1', [0], {}) == 'serve' - assert placement.is_local_host('node1.cluster', dict(SLURMD_NODENAME='node1')) - assert not placement.is_local_host('node2', dict(SLURMD_NODENAME='node1')) - - -def test_launch_remote_tracks_ownership_and_uses_a_dedicated_local_session(tmp_path, monkeypatch): - monkeypatch.setattr(placement, 'allocation_nodes', lambda env: ['node1', 'node2']) - seen = [] - def popen(command, **kwargs): - seen.append((command, kwargs)) - return NS(pid=123) - monkeypatch.setattr(placement.subprocess, 'Popen', popen) - meta = NS(instance_id='current', host='node2', gpus=[0, 1], command='serve') - proc = placement.launch_rollout_process(meta, - dict(SLURM_JOB_ID='77', SLURMD_NODENAME='node1', SLURM_GPUS_ON_NODE='4'), control_dir=tmp_path) - assert seen[0][1]['start_new_session'] is True - assert 'RL_Framework.infra.elastic.rollout_process' in seen[0][0] - assert proc._libra_rollout_owner['job_id'] == '77' - assert Path(proc._libra_rollout_owner['state_path']).parent == tmp_path / 'process-owners' - - -def test_remote_stop_cancels_only_receipted_step_and_zero_waits_for_verified_exit(tmp_path, monkeypatch): - path = tmp_path / 'owned.json' - path.write_text(json.dumps(dict(token='token', job_id='77', step_id='9', status='running'))) - owner = dict(remote=True, token='token', job_id='77', state_path=str(path), step_name='owned') - proc = NS(_libra_rollout_owner=owner) - proc.poll = lambda: 0 - stopped, commands = [], [] - monkeypatch.setenv('SLURM_JOB_ID', '77') - monkeypatch.setattr(placement, 'stop_owned_session', lambda proc, timeout: stopped.append(timeout)) - def run(argv, **kwargs): - commands.append(argv) - if argv[0] == 'scancel': - assert argv == ['scancel', '--signal=TERM', '77.9'] - path.write_text(json.dumps(dict(token='token', job_id='77', step_id='9', status='exited', owned_processes_exited=True))) - return NS(stdout='') - monkeypatch.setattr(placement.subprocess, 'run', run) - placement.stop_rollout_process(proc, timeout=0) - assert stopped == [0] and commands == [['scancel', '--signal=TERM', '77.9']] - path.write_text(json.dumps(dict(token='other-owner', job_id='77', step_id='9'))) - with pytest.raises(RuntimeError, match='does not match'): - placement.stop_rollout_process(proc, timeout=0) - assert commands == [['scancel', '--signal=TERM', '77.9']] - - -@pytest.mark.parametrize('exited', [True, False]) -def test_remote_cancel_error_requires_verified_exit(tmp_path, monkeypatch, exited): - path = tmp_path / 'owned.json' - record = dict(token='token', job_id='77', step_id='9', status='running') - path.write_text(json.dumps(record)) - owner = dict(remote=True, token='token', job_id='77', state_path=str(path), step_name='owned') - proc = NS(_libra_rollout_owner=owner, poll=lambda: None) - error = subprocess.CalledProcessError(225, ['scancel', '--signal=TERM', '77.9'], - stderr='scancel: error: Kill job error on job step id 77: Invalid job id specified\n') - stopped = [] - monkeypatch.setenv('SLURM_JOB_ID', '77') - monkeypatch.setattr(placement, 'stop_owned_session', lambda proc, timeout: stopped.append(proc)) - - def run(argv, **kwargs): - if argv[0] == 'scancel': - assert argv == error.cmd - if exited: - path.write_text(json.dumps(dict(record, status='exited', owned_processes_exited=True))) - raise error - assert argv[0] == 'squeue' - return NS(stdout='77.9|owned\n') - - monkeypatch.setattr(placement.subprocess, 'run', run) - if exited: - placement.stop_rollout_process(proc, timeout=.01) - assert stopped == [proc] - else: - with pytest.raises(subprocess.CalledProcessError) as failure: - placement.stop_rollout_process(proc, timeout=.01) - assert failure.value is error - assert not stopped - - -def test_owned_stop_covers_nested_descendant_sessions(tmp_path): - child_pid = tmp_path / 'child.pid' - script = ('import subprocess,sys,time,pathlib; ' - 'p=subprocess.Popen([sys.executable,"-c","import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(60)"],start_new_session=True); ' - f'pathlib.Path({str(child_pid)!r}).write_text(str(p.pid)); time.sleep(60)') - proc = subprocess.Popen([sys.executable, '-c', script], start_new_session=True) - try: - deadline = time.monotonic() + 3 - while not child_pid.exists() and time.monotonic() < deadline: - time.sleep(.01) - assert child_pid.exists() - pid = int(child_pid.read_text()) - placement.stop_owned_session(proc, timeout=.05) - assert proc.poll() is not None - record = placement._process_record(pid) - assert record is None or record['state'] == 'Z' - finally: - if proc.poll() is None: - os.killpg(proc.pid, signal.SIGKILL) - proc.wait() - if child_pid.exists(): - try: - os.kill(int(child_pid.read_text()), signal.SIGKILL) - except ProcessLookupError: - pass - - -@pytest.mark.parametrize('change', ['wrong-job', 'wrong-instance', 'wrong-port', 'wrong-role', 'wrong-control']) -def test_adopted_identity_mismatch_never_signals_any_pid(monkeypatch, change): - monkeypatch.setenv('SLURM_JOB_ID', '777') - contract = dict(pid=120, host='127.0.0.1', instance_id='wanted', port=9000, job_id='777', control_dir='/fyp/run/control') - argv = [sys.executable, '-m', 'RL_Framework.scripts.restartable_vllm_server', - '--instance-id', 'wanted', '--health-url', 'http://127.0.0.1:9000/health', - '--control-dir', '/fyp/run/control'] - environment = dict(SLURM_JOB_ID='777') - if change == 'wrong-job': - environment['SLURM_JOB_ID'] = 'other-job' - elif change == 'wrong-instance': - argv[argv.index('--instance-id')+1] = 'unrelated' - elif change == 'wrong-port': - argv[argv.index('--health-url')+1] = 'http://127.0.0.1:9100/health' - elif change == 'wrong-role': - argv[2] = 'unrelated.application' - elif change == 'wrong-control': - argv[-1] = '/fyp/another-run/control' - monkeypatch.setattr(placement, '_process_record', lambda pid: dict(pid=pid, state='S', start='1', parent=1, group=1)) - monkeypatch.setattr(placement, '_process_command', lambda pid: (argv, environment)) - monkeypatch.setattr(placement.os, 'kill', lambda *args: pytest.fail('unverified process must never be signalled')) - with pytest.raises(RuntimeError): - placement._stop_adopted_on_host(contract, timeout=0) - - -def test_remote_adopted_pid_is_verified_and_stopped_on_target_allocation_node(monkeypatch): - monkeypatch.setattr(placement, 'allocation_nodes', lambda env: ['train', 'rollout']) - monkeypatch.setattr(placement, '_verify_adopted_identity', lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError('not local launcher'))) - monkeypatch.setattr(placement.os, 'kill', lambda *args: pytest.fail('remote PID must never be signalled locally')) - calls = [] - def run(argv, **kwargs): - calls.append(argv) - assert argv[0] == 'srun' - assert argv[argv.index('--nodelist')+1] == 'rollout' - assert kwargs['timeout'] is None - command = shlex.split(argv[-1]) - contract = json.loads(command[command.index('--stop-adopted')+1]) - assert contract['pid'] == 999 and contract['job_id'] == '777' - assert not contract.get('discover_service') - return NS(stdout=json.dumps(dict(instance_id='wanted', port=9000, job_id='777', owned_processes_exited=True))) - monkeypatch.setattr(placement.subprocess, 'run', run) - meta = NS(pid=999, host='rollout', instance_id='wanted', port=9000, gpus=[0, 1]) - receipt = placement.stop_adopted_rollout(meta, - dict(SLURM_JOB_ID='777', SLURMD_NODENAME='train', SLURM_GPUS_ON_NODE='4'), timeout=0) - assert receipt['owned_processes_exited'] and len(calls) == 1 - - -def test_remote_adopted_stop_failure_keeps_child_stderr_visible(monkeypatch, capfd): - monkeypatch.setattr(placement, 'allocation_nodes', lambda env: ['train', 'rollout']) - monkeypatch.setattr(placement, '_verify_adopted_identity', - lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError('not local launcher'))) - child = shlex.join([sys.executable, '-c', - 'import sys; sys.stderr.write("remote adopted stop failed\\n"); sys.exit(1)']) - monkeypatch.setattr(placement, 'slurm_command', lambda *args, **kwargs: child) - meta = NS(pid=999, host='rollout', instance_id='wanted', port=9000, gpus=[0, 1]) - with pytest.raises(subprocess.CalledProcessError) as error: - placement.stop_adopted_rollout(meta, - dict(SLURM_JOB_ID='777', SLURMD_NODENAME='train')) - assert error.value.returncode == 1 - assert 'remote adopted stop failed' in capfd.readouterr().err - - -def test_verified_local_srun_registry_pid_authorizes_unique_remote_service_lookup(monkeypatch): - monkeypatch.setattr(placement, 'allocation_nodes', lambda env: ['train', 'rollout']) - record = dict(pid=111, start='birth', parent=1, state='S', group=1) - monkeypatch.setattr(placement, '_verify_adopted_identity', lambda pid, contract, launcher=False: record) - monkeypatch.setattr(placement, '_still_owned', lambda record: False) - def run(argv, **kwargs): - command = shlex.split(argv[-1]) - contract = json.loads(command[command.index('--stop-adopted')+1]) - assert contract['discover_service'] is True - return NS(stdout=json.dumps(dict(instance_id='wanted', port=9000, job_id='777', owned_processes_exited=True))) - monkeypatch.setattr(placement.subprocess, 'run', run) - meta = NS(pid=111, host='rollout', instance_id='wanted', port=9000, gpus=[0]) - assert placement.stop_adopted_rollout(meta, - dict(SLURM_JOB_ID='777', SLURMD_NODENAME='train', SLURM_GPUS_ON_NODE='4'))['owned_processes_exited'] - - -def test_local_adopted_service_stops_only_verified_tree_and_preserves_other_instance(tmp_path, monkeypatch): - monkeypatch.setenv('SLURM_JOB_ID', '777') - script = tmp_path / 'restartable_vllm_server.py' - script.write_text('import time; time.sleep(60)') - control = str(tmp_path / 'control') - commands = [[sys.executable, str(script), '--instance-id', name, '--health-url', - f'http://127.0.0.1:{port}/health', '--control-dir', control] - for name, port in [('wanted', 9000), ('unrelated', 9100)]] - processes = [subprocess.Popen(command) for command in commands] - try: - time.sleep(.05) - meta = NS(pid=processes[0].pid, host='127.0.0.1', instance_id='wanted', port=9000) - receipt = placement.stop_adopted_rollout(meta, dict(os.environ), timeout=.05, control_dir=control) - assert receipt['owned_processes_exited'] and receipt['pid'] == processes[0].pid - processes[0].wait(timeout=1) - assert processes[1].poll() is None - finally: - for proc in processes: - if proc.poll() is None: - proc.terminate() - proc.wait(timeout=1) - - -def test_remote_adopted_exit_without_matching_owner_receipt_is_rejected(monkeypatch): - monkeypatch.setattr(placement, 'allocation_nodes', lambda env: ['train', 'rollout']) - monkeypatch.setattr(placement, '_verify_adopted_identity', lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError())) - monkeypatch.setattr(placement.subprocess, 'run', lambda *args, **kwargs: NS(stdout=json.dumps( - dict(instance_id='another', port=9000, job_id='777', owned_processes_exited=True)))) - meta = NS(pid=999, host='rollout', instance_id='wanted', port=9000, gpus=[0]) - with pytest.raises(RuntimeError, match='differs from the requested owner'): - placement.stop_adopted_rollout(meta, - dict(SLURM_JOB_ID='777', SLURMD_NODENAME='train', SLURM_GPUS_ON_NODE='4')) - - -def test_owned_session_stops_process_group_members_after_launcher_exits(tmp_path): - child_pid = tmp_path / 'child.pid' - script = ('import pathlib,subprocess,sys; ' - 'p=subprocess.Popen([sys.executable,"-c","import time; time.sleep(60)"]); ' - f'pathlib.Path({str(child_pid)!r}).write_text(str(p.pid))') - proc = subprocess.Popen([sys.executable, '-c', script], start_new_session=True) - proc.wait(timeout=3) - pid = int(child_pid.read_text()) - try: - placement.stop_owned_session(proc, timeout=.05) - record = placement._process_record(pid) - assert record is None or record['state'] == 'Z' - finally: - try: - os.kill(pid, signal.SIGKILL) - except ProcessLookupError: - pass diff --git a/tests/test_rollout_supply.py b/tests/test_rollout_supply.py deleted file mode 100644 index 43d5fb9..0000000 --- a/tests/test_rollout_supply.py +++ /dev/null @@ -1,176 +0,0 @@ -"""Already generated complete-group supply survives all-engine EHP loans.""" -from types import SimpleNamespace - -from RL_Framework.infra.elastic.rollout_supply import ready_complete_samples -from RL_Framework.infra.execution.async_runner import AsyncTaskRunner, TaskResult -from RL_Framework.infra.execution.batch_dispatcher import BatchTaskDispatcher -from RL_Framework.infra.sync.staleness import StalenessManager -from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - - -def bounded_trainer_fixture(): - engine = SimpleNamespace(get_version=lambda: 0, optimizer_revision=0) - manager = StalenessManager(engine, max_concurrent_rollouts=4, - consumer_batch_size=2, max_staleness=1) - manager.configure_groups(2) - dispatcher = BatchTaskDispatcher(AsyncTaskRunner(max_queue_size=4), manager, lambda task: None) - return SimpleNamespace(config=SimpleNamespace(n_samples=2), train_engine=engine, dispatcher=dispatcher) - - -def reserve(trainer, group, ids, *, ready): - dispatcher = trainer.dispatcher - manager = dispatcher.staleness_manager - revision = manager.reserve_group(group, ids) - assert revision is not None - for index, task_id in enumerate(ids[:ready]): - member = dict(grpo_group_id=group, grpo_rollout_index=index, task_id=task_id) - manager.on_member_completed(group, task_id, revision) - dispatcher._pending_results[task_id] = TaskResult(member, task_id, float(task_id), float(task_id)) - - -def test_snapshot_is_non_consuming_and_collector_can_use_the_counted_group(): - trainer = bounded_trainer_fixture() - reserve(trainer, "a", [1, 2], ready=2) - assert ready_complete_samples(trainer) == 2 - assert ready_complete_samples(trainer) == 2 - assert [item["task_id"] for item in trainer.dispatcher.collect_batch(2, 0)] == [1, 2] - - -def test_ready_younger_group_cannot_hide_a_missing_due_member(): - trainer = bounded_trainer_fixture() - reserve(trainer, "old", [1, 2], ready=2) - reserve(trainer, "due", [3, 4], ready=1) - dispatcher = trainer.dispatcher - dispatcher.retire_batch(dispatcher.collect_batch(2, 0), 1) - dispatcher.on_publication(1) - trainer.train_engine.optimizer_revision = 1 - reserve(trainer, "young", [5, 6], ready=2) - assert ready_complete_samples(trainer) == 0 - - -def member(group, index, **kwargs): - return dict(grpo_group_id=group, grpo_rollout_index=index, **kwargs) - - -def legacy_trainer_fixture(paused=False): - runner = AsyncTaskRunner(max_queue_size=32) - if paused: - runner.pause() - dispatcher = BatchTaskDispatcher(runner, SimpleNamespace(), lambda task: None) - trainer = AsyncRLTrainer.__new__(AsyncRLTrainer) - trainer.config = SimpleNamespace(n_samples=4, global_resource_planner=SimpleNamespace( - runtime_batch_collection_timeout_s=.05, runtime_batch_collection_max_retries=0)) - trainer.is_main_process = True - trainer._pending_grpo_groups = {} - trainer.dispatcher = dispatcher - trainer.staleness_manager = SimpleNamespace(on_batch_consumed=lambda count: None) - return trainer - - -def add_result(dispatcher, task_id, data, created=None): - dispatcher._pending_results[task_id] = TaskResult(data, task_id, created or float(task_id), float(task_id)) - dispatcher._active_task_ids.add(task_id) - - -def test_snapshot_is_non_consuming_and_matches_real_wait_order(): - trainer = legacy_trainer_fixture() - dispatcher = trainer.dispatcher - add_result(dispatcher, 10, member("b", 1), created=2) - add_result(dispatcher, 20, member("a", 0), created=1) - original = list(dispatcher._pending_results) - data = dispatcher.peek_ready_data() - assert [item["grpo_group_id"] for item in data] == ["a", "b"] - data.clear() - assert list(dispatcher._pending_results) == original - assert [result.data["grpo_group_id"] for result in dispatcher.wait_results(2)] == ["a", "b"] - - -def test_ready_supply_combines_partial_groups_and_ignores_failed_duplicate_members(): - trainer = legacy_trainer_fixture(paused=True) - trainer._pending_grpo_groups = {"a": [member("a", 0), member("a", 1)], - "incomplete": [member("incomplete", 0)]} - for task_id, value in enumerate([ - member("a", 1), member("a", 2), member("a", 3), - member("b", 0), member("b", 1), member("b", 2), member("b", 3), - member("incomplete", 1), member("incomplete", 2, status="failed"), - member("incomplete", 0), None, - ]): - add_result(trainer.dispatcher, task_id, value) - before = list(trainer.dispatcher._pending_results) - pending_before = {group: list(values) for group, values in trainer._pending_grpo_groups.items()} - assert ready_complete_samples(trainer) == 8 - assert list(trainer.dispatcher._pending_results) == before - assert trainer._pending_grpo_groups == pending_before - - -def test_collector_returns_existing_complete_group_without_dispatcher_call(): - trainer = legacy_trainer_fixture(paused=True) - group = [member("ready", index) for index in range(4)] - trainer._pending_grpo_groups = {"ready": group + [dict(grpo_group_id="ready", task_id=99)]} - trainer.dispatcher = SimpleNamespace() - assert ready_complete_samples(trainer) == 4 - assert trainer._collect_complete_grpo_batch(iter(()), 4) == group - assert trainer._pending_grpo_groups == {} - - -def test_paused_real_dispatcher_consumes_enough_partial_and_ready_data_without_submitting(): - trainer = legacy_trainer_fixture(paused=True) - trainer._pending_grpo_groups = {"a": [member("a", 0), member("a", 1)]} - add_result(trainer.dispatcher, 1, member("a", 2)) - add_result(trainer.dispatcher, 2, member("a", 3)) - add_result(trainer.dispatcher, 3, member("future", 0)) - def never_submit(**kwargs): - raise AssertionError("paused ready data must not submit rollout work") - trainer.dispatcher.active_submit_and_wait = never_submit - batch = trainer._collect_complete_grpo_batch(iter(()), 4) - assert [value["grpo_rollout_index"] for value in batch] == [0, 1, 2, 3] - assert not trainer.dispatcher._pending_inputs - # Reading extra already-ready members preserves them for the next group. - assert trainer._pending_grpo_groups["future"] == [member("future", 0)] - assert ready_complete_samples(trainer) == 0 - - -def test_collector_deduplicates_ready_members_and_requests_only_deficit(): - trainer = legacy_trainer_fixture() - trainer._pending_grpo_groups = {"a": [member("a", 0), member("a", 1), member("a", 2)]} - requested = [] - def missing(**kwargs): - requested.append(kwargs["batch_size"]) - return [member("a", 3)] - trainer.dispatcher.active_submit_and_wait = missing - batch = trainer._collect_complete_grpo_batch(iter(()), 4) - assert requested == [1] - assert len(batch) == 4 - # Retransmissions of a previously consumed group cannot create another batch. - for index in range(4): - add_result(trainer.dispatcher, index, member("a", index)) - assert ready_complete_samples(trainer) == 0 - next_group = [member("b", index) for index in range(4)] - trainer.dispatcher.active_submit_and_wait = lambda **kwargs: next_group - assert trainer._collect_complete_grpo_batch(iter(()), 4) == next_group - - -def test_duplicate_and_invalid_member_indices_do_not_complete_a_group(): - trainer = legacy_trainer_fixture() - trainer._pending_grpo_groups = {"a": [member("a", 0), member("a", 1), member("a", 2), - member("a", 2), member("a", 8)]} - assert ready_complete_samples(trainer) == 0 - - -def test_duplicate_task_identity_with_missing_member_index_is_not_counted_twice(): - trainer = legacy_trainer_fixture() - trainer._pending_grpo_groups = {"a": [member("a", 0, task_id=10), member("a", 1, task_id=11), - member("a", 2, task_id=12)]} - add_result(trainer.dispatcher, 10, dict(grpo_group_id="a", task_id=10)) - assert ready_complete_samples(trainer) == 0 - - -def test_paused_insufficient_supply_never_enqueues_new_rollouts(): - trainer = legacy_trainer_fixture(paused=True) - trainer._pending_grpo_groups = {"a": [member("a", 0), member("a", 1)]} - def cannot_submit(**kwargs): - raise AssertionError("paused dispatcher submitted new work") - trainer.dispatcher.active_submit_and_wait = cannot_submit - assert trainer._collect_complete_grpo_batch(iter(()), 4) == [] - assert not trainer.dispatcher._pending_inputs - assert len(trainer._pending_grpo_groups["a"]) == 2 diff --git a/tests/test_runtime_blue_green_gpu_ownership.py b/tests/test_runtime_blue_green_gpu_ownership.py deleted file mode 100644 index ade141d..0000000 --- a/tests/test_runtime_blue_green_gpu_ownership.py +++ /dev/null @@ -1,192 +0,0 @@ -"""Blue-green restarts must release physical GPU owners before overlapping launches.""" - -from dataclasses import replace -from types import SimpleNamespace as NS - -import pytest - -from RL_Framework.infra.elastic.runtime_executor import ManagedRolloutProcess, RuntimeElasticExecutor - - -def process(name, gpus, port, *, host='node-a', pid=11): - return ManagedRolloutProcess(name, 'unused', pid, list(gpus), port, host, len(gpus)) - - -class Executor(RuntimeElasticExecutor): - def __init__(self, current, desired, *, fail_stop=None): - config = NS(global_resource_planner=NS(runtime_drain_before_reconfigure=True), - heterogeneous_rollout=NS(enabled=True, vllm_base_port=8000, instances=[ - NS(instance_id=meta.instance_id, port=meta.port) for meta in desired])) - super().__init__(config=config, planner=None) - self.desired = desired - self.events = [] - self.fail_stop = fail_stop - self._process_meta = {meta.instance_id: meta for meta in current} - self._processes = {meta.instance_id: object() for meta in current} - - def _desired_rollout_processes(self, plan): - return self.desired - - def _command_for_instance_id(self, instance_id, port): - return f'start {instance_id} {port}' - - def _start_one_rollout_process(self, meta): - self.events.append(('start', meta.instance_id)) - old = self._process_meta.get(meta.instance_id) - if old is not None and not self._same_rollout_process(old, meta): - self._blue_green_old_processes = getattr(self, '_blue_green_old_processes', []) + [ - (old, self._processes.get(meta.instance_id))] - started = replace(meta, pid=100 + len(self.events)) - self._process_meta[meta.instance_id] = started - self._processes[meta.instance_id] = object() - return started - - def _wait_rollout_process_start_ready(self, meta): - self.events.append(('ready', meta.instance_id)) - - def _stop_process_meta(self, meta, proc): - self.events.append(('stop', meta.instance_id)) - if meta.instance_id == self.fail_stop: - raise RuntimeError('old owner did not exit') - return [meta] - - def _reconfigure_rollout_engine(self, plan, *, wait_ready): - self.events.append(('cutover', wait_ready)) - - def _sleep_before_rollout_stop(self): - self.events.append(('grace-before',)) - - def _sleep_after_rollout_stop(self, stopped): - if stopped: - self.events.append(('grace-after', tuple(meta.instance_id for meta in stopped))) - - -def test_merge_releases_both_old_tp1_owners_before_new_tp2_and_preserves_survivor(): - keep = process('keep', [1], 8000) - executor = Executor([keep, process('old-b', [2], 8001), process('old-c', [3], 8002)], - [replace(keep), process('merged', [2, 3], 8001)]) - stopped, started = executor._blue_green_reconfigure_rollout_processes(None) - events = executor.events - assert events.index(('stop', 'old-b')) < events.index(('start', 'merged')) - assert events.index(('stop', 'old-c')) < events.index(('start', 'merged')) - assert events.index(('grace-after', ('old-b', 'old-c'))) < events.index(('start', 'merged')) - assert executor._process_meta['keep'] is keep and ('stop', 'keep') not in events - assert {meta.instance_id for meta in stopped} == {'old-b', 'old-c'} - assert [meta.instance_id for meta in started] == ['merged'] - assert started[0].port == 8003 - - -def test_split_releases_tp2_once_before_either_tp1_starts(): - keep = process('keep', [1], 8000) - executor = Executor([keep, process('merged', [2, 3], 8003)], - [replace(keep), process('new-b', [2], 8001), process('new-c', [3], 8002)]) - stopped, started = executor._blue_green_reconfigure_rollout_processes(None) - assert executor.events.count(('stop', 'merged')) == 1 - for name in ('new-b', 'new-c'): - assert executor.events.index(('stop', 'merged')) < executor.events.index(('start', name)) - assert [meta.instance_id for meta in stopped] == ['merged'] - assert [meta.instance_id for meta in started] == ['new-b', 'new-c'] - assert executor._process_meta['keep'] is keep - - -def test_1911493_tp2_split_keeps_distinct_publication_endpoints_and_survivors(): - from RL_Framework.infra.sync.publication_session import publication_targets - - survivors = [process('grp_tp2_0', [2, 3], 8000, host='node-a'), - process('grp_tp2_1', [0, 1], 8001, host='node-b')] - old = process('grp_tp2_2', [2, 3], 8002, host='node-b') - desired = [*(replace(meta) for meta in survivors), - process('grp_tp1_2', [2], 8002, host='node-b'), - process('grp_tp1_3', [3], 8003, host='node-b')] - executor = Executor([*survivors, old], desired) - executor.config.heterogeneous_rollout.instances = [ - NS(instance_id=meta.instance_id, host=meta.host, tp=meta.tp, port=meta.port) - for meta in desired] - - stopped, started = executor._blue_green_reconfigure_rollout_processes(None) - - targets = publication_targets(executor.config) - assert len(targets) == 4 - assert len({meta.port for meta in started}) == 2 - assert {meta.port for meta in started}.isdisjoint({8000, 8001, 8002}) - assert stopped == [old] - for survivor in survivors: - assert executor._process_meta[survivor.instance_id] is survivor - assert ('stop', survivor.instance_id) not in executor.events - - -@pytest.mark.parametrize('old_host,new_host,overlap', [ - ('node-a', 'node-b', False), ('node-a.cluster', 'node-a', False), - ('127.0.0.1', 'localhost', True), ('10.1.1.1', '10.2.2.2', False), -]) -def test_gpu_ownership_is_scoped_to_physical_host(old_host, new_host, overlap): - executor = Executor([process('old', [2], 8000, host=old_host)], - [process('new', [2], 8001, host=new_host)]) - executor._blue_green_reconfigure_rollout_processes(None) - stop = executor.events.index(('stop', 'old')) - start = executor.events.index(('start', 'new')) - assert (stop < start) is overlap - - -def test_nonoverlapping_gpu_keeps_start_ready_cutover_before_old_stop(): - executor = Executor([process('old', [2], 8000)], [process('new', [3], 8001)]) - executor._blue_green_reconfigure_rollout_processes(None) - events = executor.events - assert events.index(('start', 'new')) < events.index(('ready', 'new')) - assert events.index(('ready', 'new')) < events.index(('cutover', True)) - assert events.index(('cutover', True)) < events.index(('stop', 'old')) - assert all(event[0] != 'grace-after' for event in events) - - -def test_overlapping_stop_failure_preserves_owner_and_prevents_any_launch(): - old = process('old', [2], 8000) - executor = Executor([old], [process('new', [2], 8001)], fail_stop='old') - owned_process = executor._processes['old'] - with pytest.raises(RuntimeError, match='old owner did not exit'): - executor._blue_green_reconfigure_rollout_processes(None) - assert executor._process_meta['old'] is old - assert executor._processes['old'] is owned_process - assert executor.events == [('stop', 'old')] - - -def test_missing_stop_confirmation_prevents_overlapping_launch(): - executor = Executor([process('old', [2], 8000)], [process('new', [2], 8001)]) - executor._stop_rollout_process = lambda _identity: [] - with pytest.raises(RuntimeError, match='confirm.*exit'): - executor._blue_green_reconfigure_rollout_processes(None) - assert executor.events == [] and 'old' in executor._process_meta - - -def test_overlapping_live_pool_requires_configured_drain_before_any_stop_or_start(): - old = process('old', [2], 8000) - executor = Executor([old], [process('new', [2], 8001)]) - executor.config.global_resource_planner.runtime_drain_before_reconfigure = False - with pytest.raises(RuntimeError, match='drain'): - executor._blue_green_reconfigure_rollout_processes(None) - assert executor.events == [] and executor._process_meta['old'] is old - - -def test_new_target_cannot_borrow_unchanged_survivor_gpu(): - healthy = process('healthy', [1], 8000) - executor = Executor([healthy], [replace(healthy), process('new', [1], 8001)]) - with pytest.raises(ValueError, match='unchanged'): - executor._blue_green_reconfigure_rollout_processes(None) - assert executor.events == [] and executor._process_meta['healthy'] is healthy - - -def test_overlapping_desired_layout_rejected_before_stopping_current_owner(): - old = process('old', [2], 8000) - executor = Executor([old], [process('new-a', [2], 8001), process('new-b', [2], 8002)]) - with pytest.raises(ValueError, match='overlap'): - executor._blue_green_reconfigure_rollout_processes(None) - assert executor.events == [] and executor._process_meta['old'] is old - - -def test_same_id_replacement_stops_old_once_and_retains_new_process(): - old = process('same', [2], 8000) - executor = Executor([old], [process('same', [2, 3], 8000)]) - stopped, started = executor._blue_green_reconfigure_rollout_processes(None) - assert executor.events.index(('stop', 'same')) < executor.events.index(('start', 'same')) - assert executor.events.count(('stop', 'same')) == 1 - assert stopped == [old] and executor._process_meta['same'] is started[0] - assert started[0].pid != old.pid and started[0].port == 8001 diff --git a/tests/test_runtime_boundary.py b/tests/test_runtime_boundary.py deleted file mode 100644 index ed3577f..0000000 --- a/tests/test_runtime_boundary.py +++ /dev/null @@ -1,573 +0,0 @@ -"""CPU-only boundary protocol and real trainer/executor control-flow tests.""" - -import copy -from concurrent.futures import Future, ThreadPoolExecutor -from types import SimpleNamespace - -import pytest - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.elastic import runtime_boundary as boundary_module -from RL_Framework.infra.elastic.runtime_boundary import RuntimeBoundaryProtocol, read_record, write_record -from RL_Framework.infra.elastic.runtime_executor import RuntimeElasticExecutor -from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - - -class Clock: - def __init__(self): - self.now = 0.0 - self.sleeps = [] - - def monotonic(self): - return self.now - - def sleep(self, seconds): - self.sleeps.append(seconds) - self.now += seconds - - -class Planner: - warmup_steps = 100 - history_size = 8 - min_history_size = 1 - - def __init__(self): - self.applied = 0 - - def observe_batch(self, batch): - return len(batch) - - def observe_runtime(self, **kwargs): - return SimpleNamespace(to_dict=lambda: {}) - - def apply_plan_to_config(self, plan, config): - self.applied += 1 - - -class Decision: - def __init__(self, reconfigure=False): - self.should_reconfigure = reconfigure - self.reason = "reconfigure" if reconfigure else "same_plan" - self.num_requests = 8 - self.elastic_hybrid_signal = None - self.candidate_plan = SimpleNamespace( - train_config=SimpleNamespace(tp=1, pp=1, dp=2), train_gpus=2, - rollout_tp_list=[2], t_global=1.0, expected_gain_s=1.0, - to_dict=lambda: {"rollout": {"tp_list": [2]}}, - ) - - def to_dict(self): - return {"reason": self.reason} - - -def protocol(path, rank, run_id="test-run", timeout=0.1): - result = RuntimeBoundaryProtocol(path, rank, 2, timeout) - result.run_id = run_id - return result - - -@pytest.fixture -def trainers(tmp_path, monkeypatch): - monkeypatch.setenv("RANK", "0") - monkeypatch.setenv("WORLD_SIZE", "2") - monkeypatch.delenv("RL_TRAIN_PHASE_TRACE", raising=False) - config = AsyncRLConfig( - model_path="/unused", train_gpus=2, rollout_gpus=2, n_total_gpus=4, - train_tp_size=1, train_dp_size=2, batch_size=2, n_samples=1, micro_batch_size=1, - log_dir=str(tmp_path), - ) - cfg = config.global_resource_planner - cfg.enabled = True - cfg.runtime_drain_timeout_s = 2.0 - cfg.runtime_length_profile_enabled = False - cfg.runtime_coordinate_batch_source_only = False - leader = AsyncRLTrainer(config) - peer = AsyncRLTrainer(copy.deepcopy(config)) - peer.rank = 1 - peer.is_main_process = False - directory = leader._runtime_reconfiguration_coord_dir() - for trainer in (leader, peer): - trainer._runtime_boundary_protocol = protocol(directory, trainer.rank, timeout=2.0) - trainer._runtime_length_profile_path = lambda: "" - trainer._rebind_rollout_engine_from_config = lambda **kwargs: None - trainer.applied_states = [] - trainer._apply_runtime_reconfiguration_state = trainer.applied_states.append - leader.global_resource_planner = Planner() - executor = RuntimeElasticExecutor(config=config, planner=leader.global_resource_planner) - executor.runtime_run_id = "test-run" - leader.runtime_elastic_executor = executor - return leader, peer, executor - - -def complete(leader, decision, step=0): - future = Future() - future.set_result(decision) - leader._grp_future = future - leader._grp_future_step = step - return future - - -def test_pre_noop_does_not_consume_completed_future(trainers, monkeypatch): - leader, peer, _ = trainers - future = complete(leader, Decision(True)) - clock = Clock() - monkeypatch.setattr(boundary_module, "time", clock) - leader._runtime_reconfiguration_boundary(0, "pre") - peer._runtime_reconfiguration_boundary(0, "pre") - assert leader._grp_future is future - assert not clock.sleeps - - -@pytest.mark.parametrize("mode", ["no_planner", "warmup", "dynamic_disabled", "completed_noop"]) -def test_post_noop_without_request_polling(trainers, monkeypatch, mode): - leader, peer, executor = trainers - clock = Clock() - monkeypatch.setattr(boundary_module, "time", clock) - if mode == "no_planner": - leader.global_resource_planner = None - elif mode == "dynamic_disabled": - leader.config.global_resource_planner.runtime_dynamic_reconfiguration_enabled = False - complete(leader, Decision(True)) - elif mode == "completed_noop": - complete(leader, Decision()) - leader._run_global_resource_planner_at_boundary(0, [], {}) - peer._runtime_reconfiguration_boundary(0, "post") - assert peer._runtime_boundary_protocol.wait(0, "post")["decision"] == "no_reconfig" - assert not clock.sleeps - assert not (executor._coordination_dir() / "request.json").exists() - - -def test_post_is_explicitly_closed_when_planner_path_raises(trainers, monkeypatch): - leader, peer, _ = trainers - - def fail(*args, **kwargs): - raise RuntimeError("planner path failed") - - monkeypatch.setattr(leader, "_run_global_resource_planner", fail) - with pytest.raises(RuntimeError, match="planner path failed"): - leader._run_global_resource_planner_at_boundary(0, [], {}) - assert peer._runtime_reconfiguration_boundary(0, "post") is None - assert peer._runtime_boundary_protocol.wait(0, "post")["decision"] == "no_reconfig" - - -def test_async_future_survives_boundaries_and_is_consumed_once(trainers, monkeypatch): - leader, peer, _ = trainers - future = Future() - leader._grp_future = future - leader._grp_future_step = 0 - calls = [] - original = leader._apply_global_resource_planner_decision - def apply(step, decision, stats): - calls.append(step) - return original(step, decision, stats) - monkeypatch.setattr(leader, "_apply_global_resource_planner_decision", apply) - clock = Clock() - monkeypatch.setattr(boundary_module, "time", clock) - for step in range(4): - leader._runtime_reconfiguration_boundary(step, "pre") - peer._runtime_reconfiguration_boundary(step, "pre") - leader._run_global_resource_planner_at_boundary(step, [], {}) - peer._runtime_reconfiguration_boundary(step, "post") - assert leader._grp_future is future - assert not future.cancelled() - future.set_result(Decision()) - leader._run_global_resource_planner_at_boundary(4, [], {}) - peer._runtime_reconfiguration_boundary(4, "post") - leader._run_global_resource_planner_at_boundary(5, [], {}) - assert leader._grp_future is None - assert calls == [4] - assert not clock.sleeps - - -def test_ready_maintenance_consumes_current_estimate_before_one_transaction(trainers, monkeypatch): - leader, _, executor = trainers - complete(leader, Decision(True), step=0) - leader.global_resource_planner._history = [] - leader.global_resource_planner._build_current_plan = lambda *args: Decision().candidate_plan - monkeypatch.setattr(executor, "has_pending_boundary_work", lambda: True) - applied = [] - monkeypatch.setattr(leader, "_apply_global_resource_planner_decision", - lambda step, decision, stats: applied.append((step, decision.reason))) - leader._run_global_resource_planner_at_boundary(3, [], {}) - assert leader._grp_future is None - assert applied == [(3, "reconfigure")] - - -@pytest.mark.parametrize('collective_publication', [True, False]) -def test_approved_full_grp_plan_reaches_post_with_elastic_planning_disabled( - trainers, monkeypatch, collective_publication, -): - from RL_Framework.infra.cost_model.global_resource_planner import CoreRuntimeCapabilities, GlobalResourcePlanner - - leader, peer, executor = trainers - config = leader.config - config.global_resource_planner.runtime_drain_before_reconfigure = False - config.global_resource_planner.runtime_forced_rollout_tp_list = [2] - planner = GlobalResourcePlanner.from_config(config) - planner.runtime_capabilities = CoreRuntimeCapabilities(world_size=2, tp=1, ep=1, pp=1, dp=2, cp=1) - planner.warmup_steps = 0 - planner.min_history_size = 1 - executor.planner = leader.global_resource_planner = planner - decision = planner.plan_if_needed(step=0, config=config, batch=[dict(input_len=128, output_len=64)]) - assert decision.resource_should_reconfigure - assert decision.candidate_plan.rollout_tp_list == [2] - complete(leader, decision) - rebinds = [] - monkeypatch.setattr(leader, '_rebind_rollout_engine_from_config', lambda *, reason: rebinds.append(reason)) - if collective_publication: - executor.trainer = leader - peer.dispatcher = SimpleNamespace(pause=lambda: pytest.fail('collective publication drained generation')) - - def publish_current(): - request = read_record(executor._coordination_dir() / 'request.json') - ready = read_record(executor._coordination_dir() / 'ready/rank_1.json') - assert ready['coord_id'] == request['coord_id'] - leader._rebind_rollout_engine_from_config(reason='core_boundary_publication') - - monkeypatch.setattr(executor, '_publish_current_rollout_weights', publish_current) - - stats = {} - with ThreadPoolExecutor(max_workers=1) as pool: - following = pool.submit(peer._runtime_reconfiguration_boundary, 0, 'post') - leader._run_global_resource_planner_at_boundary(0, [], stats) - following.result(timeout=3) - - boundary = peer._runtime_boundary_protocol.wait(0, 'post') - assert boundary['decision'] == 'reconfig' - assert boundary['drain_required'] is collective_publication - assert stats['global_resource_planner']['resource_should_reconfigure'] is True - assert stats['global_resource_planner_runtime']['applied'] - assert config.heterogeneous_rollout.tp_list == [2] - assert rebinds == ['core_boundary_publication' if collective_publication else 'after_runtime_reconfiguration'] - - -@pytest.mark.parametrize('attached, core_count, publish_rollout, should_execute', [ - (True, 2, True, False), (False, 2, True, True), (True, 1, True, True), (True, 2, False, True), -]) -def test_full_grp_without_rank_coordination_requires_a_local_publication( - trainers, monkeypatch, attached, core_count, publish_rollout, should_execute, -): - leader, _, executor = trainers - leader.config.global_resource_planner.runtime_coordinate_reconfiguration_ranks = False - leader.config.global_resource_planner.apply_to_runtime = publish_rollout - leader.config.train_gpus = core_count - executor.train_engine = SimpleNamespace(world_size=core_count, train_dp_size=core_count) - if attached: - executor.trainer = leader - decision = Decision(True) - decision.candidate_plan.train_gpus = core_count - decision.candidate_plan.train_config.dp = core_count - decision.elastic_hybrid_signal = {'desired_replicas': 0} - - prepared = executor.prepare_transaction(decision) - - assert prepared.should_execute is should_execute - if not should_execute: - assert prepared.reason == 'runtime_candidate_rejected:collective_publication_requires_rank_coordination' - assert not prepared.coord_id and not prepared.drain_required - monkeypatch.setattr(executor, '_publish_current_rollout_weights', - lambda: pytest.fail('ineligible topology dispatched a collective')) - monkeypatch.setattr(executor, '_release_all_hybrid_workers', - lambda **kwargs: pytest.fail('ineligible topology changed current membership')) - assert not executor.execute_prepared(prepared).applied - assert executor.planner.applied == 0 - assert not (executor._coordination_dir() / 'core_command.json').exists() - - -def test_last_post_leaves_ready_join_and_old_decision_for_cleanup(trainers, monkeypatch): - leader, peer, executor = trainers - leader.config.total_steps = 1 - future = complete(leader, Decision(True)) - monkeypatch.setattr(executor, "has_pending_boundary_work", lambda: True) - monkeypatch.setattr(leader, "_apply_global_resource_planner_decision", - lambda *args: pytest.fail("last POST started a resource transaction")) - leader._run_global_resource_planner_at_boundary(0, [], {}) - peer._runtime_reconfiguration_boundary(0, "post") - assert peer._runtime_boundary_protocol.wait(0, "post")["decision"] == "no_reconfig" - assert leader._grp_future is future - assert not (executor._coordination_dir() / "request.json").exists() - - -def test_draining_request_precedes_decision_and_ready(trainers, monkeypatch): - leader, peer, executor = trainers - complete(leader, Decision(True)) - root = executor._coordination_dir() - seen = [] - original = leader._runtime_boundary_protocol.publish - def publish(step, point, **kwargs): - request = read_record(root / "request.json") - assert request["coord_id"] == kwargs["coord_id"] - assert not (root / "ready/rank_1.json").exists() - seen.append(request["coord_id"]) - return original(step, point, **kwargs) - monkeypatch.setattr(leader._runtime_boundary_protocol, "publish", publish) - original_reconcile = executor._reconcile_pending_hybrid_joins - - def reconcile(result=None): - if seen: - ready = read_record(root / "ready/rank_1.json") - assert ready.get("coord_id") == seen[0] - return original_reconcile(result) - - monkeypatch.setattr(executor, "_reconcile_pending_hybrid_joins", reconcile) - with ThreadPoolExecutor(max_workers=1) as pool: - following = pool.submit(peer._runtime_reconfiguration_boundary, 0, "post") - leader._run_global_resource_planner_at_boundary(0, [], {}) - following.result(timeout=3) - assert len(seen) == 1 - for name in ["request.json", "ready/rank_1.json", "applied.json"]: - state = read_record(root / name) - assert state["coord_id"] == seen[0] - assert state["run_id"] == "test-run" - assert peer.applied_states[0]["coord_id"] == seen[0] - assert executor.planner.applied == 1 - - -def test_nondraining_decision_precedes_reset_and_follow_does_not_wait(trainers): - leader, peer, executor = trainers - leader.config.global_resource_planner.runtime_drain_before_reconfigure = False - leader.config.global_resource_planner.runtime_cluster_swap_enabled = True - # Exercise the real trainer pre-reset path without cluster/GPU operations. - executor._cluster_swap_enabled = lambda strategy: False - root = executor._coordination_dir() - events = [] - class Dispatcher: - def pause(self): - decision = peer._runtime_boundary_protocol.wait(0, "post") - assert decision["decision"] == "reconfig" - assert decision["drain_required"] is False - assert not (root / "applied.json").exists() - peer._runtime_reconfiguration_boundary(0, "post") - events.append("peer_returned_before_pause") - def wait_until_idle(self, **kwargs): - events.append("drain_local") - def reset_after_reconfigure(self): - events.append("reset") - def resume(self): - events.append("resume") - leader.dispatcher = Dispatcher() - complete(leader, Decision(True)) - leader._run_global_resource_planner_at_boundary(0, [], {}) - assert events[0] == "peer_returned_before_pause" - assert not (root / "request.json").exists() - assert not (root / "ready").exists() - assert not peer.applied_states - decision = peer._runtime_boundary_protocol.wait(0, "post") - peer._follow_applied_runtime_reconfiguration_if_available(root) - assert peer.applied_states[0]["coord_id"] == decision["coord_id"] - - -def test_nondraining_transactions_have_fresh_ids(trainers): - leader, peer, executor = trainers - leader.config.global_resource_planner.runtime_drain_before_reconfigure = False - ids = [] - for step in range(2): - complete(leader, Decision(True), step) - leader._run_global_resource_planner_at_boundary(step, [], {}) - peer._runtime_reconfiguration_boundary(step, "post") - ids.append(peer._runtime_boundary_protocol.wait(step, "post")["coord_id"]) - assert ids[0] != ids[1] - assert read_record(executor._coordination_dir() / "applied.json")["coord_id"] == ids[1] - - -def test_follower_arrives_before_decision(tmp_path, monkeypatch): - leader = protocol(tmp_path, 0) - peer = protocol(tmp_path, 1) - clock = Clock() - def sleep(seconds): - clock.now += seconds - leader.publish(0, "post") - clock.sleep = sleep - monkeypatch.setattr(boundary_module, "time", clock) - assert peer.wait(0, "post")["decision"] == "no_reconfig" - assert clock.now == 0.05 - - -@pytest.mark.parametrize("stale", ["step", "run", "point", "missing"]) -def test_stale_or_missing_decision_is_protocol_timeout(tmp_path, monkeypatch, stale): - peer = protocol(tmp_path, 1) - value = {"run_id": "test-run", "step": 1, "point": "post", "decision": "no_reconfig"} - if stale != "missing": - value[{"step": "step", "run": "run_id", "point": "point"}[stale]] = { - "step": 0, "run": "old-run", "point": "pre", - }[stale] - write_record(peer.decision_path(1, "post"), value) - clock = Clock() - monkeypatch.setattr(boundary_module, "time", clock) - with pytest.raises(TimeoutError, match="boundary decision missing"): - peer.wait(1, "post") - assert clock.now < 1 - - -def test_closed_boundary_cannot_be_rewritten(tmp_path): - leader = protocol(tmp_path, 0) - leader.publish(0, "post") - with pytest.raises(RuntimeError, match="already closed"): - leader.publish(0, "post", coord_id="late", drain_required=True) - - -def test_session_reuse_rejects_old_membership(tmp_path): - def join_run(): - peers = [RuntimeBoundaryProtocol(tmp_path, rank, 8, 3) for rank in range(8)] - with ThreadPoolExecutor(max_workers=8) as pool: - # Followers may encounter the previous run's announcement first. - tasks = [pool.submit(peer.join) for peer in reversed(peers)] - for task in tasks: - task.result(timeout=4) - ids = {peer.run_id for peer in peers} - assert len(ids) == 1 - return ids.pop() - assert join_run() != join_run() - - -def test_stale_session_without_live_leader_cannot_join(tmp_path, monkeypatch): - write_record(tmp_path / "session/leader.json", {"run_id": "old", "world_size": 2}) - write_record(tmp_path / "session/old/members.json", {"0": "old0", "1": "old1"}) - clock = Clock() - monkeypatch.setattr(boundary_module, "time", clock) - with pytest.raises(TimeoutError, match="session handshake"): - RuntimeBoundaryProtocol(tmp_path, 1, 2, 0.1).join() - - -def test_request_publication_failure_propagates_without_ready_wait(trainers, monkeypatch): - leader, _, executor = trainers - complete(leader, Decision(True)) - def fail(*args, **kwargs): - raise OSError("boundary publication failed") - monkeypatch.setattr(leader._runtime_boundary_protocol, "publish", fail) - with pytest.raises(OSError, match="boundary publication failed"): - leader._run_global_resource_planner_at_boundary(0, [], {}) - assert read_record(executor._coordination_dir() / "aborted.json")["coord_id"] == executor._active_runtime_coord_id - assert not (executor._coordination_dir() / "ready/rank_1.json").exists() - - -def test_cluster_swap_coordinates_peers_once(trainers, monkeypatch): - _, _, executor = trainers - cfg = executor.config.global_resource_planner - cfg.runtime_cluster_swap_enabled = True - cfg.runtime_manage_rollout_processes = True - calls = [] - executor.dispatcher = SimpleNamespace(pause=lambda: None, resume=lambda: None) - monkeypatch.setattr(executor, "_adopt_existing_rollout_processes", lambda: None) - monkeypatch.setattr(executor, "_runtime_plan_already_applied", lambda *a, **k: False) - monkeypatch.setattr(executor, "_cluster_swap_rollout_training_pools", lambda *a: None) - monkeypatch.setattr(executor, "_reconfigure_rollout_processes", lambda *a, **k: ([], [])) - original = executor._coordinate_peer_rank_drain - def coordinate(*args, **kwargs): - calls.append(executor._current_coordination_id(Decision(True).candidate_plan)) - return original(*args, **kwargs) - def acknowledge(coord_id): - root = executor._coordination_dir() - assert read_record(root / "request.json")["coord_id"] == coord_id - import os - write_record(root / "ready/rank_1.json", { - "coord_id": coord_id, "run_id": "test-run", - "job_id": os.environ.get("SLURM_JOB_ID", os.environ.get("JOB_ID", "")), - }) - monkeypatch.setattr(executor, "_coordinate_peer_rank_drain", coordinate) - result = executor.execute(Decision(True), request_published=acknowledge) - assert len(calls) == 1 - assert result.actions.count("peer_reconfig_request") == 1 - - -def test_old_applied_state_is_not_consumed_by_new_run(trainers): - _, peer, executor = trainers - root = executor._coordination_dir() - write_record(root / "applied.json", {"run_id": "old-run", "coord_id": "old", "instances": []}) - peer._follow_applied_runtime_reconfiguration_if_available(root) - assert not peer.applied_states - - -def test_draining_abort_matches_the_announced_transaction(trainers, monkeypatch): - leader, peer, executor = trainers - complete(leader, Decision(True)) - executor.rollout_engine = SimpleNamespace(reconfigure_from_plan=lambda *a: None) - def fail(*args, **kwargs): - raise RuntimeError("simulated rollout reconfiguration failure") - monkeypatch.setattr(executor, "_reconfigure_rollout_engine", fail) - with ThreadPoolExecutor(max_workers=1) as pool: - following = pool.submit(peer._runtime_reconfiguration_boundary, 0, "post") - with pytest.raises(RuntimeError, match="simulated rollout"): - leader._run_global_resource_planner_at_boundary(0, [], {}) - with pytest.raises(RuntimeError, match="aborted on rank0"): - following.result(timeout=3) - boundary = peer._runtime_boundary_protocol.wait(0, "post") - aborted = read_record(executor._coordination_dir() / "aborted.json") - assert aborted["coord_id"] == boundary["coord_id"] - assert aborted["run_id"] == boundary["run_id"] - - -def test_old_terminal_states_do_not_complete_current_request(trainers, monkeypatch): - _, peer, executor = trainers - root = executor._coordination_dir() - import os - current = {"run_id": "test-run", "coord_id": "current", - "job_id": os.environ.get("SLURM_JOB_ID", os.environ.get("JOB_ID", ""))} - write_record(root / "request.json", current) - write_record(root / "applied.json", {**current, "coord_id": "older"}) - write_record(root / "aborted.json", {**current, "coord_id": "older", "error": "old error"}) - clock = Clock() - from RL_Framework.trainer import async_rl_trainer as trainer_module - # Fake both clocks used by the existing follower, without affecting other modules. - clock.time = clock.monotonic - monkeypatch.setattr(trainer_module, "time", clock) - peer.config.global_resource_planner.runtime_drain_timeout_s = 0.1 - with pytest.raises(TimeoutError, match="to apply"): - peer._follow_runtime_reconfiguration_if_requested(expected_coord_id="current") - assert not peer.applied_states - - -def test_background_and_boundary_do_not_apply_same_request_twice(trainers): - leader, peer, executor = trainers - complete(leader, Decision(True)) - with ThreadPoolExecutor(max_workers=2) as pool: - # The request callback also lets the background poller see the request. - original = leader._publish_runtime_boundary_transaction - background = [] - def publish(coord_id, drain_required): - original(coord_id, drain_required) - background.append(pool.submit(peer._follow_runtime_reconfiguration_if_requested)) - leader._publish_runtime_boundary_transaction = publish - following = pool.submit(peer._runtime_reconfiguration_boundary, 0, "post") - leader._run_global_resource_planner_at_boundary(0, [], {}) - following.result(timeout=3) - for task in background: - task.result(timeout=3) - assert len(peer.applied_states) == 1 - # A later non-draining transaction must not re-enter the old drain request. - leader.config.global_resource_planner.runtime_drain_before_reconfigure = False - peer.config.global_resource_planner.runtime_drain_before_reconfigure = False - leader._publish_runtime_boundary_transaction = original - complete(leader, Decision(True), 1) - leader._run_global_resource_planner_at_boundary(1, [], {}) - peer._runtime_reconfiguration_boundary(1, "post") - peer._follow_runtime_reconfiguration_if_requested() - assert len(peer.applied_states) == 2 - - -def test_request_mismatch_is_protocol_error(trainers): - leader, peer, executor = trainers - leader._runtime_boundary_protocol.publish(0, "post", coord_id="expected", drain_required=True) - write_record(executor._coordination_dir() / "request.json", { - "run_id": "test-run", "coord_id": "wrong", - }) - with pytest.raises(RuntimeError, match="mismatched drain request"): - peer._runtime_reconfiguration_boundary(0, "post") - - -def test_late_future_reconfigures_only_at_later_post(trainers): - leader, peer, executor = trainers - leader.config.global_resource_planner.runtime_drain_before_reconfigure = False - future = Future() - leader._grp_future = future - leader._grp_future_step = 0 - leader._run_global_resource_planner_at_boundary(0, [], {}) - future.set_result(Decision(True)) - leader._runtime_reconfiguration_boundary(1, "pre") - assert leader._grp_future is future - leader._run_global_resource_planner_at_boundary(1, [], {}) - assert peer._runtime_boundary_protocol.wait(0, "post")["decision"] == "no_reconfig" - assert peer._runtime_boundary_protocol.wait(1, "pre")["decision"] == "no_reconfig" - assert peer._runtime_boundary_protocol.wait(1, "post")["decision"] == "reconfig" - assert leader._grp_future is None - assert executor.planner.applied == 1 diff --git a/tests/test_runtime_core_capabilities.py b/tests/test_runtime_core_capabilities.py deleted file mode 100644 index efe4493..0000000 --- a/tests/test_runtime_core_capabilities.py +++ /dev/null @@ -1,217 +0,0 @@ -"""Live Core ranks constrain executable GRP layouts while EHP stays elastic.""" -from types import SimpleNamespace as NS -from unittest.mock import Mock - -import pytest - -from RL_Framework.config import AsyncRLConfig, HeterogeneousInstanceConfig -from RL_Framework.infra.cost_model.global_resource_planner import ( - CoreRuntimeCapabilities, ElasticHybridSignal, GlobalResourcePlan, - GlobalResourcePlanner, PlannerDecision, RuntimeResourceMetrics, -) -from RL_Framework.infra.cost_model.model import RolloutClusterConfig, TrainParallelConfig -from RL_Framework.infra.cost_model.optimizer import OptimizationResult -from RL_Framework.infra.cost_model.preflight_planner import PreflightPlanner -from RL_Framework.infra.elastic.runtime_executor import RuntimeElasticExecutor - - -ROWS = [dict(input_len=1024, output_len=2048)] * 16 - - -def config(): - result = AsyncRLConfig(model_path='not-loaded') - result.n_total_gpus, result.train_gpus, result.rollout_gpus = 12, 4, 8 - result.train_tp_size, result.train_dp_size = 4, 1 - result.batch_size, result.micro_batch_size, result.n_samples = 16, 1, 4 - result.heterogeneous_rollout.enabled = True - result.heterogeneous_rollout.instances = [HeterogeneousInstanceConfig( - instance_id=f'rollout-{index}', tp=2, gpus=[index % 2 * 2, index % 2 * 2 + 1], - host=f'rollout-{index // 2}', port=8000 + index) for index in range(4)] - planner = result.global_resource_planner - planner.enabled = True - planner.initial_allocation_strategy = 'grp' - planner.allowed_train_tp, planner.allowed_train_pp = [1, 2, 4], [1] - planner.allowed_train_ep, planner.allowed_rollout_tp = [1], [1, 2, 4] - planner.micro_batch_sizes = [1] - planner.allocation_granularity_gpus = 4 - planner.min_train_gpus = planner.min_rollout_gpus = 4 - planner.elastic_hybrid_planning_enabled = True - planner.runtime_reconfigure_training = True - planner.runtime_training_pool_only = True - planner.runtime_training_pool_plan_only = False - planner.runtime_manage_rollout_processes = planner.hybrid_worker_launch_enabled = True - planner.elastic_hybrid_require_planner_signal = True - planner.elastic_hybrid_min_rollout_gpus = 4 - planner.reconfiguration_cost_s = planner.min_gain_ratio = 0 - planner.warmup_steps = 0 - planner.min_history_size = planner.plan_interval = 1 - return result - - -def engine(world=4, tp=4): - return NS(world_size=world, train_tp_size=tp, train_pp_size=1, - train_cp_size=1, train_ep_size=1, train_dp_size=world // tp, - get_parallel_state=lambda: dict(train_tp=tp, train_pp=1, train_cp=1, - train_ep=1, train_dp=world // tp), - reconfigure_parallelism=Mock()) - - -def result(train_gpus=8, tp=4): - return OptimizationResult(train_config=TrainParallelConfig(tp=tp, pp=1, - dp=train_gpus // tp, b_micro=1), - rollout_config=RolloutClusterConfig(tp_list=[4] if train_gpus == 8 else [2, 2, 2, 2]), - t_train=.1, t_rollout=.1, t_global=.1) - - -def as_plan(value): - return GlobalResourcePlan(train_config=value.train_config, rollout_config=value.rollout_config, - t_train=value.t_train, t_rollout=value.t_rollout, t_global=value.t_global, - n_total_gpus=12, max_concurrent_rollouts=16) - - -def test_grp_replans_with_fixed_core_when_first_layout_requires_unlaunchable_ranks(): - cfg = config() - cfg.global_resource_planner.elastic_hybrid_planning_enabled = False - planner = GlobalResourcePlanner.from_config(cfg) - planner.runtime_capabilities = CoreRuntimeCapabilities.from_engine(engine()) - planner.optimizer.optimize = Mock(side_effect=[result(8), result(4)]) - metrics = RuntimeResourceMetrics(step=5, train_time_s=1, rollout_time_s=10) - decision = planner.plan_if_needed(step=5, config=cfg, batch=ROWS, runtime_metrics=metrics) - assert decision.candidate_plan.train_gpus == 4 - assert decision.candidate_plan.train_config.tp == 4 - assert decision.candidate_plan.train_config.dp == 1 - assert decision.candidate_plan.rollout_gpus == 8 - assert decision.elastic_hybrid_signal is None - assert not decision.resource_should_reconfigure - first, second = planner.optimizer.optimize.call_args_list - assert first.kwargs['fixed_train_gpus'] == 0 - assert second.kwargs['fixed_train_gpus'] == 4 - assert second.kwargs['allowed_train_tp'] == [4] - assert second.kwargs['allowed_train_ep'] == second.kwargs['allowed_train_pp'] == [1] - assert cfg.global_resource_planner.fixed_train_gpus == 0 # No configuration workaround. - proof = decision.candidate_plan.metadata['runtime_candidate_filter'] - assert proof['reason'] == 'physical_core_rank_set_changed' - assert proof['unconstrained_candidate']['train']['n_gpus'] == 8 - assert proof['elastic_demand_preserved'] - - -def test_forced_grp_resize_cannot_invent_core_ranks(monkeypatch): - cfg = config() - cfg.global_resource_planner.elastic_hybrid_planning_enabled = False - planner = GlobalResourcePlanner.from_config(cfg) - planner.runtime_capabilities = CoreRuntimeCapabilities.from_engine(engine()) - monkeypatch.setenv('GRP_FORCE_TRAIN_GPUS', '8') - monkeypatch.setenv('GRP_FORCE_ROLLOUT_TP_LIST', '4') - decision = planner.plan_if_needed(step=5, config=cfg, batch=ROWS, - runtime_metrics=RuntimeResourceMetrics(step=5, train_time_s=1, rollout_time_s=10)) - assert decision.candidate_plan.train_gpus == 4 - assert not decision.resource_should_reconfigure - assert not decision.should_reconfigure - assert decision.elastic_hybrid_signal is None - - -@pytest.mark.parametrize('initial_gpus', [4, 8]) -def test_startup_grp_retains_freedom_to_choose_the_initial_physical_world(initial_gpus): - planner = PreflightPlanner(config()) - assert planner.planner.runtime_capabilities is None - planner.planner.optimizer.optimize = Mock(return_value=result(initial_gpus)) - selected = planner.run(ROWS) - assert selected.applied and selected.planned_config.train_gpus == initial_gpus - assert selected.planned_config.rollout_gpus == 12 - initial_gpus - assert planner.planner.optimizer.optimize.call_args.kwargs['fixed_train_gpus'] == 0 - - -@pytest.mark.parametrize('axis', ['pp', 'cp', 'ep']) -def test_live_core_rebuild_rejects_unsupported_model_axes(axis): - candidate = as_plan(result(4)) - setattr(candidate.train_config, axis, 2) - candidate.train_config.dp = 1 - candidate.train_config.tp = 2 - capability = CoreRuntimeCapabilities.from_engine(engine()) - assert capability.incompatibility(candidate) == f'core_{axis}_rebuild_unsupported' - - -def test_fixed_core_keeps_rollout_repartition_executable(): - cfg = config() - cfg.global_resource_planner.elastic_hybrid_planning_enabled = False - planner = GlobalResourcePlanner.from_config(cfg) - planner.runtime_capabilities = CoreRuntimeCapabilities.from_engine(engine()) - candidate = result(4) - candidate.rollout_config = RolloutClusterConfig(tp_list=[4, 4]) - planner.optimizer.optimize = Mock(return_value=candidate) - decision = planner.plan_if_needed(step=5, config=cfg, batch=ROWS) - assert decision.resource_should_reconfigure - assert decision.candidate_plan.train_gpus == 4 - assert decision.candidate_plan.train_config.tp == 4 - assert decision.candidate_plan.train_config.dp == 1 - assert decision.candidate_plan.rollout_tp_list == [4, 4] - assert planner.optimizer.optimize.call_count == 1 - executor = RuntimeElasticExecutor(config=cfg, planner=planner, train_engine=engine()) - prepared = executor.prepare_transaction(decision) - assert prepared.should_execute and prepared.resource_reconfiguration - - -def test_fixed_core_rejects_tp_dp_change_even_if_adapter_exposes_old_rebuild_hook(): - capability = CoreRuntimeCapabilities.from_engine(engine()) - assert not capability.rebuild_tp_dp - assert capability.incompatibility(as_plan(result(4, tp=2))) == "core_tp_dp_rebuild_unsupported" - - -def test_executor_rejects_stale_resize_before_any_generation_or_core_side_effect(): - cfg, backend = config(), engine() - dispatcher = NS(pause=Mock(), wait_until_idle=Mock(), resume=Mock()) - planner = GlobalResourcePlanner.from_config(cfg) - executor = RuntimeElasticExecutor(config=cfg, planner=planner, train_engine=backend, dispatcher=dispatcher) - executor._adopt_existing_rollout_processes = Mock() - decision = PlannerDecision(step=5, should_reconfigure=True, reason='stale_async_plan', - candidate_plan=as_plan(result(8)), resource_should_reconfigure=True) - prepared = executor.prepare_transaction(decision) - assert not prepared.should_execute and not prepared.drain_required - assert prepared.reason == 'runtime_candidate_rejected:physical_core_rank_set_changed' - assert prepared.coord_id == '' - executor._adopt_existing_rollout_processes.assert_not_called() - dispatcher.pause.assert_not_called() - dispatcher.wait_until_idle.assert_not_called() - backend.reconfigure_parallelism.assert_not_called() - - -def test_executor_preserves_valid_ehp_signal_from_a_stale_unlaunchable_core_candidate(): - cfg = config() - current = as_plan(result(4)) - signal = ElasticHybridSignal(step=5, desired_workers=1, current_workers=0, - max_workers=1, action='join', reason='training_bottleneck', - train_rollout_ratio=2, rollout_pressure=0, ttl_steps=20, replica_size_gpus=4) - decision = PlannerDecision(step=5, should_reconfigure=True, reason='reconfigure', - current_plan=current, candidate_plan=as_plan(result(8)), - elastic_hybrid_signal=signal, resource_should_reconfigure=True) - executor = RuntimeElasticExecutor(config=cfg, planner=GlobalResourcePlanner.from_config(cfg), train_engine=engine()) - prepared = executor.prepare_transaction(decision) - assert prepared.should_execute and not prepared.resource_reconfiguration - assert prepared.candidate_plan is current - assert prepared.effective_planner_signal is signal - - -def test_training_backend_without_rebuild_keeps_its_actual_tp_dp(): - backend = engine() - backend.reconfigure_parallelism = None - capability = CoreRuntimeCapabilities.from_engine(backend) - assert capability.incompatibility(as_plan(result(4))) == '' - assert capability.incompatibility(as_plan(result(4, tp=2))) == 'core_tp_dp_rebuild_unsupported' - - -def test_native_trainer_installs_live_capabilities_without_a_config_freeze(): - from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - trainer = object.__new__(AsyncRLTrainer) - trainer.config = config() - planner = trainer.config.global_resource_planner - planner.runtime_coordinate_reconfiguration_ranks = False - planner.runtime_async_planning = False - trainer.is_main_process = True - trainer.train_engine = engine() - trainer.rollout_engine = trainer.dispatcher = None - trainer._runtime_boundary_protocol = trainer._elastic_gradient_server = None - trainer._elastic_membership_run_id = '' - trainer._is_rollout_source = lambda: True - trainer._init_global_resource_planner() - assert trainer.global_resource_planner.runtime_capabilities.world_size == 4 - assert trainer.config.global_resource_planner.fixed_train_gpus == 0 diff --git a/tests/test_runtime_executor_shutdown.py b/tests/test_runtime_executor_shutdown.py deleted file mode 100644 index 3bc6ca5..0000000 --- a/tests/test_runtime_executor_shutdown.py +++ /dev/null @@ -1,476 +0,0 @@ -"""Deterministic CPU tests; no actual worker, subprocess, GPU or network.""" - -import json -import threading -from concurrent.futures import CancelledError, ThreadPoolExecutor, TimeoutError as FutureTimeout -from types import SimpleNamespace - -import pytest - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.elastic.hybrid_pool import ElasticHybridPool, JoinCancelledError -from RL_Framework.infra.elastic.runtime_executor import RuntimeElasticExecutor, RuntimeReconfigurationResult -from RL_Framework.infra.elastic import runtime_executor as runtime_module - - -class FakeProcess: - def __init__(self, pid): - self.pid = pid - self.returncode = None - self.terminations = 0 - self.kills = 0 - self.fail_stop = False - - def poll(self): - return self.returncode - - def terminate(self): - if self.fail_stop: - raise OSError("simulated stop failure") - self.terminations += 1 - self.returncode = -15 - - def kill(self): - self.kills += 1 - self.returncode = -9 - - def wait(self, timeout=None): - return self.returncode - - -@pytest.fixture -def harness(tmp_path, monkeypatch): - instances = [] - processes = [] - - def popen(*args, **kwargs): - proc = FakeProcess(100 + len(processes)) - processes.append(proc) - return proc - - monkeypatch.setattr(runtime_module.subprocess, "Popen", popen) - - def make(workers=3, background=3): - cfg = AsyncRLConfig( - model_path="/unused", train_gpus=1, rollout_gpus=workers, - n_total_gpus=workers + 1, train_tp_size=1, train_dp_size=1, - batch_size=1, n_samples=1, micro_batch_size=1, log_dir=str(tmp_path), - ) - cfg.global_resource_planner.hybrid_worker_task_dir = str(tmp_path) - pool = ElasticHybridPool( - core_train_workers=["dp0"], - core_rollout_workers=[f"rollout{i}" for i in range(workers)], - zero_sync_steps=0, max_background_workers=background, - ) - executor = RuntimeElasticExecutor(config=cfg, planner=SimpleNamespace(), elastic_pool=pool) - monkeypatch.setattr(executor, "_build_hybrid_worker_command", lambda **kw: "fake worker") - monkeypatch.setattr(executor, "_cluster_swap_training_slot", lambda wid: {"host": "fake-host", "gpus": [0]}) - # Most tests isolate launch ordering. A separate test keeps the real poll. - # Launch-order tests simulate a real installation and core-boundary ACK; - # dedicated readiness tests exercise actual files/identity/TP coverage. - receipt = {"acknowledged": True, "optimizer_revision": 0, "state_version": 0, - "snapshot_id": "simulated-state"} - manifest = tmp_path / "capture.json" - manifest.write_text(json.dumps({"format": "libra-ehp-lanes-v1", "optimizer_revision": 0, - "snapshot_id": "simulated-state", "lanes": {"dp0": {"0": "ehp://fake/lane0"}}})) - monkeypatch.setattr(executor, "_snapshot_path_for_version", lambda version: str(manifest)) - monkeypatch.setattr(executor, "_capture_core_snapshot", lambda: str(manifest)) - monkeypatch.setattr(executor, "_wait_hybrid_worker_ready", lambda wid, **kw: dict(receipt)) - monkeypatch.setattr(executor, "_queue_activation", lambda replica, ack: ack) - from RL_Framework.infra.elastic import rollout_lending - def acknowledge_stop(executor, wid, request_id=None): - # The controller consumes a launch only after matching its owner. - # Runtime must leave it present until that controller operation. - launch = tmp_path / f".launch_{wid}.json" - stop = json.loads((tmp_path / f".stop_{wid}.json").read_text()) - if launch.exists(): - record = json.loads(launch.read_text()) - assert record.get("launch_owner", "") == stop["launch_owner"] - assert record.get("generation", 0) == stop["generation"] - launch.unlink() - return {"worker_id": wid, "request_id": request_id, "exited": True} - monkeypatch.setattr(rollout_lending, "wait_hybrid_stopped", acknowledge_stop) - h = SimpleNamespace(executor=executor, pool=pool, processes=processes, popen=popen, path=tmp_path) - instances.append(h) - return h - - yield make - for h in instances: - for proc in processes: - proc.fail_stop = False - h.executor.close() - - -def join(h, *, replica=False, worker="rollout0", callback=None): - callback = callback or h.executor._activate_hybrid_worker - if replica: - return h.pool.join_replica("replica_" + worker, [worker], "dp0", activation_barrier=callback) - return h.pool.join_training(worker, "dp0", activation_barrier=callback) - - -def assert_cancelled(handle): - with pytest.raises((JoinCancelledError, CancelledError)): - handle.result(timeout=3) - - -@pytest.mark.parametrize("replica", [False, True], ids=["singleton", "replica"]) -@pytest.mark.parametrize("remote", [False, True], ids=["local", "remote"]) -def test_s1_close_fences_callback_paused_before_popen(harness, monkeypatch, replica, remote): - h = harness() - h.executor.config.global_resource_planner.hybrid_worker_remote_control_enabled = remote - entered, resume = threading.Event(), threading.Event() - - def prepare(**kwargs): - entered.set() - assert resume.wait(3) - return "fake worker" - - monkeypatch.setattr(h.executor, "_build_hybrid_worker_command", prepare) - handle = join(h, replica=replica) - try: - assert entered.wait(3) - h.executor.close() - count_at_close = len(h.processes) - pool_at_close = h.pool.snapshot() - finally: - resume.set() - assert_cancelled(handle) - assert h.pool.snapshot() == pool_at_close - assert count_at_close == len(h.processes) == 0 - assert h.executor._hybrid_worker_processes == {} - assert h.executor._hybrid_worker_meta == {} - assert not list(h.path.glob(".launch_*.json")) - - -def test_s2_registered_process_stopped_before_close_returns(harness): - h = harness() - join(h).result(timeout=3) - proc = h.processes[0] - h.executor.close() - assert proc.poll() == -15 - assert proc.terminations == 1 - assert h.executor._hybrid_worker_processes == {} - assert h.executor._hybrid_worker_meta == {} - - -def test_s3_popen_to_registration_is_atomic_with_close(harness, monkeypatch): - h = harness() - created, resume, closing = threading.Event(), threading.Event(), threading.Event() - - def popen(*args, **kwargs): - proc = h.popen(*args, **kwargs) - created.set() - assert resume.wait(3) - return proc - - monkeypatch.setattr(runtime_module.subprocess, "Popen", popen) - handle = join(h) - - def close(): - closing.set() - h.executor.close() - - with ThreadPoolExecutor(max_workers=1) as runner: - try: - assert created.wait(3) - finished = runner.submit(close) - assert closing.wait(3) - with pytest.raises(FutureTimeout): - finished.result(timeout=0.05) - finally: - resume.set() - finished.result(timeout=3) - try: - handle.result(timeout=3) - except JoinCancelledError: - pass # Either final activation or close may acquire the pool lock first. - assert len(h.processes) == 1 - assert h.processes[0].poll() is not None - assert h.executor._hybrid_worker_processes == {} - - -def test_s4_close_cancels_queued_join(harness): - h = harness(background=1) - entered, resume = threading.Event(), threading.Event() - - def snapshot(*args): - entered.set() - assert resume.wait(3) - return 0 - - h.pool.snapshot_fetcher = snapshot - first = join(h) - try: - assert entered.wait(3) - queued = join(h, worker="rollout1") - h.executor.close() - assert queued.future.cancelled() - finally: - resume.set() - assert_cancelled(first) - assert_cancelled(queued) - assert not h.processes - - -def test_s5_mixed_activations_all_reach_safe_terminal_state(harness): - h = harness(background=1) - join(h).result(timeout=3) - entered, resume = threading.Event(), threading.Event() - - def paused(*args): - entered.set() - assert resume.wait(3) - h.executor._activate_hybrid_worker(*args) - - running = join(h, worker="rollout1", callback=paused) - try: - assert entered.wait(3) - queued = join(h, worker="rollout2") - h.executor.close() - finally: - resume.set() - assert_cancelled(running) - assert_cancelled(queued) - assert len(h.processes) == 1 - assert h.processes[0].poll() is not None - assert not h.executor._hybrid_worker_processes - - -def test_s6_close_is_idempotent_including_services(harness): - h = harness() - join(h).result(timeout=3) - calls = [] - h.executor.gradient_server = SimpleNamespace(close=lambda: calls.append("closed")) - h.executor.close() - h.executor.close() - assert calls == ["closed"] - assert h.processes[0].terminations == 1 - - -def test_s7_new_joins_rejected_after_close(harness): - h = harness() - h.executor.close() - with pytest.raises(RuntimeError, match="closed"): - join(h) - with pytest.raises(RuntimeError, match="closed"): - join(h, replica=True) - with pytest.raises(JoinCancelledError, match="closing"): - h.executor._ensure_elastic_pool() - with pytest.raises(JoinCancelledError, match="closing"): - h.executor._ensure_gradient_server() - - -@pytest.mark.parametrize("replica", [False, True], ids=["singleton", "replica"]) -def test_s8_cancelled_generation_cannot_launch_after_rejoin(harness, monkeypatch, replica): - h = harness() - entered, resume = threading.Event(), threading.Event() - - def prepare(**kwargs): - entered.set() - assert resume.wait(3) - return "fake worker" - - monkeypatch.setattr(h.executor, "_build_hybrid_worker_command", prepare) - old = join(h, replica=replica) - try: - assert entered.wait(3) - old.cancel() - newer = join(h, replica=replica, callback=lambda *args: {"acknowledged": True, "state_version": 0, "optimizer_revision": 0}) - newer.result(timeout=3) - finally: - resume.set() - assert_cancelled(old) - assert not h.processes - assert not h.executor._hybrid_worker_processes - - -def test_s9_remote_start_is_fenced_and_committed_start_gets_stop(harness): - h = harness() - h.executor.config.global_resource_planner.hybrid_worker_remote_control_enabled = True - args = dict(worker_id="rollout0", target_core_id="dp0", snapshot_path="/fake", command="fake", slot={"host": "fake-host", "gpus": [0]}) - h.executor._request_remote_hybrid_worker(**args) - assert (h.path / ".launch_rollout0.json").exists() - h.executor.close() - assert not (h.path / ".launch_rollout0.json").exists() - assert json.loads((h.path / ".stop_rollout0.json").read_text())["worker_id"] == "rollout0" - with pytest.raises(JoinCancelledError): - h.executor._request_remote_hybrid_worker(**args) - assert not (h.path / ".launch_rollout0.json").exists() - assert not h.executor._hybrid_worker_meta - - -def test_s10_callback_failure_during_close_cannot_skip_other_workers(harness): - h = harness() - join(h).result(timeout=3) - entered, resume = threading.Event(), threading.Event() - - def fail(*args): - entered.set() - assert resume.wait(3) - raise ValueError("callback failed") - - handle = join(h, worker="rollout1", callback=fail) - try: - assert entered.wait(3) - h.executor.close() - state = h.pool.snapshot() - finally: - resume.set() - with pytest.raises(ValueError, match="callback failed"): - handle.result(timeout=3) - assert state == h.pool.snapshot() - assert h.processes[0].poll() is not None - assert not h.executor._hybrid_worker_processes - - -def test_readiness_poll_is_cancelled_without_waiting_for_timeout(harness, monkeypatch): - h = harness() - entered = threading.Event() - h.executor.config.global_resource_planner.hybrid_worker_ready_timeout_s = 3600 - - def wait(worker, **kwargs): - entered.set() - return RuntimeElasticExecutor._wait_hybrid_worker_ready(h.executor, worker, **kwargs) - - monkeypatch.setattr(h.executor, "_wait_hybrid_worker_ready", wait) - handle = join(h) - assert entered.wait(3) - h.executor.close() - assert_cancelled(handle) - assert h.processes[0].poll() is not None - - -def test_replica_launch_callback_and_alias_cleanup(harness, monkeypatch): - h = harness() - h.executor.config.global_resource_planner.hybrid_worker_launch_enabled = True - monkeypatch.setattr(h.executor, "_desired_hybrid_workers", lambda *args: 1) - monkeypatch.setattr(h.executor, "_training_reconfiguration_targets", lambda *args: (["dp0"], "dp0", ["rollout0"])) - h.executor._reconfigure_training_pool(1, SimpleNamespace(train_gpus=2), RuntimeReconfigurationResult(False, "test")) - handle = next(iter(h.executor._pending_hybrid_joins.values())) - handle.result(timeout=3) - assert len(h.executor._hybrid_worker_processes) == 2 - h.executor.close() - assert h.processes[0].terminations == 1 - assert not h.executor._hybrid_worker_processes - assert not h.executor._hybrid_worker_meta - - -def test_replica_group_callback_preparation_can_finish_after_close(harness, monkeypatch): - h = harness() - h.executor.config.global_resource_planner.hybrid_worker_launch_enabled = True - entered, resume = threading.Event(), threading.Event() - - def prepare(**kwargs): - entered.set() - assert resume.wait(3) - return "fake worker" - - monkeypatch.setattr(h.executor, "_build_hybrid_worker_command", prepare) - monkeypatch.setattr(h.executor, "_desired_hybrid_workers", lambda *args: 1) - monkeypatch.setattr(h.executor, "_training_reconfiguration_targets", lambda *args: (["dp0"], "dp0", ["rollout0"])) - h.executor._reconfigure_training_pool(1, SimpleNamespace(train_gpus=2), RuntimeReconfigurationResult(False, "test")) - handle = next(iter(h.executor._pending_hybrid_joins.values())) - try: - assert entered.wait(3) - h.executor.close() - finally: - resume.set() - assert_cancelled(handle) - assert not h.processes - assert not h.executor._pending_hybrid_joins - assert not h.executor._hybrid_worker_processes - - -def test_remote_stop_publication_failure_is_not_silent(harness, monkeypatch): - h = harness() - h.executor.config.global_resource_planner.hybrid_worker_remote_control_enabled = True - h.executor._request_remote_hybrid_worker(worker_id="rollout0", target_core_id="dp0", snapshot_path="/fake", command="fake", slot={"host": "fake-host"}) - write = h.executor._write_json_atomic - - def fail(*args): - raise OSError("stop publication failed") - - monkeypatch.setattr(h.executor, "_write_json_atomic", fail) - with pytest.raises(RuntimeError, match="stop publication failed"): - h.executor.close() - assert "rollout0" in h.executor._hybrid_worker_meta - monkeypatch.setattr(h.executor, "_write_json_atomic", write) - h.executor.close() - assert not h.executor._hybrid_worker_meta - - -def test_close_failure_keeps_ownership_and_cleans_other_workers(harness): - h = harness() - join(h).result(timeout=3) - join(h, worker="rollout1").result(timeout=3) - h.processes[0].fail_stop = True - with pytest.raises(RuntimeError, match="shutdown cleanup failed"): - h.executor.close() - assert h.executor._closing.is_set() - assert not h.executor._closed - assert h.processes[1].poll() is not None - assert "rollout0" in h.executor._hybrid_worker_processes - count = len(h.processes) - with pytest.raises(JoinCancelledError, match="closing"): - h.executor._launch_prewarmed_hybrid_worker( - worker_id="rollout2", target_core_id="dp0", command="fake", snapshot_path="/fake", - ) - assert len(h.processes) == count - h.processes[0].fail_stop = False - h.executor.close() - assert h.executor._closed - assert not h.executor._hybrid_worker_processes - - -def test_prewarm_and_legacy_launch_are_fenced(harness): - h = harness() - handle = join(h, callback=lambda *args: {"acknowledged": True, "state_version": 0, "optimizer_revision": 0}) - handle.result(timeout=3) - h.executor.close() - with pytest.raises(JoinCancelledError): - h.executor._launch_prewarmed_hybrid_worker(worker_id="rollout0", target_core_id="dp0", command="fake", snapshot_path="/fake") - assert h.executor._launch_hybrid_worker_after_join(handle) is None - assert not h.processes - - -def test_restart_committed_before_close_is_also_reaped(harness, monkeypatch): - h = harness() - h.executor._launch_prewarmed_hybrid_worker( - worker_id="rollout0", target_core_id="dp0", command="fake", snapshot_path="/old", - ) - entered, resume = threading.Event(), threading.Event() - - def wait(worker, **kwargs): - entered.set() - assert resume.wait(3) - return {"acknowledged": True, "state_version": 0, "optimizer_revision": 0} - - monkeypatch.setattr(h.executor, "_wait_hybrid_worker_ready", wait) - handle = join(h) - try: - assert entered.wait(3) - assert len(h.processes) == 2 - h.executor.close() - finally: - resume.set() - assert_cancelled(handle) - assert all(proc.poll() is not None for proc in h.processes) - assert not h.executor._hybrid_worker_processes - - -def test_legacy_completed_join_generation_is_checked_at_launch(harness): - h = harness() - old = join(h, callback=lambda *args: {"acknowledged": True, "state_version": 0, "optimizer_revision": 0}) - old.result(timeout=3) - old.cancel() - join(h, callback=lambda *args: {"acknowledged": True, "state_version": 0, "optimizer_revision": 0}).result(timeout=3) - assert h.executor._launch_hybrid_worker_after_join(old) is None - assert not h.processes - - -def test_close_from_activation_does_not_join_its_own_thread(harness): - h = harness() - handle = join(h, callback=lambda *args: h.executor.close()) - assert_cancelled(handle) - assert h.executor._closed - assert not h.processes diff --git a/tests/test_runtime_failed_snapshot_cleanup.py b/tests/test_runtime_failed_snapshot_cleanup.py deleted file mode 100644 index d4256bf..0000000 --- a/tests/test_runtime_failed_snapshot_cleanup.py +++ /dev/null @@ -1,248 +0,0 @@ -"""Snapshot ownership survives join failure until a common Core boundary.""" -from concurrent.futures import Future -from types import SimpleNamespace as NS - -import pytest -import torch - -from RL_Framework.config import AsyncRLConfig -from RL_Framework.infra.elastic.core_reconfiguration import execute_core_command -from RL_Framework.infra.elastic.runtime_executor import RuntimeElasticExecutor -from RL_Framework.infra.elastic.state_transfer import LiveStateServer - - -class SnapshotEngine: - rank = 0 - world_size = 1 - optimizer_revision = 1 - - def __init__(self): - self.server = LiveStateServer(host='127.0.0.1', advertised_host='127.0.0.1') - self.urls, self.released = {}, [] - - def capture_elastic_state_snapshot(self, *args): - revision = self.optimizer_revision - if revision not in self.urls: - self.urls[revision] = self.server.publish({'model': torch.zeros(32)}) - return revision - - def get_elastic_state_snapshot_path(self, revision): - return self.urls[revision] - - def get_elastic_lane_state(self): - return dict(data_parallel_rank=0, tensor_parallel_rank=0, - context_parallel_rank=0, pipeline_parallel_rank=0) - - def release_elastic_state_snapshot(self, revision): - uri = self.urls.pop(revision, None) - if uri: - self.server.release(uri) - self.released.append(revision) - - -@pytest.fixture -def runtime(tmp_path): - config = AsyncRLConfig(model_path='/not-loaded', train_gpus=1, rollout_gpus=1, - n_total_gpus=2, train_tp_size=1, train_dp_size=1, log_dir=str(tmp_path)) - engine = SnapshotEngine() - executor = RuntimeElasticExecutor(config=config, planner=NS(), train_engine=engine) - executor._active_runtime_coord_id = 'snapshot-test' - yield executor, engine - engine.server.close() - - -def failed_join(): - future = Future() - future.set_exception(TimeoutError('initial installation failed')) - return NS(member_worker_ids=('rollout0',), done=future.done, result=future.result) - - -def boundary(executor, monkeypatch, *, execute=True): - prepared = NS(coord_id='common-boundary', should_execute=execute, candidate_plan=None, - decision=None, result=NS(applied=True), effective_planner_signal=None) - monkeypatch.setattr(executor, 'accept_planner_signal', lambda *args, **kwargs: None) - return executor.execute_prepared(prepared) - - -def fail_snapshot(executor): - path = executor._capture_core_snapshot() - executor._pending_hybrid_joins['replica'] = failed_join() - executor._reconcile_pending_hybrid_joins() - return path - - -def test_failed_join_releases_only_at_next_common_boundary(runtime, monkeypatch): - executor, engine = runtime - path = fail_snapshot(executor) - assert engine.released == [] # metrics/background reconciliation is not collective - boundary(executor, monkeypatch) - assert engine.released == [1] - assert not executor._snapshot_manifests - assert not engine.server._snapshots - from pathlib import Path - assert not Path(path).exists() - - -@pytest.mark.parametrize('busy', ['join', 'activation', 'cancelled_loader', 'stop']) -def test_release_waits_for_every_consumer(runtime, monkeypatch, busy): - executor, engine = runtime - fail_snapshot(executor) - if busy == 'join': - executor._pending_hybrid_joins['other'] = NS(done=lambda: False) - elif busy == 'activation': - executor._pending_activations['other'] = {} - elif busy == 'cancelled_loader': - executor._retired_hybrid_joins.append(NS(done=lambda: False)) - else: - executor._snapshot_stop_pending.add('rollout0') - monkeypatch.setattr(executor, '_stop_hybrid_worker_process', - lambda *args: (_ for _ in ()).throw(RuntimeError('exit not acknowledged'))) - if busy == 'stop': - with pytest.raises(RuntimeError, match='exit not acknowledged'): - boundary(executor, monkeypatch) - else: - boundary(executor, monkeypatch) - assert engine.released == [] - assert executor._snapshot_manifests - - -def test_no_transaction_cannot_issue_release(runtime, monkeypatch): - executor, engine = runtime - fail_snapshot(executor) - boundary(executor, monkeypatch, execute=False) - assert engine.released == [] - - -def test_collective_release_failure_retains_manifest_for_retry(runtime, monkeypatch): - executor, engine = runtime - path = fail_snapshot(executor) - import RL_Framework.infra.elastic.core_reconfiguration as commands - original = commands.dispatch_core_command - monkeypatch.setattr(commands, 'dispatch_core_command', - lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError('rank1 receipt missing'))) - with pytest.raises(RuntimeError, match='rank1 receipt missing'): - boundary(executor, monkeypatch) - assert executor._snapshot_manifests == {1: path} - monkeypatch.setattr(commands, 'dispatch_core_command', original) - boundary(executor, monkeypatch) - assert not executor._snapshot_manifests - - -def test_repeated_failed_revisions_do_not_accumulate(runtime, monkeypatch): - executor, engine = runtime - for revision in (1, 2, 3): - engine.optimizer_revision = revision - fail_snapshot(executor) - boundary(executor, monkeypatch) - assert not engine.server._snapshots - assert engine.released == [1, 2, 3] - - -def test_every_core_rank_releases_before_boundary_returns(runtime, monkeypatch): - import threading - from RL_Framework.infra.elastic.runtime_boundary import read_record - executor, engine = runtime - fail_snapshot(executor) - peer = SnapshotEngine() - peer.rank = 1 - peer.capture_elastic_state_snapshot() - engine.world_size = 2 - errors = [] - finished = threading.Event() - - def follow(): - try: - while not finished.wait(.005): - command = read_record(executor._coordination_dir() / 'core_command.json') - if command.get('operation') == 'release': - execute_core_command(peer, command, executor._coordination_dir()) - return - except Exception as exc: - errors.append(exc) - - thread = threading.Thread(target=follow) - thread.start() - try: - boundary(executor, monkeypatch) - assert not errors - assert engine.released == peer.released == [1] - assert not executor._snapshot_manifests - finally: - finished.set() - thread.join(timeout=2) - peer.server.close() - - -def test_pending_cleanup_requests_membership_boundary_without_planner_resize(runtime): - executor, _engine = runtime - fail_snapshot(executor) - assert executor.has_pending_boundary_work() - current = NS() - decision = NS(should_reconfigure=False, current_plan=current, candidate_plan=None, - resource_should_reconfigure=False, reason='hold', elastic_hybrid_signal=None) - prepared = executor.prepare_transaction(decision) - assert prepared.should_execute - assert not prepared.resource_reconfiguration - assert prepared.candidate_plan is current - assert prepared.coord_id - - -def test_cancelled_loader_remains_owned_until_future_finishes(runtime, monkeypatch): - import threading - executor, engine = runtime - executor._capture_core_snapshot() - future = Future() - cancelled = [] - handle = NS(member_worker_ids=('rollout0',), done=future.done, - cancel=lambda: cancelled.append(True)) - executor._pending_hybrid_joins['replica'] = handle - event = threading.Event() - request = {'event': event} - executor._pending_activations['replica'] = request - executor._release_all_hybrid_workers(reason='pressure') - assert cancelled and event.is_set() and request['error'] - assert not executor._pending_hybrid_joins - boundary(executor, monkeypatch) - assert not engine.released - future.set_exception(RuntimeError('cancelled generation')) - boundary(executor, monkeypatch) - assert engine.released == [1] - - -def test_partial_cancel_stop_failure_tracks_all_removed_loaders(runtime, monkeypatch): - executor, engine = runtime - executor._capture_core_snapshot() - futures = [Future(), Future()] - cancelled = [] - for index, future in enumerate(futures): - handle = NS(member_worker_ids=(f'rollout{index}',), done=future.done, - cancel=lambda index=index: cancelled.append(index)) - executor._pending_hybrid_joins[str(index)] = handle - monkeypatch.setattr(executor, '_stop_hybrid_worker_process', - lambda *args: (_ for _ in ()).throw(RuntimeError('stop failed'))) - with pytest.raises(RuntimeError, match='stop failed'): - executor._release_all_hybrid_workers(reason='pressure') - assert cancelled == [0, 1] - assert len(executor._retired_hybrid_joins) == 2 - assert not engine.released - assert executor._snapshot_stop_pending == {'rollout0', 'rollout1'} - - -def test_cold_loader_does_not_request_repeated_cleanup_boundaries(runtime): - executor, _engine = runtime - executor._capture_core_snapshot() - future = Future() - executor._pending_hybrid_joins['replica'] = NS(done=future.done) - assert not executor.has_pending_boundary_work() - future.set_exception(TimeoutError('cold load failed')) - assert executor.has_pending_boundary_work() - - -def test_cancelled_fetch_requests_cleanup_only_after_it_stops(runtime): - executor, _engine = runtime - executor._capture_core_snapshot() - future = Future() - executor._retired_hybrid_joins.append(NS(done=future.done)) - assert not executor.has_pending_boundary_work() - future.set_result(None) - assert executor.has_pending_boundary_work() diff --git a/tests/test_runtime_length_profile.py b/tests/test_runtime_length_profile.py deleted file mode 100644 index 7175d42..0000000 --- a/tests/test_runtime_length_profile.py +++ /dev/null @@ -1,42 +0,0 @@ -import json - -from RL_Framework.infra.observability.history_collector import HistoryDataCollector - - -def test_history_collector_writes_runtime_length_profile(tmp_path): - profile_path = tmp_path / "runtime_length_profile.jsonl" - collector = HistoryDataCollector( - output_dir=str(tmp_path / "history"), - flush_interval=10, - length_profile_path=str(profile_path), - ) - collector.initialize() - - collector.record_step( - step=3, - sequence_records=[ - { - "input_len": 11, - "output_len": 22, - "prompt_id": "case-1", - } - ], - ) - collector.finalize() - - rows = [ - json.loads(line) - for line in profile_path.read_text(encoding="utf-8").splitlines() - if line.strip() - ] - - assert rows == [ - { - "step": 3, - "timestamp": rows[0]["timestamp"], - "input_len": 11, - "output_len": 22, - "profile_source": "runtime_online", - "prompt_id": "case-1", - } - ] diff --git a/tests/test_runtime_repartition_eligibility.py b/tests/test_runtime_repartition_eligibility.py deleted file mode 100644 index fce5c70..0000000 --- a/tests/test_runtime_repartition_eligibility.py +++ /dev/null @@ -1,64 +0,0 @@ -"""Candidate TP layouts are checked before mutating runtime ownership.""" - -from copy import deepcopy - -import pytest - -from RL_Framework.config import AsyncRLConfig, HeterogeneousInstanceConfig -from RL_Framework.infra.cost_model.global_resource_planner import ( - GlobalResourcePlan, - GlobalResourcePlanner, - PlannerDecision, -) -from RL_Framework.infra.cost_model.model import RolloutClusterConfig, TrainParallelConfig -from RL_Framework.infra.elastic.runtime_executor import RuntimeElasticExecutor - - -@pytest.mark.parametrize('initial,target,should_execute', [ - ([1, 1, 1], [1, 2], True), - ([1, 2], [1, 1, 1], True), - ([1, 1, 1], [1, 1, 1], False), - ([1, 2], [1, 2], False), -]) -def test_prepare_recognizes_candidate_layout_without_changing_live_resources( - monkeypatch, initial, target, should_execute): - config = AsyncRLConfig(model_path='/not-loaded', train_gpus=1, rollout_gpus=3, - train_tp_size=1, train_dp_size=1, n_total_gpus=4) - config.global_resource_planner.runtime_manage_rollout_processes = True - config.heterogeneous_rollout.instances = [ - HeterogeneousInstanceConfig(instance_id=f'seed{index}', host='shared', - tp=1, gpus=[index + 1], port=8000 + index) for index in range(3) - ] - planner = GlobalResourcePlanner.from_config(config) - - def plan(degrees): - return GlobalResourcePlan(train_config=TrainParallelConfig(tp=1, dp=1, b_micro=1), - rollout_config=RolloutClusterConfig(tp_list=degrees), - t_train=1., t_rollout=1., t_global=1., n_total_gpus=4, - max_concurrent_rollouts=config.max_concurrent_rollouts) - - planner.apply_plan_to_config(plan(initial), config) - decision = PlannerDecision(step=2, should_reconfigure=True, reason='test_repartition', - current_plan=plan(initial), candidate_plan=plan(target), resource_should_reconfigure=True) - executor = RuntimeElasticExecutor(config=config, planner=planner) - executor._process_meta = {meta.instance_id: meta - for meta in executor._desired_rollout_processes(decision.current_plan)} - before_config = deepcopy(config.to_dict()) - before_owners = deepcopy(executor._process_meta) - - def forbidden(*args, **kwargs): - pytest.fail('Eligibility must not launch, stop, wait for or reconfigure a process') - - for name in ('_start_one_rollout_process', '_stop_rollout_process', - '_reconfigure_rollout_engine', '_wait_rollout_process_start_ready'): - monkeypatch.setattr(executor, name, forbidden) - prepared = executor.prepare_transaction(decision) - - assert prepared.should_execute is should_execute - assert prepared.resource_reconfiguration is True - assert prepared.candidate_plan is decision.candidate_plan - assert prepared.result.applied is False and not prepared.result.actions - assert config.to_dict() == before_config - assert executor._process_meta == before_owners and not executor._processes - if not should_execute: - assert prepared.reason == 'runtime_plan_already_applied' diff --git a/tests/test_runtime_rollout_ownership.py b/tests/test_runtime_rollout_ownership.py deleted file mode 100644 index cddcc23..0000000 --- a/tests/test_runtime_rollout_ownership.py +++ /dev/null @@ -1,59 +0,0 @@ -"""Executor never lends a rollout GPU before its owned process has exited.""" -from types import SimpleNamespace as NS - -import pytest - -from RL_Framework.infra.elastic import rollout_process -from RL_Framework.infra.elastic.runtime_executor import ManagedRolloutProcess, RuntimeElasticExecutor - - -def executor(tmp_path): - value = object.__new__(RuntimeElasticExecutor) - value.config = NS(rollout_weight_sync_control_dir=str(tmp_path), - global_resource_planner=NS(vllm_stop_timeout_s=2., vllm_stop_command_template='')) - value._processes, value._process_meta = {}, {} - value._rollout_launch_env = lambda meta: {'SLURM_JOB_ID': '123'} - return value - - -def test_start_uses_node_placement_and_stop_retains_ownership_on_failure(tmp_path, monkeypatch): - value = executor(tmp_path) - meta = ManagedRolloutProcess('rollout', 'service-command', 0, [2, 3], 8000, host='node2', tp=2) - proc = NS(pid=7) - launches = [] - monkeypatch.setattr(rollout_process, 'launch_rollout_process', - lambda meta, env, **kw: launches.append((meta.host, env, kw)) or proc) - started = value._start_one_rollout_process(meta) - assert launches[0][0] == 'node2' and launches[0][2]['control_dir'] == str(tmp_path) - - def fail(*args, **kwargs): - raise TimeoutError('service has not exited') - monkeypatch.setattr(rollout_process, 'stop_rollout_process', fail) - with pytest.raises(TimeoutError): - value._stop_rollout_process('rollout') - assert value._processes['rollout'] is proc and value._process_meta['rollout'] is started - monkeypatch.setattr(rollout_process, 'stop_rollout_process', lambda *args, **kwargs: None) - assert value._stop_rollout_process('rollout') == [started] - assert value._process_meta == value._processes == {} - assert value._stop_rollout_process('rollout') == [] - - -def test_adopted_stop_passes_remote_identity_without_local_signal(tmp_path, monkeypatch): - value = executor(tmp_path) - meta = ManagedRolloutProcess('initial', 'service', 321, [0, 1], 8001, - host='node2', tp=2, adopted=True) - value._process_meta['initial'] = meta - stopped = [] - monkeypatch.setattr(rollout_process, 'stop_adopted_rollout', - lambda meta, **kw: stopped.append((meta, kw))) - assert value._stop_rollout_process('initial') == [meta] - assert stopped[0][0].host == 'node2' and stopped[0][1]['env']['SLURM_JOB_ID'] == '123' - - -def test_unknown_process_cannot_be_reported_stopped(tmp_path): - value = executor(tmp_path) - meta = ManagedRolloutProcess('unknown', 'service', -1, [0, 1], 8000, adopted=True) - value._process_meta['unknown'] = meta - with pytest.raises(RuntimeError, match='No process ownership'): - value._stop_rollout_process('unknown') - assert value._process_meta['unknown'] is meta diff --git a/tests/test_startup_profile.py b/tests/test_startup_profile.py deleted file mode 100644 index ccfdce8..0000000 --- a/tests/test_startup_profile.py +++ /dev/null @@ -1,147 +0,0 @@ -from RL_Framework.infra.cost_model.startup_profile import ( - build_length_profile, - load_length_profile_records, - load_profile_summary, - profile_jsonl_has_records, - profile_metadata_matches, - profile_summary_matches, - sample_indices, - startup_profile_metadata, - summarize_length_profile, - write_profile_summary, -) -from RL_Framework.workflow.r2e_gym_profile import build_r2e_gym_length_profile - - -class _Tokenizer: - pad_token = "" - eos_token = "" - - def encode(self, text, add_special_tokens=False): - del add_special_tokens - return [ord(char) for char in text or ""] - - def decode(self, tokens, skip_special_tokens=True): - del skip_special_tokens - return "".join(chr(token) for token in tokens) - - def apply_chat_template(self, messages, **kwargs): - del kwargs - return "\n".join(f"{msg['role']}:{msg['content']}" for msg in messages) - - -def test_spread_sampling_covers_dataset_extremes(): - assert sample_indices(10, 4, strategy="spread") == [0, 3, 6, 9] - - -def test_build_length_profile_repeats_real_sample_records(): - rows = [ - {"prompt_id": "p0", "prompt": "aaa", "target_issue": "bb"}, - {"prompt_id": "p1", "prompt": "aaaaa", "target_issue": "bbbb"}, - {"prompt_id": "p2", "prompt": "aaaaaaa", "target_issue": "bbbbbb"}, - ] - - records = build_length_profile( - rows, - prompt_length_fn=lambda row: len(row["prompt"]), - output_length_fn=lambda row: len(row["target_issue"]), - sample_size=2, - strategy="spread", - samples_per_prompt=2, - ) - - assert [record["prompt_id"] for record in records] == ["p0", "p0", "p2", "p2"] - assert [record["input_len"] for record in records] == [3, 3, 7, 7] - assert [record["output_len"] for record in records] == [2, 2, 6, 6] - assert {record["profile_source"] for record in records} == {"startup_real_sample"} - - -def test_profile_summary_reports_output_tail(): - summary = summarize_length_profile( - [ - {"input_len": 10, "output_len": 100}, - {"input_len": 20, "output_len": 300}, - ] - ) - - assert summary["records"] == 2 - assert summary["output_len"]["max"] == 300.0 - assert summary["total_len"]["mean"] == 215.0 - - -def test_profile_jsonl_has_records_detects_real_rows(tmp_path): - path = tmp_path / "profile.jsonl" - path.write_text('{"input_len": 10, "output_len": 20}\n', encoding="utf-8") - - assert profile_jsonl_has_records(path) - - -def test_profile_metadata_reuse_matches_expected_fields(tmp_path): - expected = startup_profile_metadata( - dataset_jsonl="/data/r2e/index.jsonl", - model_path="/models/qwen3-4b", - tokenizer_path="/models/qwen3-4b", - sample_size=64, - strategy="spread", - seed=0, - samples_per_prompt=1, - max_new_tokens=128, - max_seq_length=4096, - r2e_max_turns=3, - r2e_max_prompt_tokens=0, - ) - summary_path = tmp_path / "profile_summary.json" - write_profile_summary({**expected, "records": 2}, summary_path) - - summary = load_profile_summary(summary_path) - - assert profile_metadata_matches(summary, expected) - assert profile_summary_matches(summary_path, expected) - assert summary["dataset_jsonl"] == "/data/r2e/index.jsonl" - - -def test_load_length_profile_records_flattens_step_history_and_limits_tail(tmp_path): - path = tmp_path / "runtime_profile.jsonl" - path.write_text( - "\n".join( - [ - '{"step": 0, "sequences": [{"input_len": 10, "output_len": 20}]}', - '{"input_len": 30, "output_len": 40, "profile_source": "runtime_online"}', - '{"step": 1, "raw_prompt_lengths": [50], "raw_gen_lengths": [60]}', - ] - ) - + "\n", - encoding="utf-8", - ) - - records = load_length_profile_records(path, max_records=2) - - assert [(r["input_len"], r["output_len"]) for r in records] == [ - (30, 40), - (50, 60), - ] - assert records[-1]["step"] == 1 - - -def test_r2e_gym_length_profile_uses_real_prompt_builder_and_target_issue(): - rows = [ - { - "repo_name": "repo", - "commit_hash": "abc", - "prompt": "Describe failure", - "target_issue": "Title\nExpected\nActual", - } - ] - - records = build_r2e_gym_length_profile( - rows, - tokenizer=_Tokenizer(), - sample_size=1, - max_new_tokens=512, - max_seq_length=2048, - ) - - assert len(records) == 1 - assert records[0]["prompt_id"] == "repo:abc" - assert records[0]["input_len"] > len(rows[0]["prompt"]) - assert records[0]["output_len"] > len(rows[0]["target_issue"]) diff --git a/tests/test_sync_drain_prefetch.py b/tests/test_sync_drain_prefetch.py deleted file mode 100644 index c64d5ea..0000000 --- a/tests/test_sync_drain_prefetch.py +++ /dev/null @@ -1,187 +0,0 @@ -from types import SimpleNamespace -import asyncio -import queue -import threading - -import pytest -import torch - -from RL_Framework.infra.execution.async_runner import AsyncTaskRunner -from RL_Framework.infra.execution.batch_dispatcher import BatchTaskDispatcher, TaskInput -from RL_Framework.infra.sync.staleness import StalenessManager -from RL_Framework.trainer.async_rl_trainer import AsyncRLTrainer - - -class _VersionProvider: - def get_version(self): - return 0 - - -@pytest.mark.parametrize("objective, expected", [("legacy", False), ("decoupled", True)]) -def test_sync1_r2e_requires_exact_sampling_to_enable_reservations(objective, expected): - trainer = AsyncRLTrainer.__new__(AsyncRLTrainer) - trainer.config = SimpleNamespace( - grpo_objective=objective, train_backend="megatron_core", rollout_backend="vllm", - sync_interval=1, ppo_epochs=1, weight_sync_mode="nccl", - rollout_weight_sync_mode="nccl", require_rollout_weight_sync=True, - ) - trainer.start_step = 0 - trainer.train_engine = SimpleNamespace(optimizer_revision=0, get_version=lambda: 0) - trainer._configure_rollout_production() - assert trainer._bounded_rollout_production is expected - - -def test_staleness_runtime_limit_reduces_and_restores_capacity(): - manager = StalenessManager( - _VersionProvider(), - max_concurrent_rollouts=32, - consumer_batch_size=4, - max_staleness=8, - ) - - manager.set_runtime_max_concurrent_rollouts(8) - assert manager.get_capacity() == 8 - - manager.set_runtime_max_concurrent_rollouts(None) - assert manager.get_capacity() == 32 - - -def test_dispatcher_cancels_pending_inputs_and_restores_accounting(): - runner = AsyncTaskRunner(max_queue_size=8) - manager = StalenessManager( - _VersionProvider(), - max_concurrent_rollouts=8, - consumer_batch_size=2, - max_staleness=2, - ) - dispatcher = BatchTaskDispatcher( - runner, - manager, - task_factory=lambda _task: (lambda: None), - ) - dispatcher.submit_task_input(TaskInput(task_id=1, data={})) - dispatcher.submit_task_input(TaskInput(task_id=2, data={})) - dispatcher.pause() - - cancelled = dispatcher.cancel_queued() - - assert cancelled == { - "dispatcher_queue": 2, - "runner_queue": 0, - "task_ids": [1, 2], - } - assert dispatcher.get_runtime_metrics()["pending_inputs"] == 0 - assert dispatcher.get_runtime_metrics()["active_tasks"] == 0 - stats = manager.get_stats() - assert stats.enqueued == 0 - assert stats.running == 0 - assert stats.cancelled == 2 - - -def test_sync_drain_prefetch_limit_uses_two_then_one_batch(): - trainer = AsyncRLTrainer.__new__(AsyncRLTrainer) - trainer.config = SimpleNamespace( - sync_interval=5, - rollout_sync_drain_lead_steps=2, - max_concurrent_rollouts=32, - ) - - assert trainer._sync_aware_rollout_limit(step=2, batch_size=4) is None - assert trainer._sync_aware_rollout_limit(step=3, batch_size=4) == 8 - assert trainer._sync_aware_rollout_limit(step=4, batch_size=4) == 4 - assert trainer._sync_aware_rollout_limit(step=5, batch_size=4) is None - assert trainer._sync_aware_rollout_limit(step=6, batch_size=4) is None - - -def test_dispatcher_rechecks_pause_after_dequeue_before_submit(): - class _Runner: - def __init__(self): - self.paused = threading.Event() - self.input_queue = queue.Queue() - self.output_queue = queue.Queue() - self.max_queue_size = 8 - self.submitted = [] - - def submit(self, _fn, *, task_id): - self.submitted.append(task_id) - - def cancel_queued(self): - return [] - - runner = _Runner() - manager = StalenessManager( - _VersionProvider(), - max_concurrent_rollouts=8, - consumer_batch_size=2, - max_staleness=2, - ) - dispatcher = BatchTaskDispatcher( - runner, - manager, - task_factory=lambda _task: (lambda: None), - ) - dispatcher.submit_task_input(TaskInput(task_id=7, data={})) - original_get = dispatcher._get_next_task_for_submission - - def dequeue_at_pause_boundary(): - item = original_get() - runner.paused.set() - dispatcher._shutdown_event.set() - return item - - dispatcher._get_next_task_for_submission = dequeue_at_pause_boundary - - dispatcher._commit_loop() - - assert runner.submitted == [] - assert manager.get_stats().enqueued == 1 - assert manager.get_stats().cancelled == 0 - assert dispatcher.cancel_queued()['task_ids'] == [7] - assert manager.get_stats().enqueued == 0 - assert manager.get_stats().cancelled == 1 - assert dispatcher.cancel_queued()['task_ids'] == [] - assert manager.get_stats().cancelled == 1 - - -@pytest.mark.parametrize("sync_interval", [5, 25]) -def test_legacy_collector_keeps_training_without_sample_revision_between_publications(sync_interval): - trainer = AsyncRLTrainer.__new__(AsyncRLTrainer) - trainer.config = SimpleNamespace( - n_samples=2, sync_interval=sync_interval, max_head_offpolicyness=1, - global_resource_planner=SimpleNamespace(runtime_batch_collection_timeout_s=4), - ) - trainer.is_main_process = True - trainer._pending_grpo_groups = {} - trainer.train_engine = _VersionProvider() - trainer.rollout_engine = object() - - async def episode(engine, data, **kwargs): - if data.get("timeout"): - raise asyncio.TimeoutError - return {"rewards": torch.tensor([0.0]), "versions": torch.tensor([kwargs["version"]])} - - trainer.workflow = SimpleNamespace(run_episode=episode) - manager = trainer.staleness_manager = StalenessManager(trainer.train_engine, 8, 2, 1) - runner = AsyncTaskRunner(max_queue_size=16) - dispatcher = trainer.dispatcher = BatchTaskDispatcher(runner, manager, trainer._create_rollout_task) - - def inputs(): - for group in range(sync_interval + 4): - for member in range(2): - yield TaskInput( - 2 * group + member, {"timeout": group == 0}, - group_id=str(group), rollout_index=member, - ) - - work = inputs() - runner.initialize() - dispatcher.initialize() - try: - for step in range(sync_interval): - rows = trainer._collect_complete_grpo_batch(work, 2) - assert len(rows) == 2 - assert {row["grpo_group_id"] for row in rows} == {str(step + 1)} - assert all("sample_revision" not in row for row in rows) - assert manager.get_stats().rejected == 2 - finally: - dispatcher.destroy() diff --git a/tests/test_torch_optimizer_memory.py b/tests/test_torch_optimizer_memory.py deleted file mode 100644 index ec0965d..0000000 --- a/tests/test_torch_optimizer_memory.py +++ /dev/null @@ -1,484 +0,0 @@ -"""The fallback optimizer must fit without full-model foreach temporaries.""" -import copy -import importlib -import weakref -from types import SimpleNamespace - -import pytest -import torch - -from RL_Framework.engine.optimizer_memory import bound_default_torch_adam_memory - - -def _parameters(): - return [torch.nn.Parameter(torch.linspace(-1., 1., size)) for size in (19, 31)] - - -def test_native_adamw_automatic_foreach_allocates_all_moments_but_bounded_path_does_not(monkeypatch): - # CPU uses another automatic choice; force CUDA's foreach decision while - # retaining the real PyTorch optimizer step and tensor implementations. - adam_module = importlib.import_module('torch.optim.adam') - monkeypatch.setattr(adam_module, '_default_to_fused_or_foreach', - lambda *args, **kwargs: (False, True)) - original_sqrt = torch._foreach_sqrt - allocations = [] - - def measured_sqrt(tensors): - allocations.append(sum(t.numel() * t.element_size() for t in tensors)) - return original_sqrt(tensors) - - monkeypatch.setattr(torch, '_foreach_sqrt', measured_sqrt) - automatic_parameters = _parameters() - automatic = torch.optim.AdamW(automatic_parameters, lr=.01) - for parameter in automatic_parameters: - parameter.grad = torch.ones_like(parameter) - automatic.step() - assert allocations == [sum(p.numel() * p.element_size() for p in automatic_parameters)] - - masters, reference_masters = _parameters(), _parameters() - bounded = torch.optim.AdamW(masters, lr=.01, betas=(.9, .95)) - reference = torch.optim.AdamW(reference_masters, lr=.01, betas=(.9, .95), foreach=False) - assert bound_default_torch_adam_memory(bounded) == 1 - for step in range(3): - for parameter, expected in zip(masters, reference_masters): - gradient = torch.linspace(-.3, .7, parameter.numel()) * (step + 1) - parameter.grad = gradient.clone() - expected.grad = gradient.clone() - bounded.step() - reference.step() - for parameter, expected in zip(masters, reference_masters): - assert parameter.grad is not None # The default policy does not consume gradients. - assert torch.equal(parameter, expected) - # MCore's BF16 model copy and FP32 master/moments are unchanged. - assert torch.equal(parameter.to(torch.bfloat16), expected.to(torch.bfloat16)) - for key in ('exp_avg', 'exp_avg_sq', 'step'): - assert torch.equal(bounded.state[parameter][key], reference.state[expected][key]) - assert len(allocations) == 1 - - -@pytest.mark.parametrize('optimizer_type', [torch.optim.Adam, torch.optim.AdamW]) -def test_nested_mcore_chained_and_distributed_wrappers_are_configured_once(optimizer_type): - ChainedOptimizer = pytest.importorskip("megatron.core.optimizer.optimizer").ChainedOptimizer - DistributedOptimizer = pytest.importorskip("megatron.core.optimizer.distrib_optimizer").DistributedOptimizer - - first, second = optimizer_type(_parameters()), optimizer_type(_parameters()) - distributed = DistributedOptimizer.__new__(DistributedOptimizer) - distributed.optimizer = first - inner = ChainedOptimizer.__new__(ChainedOptimizer) - inner.chained_optimizers = [distributed, SimpleNamespace(optimizer=second)] - outer = ChainedOptimizer.__new__(ChainedOptimizer) - # This also proves we never access the asserting .optimizer property of a - # multi-child chain, and shared references are not counted twice. - outer.chained_optimizers = [inner, distributed] - assert bound_default_torch_adam_memory(outer) == 2 - assert all(group['foreach'] is False for opt in (first, second) for group in opt.param_groups) - assert bound_default_torch_adam_memory(outer) == 0 - - -def test_explicit_foreach_and_fused_choices_and_non_native_optimizers_are_preserved(): - explicit = torch.optim.AdamW([ - {'params': [_parameters()[0]], 'foreach': True}, - {'params': [_parameters()[0]], 'foreach': False}, - {'params': [_parameters()[0]], 'foreach': None}, - ]) - fused = torch.optim.AdamW(_parameters(), fused=True) - - class OtherAdam(torch.optim.AdamW): - pass - - other = OtherAdam(_parameters()) - sgd = torch.optim.SGD(_parameters(), lr=.1) - tree = SimpleNamespace(chained_optimizers=[explicit, fused, other, sgd, None]) - assert bound_default_torch_adam_memory(tree) == 1 - assert [group['foreach'] for group in explicit.param_groups] == [True, False, False] - assert fused.param_groups[0]['foreach'] is None - assert fused.param_groups[0]['fused'] is True - assert other.param_groups[0]['foreach'] is None - assert sgd.param_groups[0]['foreach'] is None - - -def test_old_optimizer_state_restoration_reapplies_only_automatic_policy(): - optimizer = torch.optim.AdamW(_parameters()) - for parameter in optimizer.param_groups[0]['params']: - parameter.grad = torch.ones_like(parameter) - optimizer.step() - saved = copy.deepcopy(optimizer.state_dict()) - assert saved['param_groups'][0]['foreach'] is None - assert bound_default_torch_adam_memory(optimizer) == 1 - optimizer.load_state_dict(saved) - assert optimizer.param_groups[0]['foreach'] is None - assert bound_default_torch_adam_memory(optimizer) == 1 - actual = optimizer.state_dict() - for key, values in saved['state'].items(): - for field, tensor in values.items(): - assert torch.equal(actual['state'][key][field], tensor) - assert optimizer.defaults['foreach'] is False - optimizer.add_param_group({'params': [_parameters()[0]]}) - assert optimizer.param_groups[-1]['foreach'] is False - - -def _master_groups(parameters): - return [dict(params=parameters[:2], lr=.003, weight_decay=.01, name='body'), - dict(params=parameters[2:], lr=.007, weight_decay=0., amsgrad=True, name='head')] - - -def _assert_adam_equal(actual, expected, parameters, reference): - for parameter, target in zip(parameters, reference): - assert torch.equal(parameter, target) - assert set(actual.state[parameter]) == set(expected.state[target]) - for field, value in actual.state[parameter].items(): - assert torch.equal(value, expected.state[target][field]) - - -@pytest.mark.parametrize('optimizer_type', [torch.optim.Adam, torch.optim.AdamW]) -def test_streamed_main_gradients_preserve_multigroup_updates_and_reloadable_state(optimizer_type): - parameters = _parameters() + [torch.nn.Parameter(torch.linspace(-.4, .8, 7))] - reference = [torch.nn.Parameter(p.detach().clone()) for p in parameters] - actual = optimizer_type(_master_groups(parameters), betas=(.9, .95)) - expected = optimizer_type(_master_groups(reference), betas=(.9, .95), foreach=False) - original_groups = actual.param_groups - group_objects = list(original_groups) - bound_default_torch_adam_memory(actual, release_main_gradients=True) - streamed_step = actual.step - bound_default_torch_adam_memory(actual, release_main_gradients=True) - assert actual.step is streamed_step - for step in range(4): - for index, (parameter, target) in enumerate(zip(parameters, reference)): - gradient = torch.linspace(-.3, .7, parameter.numel()) * (step + 1) - parameter.grad = gradient.clone() if (step, index) != (2, 1) else None - target.grad = gradient.clone() if (step, index) != (2, 1) else None - # MCore computes and applies the common global clipping before Adam. - torch.nn.utils.clip_grad_norm_(parameters, 1.) - torch.nn.utils.clip_grad_norm_(reference, 1.) - actual.step() - expected.step() - assert all(parameter.grad is None for parameter in parameters) - assert actual.param_groups is original_groups - assert all(group is original for group, original in zip(actual.param_groups, group_objects)) - _assert_adam_equal(actual, expected, parameters, reference) - - saved = copy.deepcopy(actual.state_dict()) - assert [len(group['params']) for group in saved['param_groups']] == [2, 1] - assert [group['name'] for group in saved['param_groups']] == ['body', 'head'] - reloaded_parameters = [torch.nn.Parameter(p.detach().clone()) for p in parameters] - reloaded = optimizer_type(_master_groups(reloaded_parameters), betas=(.9, .95), foreach=False) - reloaded.load_state_dict(saved) - bound_default_torch_adam_memory(reloaded, release_main_gradients=True) - for parameter, target in zip(reloaded_parameters, reference): - parameter.grad = torch.ones_like(parameter) - target.grad = torch.ones_like(target) - reloaded.step() - expected.step() - _assert_adam_equal(reloaded, expected, reloaded_parameters, reference) - - -def test_streamed_state_initialization_releases_each_main_gradient_before_the_next(monkeypatch): - parameters = _parameters() + [torch.nn.Parameter(torch.zeros(7))] - optimizer = torch.optim.AdamW(parameters, foreach=False) - for parameter in parameters: - parameter.grad = torch.ones_like(parameter) - bound_default_torch_adam_memory(optimizer, release_main_gradients=True) - allocate = torch.zeros_like - resident_gradients = [] - - def measured_zeros(tensor, *args, **kwargs): - if any(tensor is parameter for parameter in parameters): - resident_gradients.append(sum(p.grad.numel() for p in parameters if p.grad is not None)) - return allocate(tensor, *args, **kwargs) - - monkeypatch.setattr(torch, 'zeros_like', measured_zeros) - optimizer.step() - # Each parameter initializes two Adam moments. Later moments must not - # overlap the FP32 main gradients of parameters already updated. - assert resident_gradients == [57, 57, 38, 38, 7, 7] - assert all(parameter.grad is None for parameter in parameters) - - -def test_streamed_step_restores_original_groups_and_propagates_allocation_failure(monkeypatch): - parameters = _parameters() + [torch.nn.Parameter(torch.zeros(7))] - optimizer = torch.optim.AdamW(_master_groups(parameters), foreach=False) - original_groups, group_objects = optimizer.param_groups, list(optimizer.param_groups) - gradients = [torch.ones_like(parameter) for parameter in parameters] - for parameter, gradient in zip(parameters, gradients): - parameter.grad = gradient - bound_default_torch_adam_memory(optimizer, release_main_gradients=True) - allocate = torch.zeros_like - - def failing_zeros(tensor, *args, **kwargs): - if tensor is parameters[1]: - raise MemoryError('injected moment allocation') - return allocate(tensor, *args, **kwargs) - - monkeypatch.setattr(torch, 'zeros_like', failing_zeros) - with pytest.raises(MemoryError, match='injected moment allocation'): - optimizer.step() - assert optimizer.param_groups is original_groups - assert all(group is original for group, original in zip(optimizer.param_groups, group_objects)) - assert parameters[0].grad is None - assert parameters[1].grad is gradients[1] and parameters[2].grad is gradients[2] - - -def test_closure_uses_one_native_step_and_keeps_main_gradients(): - parameters = _parameters() - optimizer = torch.optim.AdamW(parameters, foreach=False) - gradients = [torch.ones_like(parameter) for parameter in parameters] - for parameter, gradient in zip(parameters, gradients): - parameter.grad = gradient - bound_default_torch_adam_memory(optimizer, release_main_gradients=True) - calls = [] - - def closure(): - calls.append(True) - return torch.tensor(4.) - - assert optimizer.step(closure).item() == 4. - assert calls == [True] - assert all(p.grad is gradient for p, gradient in zip(parameters, gradients)) - - -@pytest.mark.parametrize('unsupported', ['foreach', 'fused', 'differentiable', 'capturable']) -def test_unsupported_streaming_configuration_delegates_without_clearing_gradients(unsupported): - parameters = _parameters() - optimizer = torch.optim.AdamW([ - dict(params=parameters[:1], foreach=False), - dict(params=parameters[1:], **{unsupported: True}), - ]) - gradients = [torch.ones_like(parameter) for parameter in parameters] - for parameter, gradient in zip(parameters, gradients): - parameter.grad = gradient - original_groups = optimizer.param_groups - calls, sentinel = [], object() - - def native_step(*args, **kwargs): - # Spy at the native boundary so unsupported CUDA-only modes can be - # checked on CPU without silently exercising another implementation. - calls.append(([len(group['params']) for group in optimizer.param_groups], args, kwargs)) - return sentinel - - optimizer.step = native_step - bound_default_torch_adam_memory(optimizer, release_main_gradients=True) - assert optimizer.step() is sentinel - assert calls == [([1, 1], (), {})] - assert optimizer.param_groups is original_groups - assert all(p.grad is gradient for p, gradient in zip(parameters, gradients)) - - -@pytest.fixture -def mcore_cpu(monkeypatch): - """Run MCore's real optimizer flow/math, redirecting CUDA-only test plumbing.""" - module = pytest.importorskip('megatron.core.optimizer.optimizer') - distributed = pytest.importorskip('megatron.core.optimizer.distrib_optimizer') - layers = pytest.importorskip('megatron.core.tensor_parallel.layers') - tensor, tensor_type = torch.tensor, torch.Tensor.type - reductions = [] - - def cpu_tensor(*args, **kwargs): - if kwargs.get('device') == 'cuda': - kwargs['device'] = 'cpu' - return tensor(*args, **kwargs) - - def cuda_type_for_clip(value, *args, **kwargs): - if not args and not kwargs and value.dtype == torch.float32: - return 'torch.cuda.FloatTensor' - return tensor_type(value, *args, **kwargs) - - monkeypatch.setattr(torch, 'tensor', cpu_tensor) - monkeypatch.setattr(torch.Tensor, 'type', cuda_type_for_clip) - monkeypatch.setattr(layers, 'get_tensor_model_parallel_rank', lambda: 1) - monkeypatch.setattr(torch.distributed, 'all_reduce', - lambda value, **kwargs: reductions.append((value.clone(), kwargs['group']))) - - def make(children=1): - wrappers = [] - group = object() - for child_index in range(children): - masters = _parameters() + [torch.nn.Parameter(torch.linspace(-.4, .8, 7))] - models = [] - for index, master in enumerate(masters): - master.tensor_model_parallel = index != 2 - master.shared = index == 1 - model = torch.nn.Parameter(torch.zeros(master.numel() + 4, dtype=torch.bfloat16)) - model.main_grad = torch.zeros_like(model) - models.append(model) - wrapper = distributed.DistributedOptimizer.__new__(distributed.DistributedOptimizer) - wrapper.optimizer = torch.optim.AdamW(_master_groups(masters), betas=(.9, .95), foreach=False) - wrapper.config = SimpleNamespace(bf16=True, use_precision_aware_optimizer=False, - use_precision_aware_optimizer_no_fp8_or_ds_fp8=False, optimizer_cpu_offload=False, - log_num_zeros_in_grad=False, clip_grad=.7 / (child_index + 1), timers=None, - reuse_grad_buf_for_mxfp8_param_ag=False, overlap_param_gather_with_optimizer_step=False) - wrapper.grad_scaler, wrapper.is_stub_optimizer = None, False - wrapper.ddp_config = SimpleNamespace(use_megatron_fsdp=False, overlap_param_gather=False) - wrapper.grad_stats_parallel_group = group - wrapper.model_float16_groups = [models[:2], models[2:]] - wrapper.shard_fp32_from_float16_groups = [masters[:2], masters[2:]] - wrapper.model_fp32_groups = wrapper.shard_fp32_groups = [[], []] - wrapper._get_model_param_range_map = lambda model: { - 'param': SimpleNamespace(start=2, end=model.numel()-2, size=model.numel()-4)} - - @torch.no_grad() - def copy_models(models=models, masters=masters): - for model, master in zip(models, masters): - model[2:-2].copy_(master) - - wrapper._copy_main_params_to_model_params = copy_models - wrapper.model_chunks = [SimpleNamespace(start_param_sync=lambda: None)] - wrappers.append(wrapper) - chain = module.ChainedOptimizer.__new__(module.ChainedOptimizer) - chain.chained_optimizers = wrappers - chain.config = wrappers[0].config - return SimpleNamespace(root=chain, children=wrappers, - parameters=[p for child in wrappers for group in child.optimizer.param_groups for p in group['params']], - models=[p for child in wrappers for group in child.model_float16_groups for p in group]) - - return SimpleNamespace(make=make, reductions=reductions) - - -@pytest.mark.parametrize('children', [1, 2]) -def test_bf16_prepare_streams_second_step_with_exact_global_norm_clip_and_state(mcore_cpu, monkeypatch, children): - actual, expected = mcore_cpu.make(children), mcore_cpu.make(children) - bound_default_torch_adam_memory(actual.root, release_main_gradients=True) - assert all(child._libra_streamed_bf16_main_gradients for child in actual.children) - copy_method = actual.children[0]._copy_model_grads_to_main_grads - bound_default_torch_adam_memory(actual.root, release_main_gradients=True) - assert actual.children[0]._copy_model_grads_to_main_grads is copy_method - for step in range(3): - # The second pass starts with all Adam moments already resident. - for index, (model, reference) in enumerate(zip(actual.models, expected.models)): - gradient = torch.linspace(-3., 7., model.numel()).to(torch.bfloat16) * (step + index + 1) - model.main_grad.copy_(gradient) - reference.main_grad.copy_(gradient) - source_copies = [model.main_grad.clone() for model in actual.models] - if step == 2: - for child in actual.children: - child.optimizer.load_state_dict(copy.deepcopy(child.optimizer.state_dict())) - bound_default_torch_adam_memory(actual.root, release_main_gradients=True) - expected_result = expected.root.step() - references, live_counts = [], [] - original_float = torch.Tensor.float - - def counted_float(value, *args, **kwargs): - result = original_float(value, *args, **kwargs) - if value.dtype == torch.bfloat16: - references.append(weakref.ref(result)) - live_counts.append(sum(ref() is not None for ref in references)) - return result - - with monkeypatch.context() as patch: - patch.setattr(torch.Tensor, 'float', counted_float) - actual_result = actual.root.step() - assert actual_result == expected_result - assert actual_result[1] > 1 # Clipping is exercised, across all children. - assert max(live_counts) == 1 - assert not any(ref() is not None for ref in references) - assert all(parameter.grad is None for parameter in actual.parameters) - for model, source in zip(actual.models, source_copies): - assert torch.equal(model.main_grad, source) # Never clip the BF16 source. - for child, reference in zip(actual.children, expected.children): - parameters = [p for group in child.optimizer.param_groups for p in group['params']] - targets = [p for group in reference.optimizer.param_groups for p in group['params']] - _assert_adam_equal(child.optimizer, reference.optimizer, parameters, targets) - assert all(torch.equal(a, b) for a, b in zip(actual.models, expected.models)) - # Original MCore performs one global SUM for each chain, using its own group. - reductions = mcore_cpu.reductions[-2:] - assert len(reductions) == 2 - assert torch.equal(reductions[0][0], reductions[1][0]) - assert reductions[0][1] is expected.root.get_grad_stats_parallel_group() - assert reductions[1][1] is actual.root.get_grad_stats_parallel_group() - - -@pytest.mark.parametrize('unsupported', ['grad_scaler', 'zeros', 'precision_aware', 'fsdp', 'backend']) -def test_bf16_streaming_leaves_unsupported_mcore_preparation_untouched(mcore_cpu, monkeypatch, unsupported): - actual = mcore_cpu.make() - child = actual.children[0] - original = child._copy_model_grads_to_main_grads - if unsupported == 'grad_scaler': - child.grad_scaler = object() - elif unsupported == 'zeros': - child.config.log_num_zeros_in_grad = True - elif unsupported == 'precision_aware': - child.config.use_precision_aware_optimizer = True - elif unsupported == 'fsdp': - child.ddp_config.use_megatron_fsdp = True - else: - from megatron.core.optimizer import clip_grads - monkeypatch.setattr(clip_grads, 'l2_norm_impl', lambda *args: None) - bound_default_torch_adam_memory(actual.root, release_main_gradients=True) - assert not getattr(child, '_libra_streamed_bf16_main_gradients', False) - assert child._copy_model_grads_to_main_grads == original - - -@pytest.mark.parametrize('path,children', [ - ('streaming', 2), ('eager', 2), ('dynamic_fallback', 2), - ('standalone_eager', 1), -]) -@pytest.mark.parametrize('bad_gradient', [float('nan'), float('inf')]) -def test_nonfinite_existing_norm_rejects_before_clip_or_any_adam_state_change( - mcore_cpu, monkeypatch, children, path, bad_gradient): - actual = mcore_cpu.make(children) - for model in actual.models: - model.main_grad.fill_(1.) - actual.root.step() # Populate moments and counters before the failing update. - if path.endswith('eager'): - for child in actual.children: - child.optimizer.param_groups[0]['foreach'] = True - bound_default_torch_adam_memory(actual.root, release_main_gradients=True) - if path.endswith('dynamic_fallback'): - for child in actual.children: - child.optimizer.param_groups[0]['foreach'] = True - before_parameters = [parameter.detach().clone() for parameter in actual.parameters] - before_models = [model.detach().clone() for model in actual.models] - before_states = [copy.deepcopy(child.optimizer.state_dict()) for child in actual.children] - # The later child's norm must reject before the first child is clipped or stepped. - actual.children[-1].model_float16_groups[0][0].main_grad.fill_(bad_gradient) - clipped, stepped = [], [] - from megatron.core.optimizer import clip_grads - monkeypatch.setattr(clip_grads, 'multi_tensor_scale_impl', - lambda *args: clipped.append(args)) - for child in actual.children: - monkeypatch.setattr(child.optimizer, 'step', lambda: stepped.append(True)) - mcore_cpu.reductions.clear() - root = actual.children[0] if path.startswith('standalone') else actual.root - with pytest.raises(FloatingPointError, match='non-finite gradient norm'): - root.step() - assert len(mcore_cpu.reductions) == 1 - assert not clipped and not stepped - assert all(torch.equal(parameter, before) - for parameter, before in zip(actual.parameters, before_parameters)) - assert all(torch.equal(model, before) for model, before in zip(actual.models, before_models)) - for child, before in zip(actual.children, before_states): - current = child.optimizer.state_dict() - assert current['param_groups'] == before['param_groups'] - for parameter, fields in before['state'].items(): - for name, value in fields.items(): - assert torch.equal(current['state'][parameter][name], value) - - -@pytest.mark.parametrize('path', ['streaming', 'standalone_eager']) -@pytest.mark.parametrize('zero', [False, True]) -def test_guarded_existing_norm_preserves_finite_and_zero_updates(mcore_cpu, path, zero): - children = 1 if path.startswith('standalone') else 2 - actual, expected = mcore_cpu.make(children), mcore_cpu.make(children) - if path.endswith('eager'): - for child in actual.children: - child.optimizer.param_groups[0]['foreach'] = True - bound_default_torch_adam_memory(actual.root, release_main_gradients=True) - if path.endswith('dynamic_fallback'): - for child in actual.children: - child.optimizer.param_groups[0]['foreach'] = True - for step in range(2): - for model, reference in zip(actual.models, expected.models): - gradient = torch.zeros_like(model) if zero else torch.linspace(-3., 7., model.numel()) - model.main_grad.copy_(gradient) - reference.main_grad.copy_(gradient) - actual_root = actual.children[0] if path.startswith('standalone') else actual.root - expected_root = expected.children[0] if path.startswith('standalone') else expected.root - mcore_cpu.reductions.clear() - expected_result = expected_root.step() - actual_result = actual_root.step() - assert actual_result == expected_result - assert len(mcore_cpu.reductions) == 2 - for child, reference in zip(actual.children, expected.children): - parameters = [p for group in child.optimizer.param_groups for p in group['params']] - targets = [p for group in reference.optimizer.param_groups for p in group['params']] - _assert_adam_equal(child.optimizer, reference.optimizer, parameters, targets) - assert all(torch.equal(a, b) for a, b in zip(actual.models, expected.models)) diff --git a/tests/test_train_engine.py b/tests/test_train_engine.py deleted file mode 100644 index f84a047..0000000 --- a/tests/test_train_engine.py +++ /dev/null @@ -1,98 +0,0 @@ -import json - -import pytest -import torch - -from RL_Framework.engine.train_engine import ( - FSDPTrainEngine, - _apply_fsdp_activation_checkpointing, - _checkpoint_only_with_grad, - _selected_token_logprobs, -) - - -def test_selected_token_logprobs_matches_log_softmax(): - torch.manual_seed(7) - logits = torch.randn(2, 3, 11) - targets = torch.randint(0, logits.shape[-1], (2, 3)) - - expected = torch.gather( - torch.log_softmax(logits, dim=-1), - dim=-1, - index=targets.unsqueeze(-1), - ).squeeze(-1) - actual = _selected_token_logprobs(logits, targets) - - assert torch.allclose(actual, expected, atol=1e-6) - - -def test_fsdp_local_batch_size_is_sharded(): - engine = FSDPTrainEngine(model_path="unused") - engine.world_size = 4 - - assert engine.get_local_batch_size(32) == 8 - with pytest.raises(ValueError): - engine.get_local_batch_size(10) - - -def test_fsdp_activation_checkpointing_wraps_each_transformer_layer(): - class TransformerLayer(torch.nn.Module): - def __init__(self): - super().__init__() - self.linear = torch.nn.Linear(4, 4) - - def forward(self, inputs): - return torch.relu(self.linear(inputs)) - - model = torch.nn.Sequential(TransformerLayer(), TransformerLayer()) - - wrapped = _apply_fsdp_activation_checkpointing(model, TransformerLayer) - output = model(torch.randn(2, 4, requires_grad=True)).sum() - output.backward() - - assert wrapped == 2 - assert all(parameter.grad is not None for parameter in model.parameters()) - - -def test_checkpoint_wrapper_bypasses_checkpoint_without_grad(monkeypatch): - calls = [] - - def fail_if_checkpointed(*args, **kwargs): - calls.append((args, kwargs)) - raise AssertionError("no-grad forward should bypass checkpoint") - - monkeypatch.setattr( - "RL_Framework.engine.train_engine.torch_checkpoint", - fail_if_checkpointed, - ) - value = torch.tensor(3.0) - with torch.no_grad(): - result = _checkpoint_only_with_grad(lambda item: item * 2, value) - - assert result.item() == 6.0 - assert calls == [] - - -def test_fsdp_weight_sync_phase_is_recorded_atomically(tmp_path, monkeypatch): - engine = FSDPTrainEngine.__new__(FSDPTrainEngine) - engine.rank = 3 - engine.local_rank = 1 - monkeypatch.setenv("FSDP_PROGRESS_DIR", str(tmp_path)) - monkeypatch.setenv("SLURM_JOB_ID", "42") - - weight_file = str(tmp_path / "weights" / "pytorch_model.bin") - engine._record_weight_sync_phase(5, "after_state_dict", weight_file) - - progress_path = ( - tmp_path - / "job_42" - / "update_5" - / "weight_sync" - / "rank_3.json" - ) - payload = json.loads(progress_path.read_text(encoding="utf-8")) - assert payload["rank"] == 3 - assert payload["local_rank"] == 1 - assert payload["update"] == 5 - assert payload["phase"] == "after_state_dict" - assert payload["weight_file"] == weight_file diff --git a/tests/test_vllm_cpu_offload.py b/tests/test_vllm_cpu_offload.py deleted file mode 100644 index c4c8429..0000000 --- a/tests/test_vllm_cpu_offload.py +++ /dev/null @@ -1,293 +0,0 @@ -"""Run in the supported vLLM environment; GPU tests use real CUDA tensors.""" - -import json -import tempfile -import uuid -from types import SimpleNamespace - -import pytest - -torch = pytest.importorskip("torch") -pytest.importorskip("vllm") -from RL_Framework.infra.scheduling import vllm_cpu_offload as cpu_offload -from RL_Framework.infra.scheduling.vllm_cpu_offload import LibraCPUOffloadConnector, cache_directory - - -def bare_connector(root, tp=1, rank=0): - connector = object.__new__(LibraCPUOffloadConnector) - connector.root, connector.tp, connector.rank = root, tp, rank - connector.block_size, connector.num_heads = 16, 8 - connector.matches, connector.imported = {}, {} - connector.pending = {} - connector.loads = [] - connector.verify_reload = False - return connector - - -def test_prefix_identity_and_complete_block_boundaries(): - with tempfile.TemporaryDirectory() as root: - key = uuid.uuid4().hex - directory = cache_directory(root, key) - directory.mkdir() - (directory / "rank_0.json").write_text(json.dumps({ - "tokens": list(range(64)), "source_tp": 1, "block_size": 16, - })) - connector = bare_connector(root) - request = SimpleNamespace(kv_transfer_params={"libra_load_key": key}, - request_id="r", prompt_token_ids=list(range(65))) - assert connector.get_num_new_matched_tokens(request, 16) == (48, False) - request.prompt_token_ids[1] = 999 - assert connector.get_num_new_matched_tokens(request, 0) == (0, False) - request.prompt_token_ids = list(range(64)) - # Must recompute at least one token for the next logits. - assert connector.get_num_new_matched_tokens(request, 0) == (48, False) - - -def test_largest_matching_complete_block_prefix(): - with tempfile.TemporaryDirectory() as root: - key = uuid.uuid4().hex - directory = cache_directory(root, key) - directory.mkdir() - (directory / "rank_0.json").write_text(json.dumps({ - "tokens": list(range(64)), "source_tp": 1, "block_size": 16, - })) - connector = bare_connector(root) - prompt_tokens = list(range(65)) - prompt_tokens[20] = 999 - request = SimpleNamespace( - kv_transfer_params={"libra_load_key": key}, - request_id="r", prompt_token_ids=prompt_tokens, - ) - assert connector.get_num_new_matched_tokens(request, 0) == (16, False) - assert connector.matches["r"]["num_tokens"] == 16 - - -def test_allocation_keeps_local_prefix_offset(): - connector = bare_connector("/tmp", tp=1, rank=0) - connector.matches["r"] = { - "key": "k", "source_tp": 1, "num_tokens": 48, - "num_local_tokens": 16, "request_id": "r", - } - blocks = SimpleNamespace(get_block_ids=lambda: ([10, 11, 12],)) - connector.update_state_after_alloc( - SimpleNamespace(request_id="r"), blocks, num_external_tokens=32, - ) - assert connector.loads[0]["num_local_tokens"] == 16 - assert connector.loads[0]["block_ids"] == [10, 11, 12] - - -def test_constructor_supports_optional_cache_config_and_rejects_multiple_groups( - monkeypatch, tmp_path, -): - base_calls = [] - - def base_init(self, *args): - base_calls.append(args) - - monkeypatch.setattr(cpu_offload.KVConnectorBase_V1, "__init__", base_init) - config = SimpleNamespace( - kv_transfer_config=SimpleNamespace( - get_from_extra_config=lambda name, default=None: - str(tmp_path) if name == "storage_path" else default, - ), - cache_config=SimpleNamespace(block_size=16), - parallel_config=SimpleNamespace(tensor_parallel_size=1), - model_config=SimpleNamespace(hf_config=SimpleNamespace(num_key_value_heads=8)), - ) - role = object() - - LibraCPUOffloadConnector(config, role) - assert base_calls[-1] == (config, role) - - one_group = SimpleNamespace(kv_cache_groups=[object()]) - LibraCPUOffloadConnector(config, role, one_group) - assert base_calls[-1] == (config, role, one_group) - - multiple_groups = SimpleNamespace(kv_cache_groups=[object(), object()]) - with pytest.raises(ValueError, match="exactly one KV cache group"): - LibraCPUOffloadConnector(config, role, multiple_groups) - - -@pytest.mark.parametrize("layout", ["old", "new"]) -def test_register_accepts_native_layout_as_zero_copy_view(monkeypatch, layout): - connector = bare_connector("/tmp") - native = native_strided_cache(torch.empty(2, 3, 16, 8, 4), layout) - stream = object() - monkeypatch.setattr(cpu_offload.torch.cuda, "Stream", lambda: stream) - - connector.register_kv_caches({"layer": native}) - - canonical = connector.caches["layer"] - assert canonical.shape == (2, 3, 16, 8, 4) - assert canonical.data_ptr() == native.data_ptr() - assert not canonical.is_contiguous() - assert connector.stream is stream - - -def test_allocation_rejects_external_token_count_mismatch(): - connector = bare_connector("/tmp") - connector.matches["r"] = { - "key": "k", "source_tp": 1, "num_tokens": 48, - "num_local_tokens": 16, "request_id": "r", - } - blocks = SimpleNamespace(get_block_ids=lambda: ([10, 11],)) - - with pytest.raises(RuntimeError, match="does not match the available prefix"): - connector.update_state_after_alloc( - SimpleNamespace(request_id="r"), blocks, num_external_tokens=16, - ) - assert connector.loads == [] - assert "r" not in connector.matches - - -@pytest.mark.parametrize( - "shape, message", - [ - ((3, 4, 16, 8, 4), "first two axes"), - ((2, 3, 15, 8, 4), "block_size"), - ((2, 3, 16, 7, 4), "local_heads"), - ((2, 3, 16, 8), "five-dimensional"), - ], -) -def test_register_rejects_invalid_cache_shape(shape, message): - connector = bare_connector("/tmp") - with pytest.raises(ValueError, match=message) as raised: - connector.register_kv_caches({"layer": torch.empty(shape)}) - detail = str(raised.value) - assert "layer=layer" in detail and "backend=" in detail - assert f"shape={shape}" in detail and "vLLM=" in detail - - -def test_register_rejects_ambiguous_layout_without_layer_metadata(): - connector = bare_connector("/tmp") - with pytest.raises(ValueError, match="ambiguous leading axes") as raised: - connector.register_kv_caches({"layer": torch.empty(2, 2, 16, 8, 4)}) - assert isinstance(raised.value.__cause__, AttributeError) - for detail in ("layer=layer", "backend=unresolved", "shape=(2, 2, 16, 8, 4)", "vLLM="): - assert detail in str(raised.value) - - -def native_strided_cache(canonical, layout="new"): - native_shape = canonical if layout == "old" else canonical.movedim(0, 1) - backing = torch.empty( - (*native_shape.shape[:-1], native_shape.shape[-1] * 2), - dtype=canonical.dtype, device=canonical.device, - ) - native = backing[..., ::2] - native.copy_(native_shape) - return native - - -def native_cache_block(native, layout, block): - return native[:, block] if layout == "old" else native[block] - - -def install_backend_metadata(connector, layout): - class Impl: - pass - - class Backend: - @classmethod - def get_impl_cls(cls): - return Impl - - @classmethod - def get_kv_cache_shape(cls, num_blocks, block_size, num_heads, head_size): - if layout == "old": - return (2, num_blocks, block_size, num_heads, head_size) - return (num_blocks, 2, block_size, num_heads, head_size) - - layer = SimpleNamespace(attn_backend=Backend, impl=Impl()) - connector._vllm_config = SimpleNamespace( - compilation_config=SimpleNamespace(static_forward_context={"layer": layer}), - ) - - -@pytest.mark.parametrize("layout", ["old", "new"]) -@pytest.mark.parametrize("source_tp,target_tp", [(1, 1), (1, 2), (2, 1), (2, 2)]) -def test_real_cuda_native_layout_offload_and_reload( - layout, source_tp, target_tp, caplog, monkeypatch, -): - if torch.cuda.device_count() < max(source_tp, target_tp): - pytest.skip("needs one CUDA GPU per source or target TP rank") - caplog.set_level("INFO", logger="RL_Framework.infra.scheduling.vllm_cpu_offload") - with tempfile.TemporaryDirectory() as root: - key = uuid.uuid4().hex - directory = cache_directory(root, key) - directory.mkdir() - full = torch.arange(2 * 2 * 16 * 8 * 4, dtype=torch.float32).reshape( - 2, 2, 16, 8, 4, - ) - save_item = { - "request_id": "native-offload", "key": key, "source_tp": source_tp, - "block_ids": [1, 0], "tokens": list(range(32)), - } - - # Two blocks deliberately make native axis 0 equal the KV size. - # Distinct values and non-contiguous cache strides expose axis swaps. - for rank in range(source_tp): - with torch.cuda.device(rank): - source = full.chunk(source_tp, dim=-2)[rank].to(f"cuda:{rank}") - native = native_strided_cache(source, layout) - connector = bare_connector(root, source_tp, rank) - install_backend_metadata(connector, layout) - connector.register_kv_caches({"layer": native}) - assert native.shape[:2] == (2, 2) - assert not connector.caches["layer"].is_contiguous() - connector._start_offload(save_item) - event, _gathered, host, _item, started = connector.pending["native-offload"] - event.synchronize() - connector._publish(host, save_item, started, started) - - for rank in range(target_tp): - with torch.cuda.device(rank): - seed = torch.full((2, 4, 16, 8 // target_tp, 4), -7.0, device=f"cuda:{rank}") - native = native_strided_cache(seed, layout) - connector = bare_connector(root, target_tp, rank) - install_backend_metadata(connector, layout) - connector.register_kv_caches({"layer": native}) - connector.verify_reload = True - request_id = f"native-{source_tp}-to-{target_tp}-rank-{rank}" - # One local prefix block is preserved; the single external - # block is written to destination block 2. - connector._reload({ - "key": key, "source_tp": source_tp, "num_tokens": 32, - "num_local_tokens": 16, "block_ids": [0, 2], - "request_id": request_id, - }) - expected = full[:, 0:1].chunk(target_tp, dim=-2)[rank] - indices = torch.tensor([2], device=f"cuda:{rank}") - observed = connector.caches["layer"].index_select(1, indices).cpu() - assert torch.equal(observed, expected) - # The engine-owned native tensor sees the restored values. - assert torch.equal(native_cache_block(native, layout, 2).cpu(), expected[:, 0]) - for untouched in (0, 1, 3): - actual = native_cache_block(native, layout, untouched).cpu() - assert torch.equal(actual, torch.full_like(actual, -7.0)) - - record = next( - record for record in reversed(caplog.records) - if "CPU_KV_RELOAD_VERIFIED " in record.getMessage() - ) - event = json.loads(record.getMessage().split("CPU_KV_RELOAD_VERIFIED ", 1)[1]) - assert event["event"] == "CPU_KV_RELOAD_VERIFIED" and event["verified"] is True - assert event["request_id"] == request_id - assert event["layers_verified"] == 1 - assert event["bytes"] > 0 and event["rank"] == rank - # Disabled verification still restores the KV and emits no verification record. - false_request_id = request_id + "-verification-disabled" - with monkeypatch.context() as patcher: - patcher.setattr( - cpu_offload.torch, "equal", - lambda *_args, **_kwargs: pytest.fail("verification ran while disabled"), - ) - connector.verify_reload = False - connector._reload({ - "key": key, "source_tp": source_tp, "num_tokens": 32, - "num_local_tokens": 16, "block_ids": [0, 3], - "request_id": false_request_id, - }) - assert torch.equal(native_cache_block(native, layout, 3).cpu(), expected[:, 0]) - assert not any( - false_request_id in record.getMessage() for record in caplog.records - ) diff --git a/tests/test_vllm_hot_reload.py b/tests/test_vllm_hot_reload.py deleted file mode 100644 index 60423e6..0000000 --- a/tests/test_vllm_hot_reload.py +++ /dev/null @@ -1,155 +0,0 @@ -import importlib.util -import json -from pathlib import Path -from types import SimpleNamespace -from unittest.mock import Mock - -import pytest - -from RL_Framework.vllm_hot_reload import InplaceReloadWorkerExtension - - -def _checkpoint(tmp_path: Path) -> Path: - checkpoint = tmp_path / "checkpoint" - checkpoint.mkdir() - (checkpoint / "config.json").write_text("{}", encoding="utf-8") - (checkpoint / "model.safetensors").write_bytes(b"weights") - return checkpoint - - -def _extension(monkeypatch, load_model): - synchronize = Mock() - monkeypatch.setitem( - __import__("sys").modules, - "torch", - SimpleNamespace(cuda=SimpleNamespace(synchronize=synchronize)), - ) - extension = InplaceReloadWorkerExtension() - extension.rank = 3 - extension.model_runner = SimpleNamespace( - model_config=SimpleNamespace(model="/models/old"), - load_model=load_model, - ) - extension.model_config = SimpleNamespace(model="/models/old") - extension.vllm_config = SimpleNamespace( - model_config=SimpleNamespace(model="/models/old") - ) - return extension, synchronize - - -def test_worker_extension_reloads_resident_model(monkeypatch, tmp_path): - load_model = Mock() - extension, synchronize = _extension(monkeypatch, load_model) - checkpoint = _checkpoint(tmp_path) - - result = extension.reload_weights(str(checkpoint)) - - load_model.assert_called_once_with() - synchronize.assert_called_once_with() - assert extension.model_runner.model_config.model == str(checkpoint) - assert extension.model_config.model == str(checkpoint) - assert extension.vllm_config.model_config.model == str(checkpoint) - assert result["rank"] == 3 - assert result["previous_path"] == "/models/old" - - -def test_worker_extension_restores_paths_when_reload_fails(monkeypatch, tmp_path): - extension, _ = _extension(monkeypatch, Mock(side_effect=RuntimeError("load failed"))) - checkpoint = _checkpoint(tmp_path) - - with pytest.raises(RuntimeError, match="load failed"): - extension.reload_weights(str(checkpoint)) - - assert extension.model_runner.model_config.model == "/models/old" - assert extension.model_config.model == "/models/old" - assert extension.vllm_config.model_config.model == "/models/old" - - -def test_reload_inplace_posts_checkpoint_to_reload_endpoint(monkeypatch): - script = Path(__file__).parents[1] / "scripts" / "restartable_vllm_server.py" - spec = importlib.util.spec_from_file_location("restartable_vllm_server", script) - module = importlib.util.module_from_spec(spec) - assert spec.loader is not None - spec.loader.exec_module(module) - captured = {} - - class Response: - status = 200 - - def __enter__(self): - return self - - def __exit__(self, *_args): - return False - - def read(self): - return b'{"workers": [{"rank": 0}]}' - - def urlopen(request, timeout): - captured["url"] = request.full_url - captured["payload"] = json.loads(request.data.decode("utf-8")) - captured["timeout"] = timeout - return Response() - - monkeypatch.setattr(module.urllib.request, "urlopen", urlopen) - - result = module.reload_inplace( - "http://127.0.0.1:8000/health", - "/checkpoints/v2", - 30.0, - ) - - assert captured == { - "url": "http://127.0.0.1:8000/reload_weights", - "payload": { - "checkpoint_path": "/checkpoints/v2", - "timeout_seconds": 30.0, - }, - "timeout": 40.0, - } - assert result == {"workers": [{"rank": 0}]} - - -def test_reload_nccl_posts_transport_metadata(monkeypatch): - script = Path(__file__).parents[1] / "scripts" / "restartable_vllm_server.py" - spec = importlib.util.spec_from_file_location("restartable_vllm_server_nccl", script) - module = importlib.util.module_from_spec(spec) - assert spec.loader is not None - spec.loader.exec_module(module) - captured = {} - - class Response: - status = 200 - - def __enter__(self): - return self - - def __exit__(self, *_args): - return False - - def read(self): - return b'{"workers": [{"nccl_rank": 1}]}' - - def urlopen(request, timeout): - captured["url"] = request.full_url - captured["payload"] = json.loads(request.data.decode("utf-8")) - captured["timeout"] = timeout - return Response() - - monkeypatch.setattr(module.urllib.request, "urlopen", urlopen) - payload = { - "host": "10.0.0.1", - "port": 29621, - "world_size": 3, - "rank_offset": 0, - "timeout_seconds": 30.0, - } - - result = module.reload_nccl("http://127.0.0.1:8000/health", payload, 30.0) - - assert captured == { - "url": "http://127.0.0.1:8000/reload_weights_nccl", - "payload": payload, - "timeout": 40.0, - } - assert result["workers"][0]["nccl_rank"] == 1 diff --git a/trainer/async_rl_trainer.py b/trainer/async_rl_trainer.py index ff82346..a0a40ff 100644 --- a/trainer/async_rl_trainer.py +++ b/trainer/async_rl_trainer.py @@ -117,13 +117,11 @@ def __init__(self, config: AsyncRLConfig): self._runtime_handled_request_ids: set[str] = set() self._runtime_done_published = False self._trace_train_phases = os.environ.get("RL_TRAIN_PHASE_TRACE", "0") == "1" - trace_enabled = self._trace_train_phases or bool( - getattr(config, "phase_trace_enabled", False) - ) + trace_enabled = self._trace_train_phases or bool(config.phase_trace_enabled) trace_dir = ( os.environ.get("RL_TRAIN_PHASE_TRACE_DIR", "") - or getattr(config, "phase_trace_dir", "") - or os.path.join(getattr(config, "log_dir", "./logs"), "phase_trace") + or config.phase_trace_dir + or os.path.join(config.log_dir, "phase_trace") ) self._phase_tracer = ( PhaseTracer( @@ -138,6 +136,15 @@ def __init__(self, config: AsyncRLConfig): self._elastic_membership_epochs: dict[str, int] = {} self._elastic_membership_run_id = "" self._pending_hybrid_training_batches: dict[str, list[dict[str, Any]]] = {} + self.control = None + self._consumed_grpo_group_ids: set[str] = set() + self._advantage_stats: dict[str, float] = {} + self._rollout_unavailable_ids: set[str] = set() + self._restored_rollouts_pending_publication: set[str] = set() + self._publication_target_ids: tuple[str, ...] | None = None + self._rollout_source_rank: int | None = None + self._rollout_source_world_size: int | None = None + self._paused_for_rollout_loan = False def _run_grp_memory_preflight(self) -> None: """Validate one complete recompute against the planned memory budget. @@ -146,20 +153,18 @@ def _run_grp_memory_preflight(self) -> None: accounts for implementation-specific temporary tensors. All ranks run the probe because MCore recompute uses tensor-parallel collectives. """ - planner_cfg = getattr(self.config, "global_resource_planner", None) - if planner_cfg is None: - return - if not bool(getattr(planner_cfg, "enabled", False)): + planner_cfg = self.config.global_resource_planner + if not planner_cfg.enabled: return - if not bool(getattr(planner_cfg, "memory_budget_check_enabled", True)): + if not planner_cfg.memory_budget_check_enabled: return - if not bool(getattr(planner_cfg, "memory_budget_dry_run_enabled", True)): + if not planner_cfg.memory_budget_dry_run_enabled: return - if not bool(getattr(self.config, "recompute_logprobs", True)): + if not self.config.recompute_logprobs: return if self.train_engine is None: return - if getattr(self.config, "train_backend", "") != "megatron_core": + if self.config.train_backend != "megatron_core": if self.is_main_process: print( "[GRP memory preflight] skipped for non-Megatron-Core " @@ -171,7 +176,6 @@ def _run_grp_memory_preflight(self) -> None: local_batch_size = self.train_engine.get_local_batch_size( self.config.batch_size ) - is_npu = getattr(self.train_engine, "device_backend", "") == "npu" probe_count = max(1, int(local_batch_size)) max_length = max(1, int(self.config.max_seq_length)) trajectories = [ @@ -201,11 +205,8 @@ def _run_grp_memory_preflight(self) -> None: if dist.is_initialized(): dist.barrier() self.train_engine.recompute_logprobs(trajectories) - if is_npu and hasattr(torch, "npu"): - # torch_npu versions used on Ascend 910B may return a - # torch.device from current_device(), while synchronize() - # expects an integer device index. - torch.npu.synchronize(int(self.local_rank)) + if torch.cuda.is_available(): + torch.cuda.synchronize(int(self.local_rank)) if dist.is_initialized(): dist.barrier() except RuntimeError as exc: @@ -219,11 +220,8 @@ def _run_grp_memory_preflight(self) -> None: raise finally: del trajectories - if is_npu and hasattr(torch, "npu"): - try: - torch.npu.empty_cache() - except Exception: - pass + if torch.cuda.is_available(): + torch.cuda.empty_cache() if self.is_main_process: print("[GRP memory preflight] passed", flush=True) @@ -256,12 +254,11 @@ def setup(self, workflow): self._configure_training_objective(workflow) self.workflow = workflow - planner_cfg = getattr(self.config, "global_resource_planner", None) + planner_cfg = self.config.global_resource_planner if ( - planner_cfg is not None - and bool(getattr(planner_cfg, "enabled", False)) - and str(getattr(planner_cfg, "initial_allocation_strategy", "configured")).lower() == "grp" - and not bool(getattr(planner_cfg, "initial_allocation_applied", False)) + planner_cfg.enabled + and planner_cfg.initial_allocation_strategy.lower() == "grp" + and not planner_cfg.initial_allocation_applied ): raise RuntimeError( "GRP startup allocation is mandatory: run the global resource " @@ -306,8 +303,8 @@ def setup(self, workflow): if self._is_rollout_source(): - hetero_cfg = getattr(self.config, "heterogeneous_rollout", None) - if hetero_cfg and hetero_cfg.enabled and hetero_cfg.instances: + hetero_cfg = self.config.heterogeneous_rollout + if hetero_cfg.enabled and hetero_cfg.instances: self._use_heterogeneous = True self._setup_heterogeneous_engine(hetero_cfg) else: @@ -389,7 +386,7 @@ def _setup_heterogeneous_engine(self, hetero_cfg): """Setup heterogeneous engine.""" self.rollout_engine = HeterogeneousRolloutEngine.from_config(self.config) if self.is_main_process: - scheduler_type = getattr(hetero_cfg.scheduling, "scheduler_type", "length_aware") + scheduler_type = hetero_cfg.scheduling.scheduler_type print(f"Using the heterogeneous rollout engine:") print(f" Scheduler type: {scheduler_type}") print(f" Number of instances: {self.rollout_engine.num_instances}") @@ -400,14 +397,14 @@ def _setup_heterogeneous_engine(self, hetero_cfg): def _setup_homogeneous_engine(self): """Setup homogeneous engine.""" - rollout_backend = str(getattr(self.config, "rollout_backend", "vllm")).lower() + rollout_backend = str(self.config.rollout_backend).lower() if rollout_backend == "mock": self.rollout_engine = MockRolloutEngine(model_path=self.config.model_path) if self.is_main_process: print("Using mock rollout engine for training-loop smoke testing") return - vllm_endpoints_str = getattr(self.config, "vllm_endpoints", "") or "" + vllm_endpoints_str = self.config.vllm_endpoints or "" if not vllm_endpoints_str: vllm_endpoints_str = os.environ.get("VLLM_ENDPOINTS", "") @@ -512,10 +509,20 @@ def _create_data_generator(self, dataset, workflow): """Create data generator.""" from torch.utils.data import DistributedSampler + source_world_size = ( + self._rollout_source_world_size + if self._rollout_source_world_size is not None + else self.train_engine.get_data_parallel_world_size() + ) + source_rank = ( + self._rollout_source_rank + if self._rollout_source_rank is not None + else self.train_engine.get_data_parallel_rank() + ) sampler = DistributedSampler( dataset, - num_replicas=int(getattr(self, "_rollout_source_world_size", self.train_engine.get_data_parallel_world_size())), - rank=int(getattr(self, "_rollout_source_rank", self.train_engine.get_data_parallel_rank()) or 0), + num_replicas=int(source_world_size), + rank=int(source_rank or 0), shuffle=True, seed=int(getattr(self.config, "seed", 0)), ) @@ -535,10 +542,12 @@ def _create_data_generator(self, dataset, workflow): sampler.set_epoch(epoch) for sample_index, batch in enumerate(dataloader): for item in batch: - group_id = ( - f"dp{getattr(self, '_rollout_source_rank', self.train_engine.get_data_parallel_rank())}:" - f"epoch{epoch}:sample{sample_index}" + dp_rank = ( + self._rollout_source_rank + if self._rollout_source_rank is not None + else self.train_engine.get_data_parallel_rank() ) + group_id = f"dp{dp_rank}:epoch{epoch}:sample{sample_index}" for rollout_index in range(n_samples): task_id = self._task_counter self._task_counter += 1 @@ -573,14 +582,12 @@ def _collect_legacy_grpo_batch(self, data_gen, batch_size: int): n_samples = int(self.config.n_samples) if batch_size < 0 or n_samples < 1 or batch_size % n_samples: raise ValueError("requested batch must contain complete GRPO groups") - planner_cfg = getattr(self.config, "global_resource_planner", None) - collection_timeout = float(getattr(planner_cfg, "runtime_batch_collection_timeout_s", 0.0)) + planner_cfg = self.config.global_resource_planner + collection_timeout = float(planner_cfg.runtime_batch_collection_timeout_s) timeout = collection_timeout if collection_timeout > 0 else None - max_retries = int(getattr(planner_cfg, "runtime_batch_collection_max_retries", 0)) + max_retries = int(planner_cfg.runtime_batch_collection_max_retries) pending = self._pending_grpo_groups - consumed = getattr(self, "_consumed_grpo_group_ids", None) - if consumed is None: - consumed = self._consumed_grpo_group_ids = set() + consumed = self._consumed_grpo_group_ids selected = [] retries = 0 while len(selected) < batch_size: @@ -741,13 +748,7 @@ def _wait_for_all_ranks_after_rollout( ) time.sleep(poll_interval) - planner_cfg = getattr(self.config, "global_resource_planner", None) - use_barrier = bool( - getattr(planner_cfg, "runtime_use_nccl_barrier_after_rollout", False) - if planner_cfg is not None - else False - ) - if use_barrier: + if self.config.global_resource_planner.runtime_use_nccl_barrier_after_rollout: dist.barrier() def _wait_for_all_ranks_before_weight_sync(self, step: int) -> None: @@ -799,13 +800,7 @@ def _wait_for_all_ranks_before_weight_sync(self, step: int) -> None: ) time.sleep(poll_interval) - planner_cfg = getattr(self.config, "global_resource_planner", None) - use_barrier = bool( - getattr(planner_cfg, "runtime_use_nccl_barrier_before_weight_sync", False) - if planner_cfg is not None - else False - ) - if use_barrier: + if self.config.global_resource_planner.runtime_use_nccl_barrier_before_weight_sync: dist.barrier() def _trace_train_phase(self, step: int, phase: str, **details: Any) -> None: @@ -985,7 +980,7 @@ def train(self, workflow, dataset=None): stats["recompute_logprob_time"] = recompute_time stats["step_time"] = step_total_time stats["version"] = self.train_engine.get_version() - stats.update(getattr(self, "_advantage_stats", {})) + stats.update(self._advantage_stats) self.stats = stats @@ -1088,7 +1083,7 @@ def _periodic_weight_sync(self, step): cancelled = self.dispatcher.cancel_queued() active = self.dispatcher.get_runtime_metrics()["staleness_running"] self.dispatcher.wait_until_idle( - timeout=float(getattr(self.config, "rollout_weight_sync_timeout_s", 1200.0)), + timeout=float(self.config.rollout_weight_sync_timeout_s), ) rollout_sync_drain = { "cancelled_dispatcher_queue": cancelled["dispatcher_queue"], @@ -1107,15 +1102,15 @@ def _periodic_weight_sync(self, step): self._wait_for_all_ranks_before_weight_sync(step) sync_start = time.time() skip_rollout_sync = ( - str(getattr(self.config, "rollout_weight_sync_mode", "")).lower() == "none" - and not bool(getattr(self.config, "require_rollout_weight_sync", True)) + str(self.config.rollout_weight_sync_mode).lower() == "none" + and not self.config.require_rollout_weight_sync ) if skip_rollout_sync: self._record_weight_sync_phase("sync_skipped") installed = False else: receipt = self._sync_weights(target_version=step + 1, reopen_restored=False) - installed = getattr(self.config, "weight_sync_mode", None) != "nccl" or receipt is not None + installed = self.config.weight_sync_mode != "nccl" or receipt is not None elapsed = time.time() - sync_start # A failed install exits above, before either routing or reservations open. if installed or not bounded: @@ -1124,7 +1119,7 @@ def _periodic_weight_sync(self, step): reopen_after_publication(self) if bounded and self.dispatcher is not None and self.staleness_manager.group_reservations_enabled: self.dispatcher.on_publication(step + 1) - if not bounded and not getattr(self, "_rollout_unavailable_ids", ()): + if not bounded and not self._rollout_unavailable_ids: self._rebind_rollout_engine_from_config(reason="after_weight_sync") if paused_here: self._resume_rollout_pipeline() @@ -1132,14 +1127,14 @@ def _periodic_weight_sync(self, step): return elapsed, rollout_sync_drain def _sync_aware_rollout_limit(self, *, step: int, batch_size: int) -> int | None: - interval = int(getattr(self.config, "sync_interval", 0) or 0) - lead_steps = int(getattr(self.config, "rollout_sync_drain_lead_steps", 0) or 0) + interval = int(self.config.sync_interval or 0) + lead_steps = int(self.config.rollout_sync_drain_lead_steps or 0) if interval <= 0 or lead_steps <= 0: return None steps_until_sync = interval - step % interval if steps_until_sync > lead_steps: return None - return min(int(getattr(self.config, "max_concurrent_rollouts", batch_size)), + return min(int(self.config.max_concurrent_rollouts), max(1, batch_size) * steps_until_sync) def _configure_sync_aware_rollout_prefetch(self, *, step: int, batch_size: int) -> None: @@ -1149,7 +1144,7 @@ def _configure_sync_aware_rollout_prefetch(self, *, step: int, batch_size: int) def _run_periodic_evaluation(self, workflow, dataset, step: int): """Run rank-0 evaluation while other ranks wait outside NCCL collectives.""" - interval = int(getattr(self.config, "eval_interval", 0) or 0) + interval = int(self.config.eval_interval or 0) if interval <= 0 or step <= 0 or step % interval != 0: return if not hasattr(workflow, "evaluate") or self.rollout_engine is None: @@ -1179,7 +1174,7 @@ def _run_periodic_evaluation(self, workflow, dataset, step: int): "EVAL_MAX_NEW_TOKENS", os.environ.get( "R2E_EVAL_MAX_NEW_TOKENS", - str(getattr(self.config, "max_new_tokens", 1024)), + str(self.config.max_new_tokens), ), ) ) @@ -1269,7 +1264,7 @@ def _sync_weights(self, target_version: int, *, reopen_restored: bool = True, in if self.is_main_process: print(f"Synchronizing weights (step={self.global_step})") - mode = str(getattr(self.config, "rollout_weight_sync_mode", "none")) + mode = str(self.config.rollout_weight_sync_mode) if instance_ids is not None and mode != "restart": raise ValueError("Checkpoint subset publication requires restart weight sync") with self._rollout_export_only_context(mode): @@ -1311,7 +1306,7 @@ def _sync_weights_nccl(self, target_version: int, *, read_state=None, instance_i """Export collectively, then wait for this request's installation ACKs.""" if str(getattr(self.train_engine, "train_backend", "")) != "megatron_core": raise ValueError("Direct NCCL rollout sync requires train_backend=megatron_core") - directory_value = str(getattr(self.config, "rollout_weight_sync_control_dir", "") or "") + directory_value = str(self.config.rollout_weight_sync_control_dir or "") if not directory_value: raise ValueError("NCCL weight synchronization requires rollout_weight_sync_control_dir") directory = Path(directory_value).resolve() @@ -1383,9 +1378,9 @@ def record_tensor(_name, size_bytes): def send_export(weights): send_weights(weights, NcclReloadSpec(host=request["nccl_host"], port=request["nccl_port"], world_size=world, rank=0, device=torch.cuda.current_device(), - timeout_s=float(getattr(self.config, "rollout_weight_sync_timeout_s", 1200.0)), + timeout_s=float(self.config.rollout_weight_sync_timeout_s), chunk_bytes=request["nccl_chunk_bytes"], session_id=request["nccl_session_id"], - rate_limit_gbps=float(getattr(self.config, "rollout_nccl_rate_limit_gbps", 0.0))), + rate_limit_gbps=float(self.config.rollout_nccl_rate_limit_gbps)), on_tensor=record_tensor, keepalive=keepalive) try: @@ -1395,7 +1390,7 @@ def send_export(weights): outcome = None if self.is_main_process: try: - timeout = float(getattr(self.config, "rollout_weight_sync_timeout_s", 1200.0)) + timeout = float(self.config.rollout_weight_sync_timeout_s) deadline = time.monotonic() + timeout if timeout > 0 else float("inf") pending = set(offsets) records = {} @@ -1417,7 +1412,7 @@ def send_export(weights): if pending: if time.monotonic() >= deadline: raise TimeoutError(f"Timed out waiting for NCCL reload: {sorted(pending)}") - time.sleep(float(getattr(self.config, "rollout_weight_sync_poll_interval_s", .05))) + time.sleep(float(self.config.rollout_weight_sync_poll_interval_s)) rows = verify_nccl_publication(request, targets, previous, read_ack=records.__getitem__) receipt = dict(version=target_version, snapshot_id=request["snapshot_id"], optimizer_revision=request["optimizer_revision"], targets=targets, @@ -1454,7 +1449,7 @@ def _rollout_export_only_context(self, mode: str): enabled = ( mode == "restart" and str(getattr(self.train_engine, "train_backend", "")) == "megatron_core" - and bool(getattr(self.config, "rollout_weight_sync_export_only", True)) + and bool(self.config.rollout_weight_sync_export_only) ) if not enabled: yield @@ -1472,9 +1467,7 @@ def _rollout_export_only_context(self, mode: str): def _sync_rollout_restart_with_sentinel(self, target_version: int, *, instance_ids=None) -> None: """Reload rollout servers without parking non-zero ranks in NCCL.""" - control_dir_value = str( - getattr(self.config, "rollout_weight_sync_control_dir", "") or "" - ) + control_dir_value = str(self.config.rollout_weight_sync_control_dir or "") if not control_dir_value: raise ValueError("restart weight synchronization requires rollout_weight_sync_control_dir") control_dir = Path(control_dir_value).resolve() @@ -1529,9 +1522,7 @@ def _sync_rollout_restart_with_sentinel(self, target_version: int, *, instance_i raise else: self._record_weight_sync_phase("waiting_for_rollout_reload") - timeout = float( - getattr(self.config, "rollout_weight_sync_timeout_s", 1200.0) - ) + timeout = float(self.config.rollout_weight_sync_timeout_s) deadline = time.monotonic() + timeout + 300.0 while not done_path.exists() and not error_path.exists(): if time.monotonic() > deadline: @@ -1576,8 +1567,8 @@ def _reload_rollout_from_checkpoint( instance_ids=None, snapshot_id=None, ) -> None: - mode = str(getattr(self.config, "rollout_weight_sync_mode", "none")) - required = bool(getattr(self.config, "require_rollout_weight_sync", False)) + mode = str(self.config.rollout_weight_sync_mode) + required = bool(self.config.require_rollout_weight_sync) if mode == "none": if required: raise RuntimeError( @@ -1588,9 +1579,7 @@ def _reload_rollout_from_checkpoint( if mode != "restart": raise ValueError(f"Unsupported rollout_weight_sync_mode: {mode}") - control_dir_value = str( - getattr(self.config, "rollout_weight_sync_control_dir", "") or "" - ) + control_dir_value = str(self.config.rollout_weight_sync_control_dir or "") if not control_dir_value: raise ValueError("restart weight synchronization requires rollout_weight_sync_control_dir") control_dir = Path(control_dir_value).resolve() @@ -1604,17 +1593,13 @@ def _reload_rollout_from_checkpoint( publication_targets(self.config, instance_ids=instance_ids)] if not instance_ids: return - reload_method = str( - getattr(self.config, "rollout_weight_reload_method", "restart") - ).lower() + reload_method = str(self.config.rollout_weight_reload_method).lower() if reload_method not in {"restart", "inplace"}: raise ValueError( "rollout_weight_reload_method must be 'restart' or 'inplace', " f"got {reload_method!r}" ) - reload_strategy = str( - getattr(self.config, "rollout_weight_reload_strategy", "parallel") - ).lower() + reload_strategy = str(self.config.rollout_weight_reload_strategy).lower() if reload_strategy not in {"parallel", "serial"}: raise ValueError( "rollout_weight_reload_strategy must be 'parallel' or 'serial', " @@ -1643,9 +1628,7 @@ def _reload_rollout_from_checkpoint( request_tmp.write_text(json.dumps(request), encoding="utf-8") request_tmp.replace(request_path) - timeout = float( - getattr(self.config, "rollout_weight_sync_timeout_s", 1200.0) - ) + timeout = float(self.config.rollout_weight_sync_timeout_s) deadline = time.monotonic() + timeout pending = set(instance_ids) acknowledgements = {} @@ -1719,9 +1702,7 @@ def _record_rollout_weight_version( checkpoint_path: str, instance_ids: list[str], ) -> None: - control_dir_value = str( - getattr(self.config, "rollout_weight_sync_control_dir", "") or "" - ) + control_dir_value = str(self.config.rollout_weight_sync_control_dir or "") if not control_dir_value: return self._write_json_atomic( @@ -1732,7 +1713,7 @@ def _record_rollout_weight_version( "checkpoint_path": checkpoint_path, "instances": sorted(instance_ids), "updated_at": time.time(), - "mode": str(getattr(self.config, "rollout_weight_sync_mode", "none")), + "mode": str(self.config.rollout_weight_sync_mode), }, ) @@ -1837,7 +1818,7 @@ def _cleanup_old_weights(self): for v in to_delete: try: weight_dir = Path(version_dir_map[v]).resolve() - model_path_value = str(getattr(self.config, "model_path", "") or "") + model_path_value = str(self.config.model_path or "") if model_path_value and Path(model_path_value).resolve() == weight_dir: if self.is_main_process: print(f"Preserving resume source weights: {weight_dir}") @@ -1901,11 +1882,8 @@ def _cleanup(self, *, wait_for_hybrid_tasks=False): raise failure else: if protocol is not None: - planner_cfg = getattr(self.config, "global_resource_planner", None) protocol.wait_runtime_done( - timeout=float( - getattr(planner_cfg, "runtime_drain_timeout_s", 3600.0) - ) + timeout=float(self.config.global_resource_planner.runtime_drain_timeout_s) ) if self.runtime_elastic_executor is not None: self.runtime_elastic_executor.close() @@ -2012,19 +1990,17 @@ def _log_to_wandb(self, stats: dict, step: int): def _init_global_resource_planner(self): """Init global resource planner.""" - planner_cfg = getattr(self.config, "global_resource_planner", None) - if (planner_cfg is not None and getattr(planner_cfg, "enabled", False) - and getattr(planner_cfg, "runtime_coordinate_reconfiguration_ranks", True)): + planner_cfg = self.config.global_resource_planner + if planner_cfg.enabled and planner_cfg.runtime_coordinate_reconfiguration_ranks: self._runtime_boundary_protocol = RuntimeBoundaryProtocol( self._runtime_reconfiguration_coord_dir(), self.rank, self.world_size, - timeout=float(getattr(planner_cfg, "runtime_peer_request_wait_s", 45.0)), + timeout=float(planner_cfg.runtime_peer_request_wait_s), ) self._runtime_boundary_protocol.join() if not self.is_main_process: self._start_runtime_reconfiguration_follower() return - planner_cfg = getattr(self.config, "global_resource_planner", None) - if planner_cfg is None or not getattr(planner_cfg, "enabled", False): + if not planner_cfg.enabled: return if not self.train_engine or not self._is_rollout_source(): return @@ -2046,9 +2022,9 @@ def _init_global_resource_planner(self): self.runtime_elastic_executor.runtime_run_id = self._runtime_boundary_protocol.run_id if self._elastic_gradient_server is not None: self.runtime_elastic_executor.gradient_server = self._elastic_gradient_server - if getattr(planner_cfg, "runtime_async_planning", True): + if planner_cfg.runtime_async_planning: self._grp_executor = ThreadPoolExecutor( - max_workers=max(1, int(getattr(planner_cfg, "runtime_max_pending_plans", 1) or 1)), + max_workers=max(1, int(planner_cfg.runtime_max_pending_plans or 1)), thread_name_prefix="global-resource-planner", ) print( @@ -2056,22 +2032,21 @@ def _init_global_resource_planner(self): f"interval={planner_cfg.plan_interval} " f"min_history={planner_cfg.min_history_size} " f"gain_threshold={planner_cfg.min_gain_ratio:.2%} " - f"async={getattr(planner_cfg, 'runtime_async_planning', True)}" + f"async={planner_cfg.runtime_async_planning}" ) def _initialize_elastic_communication_domains(self) -> None: """Create the isolated elastic CCL domain on every training rank.""" - planner_cfg = getattr(self.config, "global_resource_planner", None) - if planner_cfg is None or not getattr(planner_cfg, "enabled", False): + planner_cfg = self.config.global_resource_planner + if not planner_cfg.enabled: return - if not any( - bool(getattr(planner_cfg, name, False)) - for name in ("elastic_hybrid_planning_enabled", "hybrid_worker_launch_enabled", "elastic_hybrid_require_isolated_ccl") + if not ( + planner_cfg.elastic_hybrid_planning_enabled + or planner_cfg.hybrid_worker_launch_enabled + or planner_cfg.elastic_hybrid_require_isolated_ccl ): return - if not bool(getattr(planner_cfg, "decouple_communication_domains", True)): - return - if not bool(getattr(planner_cfg, "elastic_hybrid_require_isolated_ccl", False)) and not bool(getattr(planner_cfg, "decouple_communication_domains", True)): + if not planner_cfg.decouple_communication_domains: return initializer = getattr( self.train_engine, @@ -2094,49 +2069,49 @@ def _initialize_elastic_communication_domains(self) -> None: def _init_nonblocking_elastic_core(self) -> None: """Start one gradient endpoint per training rank for EHP lanes.""" - planner_cfg = getattr(self.config, "global_resource_planner", None) - if planner_cfg is None or not bool(getattr(planner_cfg, "enabled", False)): + planner_cfg = self.config.global_resource_planner + if not planner_cfg.enabled: return - if not any(bool(getattr(planner_cfg, name, False)) for name in ("elastic_hybrid_planning_enabled", "hybrid_worker_launch_enabled")): + if not (planner_cfg.elastic_hybrid_planning_enabled or planner_cfg.hybrid_worker_launch_enabled): return configure = getattr(self.train_engine, "configure_elastic_training", None) if not callable(configure): raise RuntimeError("EHP requires train-engine elastic gradient hooks") core_ids = list(getattr(self.train_engine, "get_elastic_core_replica_ids", lambda: ["dp0"])()) replica_width = ( - max(1, int(getattr(self.config, "train_tp_size", 1) or 1)) - * max(1, int(getattr(self.config, "train_pp_size", 1) or 1)) - * max(1, int(getattr(self.config, "train_cp_size", 1) or 1)) + max(1, int(self.config.train_tp_size or 1)) + * max(1, int(self.config.train_pp_size or 1)) + * max(1, int(self.config.train_cp_size or 1)) ) try: domain = configure( core_ids, - decouple_communication_domains=bool(getattr(planner_cfg, "decouple_communication_domains", True)), + decouple_communication_domains=bool(planner_cfg.decouple_communication_domains), replica_world_size=replica_width, ) except TypeError: - domain = configure(core_ids, decouple_communication_domains=bool(getattr(planner_cfg, "decouple_communication_domains", True))) + domain = configure(core_ids, decouple_communication_domains=bool(planner_cfg.decouple_communication_domains)) setter = getattr(self.train_engine, "set_elastic_active_gradient_timeout", None) if callable(setter): - setter(float(getattr(planner_cfg, "hybrid_active_gradient_timeout_s", 300.0))) - task_dir = Path(getattr(planner_cfg, "hybrid_worker_task_dir", "./logs/elastic_training_tasks")) + setter(float(planner_cfg.hybrid_active_gradient_timeout_s)) + task_dir = Path(planner_cfg.hybrid_worker_task_dir) task_dir.mkdir(parents=True, exist_ok=True) - endpoint_dir = Path(getattr(planner_cfg, "hybrid_worker_endpoint_dir", "") or task_dir) / "core_endpoints" + endpoint_dir = Path(planner_cfg.hybrid_worker_endpoint_dir or task_dir) / "core_endpoints" endpoint_dir.mkdir(parents=True, exist_ok=True) server = ElasticGradientServer( - host=str(getattr(planner_cfg, "gradient_server_host", "0.0.0.0")), + host=str(planner_cfg.gradient_server_host), port=0, - authkey=str(getattr(planner_cfg, "gradient_server_authkey", "")), + authkey=str(planner_cfg.gradient_server_authkey), on_payload=self.train_engine.enqueue_hybrid_gradient_payload, - update_timeout=float(getattr(planner_cfg, "hybrid_update_timeout_s", 300.0)), + update_timeout=float(planner_cfg.hybrid_update_timeout_s), ) endpoint = server.start() self._elastic_gradient_server = server if self.is_main_process and self.runtime_elastic_executor is not None: self.runtime_elastic_executor.gradient_server = server lane = getattr(self.train_engine, "get_elastic_lane_state", lambda: {})() - public_host = str(getattr(planner_cfg, "gradient_server_public_host", "") or socket.gethostname()) + public_host = str(planner_cfg.gradient_server_public_host or socket.gethostname()) self._write_json_atomic( endpoint_dir / f"rank_{self.rank}.json", {**endpoint.to_dict(), **lane, "host": public_host, "backend": "tcp"}, @@ -2163,10 +2138,10 @@ def publish_update(update: GradientUpdate) -> None: callback_setter(publish_update) def _start_runtime_reconfiguration_follower(self) -> None: - planner_cfg = getattr(self.config, "global_resource_planner", None) - if planner_cfg is None or not getattr(planner_cfg, "enabled", False): + planner_cfg = self.config.global_resource_planner + if not planner_cfg.enabled: return - if not getattr(planner_cfg, "runtime_coordinate_reconfiguration_ranks", True): + if not planner_cfg.runtime_coordinate_reconfiguration_ranks: return if self.train_engine is not None and not self._is_rollout_source(): return @@ -2195,12 +2170,7 @@ def follow_loop() -> None: self._runtime_follow_thread.start() def _runtime_reconfiguration_coord_dir(self) -> Path: - planner_cfg = getattr(self.config, "global_resource_planner", None) - configured = ( - getattr(planner_cfg, "runtime_reconfiguration_coord_dir", "") - if planner_cfg is not None - else "" - ) + configured = self.config.global_resource_planner.runtime_reconfiguration_coord_dir if configured: return Path(configured) return Path(self.config.log_dir) / "runtime_reconfiguration" @@ -2209,12 +2179,12 @@ def _runtime_reconfiguration_pending_path(self) -> Path: return self._runtime_reconfiguration_coord_dir() / "planning_pending.json" def _write_runtime_reconfiguration_pending(self, step: int) -> None: - planner_cfg = getattr(self.config, "global_resource_planner", None) - if planner_cfg is None or not getattr(planner_cfg, "enabled", False): + planner_cfg = self.config.global_resource_planner + if not planner_cfg.enabled: return coord_dir = self._runtime_reconfiguration_coord_dir() coord_dir.mkdir(parents=True, exist_ok=True) - wait_s = float(getattr(planner_cfg, "runtime_peer_request_wait_s", 45.0)) + wait_s = float(planner_cfg.runtime_peer_request_wait_s) self._write_json_atomic( self._runtime_reconfiguration_pending_path(), { @@ -2313,10 +2283,10 @@ def _follow_runtime_reconfiguration_if_requested(self, *, expected_coord_id: str self._consume_runtime_reconfiguration_request(expected_coord_id=expected_coord_id) def _consume_runtime_reconfiguration_request(self, *, expected_coord_id: str = "") -> None: - planner_cfg = getattr(self.config, "global_resource_planner", None) - if planner_cfg is None or not getattr(planner_cfg, "enabled", False): + planner_cfg = self.config.global_resource_planner + if not planner_cfg.enabled: return - if not getattr(planner_cfg, "runtime_coordinate_reconfiguration_ranks", True): + if not planner_cfg.runtime_coordinate_reconfiguration_ranks: return if expected_coord_id and expected_coord_id in self._runtime_handled_request_ids: return @@ -2332,7 +2302,7 @@ def _consume_runtime_reconfiguration_request(self, *, expected_coord_id: str = " return try: request = json.loads(request_path.read_text(encoding="utf-8")) - except Exception: + except (OSError, json.JSONDecodeError): return current_job_id = os.environ.get("SLURM_JOB_ID", os.environ.get("JOB_ID", "")) request_job_id = str(request.get("job_id", "")) @@ -2348,7 +2318,8 @@ def _consume_runtime_reconfiguration_request(self, *, expected_coord_id: str = " resource_reconfiguration = bool(request.get("resource_reconfiguration", True)) drain_topology = resource_reconfiguration and bool( - getattr(planner_cfg, "runtime_drain_before_reconfigure", True)) + planner_cfg.runtime_drain_before_reconfigure + ) if resource_reconfiguration and not drain_topology and not expected_coord_id: self._follow_applied_runtime_reconfiguration_if_available(coord_dir) return @@ -2365,18 +2336,14 @@ def _consume_runtime_reconfiguration_request(self, *, expected_coord_id: str = " self.dispatcher.pause() if hasattr(self.dispatcher, "wait_until_idle"): self.dispatcher.wait_until_idle( - timeout=float( - getattr(planner_cfg, "runtime_drain_timeout_s", 3600.0) - ) + timeout=float(planner_cfg.runtime_drain_timeout_s) ) if ( drain_rollout and self.rollout_engine is not None and hasattr(self.rollout_engine, "wait_until_idle") ): self.rollout_engine.wait_until_idle( - timeout=float( - getattr(planner_cfg, "runtime_drain_timeout_s", 3600.0) - ) + timeout=float(planner_cfg.runtime_drain_timeout_s) ) ready_dir = coord_dir / "ready" @@ -2398,7 +2365,7 @@ def _consume_runtime_reconfiguration_request(self, *, expected_coord_id: str = " ) tmp_ready.replace(ready_path) - timeout = float(getattr(planner_cfg, "runtime_drain_timeout_s", 3600.0)) + timeout = float(planner_cfg.runtime_drain_timeout_s) deadline = time.monotonic() + timeout if timeout > 0 else None applied_path = coord_dir / "applied.json" aborted_path = coord_dir / "aborted.json" @@ -2451,7 +2418,7 @@ def _follow_applied_runtime_reconfiguration_if_available(self, coord_dir: Path) if applied_path.exists(): try: state = json.loads(applied_path.read_text(encoding="utf-8")) - except Exception: + except (OSError, json.JSONDecodeError): return else: state = self._runtime_reconfiguration_state_from_manifest() @@ -2501,13 +2468,14 @@ def _rollout_engine_endpoint_keys(self) -> set[str]: endpoints.add(endpoint.rstrip("/")) return endpoints + def _runtime_reconfiguration_state_from_manifest(self) -> dict[str, Any] | None: manifest_path = Path(self.config.log_dir) / "global_resource_rollout_manifest.json" if not manifest_path.exists(): return None try: manifest = json.loads(manifest_path.read_text(encoding="utf-8")) - except Exception: + except (OSError, json.JSONDecodeError): return None if (str(manifest.get("phase", "")) != "applied" or not self._runtime_state_is_current(manifest)): @@ -2582,28 +2550,18 @@ def _rebind_rollout_engine_from_config(self, *, reason: str) -> None: self.rollout_engine.reconfigure_from_plan(None, self.config) if hasattr(self.rollout_engine, "wait_for_ready"): self.rollout_engine.wait_for_ready( - timeout=float( - getattr( - self.config.global_resource_planner, - "vllm_ready_timeout_s", - 300.0, - ) - ) + timeout=float(self.config.global_resource_planner.vllm_ready_timeout_s) ) - executor = getattr(self, "runtime_elastic_executor", None) + executor = self.runtime_elastic_executor if executor is not None: executor.rollout_engine = self.rollout_engine if self.is_main_process: - instances = getattr(self.config.heterogeneous_rollout, "instances", []) - default_host = ( - getattr(self.config.heterogeneous_rollout, "vllm_host", "") - or "127.0.0.1" - ) + instances = self.config.heterogeneous_rollout.instances + default_host = self.config.heterogeneous_rollout.vllm_host or "127.0.0.1" if default_host == "0.0.0.0": default_host = "127.0.0.1" endpoints = [ - f"{getattr(inst, 'host', '') or default_host}:" - f"{getattr(inst, 'port', '')}" + f"{inst.host or default_host}:{inst.port}" for inst in instances ] print( @@ -2653,16 +2611,10 @@ def _apply_training_reconfiguration_state(self, state: dict[str, Any]) -> None: core_ids = [str(item) for item in state.get("core_replica_ids") or []] if not core_ids: - dp = max(1, int(getattr(self.config, "train_dp_size", 1) or 1)) + dp = max(1, int(self.config.train_dp_size or 1)) core_ids = [f"dp{i}" for i in range(dp)] - decoupled = bool( - getattr( - self.config.global_resource_planner, - "decouple_communication_domains", - True, - ) - ) + decoupled = bool(self.config.global_resource_planner.decouple_communication_domains) configure = getattr(self.train_engine, "configure_elastic_training", None) if callable(configure): try: @@ -2679,11 +2631,7 @@ def _apply_training_reconfiguration_state(self, state: dict[str, Any]) -> None: core_replica_ids=core_ids, decouple_communication_domains=decoupled, require_isolated_process_group=bool( - getattr( - self.config.global_resource_planner, - "elastic_hybrid_require_isolated_ccl", - False, - ) + self.config.global_resource_planner.elastic_hybrid_require_isolated_ccl ), ) setter = getattr(self.train_engine, "set_elastic_gradient_domain", None) @@ -2753,13 +2701,27 @@ def _initialize_rollout_source_layout(self) -> None: ) def _is_rollout_source(self) -> bool: - if hasattr(self, "_rollout_source_rank"): - return self._rollout_source_rank is not None + if self._rollout_source_rank is not None: + return True + if self._rollout_source_world_size is not None: + return False return self.train_engine.is_batch_source() def _source_batch_sample_count(self) -> int: - source_size = int(getattr(self, "_rollout_source_world_size", self.train_engine.get_data_parallel_world_size())) - source_rank = getattr(self, "_rollout_source_rank", self.train_engine.get_data_parallel_rank()) + source_size = int( + self._rollout_source_world_size + if self._rollout_source_world_size is not None + else self.train_engine.get_data_parallel_world_size() + ) + source_rank = ( + self._rollout_source_rank + if self._rollout_source_rank is not None + else ( + None + if self._rollout_source_world_size is not None + else self.train_engine.get_data_parallel_rank() + ) + ) if source_rank is None: return 0 counts = complete_group_sample_counts( @@ -2782,15 +2744,20 @@ def _collect_fixed_global_batch(self, data_gen, source_count, active_hybrid_ids) ) except Exception as exc: trajectories, error = [], f"{type(exc).__name__}: {exc}" + source_rank = ( + self._rollout_source_rank + if self._rollout_source_rank is not None + else self.train_engine.get_data_parallel_rank() + ) record = { - "source_rank": int(getattr(self, "_rollout_source_rank", self.train_engine.get_data_parallel_rank())), + "source_rank": int(source_rank), "trajectories": trajectories, "error": error, } # Rollout may run longer than the NCCL process-group timeout. Wait # through the existing out-of-band readiness protocol before entering # the data collective, including on a source that collected an error. self._wait_for_all_ranks_after_rollout( - int(getattr(self, "global_step", 0)), + int(self.global_step), record["trajectories"] if record is not None else [], ) if dist.is_available() and dist.is_initialized(): @@ -2817,7 +2784,11 @@ def _collect_fixed_global_batch(self, data_gen, source_count, active_hybrid_ids) if source["source_rank"] in sources: raise RuntimeError(f"multiple logical batch sources for {source['source_rank']}") sources[source["source_rank"]] = source - source_size = int(getattr(self, "_rollout_source_world_size", self.train_engine.get_data_parallel_world_size())) + source_size = int( + self._rollout_source_world_size + if self._rollout_source_world_size is not None + else self.train_engine.get_data_parallel_world_size() + ) if set(sources) != set(range(source_size)): raise RuntimeError("missing logical batch source") dp_size = int(self.train_engine.get_data_parallel_world_size()) @@ -2865,12 +2836,12 @@ def _assign_fixed_global_batch(self, step, global_batch, participants): return core_batch def _refresh_nonblocking_elastic_membership(self) -> None: - planner_cfg = getattr(self.config, "global_resource_planner", None) + planner_cfg = self.config.global_resource_planner domain = getattr(self.train_engine, "elastic_gradient_domain", None) run_id = self._elastic_membership_run_id - if domain is None or planner_cfg is None or not run_id: + if domain is None or not run_id: return - membership_dir = Path(getattr(planner_cfg, "hybrid_worker_task_dir", "./logs/elastic_training_tasks")) / "membership" + membership_dir = Path(planner_cfg.hybrid_worker_task_dir) / "membership" for path in membership_dir.glob("*.json"): try: state = json.loads(path.read_text(encoding="utf-8")) @@ -2900,9 +2871,9 @@ def _dispatch_hybrid_training_batches(self, step: int) -> None: if not self._pending_hybrid_training_batches or not self.is_main_process: return planner_cfg = self.config.global_resource_planner - task_dir = Path(getattr(planner_cfg, "hybrid_worker_task_dir", "./logs/elastic_training_tasks")) + task_dir = Path(planner_cfg.hybrid_worker_task_dir) task_dir.mkdir(parents=True, exist_ok=True) - lockstep = bool(getattr(planner_cfg, "hybrid_lockstep_gradient_sync", True)) + lockstep = bool(planner_cfg.hybrid_lockstep_gradient_sync) domain = getattr(self.train_engine, "elastic_gradient_domain", None) frozen_epochs = domain.membership_state().get("membership_epochs", {}) if domain is not None else {} state_version = int(getattr(self.train_engine, "optimizer_revision", self.train_engine.get_version())) @@ -2954,12 +2925,10 @@ def _dispatch_hybrid_training_batches(self, step: int) -> None: self._pending_hybrid_training_batches.clear() def _runtime_length_profile_path(self) -> str: - planner_cfg = getattr(self.config, "global_resource_planner", None) - if planner_cfg is None: - return "" - if not getattr(planner_cfg, "runtime_length_profile_enabled", True): + planner_cfg = self.config.global_resource_planner + if not planner_cfg.runtime_length_profile_enabled: return "" - return str(getattr(planner_cfg, "runtime_length_profile_jsonl", "") or "") + return str(planner_cfg.runtime_length_profile_jsonl or "") def _refresh_global_resource_history_from_profile( self, @@ -3000,7 +2969,7 @@ def _run_global_resource_planner(self, step: int, batch: list, stats: dict): runtime_profile_path = self._runtime_length_profile_path() if runtime_profile_path: self.global_resource_planner.observe_training_batch(batch) - if not getattr(planner_cfg, "runtime_async_planning", True): + if not planner_cfg.runtime_async_planning: profile_records = self._refresh_global_resource_history_from_profile( step=step, stats=stats, @@ -3253,13 +3222,7 @@ def _apply_global_resource_planner_decision(self, step: int, decision, stats: di "wait_until_idle", ): self.dispatcher.wait_until_idle( - timeout=float( - getattr( - self.config.global_resource_planner, - "runtime_drain_timeout_s", - 3600.0, - ) - ) + timeout=float(self.config.global_resource_planner.runtime_drain_timeout_s) ) print( "[RuntimeElasticExecutor] rollout pipeline drained " @@ -3283,7 +3246,7 @@ def _apply_global_resource_planner_decision(self, step: int, decision, stats: di # already installed the weights and rebuilt these clients. if (prepared.resource_reconfiguration and prepared.rollout_runtime_enabled and getattr(self.runtime_elastic_executor, "trainer", None) is not self - and not getattr(self, "_rollout_unavailable_ids", ())): + and not self._rollout_unavailable_ids): self._rebind_rollout_engine_from_config( reason="after_runtime_reconfiguration" ) @@ -3311,35 +3274,17 @@ def _pause_rollout_pipeline(self) -> None: self.dispatcher.pause() def _resume_rollout_pipeline(self) -> None: - instances = getattr(getattr(self.config, "heterogeneous_rollout", None), "instances", ()) - if instances and len(getattr(self, "_rollout_unavailable_ids", ())) == len(instances): + instances = self.config.heterogeneous_rollout.instances + if instances and len(self._rollout_unavailable_ids) == len(instances): return if self.dispatcher is not None and hasattr(self.dispatcher, "resume"): self.dispatcher.resume() def _should_pre_reset_rollout_pipeline_for_reconfigure(self) -> bool: - grp_cfg = getattr(self.config, "global_resource_planner", None) - if grp_cfg is None: - return False - strategy = str( - getattr( - grp_cfg, - "runtime_rollout_reconfigure_strategy", - getattr(grp_cfg, "rollout_reconfigure_strategy", "restart_all"), - ) - ).lower() - cluster_swap = bool( - getattr(grp_cfg, "runtime_cluster_swap_enabled", False) - or strategy == "cluster_swap" - ) - drain = bool( - getattr( - grp_cfg, - "runtime_drain_before_reconfigure", - getattr(grp_cfg, "drain_before_reconfigure", True), - ) - ) - return cluster_swap and not drain + grp_cfg = self.config.global_resource_planner + strategy = str(grp_cfg.runtime_rollout_reconfigure_strategy).lower() + cluster_swap = bool(grp_cfg.runtime_cluster_swap_enabled or strategy == "cluster_swap") + return cluster_swap and not grp_cfg.runtime_drain_before_reconfigure def _record_runtime_reconfiguration_event(self, step: int, decision, result) -> None: try: @@ -3363,26 +3308,20 @@ def _init_history_collector(self): """Init history collector.""" if not self.is_main_process: return - planner_cfg = getattr(self.config, "global_resource_planner", None) - planner_enabled = bool( - planner_cfg is not None and getattr(planner_cfg, "enabled", False) - ) + planner_cfg = self.config.global_resource_planner runtime_profile_enabled = bool( - planner_enabled - and getattr(planner_cfg, "runtime_length_profile_enabled", True) + planner_cfg.enabled and planner_cfg.runtime_length_profile_enabled ) - if not getattr(self.config, "enable_history_collection", False) and not runtime_profile_enabled: + if not self.config.enable_history_collection and not runtime_profile_enabled: return - output_dir = getattr(self.config, "history_output_dir", "") or "" - if not output_dir: - output_dir = os.path.join(self.config.log_dir, "history") + output_dir = self.config.history_output_dir or os.path.join( + self.config.log_dir, "history" + ) runtime_profile_path = "" if runtime_profile_enabled: - runtime_profile_path = str( - getattr(planner_cfg, "runtime_length_profile_jsonl", "") or "" - ) + runtime_profile_path = str(planner_cfg.runtime_length_profile_jsonl or "") if not runtime_profile_path: runtime_profile_path = os.path.join( output_dir, @@ -3390,7 +3329,7 @@ def _init_history_collector(self): ) planner_cfg.runtime_length_profile_jsonl = runtime_profile_path - experiment_name = getattr(self.config, "history_experiment_name", "") or "" + experiment_name = self.config.history_experiment_name or "" # Keep history artifacts isolated per launched run. The validated # six-node configs intentionally share a history root/name so that # operators do not need to edit YAML between EHP and non-EHP runs. @@ -3404,8 +3343,8 @@ def _init_history_collector(self): self.history_collector = HistoryDataCollector( output_dir=output_dir, - save_raw_lengths=getattr(self.config, "history_save_raw_lengths", False), - flush_interval=getattr(self.config, "history_flush_interval", 10), + save_raw_lengths=self.config.history_save_raw_lengths, + flush_interval=self.config.history_flush_interval, experiment_name=experiment_name, length_profile_path=runtime_profile_path, )