diff --git a/engine/train_engine.py b/engine/train_engine.py index 61fb2b2..f923ed2 100644 --- a/engine/train_engine.py +++ b/engine/train_engine.py @@ -49,6 +49,30 @@ def _env_flag(name: str, default: bool) -> bool: return value.lower() not in {"0", "false", "no", "off"} +_DTYPE_ALIASES = { + "bfloat16": torch.bfloat16, + "bf16": torch.bfloat16, + "float16": torch.float16, + "fp16": torch.float16, + "float32": torch.float32, + "fp32": torch.float32, +} + + +def _resolve_train_dtype() -> torch.dtype: + """Resolve model/FSDP precision from FSDP_DTYPE, falling back safely on pre-Ampere GPUs.""" + raw = os.environ.get("FSDP_DTYPE", "auto").strip().lower() + if raw in ("", "auto"): + if not torch.cuda.is_available() or torch.cuda.is_bf16_supported(): + return torch.bfloat16 + return torch.float32 + if raw not in _DTYPE_ALIASES: + raise ValueError( + f"Unsupported FSDP_DTYPE={raw!r}; expected auto, bfloat16, float16, or float32" + ) + return _DTYPE_ALIASES[raw] + + def _checkpoint_only_with_grad( function: Any, *args: Any, @@ -251,9 +275,10 @@ def initialize(self, max_seq_length: int = 2048): if self.is_main_process: print(f"Loading model: {self.model_path}") + model_dtype = _resolve_train_dtype() self.model = AutoModelForCausalLM.from_pretrained( self.model_path, - torch_dtype=torch.bfloat16, + torch_dtype=model_dtype, device_map=None, trust_remote_code=True, ) @@ -279,9 +304,9 @@ def initialize(self, max_seq_length: int = 2048): if self.is_distributed: mp_policy = MixedPrecision( - param_dtype=torch.bfloat16, + param_dtype=model_dtype, reduce_dtype=torch.float32, - buffer_dtype=torch.bfloat16, + buffer_dtype=model_dtype, ) decoder_layers = getattr( getattr(self.model, "model", None), diff --git a/infra/execution/batch_dispatcher.py b/infra/execution/batch_dispatcher.py index 82ce410..0359592 100644 --- a/infra/execution/batch_dispatcher.py +++ b/infra/execution/batch_dispatcher.py @@ -469,13 +469,15 @@ def active_submit_and_wait( )) raise TimeoutError(f"active batch collection timed out: {len(results)}/{batch_size}") - with self._input_cv: + with self._input_cv, self._result_cv: pending_inputs = len(self._pending_inputs) + in_flight = len(self._active_task_ids) capacity = min( self.staleness_manager.get_pending_limit() - pending_inputs, self.runner.max_queue_size - self.runner.input_queue.qsize(), ) - for _ in range(min(batch_size - len(results), capacity)): + needed_to_submit = max(0, batch_size - len(results) - in_flight) + for _ in range(min(needed_to_submit, max(0, capacity))): try: self.submit_task_input(next(input_generator)) except StopIteration: diff --git a/repro/tier2_four_gpu_closed_loop/README.md b/repro/tier2_four_gpu_closed_loop/README.md new file mode 100644 index 0000000..38469f5 --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/README.md @@ -0,0 +1,151 @@ +# Tier 2 — 8-GPU & 4-GPU Heterogeneous Closed-Loop RL & Google Colab Quickstart + +Tier 2 provides **Slurm-free** real-GPU **end-to-end closed-loop RL** entry points (`AsyncRLTrainer` + `FSDPTrainEngine` + `DAPOMathWorkflow` + supervised `vllm_hot_reload_api_server.py` with confirmed in-place weight reloads): + +1. **8-GPU Heterogeneous Closed Loop (`1 Train + 7 Rollout [TP=1, TP=2, TP=4]`)**: Real end-to-end GRPO closed-loop training across three heterogeneous serving tiers (`TP=1` on GPU 1, `TP=2` on GPUs 2–3, `TP=4` on GPUs 4–7) with confirmed in-place vLLM weight reloads. +2. **4-GPU Heterogeneous Closed Loop (`1 Train + 3 Rollout [TP=1, TP=2]`)**: Smaller 4-GPU heterogeneous closed-loop setup (`TP=1` on GPU 1, `TP=2` on GPUs 2–3). +3. **Google Colab 1-GPU Co-Located Startup**: Single-GPU closed-loop verification with automatic VRAM/SM tier detection (`T4 16GB`, `L4 24GB`, `A100 40GB`, `A100 80GB`). + +> Looking for pure rollout scheduling policy comparison (`round_robin`, `least_connections`, `cmlfq`, `cmlfq_cost`)? See Tier 1 (`repro/tier1_zero_gpu_replay/`) in [../tier1_zero_gpu_replay/README.md](../tier1_zero_gpu_replay/README.md). Below, Tier 2 focuses on end-to-end closed-loop RL bring-up and the 8-GPU **GRP** and **EHP** system benchmarks. + +--- + +## Mode 1: 8-GPU Heterogeneous Closed Loop (`1 Train + TP=1, 2, 4`) + +Launch an 8-GPU end-to-end closed-loop RL run without Slurm (`1 × FSDPTrainEngine` on GPU `0` + `TP=1` on GPU `1` + `TP=2` on GPUs `2,3` + `TP=4` on GPUs `4..7`, `bfloat16`, `batch_size=16`, `micro_batch_size=1`, `max_model_len=6144`, `rollout_weight_reload_method=inplace`): + +```bash +# Dry-run: validate topology, CostModel profile, seeded trees, and commands without GPUs +python3 repro/tier2_four_gpu_closed_loop/launch_4gpu.py \ + --mode 8gpu \ + --gpus 0,1,2,3,4,5,6,7 \ + --dry-run + +# End-to-end real-GPU closed-loop RL run on 8x H20-3e +bash repro/tier2_four_gpu_closed_loop/run_8gpu.sh \ + --gpus 0,1,2,3,4,5,6,7 \ + --model Qwen/Qwen3-4B \ + --output-dir ./logs/tier2_8gpu +``` + +--- + +## Mode 2: 4-GPU Heterogeneous Closed Loop (No Slurm Required) + +Runs 1 FSDP trainer on GPU 0 and 2 heterogeneous vLLM rollout instances on GPUs `1` (`TP=1`) and `2,3` (`TP=2`): + +```bash +# Single policy run (default: cmlfq_cost on DAPO-Math mini + Qwen3-4B) +bash repro/tier2_four_gpu_closed_loop/run_4gpu.sh \ + --model Qwen/Qwen3-4B \ + --gpus 0,1,2,3 + +# Full policy sweep across round_robin, least_connections, and cmlfq_cost +bash repro/tier2_four_gpu_closed_loop/run_4gpu.sh \ + --model Qwen/Qwen3-4B \ + --policy all \ + --gpus 0,1,2,3 \ + --output-dir ./logs/tier2_ab + +# Example: run on a 4-GPU slice of a multi-GPU H20/A800 server +CUDA_VISIBLE_DEVICES=0,1,2,3 bash repro/tier2_four_gpu_closed_loop/run_4gpu.sh \ + --model /path/to/Qwen3-4B \ + --steps 8 \ + --output-dir ./logs/tier2_h20_4gpu +``` + +Validate configs and inspect exact commands without starting GPUs: + +```bash +python3 repro/tier2_four_gpu_closed_loop/launch_4gpu.py --dry-run +``` + +--- + +## Mode 3: Google Colab 1-GPU Co-Located Startup + +Open [colab_quickstart.ipynb](colab_quickstart.ipynb) directly in Google Colab: + +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NetX-lab/Libra/blob/main/repro/tier2_four_gpu_closed_loop/colab_quickstart.ipynb) + +Or launch locally on any single GPU (`T4` / `L4` / `A100` / `RTX`): + +```bash +python3 repro/tier2_four_gpu_closed_loop/launch_4gpu.py \ + --mode colab-1gpu \ + --colab-tier auto \ + --steps 4 +``` + +### Automatic Colab Presets (`--colab-tier auto`) + +| Preset | Trigger Condition | Model | vLLM / FSDP Dtype | KV Utilization | `max_model_len` | +| :--- | :--- | :--- | :--- | :---: | :---: | +| `t4` | `SM < 8.0` or `< 20 GiB` | `Qwen/Qwen2.5-0.5B-Instruct` | `half` / `float32` | `0.30` | `1024` | +| `l4` | `>= 20 GiB` (`SM >= 8.0`) | `Qwen/Qwen2.5-1.5B-Instruct` | `bfloat16` / `bfloat16` | `0.35` | `1536` | +| `a100-40g` | `>= 36 GiB` (`SM >= 8.0`) | `Qwen/Qwen3-1.7B` | `bfloat16` / `bfloat16` | `0.38` | `2048` | +| `a100-80g` | `>= 70 GiB` (`SM >= 8.0`) | `Qwen/Qwen3-4B` | `bfloat16` / `bfloat16` | `0.38` | `2048` | + +> Why `float32` FSDP on T4? T4 (`sm_75`) lacks hardware `bfloat16` Tensor Cores. `engine/train_engine.py` reads `FSDP_DTYPE` (`auto` falls back to `float32` when `not torch.cuda.is_bf16_supported()`), while vLLM runs in `half`. + +--- + +## GRP (Global Resource Planner) 8-GPU Benchmark + +Evaluates `PreflightPlanner` / `TwoLevelNestedOptimizer` configuration selection and closed-loop multi-GPU allocation efficiency on `8 × NVIDIA H20-3e` (`Qwen/Qwen3-4B`, `4 steps × 16 trajectories`, `n_samples=2`, `max_new_tokens=1792`, `sync_interval=4`, `inplace` weight reload): + +- **Phase 1 (Cost-Model Preflight Planning)**: Evaluates 8-GPU allocations against skewed DAPO length quartiles (`prompt=512`, `response=[128, 384, 1536, 4096]`). `PreflightPlanner` explores candidate training/rollout partitions in `15.0 ms` and selects **`1 Train (DP=1, GPU 0) + 7 Rollout (TP=[4, 2, 1], GPUs 1–7)`** (`-56.21%` predicted step time vs. fixed `4/4 TP=1`). +- **Phase 2 (Real `vLLM + FSDP` Closed-Loop Execution on `8 × H20-3e`)**: + +| Allocation | Train GPUs (Active / Reserved) | Rollout Layout & Policy | Wall Time (`steps.jsonl`) | Rollout / Train / Sync (s) | Throughput | Reload ACKs | Speedup vs `4/4 TP=1` | +| :--- | :---: | :--- | :---: | :---: | :---: | :---: | :---: | +| `fixed_4train_4rollout_tp1` | `1 / 4` | `TP=[1,1,1,1]` (`round_robin + prefix_affinity`) | `222.275 s` | `176.315 / 29.538 / 16.404` | `17.276 rollouts/min` (`314.06 tok/s`) | `4/4` | `1.000x` | +| `fixed_2train_6rollout_tp2` | `1 / 2` | `TP=[2,2,2]` (`least_connections + prefix_affinity`) | `266.654 s` | `220.797 / 29.535 / 16.304` | `14.401 rollouts/min` (`262.03 tok/s`) | `3/3` | `0.834x` (`-19.97%`) | +| **`grp_optimal_1train_7rollout_hetero`** | **`1 / 1`** | **`TP=[1,2,4]` (`cmlfq_cost`)** | **`115.375 s`** | **`69.981 / 29.353 / 16.020`** | **`33.283 rollouts/min` (`607.22 tok/s`)** | **`3/3`** | **`1.927x` (`+48.09%`)** | + +```bash +# CPU dry-run (Phase 1 planning + Phase 2 config validation without GPUs): +python3 repro/tier2_four_gpu_closed_loop/benchmark_grp.py --dry-run --output-dir /tmp/grp_dry + +# Full 8 x H20 closed-loop benchmark: +bash repro/tier2_four_gpu_closed_loop/run_grp.sh +``` + +--- + +## EHP (Elastic Hybrid Parallelism) 8-GPU Benchmark + +Verifies elastic GPU borrowing from the heterogeneous rollout pool to accelerate RL policy updates across three phases: + +- **Phase 1 (Lending Capacity & Cost Horizon)**: Verifies `loan_replica_capacity` reserve guards across an 8-GPU GRP layout (`TP=[4, 2, 1]`: lends `0`, `1`, `3` GPUs with reserve satisfied, returns `0` when breaching reserve) and `bounded_update_time` (`111.2 s -> 104.2 s -> 101.2 s`). +- **Phase 2 (`ElasticHybridPool`, `ZERO_SYNC` Safety & Gradient IPC)**: Joins `hybrid_0..2` into `HYBRID_TRAINING / ACTIVE` state, confirms `ZERO_SYNC` placeholder rejection on `step >= 0` (`ValueError`), verifies loopback `ElasticGradientClient -> ElasticGradientServer` (`3/3` ACKs, `4.586 ms` mean latency on H20), and asserts exact weighted `InterReplicaGradientDomain.reduce_core_gradients` output (`2.500000`). +- **Phase 3 (Real `Qwen/Qwen3-4B` Elastic Data-Parallel Training on `8 × H20-3e`)**: Runs `partition_complete_grpo_groups` + `ThreadPoolExecutor` (`bf16`, `sdpa`, `16` trajectories × `seq_len=1536`, `micro_batch_size=2`, `warmup=1`, `steps=3`) + compact TCP norm IPC + GPU `in_place=True` NVLink `reduce_core_gradients` + Core `AdamW` step & parameter sync: + +| Mode | Devices | Hybrid Activation | Avg Step (s) | Steady-State Step 1–2 (s) | Compute / IPC / Reduce / Opt+Sync (s) | Peak VRAM | Speedup vs `1 GPU` | `grad_norm` (Steps 0/1/2) | +| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :--- | +| `static_core_1gpu` | `cuda:0` | `0.0001 s` | `8.3562 s` | `8.3562 s` | `8.2611 / 0.0000 / 0.0023 / 0.0895` | `60.322 GB` | `1.000x` | `1.460938 / 1.46875 / 1.476562` | +| `ehp_borrow_1gpu` | `cuda:0–1` | `0.2828 s` | `4.3236 s` | `4.3234 s` | `4.1505 / 0.0026 / 0.0508 / 0.1167` | `60.239 GB` | **`1.933x`** | `1.46875 / 1.46875 / 1.476562` | +| **`ehp_borrow_3gpus`** | **`cuda:0–3`** | **`0.8206 s`** | **`3.0834 s`** | **`2.4020 s` (`3.48x`)** | `2.7612 / 0.0039 / 0.1421 / 0.1719` | `60.195 GB` | **`2.710x`** | `1.46875 / 1.46875 / 1.476562` | + +```bash +# CPU dry-run (Phase 1, Phase 2, and CPU gradient-parity verification): +python3 repro/tier2_four_gpu_closed_loop/benchmark_ehp.py --dry-run --output-dir /tmp/ehp_dry + +# Full multi-GPU H20 EHP benchmark: +bash repro/tier2_four_gpu_closed_loop/run_ehp.sh +``` + +--- + +## Bundled Sample Data, Scripts & Templates + +- [launch_4gpu.py](launch_4gpu.py), [run_8gpu.sh](run_8gpu.sh), & [run_4gpu.sh](run_4gpu.sh): Slurm-free 8-GPU (`--mode 8gpu`) and 4-GPU (`--mode 4gpu`) closed-loop RL and 1-GPU Colab (`--mode colab-1gpu`) launcher. +- [benchmark_grp.py](benchmark_grp.py) & [run_grp.sh](run_grp.sh): GRP `PreflightPlanner` cost-model verification and 3-way `8 × H20` closed-loop allocation benchmark. +- [benchmark_ehp.py](benchmark_ehp.py) & [run_ehp.sh](run_ehp.sh): EHP 3-phase rollout lending, `ElasticHybridPool` / `ZERO_SYNC` / IPC safety, and real `Qwen3-4B` multi-GPU elastic training benchmark. +- [colab_quickstart.ipynb](colab_quickstart.ipynb): End-to-end Google Colab notebook (Tier 1 replay + Tier 2 closed-loop RL). +- [sample_data/dapo_math_mini.jsonl](sample_data/dapo_math_mini.jsonl): 64 deterministic math verification problems with multi-turn rollout profiles (works offline out of the box; pass `--dataset /path/to/dapo-math-17k.parquet` for full DAPO-Math-17K). +- [sample_data/dapo_cost_profile.json](sample_data/dapo_cost_profile.json): Empirical H20-3e tier latency profile for `cmlfq_cost` in 8-GPU closed-loop evaluation. +- [config_8gpu_qwen3_4b.yaml](config_8gpu_qwen3_4b.yaml): Static 8-GPU configuration template (`1 Train + TP=1 + TP=2 + TP=4`). +- [config_4gpu_qwen3_4b.yaml](config_4gpu_qwen3_4b.yaml): Static 4-GPU configuration template (`1 Train + TP=1 + TP=2`). +- [config_colab_1gpu.yaml](config_colab_1gpu.yaml): Static 1-GPU Colab co-located configuration template. +- **Runtime dependencies**: In addition to CPU CI deps, GPU execution requires `vllm`, `transformers`, `datasets`, `sympy`, `regex`, `latex2sympy2`, and `word2number` (pre-installed by Colab notebook Cell 1). diff --git a/repro/tier2_four_gpu_closed_loop/benchmark_ehp.py b/repro/tier2_four_gpu_closed_loop/benchmark_ehp.py new file mode 100644 index 0000000..ec56b9d --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/benchmark_ehp.py @@ -0,0 +1,970 @@ +#!/usr/bin/env python3 +"""EHP (Elastic Hybrid Parallelism) 3-Phase Benchmark for 8x H20 / Tier 2. + +Verifies Elastic Hybrid Parallelism across three phases: + Phase 1: Rollout capacity lending (`loan_replica_capacity`) and elastic cost + horizon (`bounded_update_time`) over an 8-GPU heterogeneous cluster. + Phase 2: `ElasticHybridPool` worker lifecycle, `ZERO_SYNC` placeholder safety, + `InterReplicaGradientDomain` reduction, and loopback `ElasticGradientClient` + / `ElasticGradientServer` IPC. + Phase 3: Multi-GPU elastic data-parallel GRPO training (`Qwen/Qwen3-4B` on CUDA, + or lightweight deterministic CPU proxy in `--dry-run`), comparing: + - static_core_1gpu (1 GPU: cuda:0) + - ehp_borrow_1gpu (2 GPUs: cuda:0 + 1 borrowed rollout GPU) + - ehp_borrow_3gpus (4 GPUs: cuda:0 + 3 borrowed rollout GPUs) + +Usage: + # Local CPU dry-run (verifies Phase 1, Phase 2, and CPU Phase 3): + python repro/tier2_four_gpu_closed_loop/benchmark_ehp.py --dry-run \\ + --output-dir /tmp/ehp_dry_run + + # Real 8x H20 GPU benchmark: + python repro/tier2_four_gpu_closed_loop/benchmark_ehp.py \\ + --model /mnt/tidal-alsh-hilab/dataset/diandian/model/qwen3/Qwen3-4B \\ + --output-dir /workspace/libra-tier2-eval/runs/h20_8gpu_ehp +""" + +from __future__ import annotations + +import argparse +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +import gc +import json +from pathlib import Path +import random +import sys +import time +from typing import Any + +import torch +import torch.nn.functional as F + +REPO_ROOT = Path(__file__).resolve().parents[2] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from infra.cost_model.global_resource_planner import bounded_update_time +from infra.elastic.batch_partition import partition_complete_grpo_groups +from infra.elastic.gradient_ipc import ElasticGradientClient, ElasticGradientServer +from infra.elastic.hybrid_pool import ( + ElasticHybridPool, + GradientPayload, + InterReplicaGradientDomain, + JoinState, + ReplicaRole, +) +from infra.elastic.rollout_lending import loan_replica_capacity + +DEFAULT_DATASET = REPO_ROOT / "repro" / "tier2_four_gpu_closed_loop" / "sample_data" / "dapo_math_mini.jsonl" +DEFAULT_MODEL = "/mnt/tidal-alsh-hilab/dataset/diandian/model/qwen3/Qwen3-4B" + + +@dataclass(frozen=True) +class _InstanceMeta: + host: str + gpus: tuple[int, ...] + + +def run_phase1_cost_model(*, groups_per_batch: int = 16) -> dict[str, Any]: + """Verify rollout lending capacity rules and elastic bounded_update_time.""" + # Mirror an 8-GPU GRP cluster: GPU 0 is Core training, GPUs 1..7 are GRP + # heterogeneous rollout instances ([4, 2, 1]). + rollout_tp4 = _InstanceMeta(host="h20-node-0", gpus=(1, 2, 3, 4)) + rollout_tp2 = _InstanceMeta(host="h20-node-0", gpus=(5, 6)) + rollout_tp1 = _InstanceMeta(host="h20-node-0", gpus=(7,)) + rollout_instances = [rollout_tp4, rollout_tp2, rollout_tp1] + + lending_cases = { + "borrow_0_static": loan_replica_capacity( + rollout_instances, [], width=1, reserve=4 + ), + "borrow_1_from_tp1_reserve_6": loan_replica_capacity( + rollout_instances, [rollout_tp1], width=1, reserve=6 + ), + "borrow_3_from_tp1_tp2_reserve_4": loan_replica_capacity( + rollout_instances, [rollout_tp1, rollout_tp2], width=1, reserve=4 + ), + "borrow_blocked_exceeds_reserve": loan_replica_capacity( + rollout_instances, [rollout_tp1, rollout_tp2], width=1, reserve=5 + ), + } + assert lending_cases["borrow_0_static"] == 0 + assert lending_cases["borrow_1_from_tp1_reserve_6"] == 1 + assert lending_cases["borrow_3_from_tp1_tp2_reserve_4"] == 3 + assert lending_cases["borrow_blocked_exceeds_reserve"] == 0 + + base_core_train_s = 12.0 + horizon_estimates: dict[str, Any] = {} + baseline_bound_s: float | None = None + for k_borrowed in (0, 1, 3): + world = 1 + k_borrowed + eff_train_s = base_core_train_s / world + (0.45 if k_borrowed > 0 else 0.0) + bound_s = bounded_update_time( + train_s=eff_train_s, + rollout_batch_s=24.0, + groups_per_batch=groups_per_batch, + horizon=4, + max_age=2, + revision=0, + reservations=[], + publish_s=0.8, + hybrid_publish_s=0.35, + active_hybrid_replicas=k_borrowed, + core_train_s=base_core_train_s, + pending_activation=(k_borrowed > 0), + activation_s=0.35 if k_borrowed > 0 else 0.0, + activation_ready_replicas=k_borrowed, + activation_train_s=[eff_train_s] if k_borrowed > 0 else None, + activation_ready_times_s=[0.35] * k_borrowed if k_borrowed > 0 else None, + ) + if baseline_bound_s is None: + baseline_bound_s = bound_s + horizon_estimates[f"borrow_{k_borrowed}_gpus"] = { + "train_gpus": world, + "effective_train_step_s": round(eff_train_s, 4), + "bounded_update_time_s": round(bound_s, 4), + "speedup_vs_static": round(baseline_bound_s / bound_s, 3), + } + + return { + "rollout_cluster_gpus": [1, 2, 3, 4, 5, 6, 7], + "rollout_tp_layout": [4, 2, 1], + "lending_capacity_checks": lending_cases, + "bounded_update_time_estimates": horizon_estimates, + "passed": True, + } + + +def run_phase2_lifecycle_and_ipc() -> dict[str, Any]: + """Verify ElasticHybridPool lifecycle, ZERO_SYNC guard, and gradient IPC.""" + worker_ids = ["hybrid_0", "hybrid_1", "hybrid_2"] + pool = ElasticHybridPool( + core_train_workers=["dp0"], + core_rollout_workers=worker_ids, + require_state_ack=False, + zero_sync_steps=1, + ) + received_payloads: list[dict[str, Any]] = [] + + def _on_payload(payload: GradientPayload) -> None: + received_payloads.append( + { + "replica_id": payload.replica_id, + "step": payload.step, + "sample_count": payload.sample_count, + "numel": sum(t.numel() for t in payload.tensors), + } + ) + + server = ElasticGradientServer(host="127.0.0.1", port=0, on_payload=_on_payload) + try: + endpoint = server.start() + for wid in worker_ids: + handle = pool.join_training(wid, "dp0") + worker_state = handle.result(timeout=5.0) + assert worker_state.role == ReplicaRole.HYBRID_TRAINING + assert worker_state.join_state == JoinState.ACTIVE + + snapshot = pool.snapshot() + active_hybrids = [ + wid + for wid in worker_ids + if snapshot[wid].role == ReplicaRole.HYBRID_TRAINING + and snapshot[wid].join_state == JoinState.ACTIVE + ] + assert len(active_hybrids) == len(worker_ids) + + domain = pool.gradient_domain + epochs = {wid: domain.membership_epoch(wid) for wid in worker_ids} + + # Guard check: ZERO_SYNC placeholder cannot participate in an active step >= 0. + zero_sync_blocked = False + try: + bad_payload = GradientPayload( + replica_id="hybrid_0", + target_core_id="dp0", + tensors=(torch.zeros(4, dtype=torch.float32),), + zero_placeholder=True, + step=0, + state_version=0, + membership_epoch=epochs["hybrid_0"], + sample_count=4, + global_sample_count=16, + ) + domain.reduce_core_gradients( + core_gradients={"dp0": (torch.ones(4, dtype=torch.float32),)}, + hybrid_payloads=[bad_payload], + core_sample_counts={"dp0": 4}, + global_sample_count=16, + step=0, + state_version=0, + ) + except ValueError: + zero_sync_blocked = True + assert zero_sync_blocked, "ZERO_SYNC placeholder should be rejected for step >= 0" + + # Valid IPC transfer + mathematical reduction verification: + # Mean gradient across dp0 (value=1.0, 4 samples) + 3 hybrids (values=2,3,4; 4 samples each) + # Expected weighted average = (4*1 + 4*2 + 4*3 + 4*4) / 16 = 40/16 = 2.5 + client = ElasticGradientClient(endpoint, timeout=15.0) + hybrid_payloads: list[GradientPayload] = [] + ipc_latencies_ms: list[float] = [] + for idx, wid in enumerate(worker_ids): + tensor = torch.full((1024,), float(idx + 2), dtype=torch.float32) + payload = GradientPayload( + replica_id=wid, + target_core_id="dp0", + tensors=(tensor,), + zero_placeholder=False, + step=0, + state_version=0, + membership_epoch=epochs[wid], + sample_count=4, + global_sample_count=16, + stats={"worker_idx": idx}, + ) + t0 = time.perf_counter() + client.send(payload, expect_update=False) + ipc_latencies_ms.append((time.perf_counter() - t0) * 1000.0) + hybrid_payloads.append(payload) + + reduced = domain.reduce_core_gradients( + core_gradients={"dp0": (torch.full((1024,), 1.0, dtype=torch.float32),)}, + hybrid_payloads=hybrid_payloads, + core_sample_counts={"dp0": 4}, + global_sample_count=16, + step=0, + state_version=0, + in_place=True, + ) + reduced_val = float(reduced["dp0"][0].mean().item()) + assert abs(reduced_val - 2.5) < 1e-5, f"Unexpected reduced mean {reduced_val}" + assert server.received_count == len(worker_ids) + + return { + "active_hybrids": active_hybrids, + "membership_epochs": epochs, + "zero_sync_guard_passed": zero_sync_blocked, + "ipc_endpoint": f"{endpoint.host}:{endpoint.port}", + "ipc_received_count": server.received_count, + "ipc_mean_latency_ms": round(sum(ipc_latencies_ms) / len(ipc_latencies_ms), 3), + "reduced_mean_verified": round(reduced_val, 6), + "passed": True, + } + finally: + server.close() + pool.close() + + +def _load_prompts(dataset_path: Path, limit: int = 32) -> list[str]: + prompts: list[str] = [] + if dataset_path.exists(): + for line in dataset_path.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line: + continue + obj = json.loads(line) + prompts.append(str(obj.get("prompt", "Solve 2x + 3 = 11."))) + if len(prompts) >= limit: + break + while len(prompts) < limit: + idx = len(prompts) + prompts.append(f"Problem {idx}: Compute the sum of the first {idx + 5} positive integers.") + return prompts + + +def _selected_logprobs( + logits: torch.Tensor, input_ids: torch.Tensor, loss_mask: torch.Tensor +) -> tuple[torch.Tensor, torch.Tensor]: + """Compute per-token log-probabilities shifted by 1 position.""" + shift_logits = logits[:, :-1, :].contiguous() + shift_labels = input_ids[:, 1:].contiguous() + shift_mask = loss_mask[:, 1:].to(shift_logits.dtype) + log_probs = F.log_softmax(shift_logits, dim=-1) + token_lp = log_probs.gather(dim=-1, index=shift_labels.unsqueeze(-1)).squeeze(-1) + return token_lp, shift_mask + + +def _build_synthetic_trajectories( + prompts: list[str], + *, + groups_per_batch: int, + group_size: int, + seq_len: int, + vocab_size: int, + tokenizer: Any | None, + seed: int, +) -> list[dict[str, Any]]: + """Build deterministic GRPO trajectories grouped by grpo_group_id.""" + rng = random.Random(seed) + trajectories: list[dict[str, Any]] = [] + prompt_len = min(192, seq_len // 4) + adv_pattern = [-1.2, -0.4, 0.4, 1.2] + + for g_idx in range(groups_per_batch): + prompt_text = prompts[g_idx % len(prompts)] + if tokenizer is not None: + encoded = tokenizer( + prompt_text, + add_special_tokens=True, + truncation=True, + max_length=prompt_len, + )["input_ids"] + else: + encoded = [((ord(ch) + g_idx) % (vocab_size - 8)) + 4 for ch in prompt_text[:prompt_len]] + if not encoded: + encoded = [1, 2, 3, 4] + actual_prompt_len = len(encoded) + for r_idx in range(group_size): + response_len = seq_len - actual_prompt_len + base_tokens = [ + ((i * 13 + g_idx * 31 + r_idx * 7 + rng.randint(0, 50)) % max(16, vocab_size - 16)) + + 8 + for i in range(response_len) + ] + input_ids = torch.tensor(encoded + base_tokens, dtype=torch.long) + loss_mask = torch.zeros(seq_len, dtype=torch.float32) + loss_mask[actual_prompt_len:] = 1.0 + trajectories.append( + { + "grpo_group_id": f"group-{g_idx}", + "rollout_index": r_idx, + "input_ids": input_ids, + "attention_mask": torch.ones(seq_len, dtype=torch.long), + "loss_mask": loss_mask, + "advantage": float(adv_pattern[r_idx % len(adv_pattern)]), + } + ) + return trajectories + + +def _run_phase3_dry_run( + *, + dataset_path: Path, + groups_per_batch: int, + group_size: int, + steps: int, + lr: float, + seed: int, +) -> dict[str, Any]: + """CPU-safe Phase 3 verification using tiny MLP models and real EHP primitives.""" + prompts = _load_prompts(dataset_path, limit=groups_per_batch) + vocab_size = 64 + seq_len = 64 + trajectories = _build_synthetic_trajectories( + prompts, + groups_per_batch=groups_per_batch, + group_size=group_size, + seq_len=seq_len, + vocab_size=vocab_size, + tokenizer=None, + seed=seed, + ) + torch.manual_seed(seed) + + def _make_tiny_lm() -> torch.nn.Module: + return torch.nn.Sequential( + torch.nn.Embedding(vocab_size, 32), + torch.nn.Linear(32, 32), + torch.nn.SiLU(), + torch.nn.Linear(32, vocab_size), + ) + + base_model = _make_tiny_lm() + init_state = {k: v.detach().clone() for k, v in base_model.state_dict().items()} + with torch.no_grad(): + batch_ids = torch.stack([t["input_ids"] for t in trajectories]) + batch_mask = torch.stack([t["loss_mask"] for t in trajectories]) + ref_lp_all, _ = _selected_logprobs(base_model(batch_ids), batch_ids, batch_mask) + for i, traj in enumerate(trajectories): + traj["ref_logprobs"] = ref_lp_all[i].detach().clone() + + configs = [ + ("static_core_1gpu", 1), + ("ehp_borrow_1gpu", 2), + ("ehp_borrow_3gpus", 4), + ] + results: dict[str, Any] = {} + reference_first_step_grad_norm: float | None = None + + for mode_name, world in configs: + hybrid_ids = [f"hybrid_{i}" for i in range(world - 1)] + all_worker_ids = ["dp0"] + hybrid_ids + pool = ElasticHybridPool( + core_train_workers=["dp0"], + core_rollout_workers=hybrid_ids, + require_state_ack=False, + zero_sync_steps=1, + ) + server = ElasticGradientServer(host="127.0.0.1", port=0, on_payload=lambda _p: None) + try: + endpoint = server.start() + client = ElasticGradientClient(endpoint, timeout=15.0) + for wid in hybrid_ids: + pool.join_training(wid, "dp0").result(timeout=5.0) + domain = pool.gradient_domain + epochs = {wid: domain.membership_epoch(wid) for wid in hybrid_ids} + + core_model = _make_tiny_lm() + core_model.load_state_dict(init_state) + opt = torch.optim.AdamW(core_model.parameters(), lr=lr) + hybrid_models = {} + for wid in hybrid_ids: + hm = _make_tiny_lm() + hm.load_state_dict(init_state) + hybrid_models[wid] = hm + + step_times: list[float] = [] + grad_norms: list[float] = [] + losses: list[float] = [] + + for step_idx in range(steps): + t0 = time.perf_counter() + assigned = partition_complete_grpo_groups( + trajectories, group_size, all_worker_ids + ) + assert sum(len(v) for v in assigned.values()) == len(trajectories) + + def _local_pass(wid: str, model: torch.nn.Module) -> tuple[tuple[torch.Tensor, ...], float]: + local_trajs = assigned[wid] + model.zero_grad(set_to_none=True) + ids = torch.stack([t["input_ids"] for t in local_trajs]) + mask = torch.stack([t["loss_mask"] for t in local_trajs]) + ref_lp = torch.stack([t["ref_logprobs"] for t in local_trajs]) + adv = torch.tensor([t["advantage"] for t in local_trajs], dtype=torch.float32).unsqueeze(-1) + with torch.no_grad(): + old_lp, shift_mask = _selected_logprobs(model(ids), ids, mask) + new_lp, shift_mask = _selected_logprobs(model(ids), ids, mask) + ratio = torch.exp(torch.clamp(new_lp - old_lp, -20.0, 20.0)) + surr1 = ratio * adv + surr2 = torch.clamp(ratio, 0.8, 1.2) * adv + pg_loss = -torch.min(surr1, surr2) + kl = torch.exp(torch.clamp(ref_lp - new_lp, -20.0, 20.0)) - (ref_lp - new_lp) - 1.0 + per_tok = (pg_loss + 0.04 * kl) * shift_mask + loss = per_tok.sum() / torch.clamp(shift_mask.sum(), min=1.0) + loss.backward() + grads = tuple(p.grad.detach().clone().contiguous() for p in model.parameters()) + return grads, float(loss.item()) + + worker_models = {"dp0": core_model, **hybrid_models} + with ThreadPoolExecutor(max_workers=world) as ex: + futs = { + wid: ex.submit(_local_pass, wid, worker_models[wid]) + for wid in all_worker_ids + } + outs = {wid: fut.result() for wid, fut in futs.items()} + + core_grads = outs["dp0"][0] + hybrid_payloads: list[GradientPayload] = [] + for wid in hybrid_ids: + h_grads = outs[wid][0] + # Verify loopback IPC transport cleanly. + ipc_payload = GradientPayload( + replica_id=wid, + target_core_id="dp0", + tensors=(h_grads[-1],), + zero_placeholder=False, + step=step_idx, + state_version=step_idx, + membership_epoch=epochs[wid], + sample_count=len(assigned[wid]), + global_sample_count=len(trajectories), + ) + client.send(ipc_payload, expect_update=False) + hybrid_payloads.append( + GradientPayload( + replica_id=wid, + target_core_id="dp0", + tensors=h_grads, + zero_placeholder=False, + step=step_idx, + state_version=step_idx, + membership_epoch=epochs[wid], + sample_count=len(assigned[wid]), + global_sample_count=len(trajectories), + ) + ) + + reduced = domain.reduce_core_gradients( + core_gradients={"dp0": core_grads}, + hybrid_payloads=hybrid_payloads, + core_sample_counts={"dp0": len(assigned["dp0"])}, + global_sample_count=len(trajectories), + step=step_idx, + state_version=step_idx, + in_place=True, + ) + for p, rg in zip(core_model.parameters(), reduced["dp0"]): + p.grad = rg + + grad_norm = float( + torch.nn.utils.clip_grad_norm_(core_model.parameters(), 1.0).item() + ) + opt.step() + opt.zero_grad(set_to_none=True) + with torch.no_grad(): + for hm in hybrid_models.values(): + for p_c, p_h in zip(core_model.parameters(), hm.parameters()): + p_h.copy_(p_c) + + step_times.append(time.perf_counter() - t0) + grad_norms.append(grad_norm) + losses.append(sum(outs[w][1] for w in all_worker_ids) / world) + + if reference_first_step_grad_norm is None: + reference_first_step_grad_norm = grad_norms[0] + results[mode_name] = { + "world_size": world, + "devices": [f"cpu:{i}" for i in range(world)], + "avg_step_s": round(sum(step_times) / len(step_times), 5), + "first_step_grad_norm": round(grad_norms[0], 6), + "grad_norm_diff_vs_static": round( + abs(grad_norms[0] - reference_first_step_grad_norm), 7 + ), + "final_loss": round(losses[-1], 6), + "ipc_acks": server.received_count, + } + finally: + server.close() + pool.close() + + return { + "mode": "dry_run_cpu", + "groups_per_batch": groups_per_batch, + "group_size": group_size, + "global_batch_size": groups_per_batch * group_size, + "steps": steps, + "runs": results, + } + + +def _replica_compute_cuda( + wid: str, + model: torch.nn.Module, + device: str, + local_trajs: list[dict[str, Any]], + micro_batch_size: int, +) -> dict[str, Any]: + """Run recompute_logprobs + gradient-accumulated GRPO backward on one GPU.""" + t_start = time.perf_counter() + total_local = len(local_trajs) + with torch.cuda.device(device): + model.zero_grad(set_to_none=True) + total_loss_val = 0.0 + for mb_start in range(0, total_local, micro_batch_size): + mb = local_trajs[mb_start : mb_start + micro_batch_size] + ids = torch.stack([t["input_ids"] for t in mb]).to(device, non_blocking=True) + mask = torch.stack([t["loss_mask"] for t in mb]).to(device, non_blocking=True) + ref_lp = torch.stack([t["ref_logprobs"] for t in mb]).to(device, non_blocking=True) + adv = ( + torch.tensor([t["advantage"] for t in mb], dtype=torch.bfloat16) + .to(device, non_blocking=True) + .unsqueeze(-1) + ) + with torch.no_grad(): + old_logits = model(input_ids=ids, use_cache=False).logits + old_lp, _ = _selected_logprobs(old_logits, ids, mask) + del old_logits + + logits = model(input_ids=ids, use_cache=False).logits + new_lp, shift_mask = _selected_logprobs(logits, ids, mask) + del logits + + ratio = torch.exp(torch.clamp(new_lp - old_lp, -20.0, 20.0)) + surr1 = ratio * adv + surr2 = torch.clamp(ratio, 0.8, 1.2) * adv + pg_loss = -torch.min(surr1, surr2) + kl = torch.exp(torch.clamp(ref_lp - new_lp, -20.0, 20.0)) - (ref_lp - new_lp) - 1.0 + per_tok = (pg_loss + 0.04 * kl) * shift_mask + mb_loss = (per_tok.sum() / torch.clamp(shift_mask.sum(), min=1.0)) * ( + len(mb) / float(total_local) + ) + mb_loss.backward() + total_loss_val += float(mb_loss.detach().item()) + + torch.cuda.synchronize(device) + grads = tuple( + p.grad.detach().contiguous() + if p.grad is not None + else torch.zeros_like(p.data, dtype=p.dtype, device=device) + for p in model.parameters() + if p.requires_grad + ) + return { + "worker_id": wid, + "compute_s": time.perf_counter() - t_start, + "grads": grads, + "loss": total_loss_val, + } + + +def _run_phase3_cuda( + *, + model_path: str, + dataset_path: Path, + groups_per_batch: int, + group_size: int, + seq_len: int, + micro_batch_size: int, + steps: int, + warmup_steps: int, + lr: float, + seed: int, +) -> dict[str, Any]: + """Run real Qwen3-4B multi-GPU EHP benchmark on CUDA GPUs.""" + from transformers import AutoModelForCausalLM, AutoTokenizer + + n_gpus = torch.cuda.device_count() + if n_gpus < 4: + raise RuntimeError(f"benchmark_ehp.py CUDA mode needs >= 4 GPUs, found {n_gpus}") + + tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) + prompts = _load_prompts(dataset_path, limit=groups_per_batch) + vocab_size = int(getattr(tokenizer, "vocab_size", 151936) or 151936) + + trajectories = _build_synthetic_trajectories( + prompts, + groups_per_batch=groups_per_batch, + group_size=group_size, + seq_len=seq_len, + vocab_size=vocab_size, + tokenizer=tokenizer, + seed=seed, + ) + + core_dev = "cuda:0" + core_model = AutoModelForCausalLM.from_pretrained( + model_path, + torch_dtype=torch.bfloat16, + attn_implementation="sdpa", + trust_remote_code=True, + ).to(core_dev) + core_model.train() + core_model.config.use_cache = False + + # Capture CPU snapshot so every EHP configuration starts from identical initial weights. + initial_cpu_state = { + name: param.detach().to("cpu").clone() + for name, param in core_model.state_dict().items() + } + + # Precompute frozen reference policy log-probabilities once on cuda:0. + with torch.no_grad(), torch.cuda.device(core_dev): + for idx in range(0, len(trajectories), micro_batch_size): + mb = trajectories[idx : idx + micro_batch_size] + ids = torch.stack([t["input_ids"] for t in mb]).to(core_dev) + mask = torch.stack([t["loss_mask"] for t in mb]).to(core_dev) + ref_logits = core_model(input_ids=ids, use_cache=False).logits + ref_lp, _ = _selected_logprobs(ref_logits, ids, mask) + for j, traj in enumerate(mb): + traj["ref_logprobs"] = ref_lp[j].detach().to("cpu") + del ref_logits, ref_lp + torch.cuda.synchronize(core_dev) + + mode_specs = [ + ("static_core_1gpu", ["cuda:0"]), + ("ehp_borrow_1gpu", ["cuda:0", "cuda:1"]), + ("ehp_borrow_3gpus", ["cuda:0", "cuda:1", "cuda:2", "cuda:3"]), + ] + + mode_results: dict[str, Any] = {} + static_avg_step_s: float | None = None + + try: + for mode_name, devices in mode_specs: + world = len(devices) + hybrid_ids = [f"hybrid_{i}" for i in range(world - 1)] + all_worker_ids = ["dp0"] + hybrid_ids + + # Reset Core weights & optimizer cleanly. + with torch.no_grad(): + core_model.load_state_dict(initial_cpu_state, assign=False) + core_model.train() + optimizer = torch.optim.AdamW(core_model.parameters(), lr=lr) + + # Instantiate hybrid replica models directly on target GPUs (no optimizer states). + hybrid_models: dict[str, torch.nn.Module] = {} + activation_start = time.perf_counter() + for wid, dev in zip(hybrid_ids, devices[1:]): + with torch.device(dev): + hm = AutoModelForCausalLM.from_config( + core_model.config, + torch_dtype=torch.bfloat16, + attn_implementation="sdpa", + ) + with torch.no_grad(): + for p_c, p_h in zip(core_model.parameters(), hm.parameters()): + p_h.copy_(p_c, non_blocking=True) + for b_c, b_h in zip(core_model.buffers(), hm.buffers()): + b_h.copy_(b_c, non_blocking=True) + hm.train() + hm.config.use_cache = False + hybrid_models[wid] = hm + for dev in devices: + torch.cuda.synchronize(dev) + torch.cuda.reset_peak_memory_stats(dev) + activation_s = time.perf_counter() - activation_start + print( + f"[ehp] starting mode={mode_name} world={world} activation_s={activation_s:.3f}", + flush=True, + ) + + pool = ElasticHybridPool( + core_train_workers=["dp0"], + core_rollout_workers=hybrid_ids, + require_state_ack=False, + zero_sync_steps=1, + ) + server = ElasticGradientServer(host="127.0.0.1", port=0, on_payload=lambda _p: None) + + try: + endpoint = server.start() + client = ElasticGradientClient(endpoint, timeout=30.0) + for wid in hybrid_ids: + pool.join_training(wid, "dp0").result(timeout=10.0) + domain = pool.gradient_domain + epochs = {wid: domain.membership_epoch(wid) for wid in hybrid_ids} + + step_records: list[dict[str, Any]] = [] + total_iters = warmup_steps + steps + + for it in range(total_iters): + is_warmup = it < warmup_steps + t_step_start = time.perf_counter() + + assigned = partition_complete_grpo_groups( + trajectories, group_size, all_worker_ids + ) + worker_models = {"dp0": core_model, **hybrid_models} + worker_devs = {"dp0": core_dev, **dict(zip(hybrid_ids, devices[1:]))} + + with ThreadPoolExecutor(max_workers=world) as ex: + futs = { + wid: ex.submit( + _replica_compute_cuda, + wid, + worker_models[wid], + worker_devs[wid], + assigned[wid], + micro_batch_size, + ) + for wid in all_worker_ids + } + outs = {wid: fut.result() for wid, fut in futs.items()} + + max_compute_s = max(outs[wid]["compute_s"] for wid in all_worker_ids) + + # Compact loopback TCP verification payload (last-layer gradient tensor) + t_ipc_start = time.perf_counter() + hybrid_payloads: list[GradientPayload] = [] + for wid in hybrid_ids: + h_grads = outs[wid]["grads"] + client.send( + GradientPayload( + replica_id=wid, + target_core_id="dp0", + tensors=(h_grads[-1].detach().to("cpu"),), + zero_placeholder=False, + step=it, + state_version=it, + membership_epoch=epochs[wid], + sample_count=len(assigned[wid]), + global_sample_count=len(trajectories), + stats={"mode": mode_name}, + ), + expect_update=False, + ) + hybrid_payloads.append( + GradientPayload( + replica_id=wid, + target_core_id="dp0", + tensors=h_grads, + zero_placeholder=False, + step=it, + state_version=it, + membership_epoch=epochs[wid], + sample_count=len(assigned[wid]), + global_sample_count=len(trajectories), + ) + ) + ipc_verify_s = time.perf_counter() - t_ipc_start + + # NVLink/P2P 16MB streaming in-place gradient reduction onto cuda:0. + t_reduce_start = time.perf_counter() + core_grads = outs["dp0"]["grads"] + reduced = domain.reduce_core_gradients( + core_gradients={"dp0": core_grads}, + hybrid_payloads=hybrid_payloads, + core_sample_counts={"dp0": len(assigned["dp0"])}, + global_sample_count=len(trajectories), + step=it, + state_version=it, + in_place=True, + ) + trainable_params = [p for p in core_model.parameters() if p.requires_grad] + for p, rg in zip(trainable_params, reduced["dp0"]): + p.grad = rg + torch.cuda.synchronize(core_dev) + reduce_s = time.perf_counter() - t_reduce_start + + # Optimizer step on Core + weight sync back to hybrids. + t_opt_start = time.perf_counter() + grad_norm = float( + torch.nn.utils.clip_grad_norm_(trainable_params, 1.0).item() + ) + optimizer.step() + optimizer.zero_grad(set_to_none=True) + with torch.no_grad(): + for hm in hybrid_models.values(): + for p_c, p_h in zip(core_model.parameters(), hm.parameters()): + p_h.copy_(p_c, non_blocking=True) + for dev in devices: + torch.cuda.synchronize(dev) + opt_sync_s = time.perf_counter() - t_opt_start + + step_total_s = time.perf_counter() - t_step_start + avg_loss = sum(outs[wid]["loss"] for wid in all_worker_ids) / world + + # Release intermediate gradient references before next step. + outs.clear() + hybrid_payloads.clear() + + if not is_warmup: + step_rec = { + "step": it - warmup_steps, + "step_total_s": round(step_total_s, 4), + "compute_s": round(max_compute_s, 4), + "ipc_verify_s": round(ipc_verify_s, 4), + "reduce_s": round(reduce_s, 4), + "opt_sync_s": round(opt_sync_s, 4), + "loss": round(avg_loss, 6), + "grad_norm": round(grad_norm, 6), + } + step_records.append(step_rec) + print(f"[ehp] mode={mode_name} {step_rec}", flush=True) + + avg_step_s = sum(r["step_total_s"] for r in step_records) / len(step_records) + if static_avg_step_s is None: + static_avg_step_s = avg_step_s + peak_mem_gb = max( + torch.cuda.max_memory_allocated(dev) / (1024**3) for dev in devices + ) + + mode_results[mode_name] = { + "world_size": world, + "devices": devices, + "activation_s": round(activation_s, 4), + "avg_step_s": round(avg_step_s, 4), + "avg_compute_s": round( + sum(r["compute_s"] for r in step_records) / len(step_records), 4 + ), + "avg_ipc_verify_s": round( + sum(r["ipc_verify_s"] for r in step_records) / len(step_records), 4 + ), + "avg_reduce_s": round( + sum(r["reduce_s"] for r in step_records) / len(step_records), 4 + ), + "avg_opt_sync_s": round( + sum(r["opt_sync_s"] for r in step_records) / len(step_records), 4 + ), + "speedup_vs_static_1gpu": round(static_avg_step_s / avg_step_s, 3), + "peak_memory_gb": round(peak_mem_gb, 3), + "ipc_acks": server.received_count, + "steps": step_records, + } + finally: + server.close() + pool.close() + del optimizer + hybrid_models.clear() + gc.collect() + torch.cuda.empty_cache() + + return { + "mode": "real_cuda_qwen3_4b", + "model_path": model_path, + "groups_per_batch": groups_per_batch, + "group_size": group_size, + "global_batch_size": groups_per_batch * group_size, + "seq_len": seq_len, + "micro_batch_size": micro_batch_size, + "warmup_steps": warmup_steps, + "steps": steps, + "runs": mode_results, + } + finally: + del core_model + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + +def run_benchmark(args: argparse.Namespace) -> dict[str, Any]: + """Run all three EHP verification phases and write ehp_summary.json.""" + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + dataset_path = Path(args.dataset) + + phase1 = run_phase1_cost_model(groups_per_batch=args.groups_per_batch * args.group_size) + phase2 = run_phase2_lifecycle_and_ipc() + if args.dry_run: + phase3 = _run_phase3_dry_run( + dataset_path=dataset_path, + groups_per_batch=args.groups_per_batch, + group_size=args.group_size, + steps=args.steps, + lr=args.lr, + seed=args.seed, + ) + else: + phase3 = _run_phase3_cuda( + model_path=args.model, + dataset_path=dataset_path, + groups_per_batch=args.groups_per_batch, + group_size=args.group_size, + seq_len=args.seq_len, + micro_batch_size=args.micro_batch_size, + steps=args.steps, + warmup_steps=args.warmup_steps, + lr=args.lr, + seed=args.seed, + ) + + summary = { + "benchmark": "ehp_elastic_hybrid_parallelism", + "dry_run": bool(args.dry_run), + "phase1_cost_model": phase1, + "phase2_lifecycle_and_ipc": phase2, + "phase3_elastic_training": phase3, + } + summary_path = output_dir / "ehp_summary.json" + summary_path.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + return summary + + +def main() -> None: + parser = argparse.ArgumentParser(description="EHP 3-phase benchmark") + parser.add_argument("--model", default=DEFAULT_MODEL) + parser.add_argument("--dataset", default=str(DEFAULT_DATASET)) + parser.add_argument( + "--output-dir", + default="/workspace/libra-tier2-eval/runs/h20_8gpu_ehp", + ) + parser.add_argument("--steps", type=int, default=3) + parser.add_argument("--warmup-steps", type=int, default=1) + parser.add_argument("--groups-per-batch", type=int, default=4) + parser.add_argument("--group-size", type=int, default=4) + parser.add_argument("--seq-len", type=int, default=1536) + parser.add_argument("--micro-batch-size", type=int, default=2) + parser.add_argument("--lr", type=float, default=1e-6) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + + summary = run_benchmark(args) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/repro/tier2_four_gpu_closed_loop/benchmark_grp.py b/repro/tier2_four_gpu_closed_loop/benchmark_grp.py new file mode 100644 index 0000000..9d12cea --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/benchmark_grp.py @@ -0,0 +1,581 @@ +#!/usr/bin/env python3 +"""GRP (Global Resource Planner) 2-Phase Benchmark for 8x H20 / Tier 2. + +Verifies Global Resource Planner across two phases: + Phase 1: Runs `PreflightPlanner` / `TwoLevelNestedOptimizer` over 8 H20-3e GPUs + with `Qwen/Qwen3-4B` architecture specs and representative DAPO + length quantiles, and compares analytical costs of: + - fixed_4train_4rollout_tp1 (4 train reserved, 4x TP=1 rollout) + - fixed_2train_6rollout_tp2 (2 train reserved, 3x TP=2 rollout) + - grp_optimal_1train_7rollout_hetero (1 train, TP=[1,2,4] hetero + C-MLFQ) + Phase 2: Materializes and executes all three 8-GPU closed-loop allocations on + real `vLLM` + `AsyncRLTrainer` (`--dry-run` validates configs via + `AsyncRLConfig.from_yaml` and writes `launch_plan.json` + `grp_summary.json` + without spawning GPU processes). + +Usage: + # Local CPU dry-run (Phase 1 planning + Phase 2 config/plan verification): + python repro/tier2_four_gpu_closed_loop/benchmark_grp.py --dry-run \\ + --output-dir /tmp/grp_dry_run + + # Real 8x H20 GPU benchmark: + python repro/tier2_four_gpu_closed_loop/benchmark_grp.py \\ + --model /mnt/tidal-alsh-hilab/dataset/diandian/model/qwen3/Qwen3-4B \\ + --output-dir /workspace/libra-tier2-eval/runs/h20_8gpu_grp +""" + +from __future__ import annotations + +import argparse +from copy import deepcopy +from dataclasses import dataclass +import json +import os +from pathlib import Path +import sys +import time +from typing import Any + +import yaml + +REPO_ROOT = Path(__file__).resolve().parents[2] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from config import AsyncRLConfig +from infra.cost_model.optimizer import ( + RequestInfo, + RolloutClusterConfig, + TrainParallelConfig, +) +from infra.cost_model.preflight_planner import PreflightPlanner +from repro.tier2_four_gpu_closed_loop import launch_4gpu + +DEFAULT_MODEL = "/mnt/tidal-alsh-hilab/dataset/diandian/model/qwen3/Qwen3-4B" +DEFAULT_CONFIG = ( + REPO_ROOT / "repro" / "tier2_four_gpu_closed_loop" / "config_8gpu_qwen3_4b.yaml" +) + + +@dataclass(frozen=True) +class GRPAllocationSpec: + name: str + reserved_train_gpus: int + rollout_gpus: int + rollout_instances: tuple[tuple[str, tuple[int, ...]], ...] + policy: str + prefix_affinity: bool + description: str + + +GRP_ALLOCATIONS: tuple[GRPAllocationSpec, ...] = ( + GRPAllocationSpec( + name="fixed_4train_4rollout_tp1", + reserved_train_gpus=4, + rollout_gpus=4, + rollout_instances=( + ("tp1_0", (4,)), + ("tp1_1", (5,)), + ("tp1_2", (6,)), + ("tp1_3", (7,)), + ), + policy="round_robin", + prefix_affinity=True, + description="Static 4 train (GPUs 0-3) / 4x TP=1 rollout (GPUs 4-7), round_robin + prefix_affinity", + ), + GRPAllocationSpec( + name="fixed_2train_6rollout_tp2", + reserved_train_gpus=2, + rollout_gpus=6, + rollout_instances=( + ("tp2_0", (2, 3)), + ("tp2_1", (4, 5)), + ("tp2_2", (6, 7)), + ), + policy="least_connections", + prefix_affinity=True, + description="Static 2 train (GPUs 0-1) / 3x TP=2 rollout (GPUs 2-7), least_connections + prefix_affinity", + ), + GRPAllocationSpec( + name="grp_optimal_1train_7rollout_hetero", + reserved_train_gpus=1, + rollout_gpus=7, + rollout_instances=( + ("tp1", (1,)), + ("tp2", (2, 3)), + ("tp4", (4, 5, 6, 7)), + ), + policy="cmlfq_cost", + prefix_affinity=False, + description="GRP optimal 1 train (GPU 0) / TP=[1,2,4] hetero rollout (GPUs 1-7) + cmlfq_cost", + ), +) + + +def run_phase1_preflight(config_path: Path = DEFAULT_CONFIG) -> dict[str, Any]: + """Run PreflightPlanner and evaluate all three 8-GPU GRP allocations.""" + cfg = AsyncRLConfig.from_yaml(str(config_path)) + cfg.global_resource_planner.allowed_train_tp = [1] + cfg.global_resource_planner.allowed_train_pp = [1] + cfg.global_resource_planner.micro_batch_sizes = [1] + + # Representative skewed DAPO multi-turn length profile (4 quartiles, 16 rollouts). + history = [ + {"prompt_length": 512, "response_length": [128, 384, 1536, 4096][i % 4]} + for i in range(16) + ] + + preflight = PreflightPlanner(cfg) + result = preflight.run(history) + best_plan = result.applied_plan.to_dict() if result.applied_plan else {} + + optimizer = preflight.planner.optimizer + evaluator = preflight.planner.evaluator + reqs = [ + RequestInfo( + prompt_length=h["prompt_length"], + gen_length=h["response_length"], + training_length=h["prompt_length"] + h["response_length"], + ) + for h in history + ] + seq_lens = [h["prompt_length"] + h["response_length"] for h in history] + + plan_evals: dict[str, Any] = {} + baseline_t_global: float | None = None + for spec in GRP_ALLOCATIONS: + tp_list = sorted([len(gpus) for _, gpus in spec.rollout_instances], reverse=True) + train_cfg = TrainParallelConfig( + tp=1, ep=1, pp=1, dp=spec.reserved_train_gpus, b_micro=1 + ) + rollout_cfg = RolloutClusterConfig(tp_list=tp_list) + t_train, _ = evaluator.evaluate_training(train_cfg, len(history), seq_lens) + t_rollout, _ = optimizer.evaluate_fixed_rollout_config(rollout_cfg, reqs) + t_global = max(t_train, t_rollout) + if baseline_t_global is None: + baseline_t_global = t_global + speedup = baseline_t_global / max(t_global, 1e-9) + improvement_pct = (baseline_t_global - t_global) / max(baseline_t_global, 1e-9) * 100.0 + plan_evals[spec.name] = { + "reserved_train_gpus": spec.reserved_train_gpus, + "rollout_gpus": spec.rollout_gpus, + "rollout_tp_list": tp_list, + "predicted_t_train_s": round(t_train, 6), + "predicted_t_rollout_s": round(t_rollout, 6), + "predicted_t_global_s": round(t_global, 6), + "predicted_speedup_vs_4train_4rollout": round(speedup, 3), + "predicted_time_reduction_pct": round(improvement_pct, 2), + } + + return { + "preflight_applied": bool(result.applied), + "best_plan": best_plan, + "n_configs_explored": int( + getattr(result.decision.optimization_result, "n_configs_explored", 0) + ), + "optimization_time_ms": round( + float( + getattr(result.decision.optimization_result, "optimization_time_ms", 0.0) + ), + 3, + ), + "plan_evaluations": plan_evals, + } + + +def _max_num_seqs_for_tp(tp_size: int) -> int: + if tp_size <= 1: + return 1 + if tp_size == 2: + return 2 + return 16 + + +def build_grp_allocation_plan( + spec: GRPAllocationSpec, + *, + output_dir: Path, + dataset_path: Path, + model_path: str | None, + steps: int | None, + batch_size: int | None, + n_samples: int, + sync_interval: int | None, + seed: int, + base_port: int, + gpu_memory_utilization: float | None, + max_model_len: int | None, + max_new_tokens: int | None, + python_bin: str, +) -> dict[str, Any]: + """Build a launch_4gpu-compatible run plan for one 8-GPU GRP allocation.""" + # Start from launch_4gpu's verified 8-GPU base plan, then rewire topology & directory. + plan = deepcopy( + launch_4gpu.build_run_plan( + mode="8gpu", + policy=spec.policy, + gpus=list(range(8)), + output_dir=output_dir, + dataset_path=dataset_path, + model_path=model_path, + steps=steps, + batch_size=batch_size, + n_samples=n_samples, + sync_interval=sync_interval, + seed=seed, + base_port=base_port, + gpu_memory_utilization=gpu_memory_utilization, + max_model_len=max_model_len, + max_new_tokens=max_new_tokens, + python_bin=python_bin, + ) + ) + + run_dir = output_dir / f"{spec.name}_{seed}" + config_path = run_dir / "config.yaml" + control_dir = run_dir / "control" + tree_path = run_dir / "tree.json" + kv_storage_dir = run_dir / "kv_cache" + + plan["run_dir"] = str(run_dir) + plan["config_path"] = str(config_path) + plan["policy"] = spec.policy + plan["kv_storage_dir"] = str(kv_storage_dir) + plan["grp_allocation"] = { + "name": spec.name, + "description": spec.description, + "reserved_train_gpus": spec.reserved_train_gpus, + "active_train_gpus": 1, + "rollout_gpus": spec.rollout_gpus, + "prefix_affinity": spec.prefix_affinity, + } + + cfg = plan["config"] + cfg["train_gpus"] = 1 + cfg["train_dp_size"] = 1 + cfg["rollout_gpus"] = spec.rollout_gpus + cfg["log_dir"] = str(run_dir) + cfg["history_output_dir"] = str(run_dir / "history") + cfg["history_experiment_name"] = f"tier2_8gpu_{spec.name}" + shm_root = Path("/dev/shm") + cfg["sync_path"] = ( + str(shm_root / "libra_tier2_8gpu" / f"{spec.name}_{seed}" / "weights") + if shm_root.exists() + else str(run_dir / "weights") + ) + cfg["rollout_weight_sync_control_dir"] = str(control_dir) + + env_over = dict(plan.get("env_overrides") or {}) + env_over["BENCH_RUN_DIR"] = str(run_dir) + env_over["FSDP_PROGRESS_DIR"] = str(run_dir / "progress") + existing_pp = [p for p in str(env_over.get("PYTHONPATH", "")).split(os.pathsep) if p] + for extra in str(os.environ.get("PYTHONPATH", "")).split(os.pathsep): + if extra and extra not in existing_pp: + existing_pp.append(extra) + if existing_pp: + env_over["PYTHONPATH"] = os.pathsep.join(existing_pp) + plan["env_overrides"] = env_over + + hetero = cfg["heterogeneous_rollout"] + hetero["total_gpus"] = spec.rollout_gpus + hetero["scheduling"] = launch_4gpu._scheduling_block( + spec.policy, + run_dir, + "recompute", + "8gpu", + int(hetero.get("max_model_len", 6144)), + ) + hetero["scheduling"]["prefix_affinity"] = spec.prefix_affinity + hetero["scheduling"]["cmlfq_tree_path"] = str(tree_path) + + effective_model = model_path or str(plan.get("model") or cfg.get("model_name") or "Qwen/Qwen3-4B") + eff_max_model_len = int(hetero.get("max_model_len", 6144)) + eff_gpu_util = float(hetero.get("gpu_memory_utilization", 0.75)) + + instances = [] + rollout_specs = [] + for idx, (inst_id, gpus_tuple) in enumerate(spec.rollout_instances): + gpus_list = list(gpus_tuple) + tp = len(gpus_list) + port = base_port + idx + health_url = f"http://127.0.0.1:{port}/health" + log_path = run_dir / f"vllm_{inst_id}.log" + instances.append( + { + "instance_id": inst_id, + "tp": tp, + "gpus": gpus_list, + "host": "127.0.0.1", + "port": port, + } + ) + rollout_specs.append( + { + "instance_id": inst_id, + "tp": tp, + "gpus": gpus_list, + "cuda_visible_devices": ",".join(str(g) for g in gpus_list), + "port": port, + "health_url": health_url, + "log_path": str(log_path), + "command": launch_4gpu._vllm_supervisor_command( + python_bin, + instance_id=inst_id, + control_dir=control_dir, + health_url=health_url, + initial_model=effective_model, + port=port, + tp_size=tp, + vllm_dtype=str(plan.get("vllm_dtype", "bfloat16")), + max_model_len=eff_max_model_len, + gpu_memory_utilization=eff_gpu_util, + max_num_seqs=_max_num_seqs_for_tp(tp), + seed=seed, + kv_storage_dir=kv_storage_dir, + ), + } + ) + + hetero["instances"] = instances + plan["rollout_specs"] = rollout_specs + plan["train_spec"]["log_path"] = str(run_dir / "train.log") + plan["train_spec"]["command"] = [ + python_bin, + str(REPO_ROOT / "scripts" / "benchmark_scheduler_train.py"), + "--config", + str(config_path), + ] + return plan + + +def _is_completed_run(run_dir: Path, expected_steps: int) -> bool: + completed_path = run_dir / "completed.json" + steps_path = run_dir / "steps.jsonl" + if not completed_path.exists() or not steps_path.exists(): + return False + rows = [ + line for line in steps_path.read_text(encoding="utf-8").splitlines() if line.strip() + ] + return len(rows) >= expected_steps + + +def _parse_run_metrics(run_dir: Path, spec: GRPAllocationSpec) -> dict[str, Any]: + steps_path = run_dir / "steps.jsonl" + rows = [ + json.loads(line) + for line in steps_path.read_text(encoding="utf-8").splitlines() + if line.strip() + ] + stats_list = [r.get("stats", r) for r in rows] + step_times = [float(s.get("step_time", s.get("step_time_s", 0.0))) for s in stats_list] + rollout_times = [float(s.get("rollout_time", s.get("rollout_time_s", 0.0))) for s in stats_list] + train_times = [float(s.get("train_time", s.get("train_time_s", 0.0))) for s in stats_list] + weight_sync_times = [float(s.get("weight_sync_time", 0.0)) for s in stats_list] + wall_s = sum(step_times) + + completed_path = run_dir / "completed.json" + total_elapsed_s = wall_s + if completed_path.exists(): + try: + comp = json.loads(completed_path.read_text(encoding="utf-8")) + if "start" in comp and "end" in comp: + total_elapsed_s = float(comp["end"]) - float(comp["start"]) + except Exception: + pass + + total_rollouts = sum( + int(s.get("n_trajectories", 0) or s.get("rollout_count", 0) or s.get("accepted_rollouts", 0)) + for s in stats_list + ) + total_generated_tokens = sum(int(r.get("generated_tokens", 0)) for r in rows) + + control_dir = run_dir / "control" + ack_files = sorted(control_dir.glob("*ack*.json")) if control_dir.exists() else [] + ack_count = 0 + for af in ack_files: + try: + payload = json.loads(af.read_text(encoding="utf-8")) + if isinstance(payload, dict) and ( + payload.get("reload_method") == "inplace" + or payload.get("version") is not None + or payload.get("status") in {"ok", "reloaded", "acked"} + ): + ack_count += 1 + except Exception: + pass + + inplace_log_acks = 0 + for vllm_log in run_dir.glob("vllm_*.log"): + text = vllm_log.read_text(encoding="utf-8", errors="ignore") + if "inplace" in text.lower() or "reload" in text.lower(): + inplace_log_acks += 1 + + return { + "name": spec.name, + "run_dir": str(run_dir), + "reserved_train_gpus": spec.reserved_train_gpus, + "rollout_gpus": spec.rollout_gpus, + "rollout_tp_list": [len(g) for _, g in spec.rollout_instances], + "policy": spec.policy, + "prefix_affinity": spec.prefix_affinity, + "steps_completed": len(rows), + "wall_s": round(wall_s, 3), + "total_elapsed_s": round(total_elapsed_s, 3), + "avg_step_s": round(sum(step_times) / max(len(step_times), 1), 3), + "rollout_sum_s": round(sum(rollout_times), 3), + "train_sum_s": round(sum(train_times), 3), + "weight_sync_sum_s": round(sum(weight_sync_times), 3), + "total_rollouts": total_rollouts, + "total_generated_tokens": total_generated_tokens, + "throughput_rollouts_per_min": round( + total_rollouts / max(wall_s / 60.0, 1e-6), 3 + ), + "tokens_per_s": round(total_generated_tokens / max(wall_s, 1e-6), 2), + "reload_ack_files": len(ack_files), + "reload_ack_count": ack_count, + "vllm_logs_with_reload": inplace_log_acks, + } + + +def run_benchmark(args: argparse.Namespace) -> dict[str, Any]: + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + dataset_path = Path(args.dataset) + python_bin = args.python_bin or sys.executable + + phase1 = run_phase1_preflight(DEFAULT_CONFIG) + + selected_specs = [ + spec + for spec in GRP_ALLOCATIONS + if not args.plans or spec.name in args.plans + ] + if not selected_specs: + raise ValueError(f"No matching plans in {args.plans}") + + materialized_plans: dict[str, Any] = {} + run_results: dict[str, Any] = {} + + for spec in selected_specs: + plan = build_grp_allocation_plan( + spec, + output_dir=output_dir, + dataset_path=dataset_path, + model_path=None if args.dry_run and args.model == DEFAULT_MODEL else args.model, + steps=args.steps, + batch_size=args.batch_size, + n_samples=args.n_samples, + sync_interval=args.sync_interval, + seed=args.seed, + base_port=args.base_port, + gpu_memory_utilization=args.gpu_memory_utilization, + max_model_len=args.max_model_len, + max_new_tokens=args.max_new_tokens, + python_bin=python_bin, + ) + run_dir = Path(plan["run_dir"]) + expected_steps = int(plan["config"].get("total_steps", 4)) + reused = ( + not args.dry_run + and not args.plan_only + and not args.force + and _is_completed_run(run_dir, expected_steps) + ) + if not reused: + launch_4gpu.materialize_run_plan(plan) + + # Validate config with AsyncRLConfig.from_yaml (when newly materialized or present). + cfg_file = Path(plan["config_path"]) + if cfg_file.exists(): + loaded_cfg = AsyncRLConfig.from_yaml(str(cfg_file)) + assert int(loaded_cfg.rollout_gpus) == spec.rollout_gpus + if not reused: + assert ( + bool(loaded_cfg.heterogeneous_rollout.scheduling.prefix_affinity) + == spec.prefix_affinity + ) + + materialized_plans[spec.name] = { + "run_dir": str(run_dir), + "config_path": plan["config_path"], + "reserved_train_gpus": spec.reserved_train_gpus, + "rollout_gpus": spec.rollout_gpus, + "rollout_tp_list": [s["tp"] for s in plan["rollout_specs"]], + "rollout_gpu_ids": [s["gpus"] for s in plan["rollout_specs"]], + "policy": spec.policy, + "prefix_affinity": spec.prefix_affinity, + "config_validated": cfg_file.exists(), + } + + if args.dry_run or args.plan_only: + continue + + if reused: + run_results[spec.name] = { + **_parse_run_metrics(run_dir, spec), + "reused_completed_run": True, + } + continue + + t0 = time.perf_counter() + launch_4gpu.execute_run_plan(plan, timeout_s=args.timeout_s) + exec_wall_s = time.perf_counter() - t0 + parsed = _parse_run_metrics(run_dir, spec) + parsed["exec_wall_s"] = round(exec_wall_s, 3) + parsed["reused_completed_run"] = False + run_results[spec.name] = parsed + + if run_results: + base_wall = run_results.get("fixed_4train_4rollout_tp1", {}).get("wall_s") + for res in run_results.values(): + w = res.get("wall_s") or res.get("exec_wall_s") + if base_wall and w: + res["speedup_vs_4train_4rollout"] = round(base_wall / w, 3) + res["time_reduction_pct_vs_4train_4rollout"] = round( + (base_wall - w) / base_wall * 100.0, 2 + ) + + summary = { + "benchmark": "grp_global_resource_planner", + "dry_run": bool(args.dry_run), + "plan_only": bool(args.plan_only), + "phase1_preflight_planning": phase1, + "phase2_materialized_plans": materialized_plans, + "phase2_execution_results": run_results, + } + summary_path = output_dir / "grp_summary.json" + summary_path.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + return summary + + +def main() -> None: + parser = argparse.ArgumentParser(description="GRP 8-GPU Benchmark") + parser.add_argument("--model", default=DEFAULT_MODEL) + parser.add_argument("--dataset", default=str(launch_4gpu.DEFAULT_DATASET)) + parser.add_argument( + "--output-dir", + default="/workspace/libra-tier2-eval/runs/h20_8gpu_grp", + ) + parser.add_argument("--steps", type=int, default=None) + parser.add_argument("--batch-size", type=int, default=None) + parser.add_argument("--n-samples", type=int, default=2) + parser.add_argument("--sync-interval", type=int, default=None) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--base-port", type=int, default=18920) + parser.add_argument("--gpu-memory-utilization", type=float, default=None) + parser.add_argument("--max-model-len", type=int, default=None) + parser.add_argument("--max-new-tokens", type=int, default=None) + parser.add_argument("--timeout-s", type=float, default=2400.0) + parser.add_argument("--python-bin", default=None) + parser.add_argument("--plans", nargs="*", default=None) + parser.add_argument("--force", action="store_true") + parser.add_argument("--plan-only", action="store_true") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + + summary = run_benchmark(args) + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/repro/tier2_four_gpu_closed_loop/colab_quickstart.ipynb b/repro/tier2_four_gpu_closed_loop/colab_quickstart.ipynb new file mode 100644 index 0000000..7be71ce --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/colab_quickstart.ipynb @@ -0,0 +1,146 @@ +{ + "nbformat": 4, + "nbformat_minor": 5, + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.11" + }, + "accelerator": "GPU" + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Libra Tier 2 \u2014 Google Colab Quickstart (0-GPU Replay + 1-GPU Real Closed-Loop RL)\n", + "\n", + "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NetX-lab/Libra/blob/main/repro/tier2_four_gpu_closed_loop/colab_quickstart.ipynb)\n", + "\n", + "This notebook runs two verification stages inside a standard Google Colab runtime (`Runtime -> Change runtime type -> T4 / L4 / A100 GPU`):\n", + "\n", + "1. **Tier 1 (0-GPU CPU Replay)**: Runs Libra's heterogeneous schedulers (`round_robin`, `least_connections`, `length_aware`, `la_mlfq`, `cmlfq`, `cmlfq_cost`) and `GlobalResourcePlanner` in ~2 seconds.\n", + "2. **Tier 2 (1-GPU Co-Located Real Closed-Loop RL)**: Launches 1 real vLLM rollout worker (`InplaceReloadWorkerExtension`) and 1 `FSDPTrainEngine` DAPO-Math RL trainer sharing GPU 0 with confirmed in-place checkpoint reloads.\n", + "\n", + "| Colab Runtime | VRAM | Auto Preset Model | Precision (`vLLM` / `FSDP`) | vLLM KV Fraction |\n", + "| :--- | :---: | :--- | :--- | :---: |\n", + "| **T4 (Free)** | 16 GB | `Qwen/Qwen2.5-0.5B-Instruct` | `half` / `float32` | `0.30` |\n", + "| **L4** | 24 GB | `Qwen/Qwen2.5-1.5B-Instruct` | `bfloat16` / `bfloat16` | `0.35` |\n", + "| **A100-40GB** | 40 GB | `Qwen/Qwen3-1.7B` | `bfloat16` / `bfloat16` | `0.38` |\n", + "| **A100-80GB** | 80 GB | `Qwen/Qwen3-4B` | `bfloat16` / `bfloat16` | `0.38` |\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Inspect Colab GPU & Install Libra Runtime Dependencies\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os, subprocess, torch\n", + "\n", + "!nvidia-smi --query-gpu=name,memory.total,compute_cap --format=csv\n", + "print(\"CUDA available:\", torch.cuda.is_available())\n", + "if torch.cuda.is_available():\n", + " props = torch.cuda.get_device_properties(0)\n", + " print(f\"Detected GPU: {props.name} | VRAM={props.total_memory / 1024**3:.1f} GiB | SM={props.major}.{props.minor}\")\n", + "\n", + "if not os.path.exists(\"Libra\"):\n", + " !git clone --depth 1 https://github.com/NetX-lab/Libra.git\n", + "%cd Libra\n", + "\n", + "!pip -q install --upgrade vllm transformers \"datasets>=2.18.0,<3.0.0\" pyyaml httpx fastapi sympy regex latex2sympy2 word2number\n", + "!pip -q install -e . --no-deps" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Tier 1 \u2014 0-GPU Scheduling Replay & GRP Offline Benchmark (~2s)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "!python repro/tier1_zero_gpu_replay/run_replay.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Tier 2 \u2014 Real 1-GPU Closed-Loop DAPO-Math Training\n", + "\n", + "`launch_4gpu.py --mode colab-1gpu` automatically picks the safe precision & model tier (`--colab-tier auto`), starts a supervised `vllm_hot_reload_api_server.py` worker on GPU 0, runs `benchmark_scheduler_train.py` (`FSDPTrainEngine` + `DAPOMathWorkflow`), and triggers verified in-place weight reloads.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "!python repro/tier2_four_gpu_closed_loop/launch_4gpu.py \\\n", + " --mode colab-1gpu \\\n", + " --colab-tier auto \\\n", + " --steps 4 \\\n", + " --sync-interval 2 \\\n", + " --output-dir ./logs/colab_tier2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Inspect Training Metrics, Weight Reload Acks, and Replay Collected Rollout Trace\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import glob, json\n", + "from pathlib import Path\n", + "\n", + "summary_path = Path(\"./logs/colab_tier2/summary.json\")\n", + "if summary_path.exists():\n", + " print(\"=== summary.json ===\")\n", + " print(summary_path.read_text())\n", + "\n", + "steps_files = sorted(glob.glob(\"./logs/colab_tier2/*/steps.jsonl\"))\n", + "if steps_files:\n", + " print(f\"=== Step Records ({steps_files[0]}) ===\")\n", + " for line in Path(steps_files[0]).read_text().splitlines():\n", + " row = json.loads(line)\n", + " print(f\"step={row[\"step\"]} stats={row[\"stats\"]}\")\n", + "\n", + "acks = sorted(glob.glob(\"./logs/colab_tier2/*/control/ack_*.json\"))\n", + "print(f\"Confirmed in-place weight reload acks: {len(acks)}\")\n", + "for ack in acks:\n", + " print(\" \", ack)\n", + "\n", + "history_files = sorted(glob.glob(\"./logs/colab_tier2/*/history/*.jsonl\"))\n", + "if history_files:\n", + " print(\"\\n=== Replaying Colab Rollout History with Tier 1 ===\")\n", + " !python repro/tier1_zero_gpu_replay/run_replay.py --trace {history_files[0]} --tp-layout 1 --online-only --skip-grp" + ] + } + ] +} diff --git a/repro/tier2_four_gpu_closed_loop/config_4gpu_qwen3_4b.yaml b/repro/tier2_four_gpu_closed_loop/config_4gpu_qwen3_4b.yaml new file mode 100644 index 0000000..785e2ed --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/config_4gpu_qwen3_4b.yaml @@ -0,0 +1,95 @@ +# Tier 2: 4-GPU Heterogeneous Small-Scale Closed Loop (1 Train + 3 Rollout GPUs) +# Verified baseline: DAPO-Math + Qwen3-4B (no Slurm required). +hardware_config: ../../configs/hardware_config/a800_80g.yaml +model_arch_config: ../../configs/model_arch_config/qwen3-4b.yaml + +model_path: "Qwen/Qwen3-4B" +tokenizer_path: "Qwen/Qwen3-4B" + +train_backend: "fsdp" +train_gpus: 1 +rollout_gpus: 3 +tp_size: 1 +train_tp_size: 1 +train_pp_size: 1 +train_dp_size: 1 + +batch_size: 8 +micro_batch_size: 1 +total_steps: 8 +learning_rate: 1.0e-6 +ppo_epochs: 1 +kl_coef: 0.001 +clip_epsilon: 0.2 +gamma: 1.0 +recompute_logprobs: true + +max_concurrent_rollouts: 16 +max_head_offpolicyness: 4 +queue_size: 32 +max_new_tokens: 512 +max_seq_length: 2048 +n_samples: 2 +temperature: 0.8 +top_p: 0.95 + +sync_interval: 4 +rollout_sync_drain_lead_steps: 1 +weight_sync_mode: "disk" +sync_path: "./logs/tier2_4gpu/weights" +rollout_weight_sync_mode: "restart" +rollout_weight_reload_method: "inplace" +rollout_weight_reload_strategy: "parallel" +rollout_weight_sync_control_dir: "./logs/tier2_4gpu/control" +rollout_weight_sync_timeout_s: 1200 +require_rollout_weight_sync: true + +eval_interval: 0 +save_interval: 0 +log_dir: "./logs/tier2_4gpu" +seed: 42 + +enable_history_collection: true +history_output_dir: "./logs/tier2_4gpu/history" +history_save_raw_lengths: true +history_flush_interval: 1 +history_experiment_name: "tier2_4gpu_dapo_math" + +heterogeneous_rollout: + enabled: true + total_gpus: 3 + vllm_host: "127.0.0.1" + vllm_base_port: 18920 + max_model_len: 2048 + gpu_memory_utilization: 0.65 + + instances: + - instance_id: "tp1" + tp: 1 + gpus: [1] + host: "127.0.0.1" + port: 18920 + - instance_id: "tp2" + tp: 2 + gpus: [2, 3] + host: "127.0.0.1" + port: 18921 + + scheduling: + scheduler_type: "cmlfq_cost" + load_balance_strategy: "least_connections" + max_queue_length: 16 + enable_fallback: true + cmlfq_rebuild_interval: 8 + cmlfq_tree_path: "./logs/tier2_4gpu/tree.json" + cmlfq_kv_backend: "recompute" + cmlfq_kv_transfer_tp_pairs: + - [1, 2] + - [2, 1] + cmlfq_buckets: + short: + tp_degrees: [1] + max_tokens: 512 + long: + tp_degrees: [2] + max_tokens: 2048 diff --git a/repro/tier2_four_gpu_closed_loop/config_8gpu_qwen3_4b.yaml b/repro/tier2_four_gpu_closed_loop/config_8gpu_qwen3_4b.yaml new file mode 100644 index 0000000..ea4a60b --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/config_8gpu_qwen3_4b.yaml @@ -0,0 +1,103 @@ +# Tier 2: 8-GPU Heterogeneous Closed Loop (1 Train + 7 Rollout GPUs: TP=1 + TP=2 + TP=4) +# Verified baseline: DAPO-Math + Qwen3-4B (no Slurm required). +hardware_config: ../../configs/hardware_config/h20_3e_141g.yaml +model_arch_config: ../../configs/model_arch_config/qwen3-4b.yaml + +model_path: "Qwen/Qwen3-4B" +tokenizer_path: "Qwen/Qwen3-4B" + +train_backend: "fsdp" +train_gpus: 1 +rollout_gpus: 7 +tp_size: 1 +train_tp_size: 1 +train_pp_size: 1 +train_dp_size: 1 + +batch_size: 16 +micro_batch_size: 1 +recompute_micro_batch_size: 1 +total_steps: 4 +learning_rate: 1.0e-6 +ppo_epochs: 1 +kl_coef: 0.001 +clip_epsilon: 0.2 +gamma: 1.0 +recompute_logprobs: false + +max_concurrent_rollouts: 32 +max_head_offpolicyness: 4 +queue_size: 32 +max_new_tokens: 1792 +max_seq_length: 6144 +n_samples: 2 +temperature: 0.8 +top_p: 0.95 + +sync_interval: 4 +rollout_sync_drain_lead_steps: 1 +weight_sync_mode: "disk" +sync_path: "./logs/tier2_8gpu/weights" +rollout_weight_sync_mode: "restart" +rollout_weight_reload_method: "inplace" +rollout_weight_reload_strategy: "parallel" +rollout_weight_sync_control_dir: "./logs/tier2_8gpu/control" +rollout_weight_sync_timeout_s: 1200 +require_rollout_weight_sync: true + +eval_interval: 0 +save_interval: 0 +log_dir: "./logs/tier2_8gpu" +seed: 42 + +enable_history_collection: true +history_output_dir: "./logs/tier2_8gpu/history" +history_save_raw_lengths: true +history_flush_interval: 1 +history_experiment_name: "tier2_8gpu_dapo_math" + +heterogeneous_rollout: + enabled: true + total_gpus: 7 + vllm_host: "127.0.0.1" + vllm_base_port: 18920 + max_model_len: 6144 + gpu_memory_utilization: 0.75 + + instances: + - instance_id: "tp1" + tp: 1 + gpus: [1] + host: "127.0.0.1" + port: 18920 + - instance_id: "tp2" + tp: 2 + gpus: [2, 3] + host: "127.0.0.1" + port: 18921 + - instance_id: "tp4" + tp: 4 + gpus: [4, 5, 6, 7] + host: "127.0.0.1" + port: 18922 + + scheduling: + scheduler_type: "cmlfq_cost" + load_balance_strategy: "least_connections" + max_queue_length: 16 + enable_fallback: true + cmlfq_rebuild_interval: 8 + cmlfq_tree_path: "./logs/tier2_8gpu/tree.json" + cmlfq_cost_profile_path: "./repro/tier2_four_gpu_closed_loop/sample_data/dapo_cost_profile.json" + cmlfq_kv_backend: "recompute" + cmlfq_kv_transfer_tp_pairs: [] + cmlfq_buckets: + short: + tp_degrees: [1] + max_tokens: 400 + medium: + tp_degrees: [2] + max_tokens: 1200 + long: + tp_degrees: [4] + max_tokens: 6144 diff --git a/repro/tier2_four_gpu_closed_loop/config_colab_1gpu.yaml b/repro/tier2_four_gpu_closed_loop/config_colab_1gpu.yaml new file mode 100644 index 0000000..dc1873b --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/config_colab_1gpu.yaml @@ -0,0 +1,77 @@ +# Tier 2 Colab: 1-GPU Co-Located Closed Loop (1 vLLM Rollout + 1 FSDP Trainer sharing GPU 0) +# Default preset sized for Colab Free T4 16GB (launch_4gpu.py scales automatically on L4 / A100). +hardware_config: ../../configs/hardware_config/a800_80g.yaml +model_arch_config: ../../configs/model_arch_config/qwen2.5-3b.yaml + +model_path: "Qwen/Qwen2.5-0.5B-Instruct" +tokenizer_path: "Qwen/Qwen2.5-0.5B-Instruct" + +train_backend: "fsdp" +train_gpus: 1 +rollout_gpus: 1 +tp_size: 1 +train_tp_size: 1 +train_pp_size: 1 +train_dp_size: 1 + +batch_size: 4 +micro_batch_size: 1 +total_steps: 4 +learning_rate: 1.0e-6 +ppo_epochs: 1 +kl_coef: 0.001 +clip_epsilon: 0.2 +gamma: 1.0 +recompute_logprobs: true + +max_concurrent_rollouts: 4 +max_head_offpolicyness: 4 +queue_size: 16 +max_new_tokens: 256 +max_seq_length: 1024 +n_samples: 2 +temperature: 0.8 +top_p: 0.95 + +sync_interval: 2 +rollout_sync_drain_lead_steps: 1 +weight_sync_mode: "disk" +sync_path: "./logs/tier2_colab/weights" +rollout_weight_sync_mode: "restart" +rollout_weight_reload_method: "inplace" +rollout_weight_reload_strategy: "parallel" +rollout_weight_sync_control_dir: "./logs/tier2_colab/control" +rollout_weight_sync_timeout_s: 1200 +require_rollout_weight_sync: true + +eval_interval: 0 +save_interval: 0 +log_dir: "./logs/tier2_colab" +seed: 42 + +enable_history_collection: true +history_output_dir: "./logs/tier2_colab/history" +history_save_raw_lengths: true +history_flush_interval: 1 +history_experiment_name: "tier2_colab_dapo_math" + +heterogeneous_rollout: + enabled: true + total_gpus: 1 + vllm_host: "127.0.0.1" + vllm_base_port: 18920 + max_model_len: 1024 + gpu_memory_utilization: 0.30 + + instances: + - instance_id: "tp1" + tp: 1 + gpus: [0] + host: "127.0.0.1" + port: 18920 + + scheduling: + scheduler_type: "load_balance" + load_balance_strategy: "least_connections" + max_queue_length: 8 + enable_fallback: true diff --git a/repro/tier2_four_gpu_closed_loop/launch_4gpu.py b/repro/tier2_four_gpu_closed_loop/launch_4gpu.py new file mode 100755 index 0000000..af3e1df --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/launch_4gpu.py @@ -0,0 +1,1011 @@ +#!/usr/bin/env python3 +"""Slurm-free Tier 2 launcher for 8-GPU / 4-GPU heterogeneous and 1-GPU Colab closed-loop RL.""" + +from __future__ import annotations + +import argparse +import importlib.util +import json +import os +import shutil +import signal +import subprocess +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path +from typing import Any + +import torch +import yaml + + +def _build_pythonpath(repo_root: Path, existing: str | None) -> str: + """Build an order-preserving, deduplicated PYTHONPATH for subprocesses.""" + entries: list[str] = [] + if repo_root.name == "RL_Framework": + entries.append(str(repo_root.parent)) + entries.append(str(repo_root)) + if existing: + for item in existing.split(os.pathsep): + if item: + entries.append(item) + deduped = list(dict.fromkeys(entries)) + return os.pathsep.join(deduped) + + +def _ensure_rl_framework_importable() -> Path: + repo_root = Path(__file__).resolve().parents[2] + if str(repo_root) not in sys.path: + sys.path.insert(0, str(repo_root)) + if importlib.util.find_spec("RL_Framework") is None: + spec = importlib.util.spec_from_file_location( + "RL_Framework", + repo_root / "__init__.py", + submodule_search_locations=[str(repo_root)], + ) + if spec is None or spec.loader is None: + raise ImportError(f"Unable to locate RL_Framework at {repo_root}") + module = importlib.util.module_from_spec(spec) + sys.modules["RL_Framework"] = module + spec.loader.exec_module(module) + return repo_root + + +REPO_ROOT = _ensure_rl_framework_importable() + +from RL_Framework.config import AsyncRLConfig # noqa: E402 +from RL_Framework.infra.scheduling.cmlfq_prefix_tree import CausalPrefixTree, Trajectory # noqa: E402 +from RL_Framework.infra.scheduling.cmlfq_tool_state import ( # noqa: E402 + ExecutionStatus, + PayloadSizeClass, + ToolReturnState, +) +from RL_Framework.scripts.summarize_scheduler_rl import summarize # noqa: E402 + + +DEFAULT_DATASET = ( + REPO_ROOT / "repro/tier2_four_gpu_closed_loop/sample_data/dapo_math_mini.jsonl" +) +DEFAULT_COST_PROFILE = ( + REPO_ROOT / "repro/tier2_four_gpu_closed_loop/sample_data/dapo_cost_profile.json" +) + +EIGHT_GPU_POLICIES = ("round_robin", "least_connections", "cmlfq", "cmlfq_cost") +FOUR_GPU_POLICIES = ("round_robin", "least_connections", "cmlfq", "cmlfq_cost") +COLAB_POLICIES = ("round_robin", "least_connections") + +COLAB_TIER_PRESETS: dict[str, dict[str, Any]] = { + "t4": { + "model": "Qwen/Qwen2.5-0.5B-Instruct", + "model_arch_yaml": "qwen2.5-3b.yaml", + "vllm_dtype": "half", + "fsdp_dtype": "float32", + "gpu_memory_utilization": 0.30, + "max_model_len": 1024, + "max_new_tokens": 256, + "batch_size": 4, + "max_num_seqs": 8, + "sync_interval": 2, + }, + "l4": { + "model": "Qwen/Qwen2.5-1.5B-Instruct", + "model_arch_yaml": "qwen2.5-3b.yaml", + "vllm_dtype": "bfloat16", + "fsdp_dtype": "bfloat16", + "gpu_memory_utilization": 0.35, + "max_model_len": 1536, + "max_new_tokens": 384, + "batch_size": 4, + "max_num_seqs": 8, + "sync_interval": 2, + }, + "a100-40g": { + "model": "Qwen/Qwen3-1.7B", + "model_arch_yaml": "qwen2.5-3b.yaml", + "vllm_dtype": "bfloat16", + "fsdp_dtype": "bfloat16", + "gpu_memory_utilization": 0.38, + "max_model_len": 2048, + "max_new_tokens": 512, + "batch_size": 8, + "max_num_seqs": 16, + "sync_interval": 2, + }, + "a100-80g": { + "model": "Qwen/Qwen3-4B", + "model_arch_yaml": "qwen3-4b.yaml", + "vllm_dtype": "bfloat16", + "fsdp_dtype": "bfloat16", + "gpu_memory_utilization": 0.38, + "max_model_len": 2048, + "max_new_tokens": 512, + "batch_size": 8, + "max_num_seqs": 16, + "sync_interval": 2, + }, +} + + +def detect_colab_tier() -> str: + """Detect GPU tier from CUDA compute capability and VRAM (defaults to t4 on CPU/T4).""" + if not torch.cuda.is_available(): + return "t4" + props = torch.cuda.get_device_properties(0) + total_mem_gib = props.total_memory / (1024**3) + if props.major < 8: + return "t4" + if total_mem_gib >= 70.0: + return "a100-80g" + if total_mem_gib >= 36.0: + return "a100-40g" + if total_mem_gib >= 20.0: + return "l4" + return "t4" + + +def parse_gpu_list(raw: str | None, *, mode: str) -> list[int]: + """Parse GPU indices from --gpus or CUDA_VISIBLE_DEVICES.""" + default_str = { + "8gpu": "0,1,2,3,4,5,6,7", + "4gpu": "0,1,2,3", + "colab-1gpu": "0", + }[mode] + source = ( + raw + if raw is not None + else (os.environ.get("CUDA_VISIBLE_DEVICES") or default_str) + ) + gpus = [int(item.strip()) for item in source.split(",") if item.strip()] + min_gpus = {"8gpu": 8, "4gpu": 4, "colab-1gpu": 1}[mode] + if len(gpus) < min_gpus: + raise ValueError( + f"Mode {mode!r} requires at least {min_gpus} GPU(s), got {gpus}" + ) + return gpus + + +def resolve_policies(policy: str, mode: str) -> list[str]: + """Resolve CLI --policy string into an ordered list of policies to run.""" + if mode == "8gpu": + if policy == "auto": + return ["cmlfq_cost"] + if policy == "all": + return ["round_robin", "least_connections", "cmlfq", "cmlfq_cost"] + if policy not in EIGHT_GPU_POLICIES: + raise ValueError( + f"Unsupported policy {policy!r} for 8gpu; choose from {EIGHT_GPU_POLICIES} or 'all'" + ) + return [policy] + + if mode == "4gpu": + if policy == "auto": + return ["cmlfq_cost"] + if policy == "all": + return ["round_robin", "least_connections", "cmlfq_cost"] + if policy not in FOUR_GPU_POLICIES: + raise ValueError( + f"Unsupported policy {policy!r} for 4gpu; choose from {FOUR_GPU_POLICIES} or 'all'" + ) + return [policy] + + if policy == "auto": + return ["least_connections"] + if policy == "all": + return ["round_robin", "least_connections"] + if policy not in COLAB_POLICIES: + raise ValueError( + f"Unsupported policy {policy!r} for colab-1gpu; choose from {COLAB_POLICIES} or 'all'" + ) + return [policy] + + +def _scheduling_block( + policy: str, + run_dir: Path, + kv_backend: str, + mode: str, + max_model_len: int, +) -> dict[str, Any]: + if mode == "colab-1gpu": + return { + "scheduler_type": "load_balance", + "load_balance_strategy": ( + "round_robin" if policy == "round_robin" else "least_connections" + ), + "max_queue_length": 8, + "enable_fallback": True, + } + + is_causal = policy in ("cmlfq", "cmlfq_cost") + if mode == "8gpu": + buckets = { + "short": {"tp_degrees": [1], "max_tokens": 400}, + "medium": {"tp_degrees": [2], "max_tokens": 1200}, + "long": {"tp_degrees": [4], "max_tokens": max(6144, max_model_len)}, + } + transfer_pairs = ( + [[1, 2], [2, 1], [1, 4], [4, 1], [2, 4], [4, 2]] + if (is_causal and kv_backend == "cpu_offload") + else [] + ) + else: + buckets = { + "short": {"tp_degrees": [1], "max_tokens": 512}, + "long": {"tp_degrees": [2], "max_tokens": max(2048, max_model_len)}, + } + transfer_pairs = ( + [[1, 2], [2, 1]] if (is_causal and kv_backend == "cpu_offload") else [] + ) + + block: dict[str, Any] = { + "scheduler_type": policy if is_causal else "load_balance", + "load_balance_strategy": ( + "round_robin" if policy == "round_robin" else "least_connections" + ), + "max_queue_length": 16, + "enable_fallback": True, + "cmlfq_kv_backend": kv_backend if is_causal else "recompute", + "cmlfq_tree_path": str(run_dir / "tree.json"), + "cmlfq_rebuild_interval": 8, + "cmlfq_kv_transfer_tp_pairs": transfer_pairs, + "cmlfq_buckets": buckets, + } + if policy == "cmlfq_cost" and DEFAULT_COST_PROFILE.is_file(): + block["cmlfq_cost_profile_path"] = str(DEFAULT_COST_PROFILE.resolve()) + return block + + +def _vllm_supervisor_command( + python_bin: str, + *, + instance_id: str, + control_dir: Path, + health_url: str, + initial_model: str, + port: int, + tp_size: int, + vllm_dtype: str, + max_model_len: int, + gpu_memory_utilization: float, + max_num_seqs: int, + seed: int, + kv_storage_dir: Path | None, + enable_cuda_graphs: bool = False, +) -> list[str]: + vllm_cmd = [ + python_bin, + str(REPO_ROOT / "scripts/vllm_hot_reload_api_server.py"), + "--model", + "__MODEL_PATH__", + "--host", + "127.0.0.1", + "--port", + str(port), + "--tensor-parallel-size", + str(tp_size), + "--dtype", + vllm_dtype, + "--max-model-len", + str(max_model_len), + "--gpu-memory-utilization", + str(gpu_memory_utilization), + "--max-num-seqs", + str(max_num_seqs), + ] + if enable_cuda_graphs and kv_storage_dir is None: + vllm_cmd.extend(["--disable-log-requests", "--enable-prefix-caching"]) + else: + vllm_cmd.extend( + ["--enforce-eager", "--disable-log-requests", "--no-enable-prefix-caching"] + ) + vllm_cmd.extend( + [ + "--seed", + str(seed), + "--worker-extension-cls", + "RL_Framework.vllm_hot_reload.InplaceReloadWorkerExtension", + ] + ) + if kv_storage_dir is not None: + vllm_cmd.extend( + [ + "--kv-transfer-config", + json.dumps( + { + "kv_connector": "LibraCPUOffloadConnector", + "kv_role": "kv_both", + "kv_connector_module_path": "RL_Framework.infra.scheduling.vllm_cpu_offload", + "kv_connector_extra_config": { + "storage_path": str(kv_storage_dir) + }, + } + ), + ] + ) + return [ + python_bin, + str(REPO_ROOT / "scripts/restartable_vllm_server.py"), + "--instance-id", + instance_id, + "--control-dir", + str(control_dir), + "--health-url", + health_url, + "--initial-model", + initial_model, + "--reload-method", + "inplace", + "--", + *vllm_cmd, + ] + + +def build_run_plan( + *, + mode: str, + policy: str, + gpus: list[int], + output_dir: Path, + dataset_path: Path, + model_path: str | None = None, + colab_tier: str = "auto", + steps: int | None = None, + batch_size: int | None = None, + n_samples: int = 2, + sync_interval: int | None = None, + seed: int = 42, + base_port: int = 18920, + kv_backend: str = "recompute", + gpu_memory_utilization: float | None = None, + max_model_len: int | None = None, + max_new_tokens: int | None = None, + max_turns: int | None = None, + python_bin: str = sys.executable, +) -> dict[str, Any]: + """Build a complete Slurm-free launch plan for one trial run.""" + run_dir = (output_dir / f"{policy}_{seed}").resolve() + control_dir = run_dir / "control" + resolved_tier: str | None = None + resolved_turns = max_turns if max_turns is not None else (3 if mode == "8gpu" else 2) + enable_cuda_graphs = mode in ("8gpu", "4gpu") and kv_backend == "recompute" + + if mode == "colab-1gpu": + resolved_tier = detect_colab_tier() if colab_tier == "auto" else colab_tier + preset = COLAB_TIER_PRESETS[resolved_tier] + resolved_model = model_path or preset["model"] + arch_yaml = preset["model_arch_yaml"] + hw_yaml = "a800_80g.yaml" + vllm_dtype = preset["vllm_dtype"] + fsdp_dtype = preset["fsdp_dtype"] + gpu_util = ( + gpu_memory_utilization + if gpu_memory_utilization is not None + else preset["gpu_memory_utilization"] + ) + resolved_max_len = max_model_len or preset["max_model_len"] + resolved_max_new = max_new_tokens or preset["max_new_tokens"] + resolved_batch = batch_size or preset["batch_size"] + resolved_micro_batch = 1 + resolved_steps = steps or 4 + resolved_sync = sync_interval or preset["sync_interval"] + max_num_seqs = preset["max_num_seqs"] + max_concurrent = resolved_batch * n_samples + train_gpu = gpus[0] + rollout_layout = [("tp1", 1, [gpus[0]], base_port)] + rollout_gpus = 1 + kv_storage_dir = None + elif mode == "8gpu": + resolved_model = model_path or "Qwen/Qwen3-4B" + arch_yaml = "qwen3-4b.yaml" + h20_cfg = REPO_ROOT / "configs/hardware_config/h20_3e_141g.yaml" + hw_yaml = "h20_3e_141g.yaml" if h20_cfg.is_file() else "a800_80g.yaml" + vllm_dtype = "bfloat16" + fsdp_dtype = "bfloat16" + gpu_util = gpu_memory_utilization if gpu_memory_utilization is not None else 0.75 + resolved_max_len = max_model_len or 6144 + resolved_max_new = max_new_tokens or 1792 + resolved_batch = batch_size or 16 + resolved_micro_batch = 1 + resolved_steps = steps or 4 + resolved_sync = sync_interval or 4 + max_num_seqs = 16 + max_concurrent = max(32, resolved_batch * 2) + train_gpu = gpus[0] + rollout_layout = [ + ("tp1", 1, [gpus[1]], base_port), + ("tp2", 2, [gpus[2], gpus[3]], base_port + 1), + ("tp4", 4, [gpus[4], gpus[5], gpus[6], gpus[7]], base_port + 2), + ] + rollout_gpus = 7 + kv_base = Path("/dev/shm") if Path("/dev/shm").is_dir() else run_dir + kv_storage_dir = ( + kv_base / f"libra-tier2-{os.getpid()}-{policy}-s{seed}" + if (kv_backend == "cpu_offload" and policy in ("cmlfq", "cmlfq_cost")) + else None + ) + else: + resolved_model = model_path or "Qwen/Qwen3-4B" + arch_yaml = "qwen3-4b.yaml" + hw_yaml = "a800_80g.yaml" + vllm_dtype = "bfloat16" + fsdp_dtype = "bfloat16" + gpu_util = gpu_memory_utilization if gpu_memory_utilization is not None else 0.65 + resolved_max_len = max_model_len or 2048 + resolved_max_new = max_new_tokens or 512 + resolved_batch = batch_size or 8 + resolved_micro_batch = 1 + resolved_steps = steps or 8 + resolved_sync = sync_interval or 4 + max_num_seqs = 16 + max_concurrent = max(16, resolved_batch * n_samples) + train_gpu = gpus[0] + rollout_layout = [ + ("tp1", 1, [gpus[1]], base_port), + ("tp2", 2, [gpus[2], gpus[3]], base_port + 1), + ] + rollout_gpus = 3 + kv_base = Path("/dev/shm") if Path("/dev/shm").is_dir() else run_dir + kv_storage_dir = ( + kv_base / f"libra-tier2-{os.getpid()}-{policy}-s{seed}" + if (kv_backend == "cpu_offload" and policy in ("cmlfq", "cmlfq_cost")) + else None + ) + + instances = [ + { + "instance_id": inst_id, + "tp": tp, + "gpus": inst_gpus, + "host": "127.0.0.1", + "port": port, + } + for inst_id, tp, inst_gpus, port in rollout_layout + ] + + config_dict: dict[str, Any] = { + "hardware_config": str( + (REPO_ROOT / "configs/hardware_config" / hw_yaml).resolve() + ), + "model_arch_config": str( + (REPO_ROOT / "configs/model_arch_config" / arch_yaml).resolve() + ), + "model_path": resolved_model, + "tokenizer_path": resolved_model, + "train_backend": "fsdp", + "train_gpus": 1, + "rollout_gpus": rollout_gpus, + "tp_size": 1, + "train_tp_size": 1, + "train_pp_size": 1, + "train_dp_size": 1, + "batch_size": resolved_batch, + "micro_batch_size": resolved_micro_batch, + "recompute_micro_batch_size": resolved_micro_batch, + "total_steps": resolved_steps, + "n_samples": n_samples, + "max_concurrent_rollouts": max_concurrent, + "max_head_offpolicyness": 4, + "queue_size": 32, + "max_new_tokens": resolved_max_new, + "max_seq_length": resolved_max_len, + "temperature": 0.8, + "top_p": 0.95, + "learning_rate": 1.0e-6, + "ppo_epochs": 1, + "seed": seed, + "recompute_logprobs": False if mode == "8gpu" else True, + "sync_interval": resolved_sync, + "rollout_sync_drain_lead_steps": 1, + "weight_sync_mode": "disk", + "sync_path": str(run_dir / "weights"), + "rollout_weight_sync_mode": "restart", + "rollout_weight_reload_method": "inplace", + "rollout_weight_reload_strategy": "parallel", + "rollout_weight_sync_control_dir": str(control_dir), + "require_rollout_weight_sync": True, + "eval_interval": 0, + "save_interval": 0, + "log_dir": str(run_dir), + "enable_history_collection": True, + "history_output_dir": str(run_dir / "history"), + "history_save_raw_lengths": True, + "history_flush_interval": 1, + "history_experiment_name": f"tier2_{mode}_{policy}", + "heterogeneous_rollout": { + "enabled": True, + "total_gpus": rollout_gpus, + "vllm_host": "127.0.0.1", + "vllm_base_port": base_port, + "max_model_len": resolved_max_len, + "gpu_memory_utilization": gpu_util, + "instances": instances, + "scheduling": _scheduling_block( + policy, run_dir, kv_backend, mode, resolved_max_len + ), + }, + } + + env_overrides: dict[str, str] = { + "PYTHONPATH": _build_pythonpath(REPO_ROOT, os.environ.get("PYTHONPATH")), + "VLLM_USE_V1": "1", + "VLLM_WORKER_MULTIPROC_METHOD": "spawn", + "OMP_NUM_THREADS": "4", + "TOKENIZERS_PARALLELISM": "false", + "WANDB_MODE": "disabled", + "FSDP_GRADIENT_CHECKPOINTING": "0" if mode == "8gpu" else "1", + "FSDP_DTYPE": fsdp_dtype, + "FSDP_PROGRESS_DIR": str(run_dir / "progress"), + "BENCH_RUN_DIR": str(run_dir), + "DAPO_MATH_PATH": str(dataset_path.resolve()), + "DAPO_MAX_TURNS": str(resolved_turns), + "DAPO_MAX_PROMPT_TOKENS": "384" if resolved_max_len <= 1024 else "512", + "NO_PROXY": "localhost,127.0.0.1", + "no_proxy": "localhost,127.0.0.1", + } + if kv_storage_dir is not None: + env_overrides["LIBRA_KV_STORAGE_PATH"] = str(kv_storage_dir) + env_overrides["VLLM_ATTENTION_BACKEND"] = os.environ.get( + "VLLM_ATTENTION_BACKEND", "FLASH_ATTN" + ) + + config_path = run_dir / "config.yaml" + rollout_specs = [] + for inst_id, tp, inst_gpus, port in rollout_layout: + health_url = f"http://127.0.0.1:{port}/health" + inst_max_num_seqs = ( + {1: 1, 2: 2, 4: 16}.get(tp, max_num_seqs) + if mode == "8gpu" + else max_num_seqs + ) + rollout_specs.append( + { + "instance_id": inst_id, + "tp": tp, + "gpus": inst_gpus, + "cuda_visible_devices": ",".join(str(g) for g in inst_gpus), + "port": port, + "health_url": health_url, + "log_path": str(run_dir / f"vllm_{inst_id}.log"), + "command": _vllm_supervisor_command( + python_bin, + instance_id=inst_id, + control_dir=control_dir, + health_url=health_url, + initial_model=resolved_model, + port=port, + tp_size=tp, + vllm_dtype=vllm_dtype, + max_model_len=resolved_max_len, + gpu_memory_utilization=gpu_util, + max_num_seqs=inst_max_num_seqs, + seed=seed, + kv_storage_dir=kv_storage_dir, + enable_cuda_graphs=enable_cuda_graphs, + ), + } + ) + + train_spec = { + "gpus": [train_gpu], + "cuda_visible_devices": str(train_gpu), + "log_path": str(run_dir / "train.log"), + "env_overrides": { + "RANK": "0", + "LOCAL_RANK": "0", + "WORLD_SIZE": "1", + }, + "command": [ + python_bin, + str(REPO_ROOT / "scripts/benchmark_scheduler_train.py"), + "--config", + str(config_path), + ], + } + + return { + "mode": mode, + "policy": policy, + "seed": seed, + "colab_tier": resolved_tier, + "model": resolved_model, + "vllm_dtype": vllm_dtype, + "fsdp_dtype": fsdp_dtype, + "run_dir": str(run_dir), + "config_path": str(config_path), + "config": config_dict, + "env_overrides": env_overrides, + "rollout_specs": rollout_specs, + "train_spec": train_spec, + "kv_storage_dir": str(kv_storage_dir) if kv_storage_dir is not None else None, + } + + +def _seed_warmup_tree_file(tree_path: Path, mode: str, policy: str) -> None: + """Seed causal warmup trajectories into ``tree_path`` for ``cmlfq`` / ``cmlfq_cost``.""" + unit = "model_generated_tokens" if policy == "cmlfq_cost" else "context_tokens" + tree = CausalPrefixTree() + + small_fail = ToolReturnState( + "dapo_math_validator", PayloadSizeClass.SizeSmall, ExecutionStatus.ToolFailure + ) + small_succ = ToolReturnState( + "dapo_math_validator", PayloadSizeClass.SizeSmall, ExecutionStatus.ToolSuccess + ) + small_timeout = ToolReturnState( + "dapo_math_validator", PayloadSizeClass.SizeSmall, ExecutionStatus.ToolTimeout + ) + med_fail = ToolReturnState( + "dapo_math_validator", PayloadSizeClass.SizeMedium, ExecutionStatus.ToolFailure + ) + med_succ = ToolReturnState( + "dapo_math_validator", PayloadSizeClass.SizeMedium, ExecutionStatus.ToolSuccess + ) + large_fail = ToolReturnState( + "dapo_math_validator", PayloadSizeClass.SizeLarge, ExecutionStatus.ToolFailure + ) + large_succ = ToolReturnState( + "dapo_math_validator", PayloadSizeClass.SizeLarge, ExecutionStatus.ToolSuccess + ) + + if mode == "8gpu": + # Preserves bimodal Turn-1 signal on small:failure (mean in medium <= 1200, + # p90 in long > 1200) across Steps 0..3 so cmlfq waits until Turn 2 while + # cmlfq_cost eagerly promotes via residual_distribution + dapo_cost_profile.json. + specs = [ + (3, [large_fail, large_fail], [3584.0, 1792.0], 3616.0), + (1, [large_fail, large_succ], [3584.0, 1792.0], 3616.0), + (3, [med_fail], [1120.0], 1152.0), + (1, [med_succ], [1120.0], 1152.0), + (6, [small_timeout, small_timeout], [320.0, 160.0], 352.0), + (18, [small_fail], [96.0], 128.0), + (2, [small_fail, small_fail], [3584.0, 1792.0], 3616.0), + (1, [small_fail, small_succ], [3584.0, 1792.0], 3616.0), + ] + else: + specs = [ + (2, [large_fail, large_fail], [1536.0, 768.0], 1664.0), + (1, [large_fail, large_succ], [1536.0, 768.0], 1664.0), + (4, [small_fail], [96.0], 224.0), + (1, [small_fail, small_fail], [1536.0, 768.0], 1664.0), + ] + + idx = 0 + for count, states, rem, total_len in specs: + for _ in range(count): + tree.insert( + Trajectory( + prompt_id=f"__warmup_{idx}", + return_states=list(states), + total_remaining_lengths=list(rem), + total_length=total_len, + remaining_unit=unit, + ) + ) + idx += 1 + + suffix = tree_path.suffix or ".json" + stem = tree_path.name[: -len(tree_path.suffix)] if tree_path.suffix else tree_path.name + for stale in tree_path.parent.glob(f"{stem}.rank_*{suffix}"): + stale.unlink(missing_ok=True) + tree.save(str(tree_path)) + + +def materialize_run_plan(plan: dict[str, Any]) -> None: + """Write config.yaml + launch_plan.json and validate with AsyncRLConfig.from_yaml.""" + run_dir = Path(plan["run_dir"]) + run_dir.mkdir(parents=True, exist_ok=True) + Path(plan["config"]["rollout_weight_sync_control_dir"]).mkdir( + parents=True, exist_ok=True + ) + if plan["kv_storage_dir"]: + Path(plan["kv_storage_dir"]).mkdir(parents=True, exist_ok=True) + + sched_cfg = plan["config"]["heterogeneous_rollout"]["scheduling"] + if plan["policy"] in ("cmlfq", "cmlfq_cost") and plan["mode"] in ("8gpu", "4gpu"): + tree_path_str = sched_cfg.get("cmlfq_tree_path") + if tree_path_str: + _seed_warmup_tree_file(Path(tree_path_str), plan["mode"], plan["policy"]) + + config_path = Path(plan["config_path"]) + config_path.write_text( + yaml.safe_dump(plan["config"], sort_keys=False), encoding="utf-8" + ) + AsyncRLConfig.from_yaml(str(config_path)) + + plan_file = run_dir / "launch_plan.json" + plan_file.write_text( + json.dumps( + { + "mode": plan["mode"], + "policy": plan["policy"], + "seed": plan["seed"], + "colab_tier": plan["colab_tier"], + "model": plan["model"], + "vllm_dtype": plan["vllm_dtype"], + "fsdp_dtype": plan["fsdp_dtype"], + "config_path": plan["config_path"], + "env_overrides": plan["env_overrides"], + "rollout_specs": plan["rollout_specs"], + "train_spec": plan["train_spec"], + }, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + + +def _stop_process(proc: subprocess.Popen[Any]) -> None: + if proc.poll() is not None: + return + try: + os.killpg(proc.pid, signal.SIGTERM) + proc.wait(timeout=30) + except (ProcessLookupError, subprocess.TimeoutExpired): + try: + os.killpg(proc.pid, signal.SIGKILL) + proc.wait(timeout=10) + except ProcessLookupError: + pass + + +def _wait_for_health( + processes: list[subprocess.Popen[Any]], + health_urls: list[str], + timeout_s: float = 600.0, +) -> None: + deadline = time.monotonic() + timeout_s + for url in health_urls: + while True: + for proc in processes: + if proc.poll() is not None: + raise RuntimeError( + f"Rollout server exited early with code {proc.returncode}; check vLLM logs." + ) + try: + with urllib.request.urlopen(url, timeout=2) as resp: + if resp.status == 200: + break + except (OSError, urllib.error.URLError): + pass + if time.monotonic() > deadline: + raise TimeoutError(f"Rollout server health check timed out: {url}") + time.sleep(2) + + +def execute_run_plan(plan: dict[str, Any], timeout_s: float = 2400.0) -> None: + """Launch supervised vLLM rollout servers and FSDP trainer, cleaning up on exit.""" + materialize_run_plan(plan) + env = dict(os.environ, **plan["env_overrides"]) + processes: list[subprocess.Popen[Any]] = [] + log_handles = [] + cache_dirs: list[Path] = [] + + try: + health_urls = [] + for spec in plan["rollout_specs"]: + inst_cache = Path(plan["run_dir"]) / f"cache_{spec['instance_id']}" + for sub in ("vllm", "inductor", "triton"): + (inst_cache / sub).mkdir(parents=True, exist_ok=True) + cache_dirs.append(inst_cache) + inst_env = dict( + env, + CUDA_VISIBLE_DEVICES=spec["cuda_visible_devices"], + VLLM_CACHE_ROOT=str(inst_cache / "vllm"), + TORCHINDUCTOR_CACHE_DIR=str(inst_cache / "inductor"), + TRITON_CACHE_DIR=str(inst_cache / "triton"), + ) + log_file = Path(spec["log_path"]).open("w", encoding="utf-8") + log_handles.append(log_file) + proc = subprocess.Popen( + spec["command"], + env=inst_env, + stdout=log_file, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + processes.append(proc) + health_urls.append(spec["health_url"]) + + print(f"[Tier 2] Waiting for rollout health checks: {health_urls}") + _wait_for_health(processes, health_urls, timeout_s=600.0) + print("[Tier 2] All rollout servers ready. Starting FSDP trainer...") + + train_spec = plan["train_spec"] + train_log = Path(train_spec["log_path"]).open("w", encoding="utf-8") + log_handles.append(train_log) + train_env = dict( + env, + **train_spec.get("env_overrides", {}), + CUDA_VISIBLE_DEVICES=train_spec["cuda_visible_devices"], + ) + for key in ( + "MASTER_ADDR", + "MASTER_PORT", + "GROUP_RANK", + "ROLE_RANK", + "LOCAL_WORLD_SIZE", + ): + train_env.pop(key, None) + train_proc = subprocess.Popen( + train_spec["command"], + env=train_env, + stdout=train_log, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + processes.append(train_proc) + + deadline = time.monotonic() + timeout_s + while train_proc.poll() is None: + if time.monotonic() > deadline: + raise TimeoutError(f"Training exceeded {timeout_s}s timeout") + time.sleep(5) + + if train_proc.returncode != 0: + raise RuntimeError( + f"Trainer exited with code {train_proc.returncode}; inspect {train_spec['log_path']}" + ) + finally: + for proc in processes: + _stop_process(proc) + for handle in log_handles: + handle.close() + for cdir in cache_dirs: + shutil.rmtree(cdir, ignore_errors=True) + if plan["kv_storage_dir"]: + shutil.rmtree(plan["kv_storage_dir"], ignore_errors=True) + + +def _print_dry_run_summary(plans: list[dict[str, Any]]) -> None: + print("# Libra Tier 2 — Dry-Run Launch Plan (Slurm-Free)") + for plan in plans: + print( + f"\n## Policy: `{plan['policy']}` | Mode: `{plan['mode']}`" + + (f" (`{plan['colab_tier']}`)" if plan["colab_tier"] else "") + ) + print(f"- Model: `{plan['model']}` (`vllm={plan['vllm_dtype']}`, `fsdp={plan['fsdp_dtype']}`)") + print(f"- Config: `{plan['config_path']}` (validated via `AsyncRLConfig.from_yaml`)") + for spec in plan["rollout_specs"]: + print( + f"- Rollout `{spec['instance_id']}` (GPU={spec['cuda_visible_devices']}, TP={spec['tp']}): " + f"`{' '.join(spec['command'])}`" + ) + train_spec = plan["train_spec"] + print( + f"- Trainer (GPU={train_spec['cuda_visible_devices']}): " + f"`{' '.join(train_spec['command'])}`" + ) + + +def build_arg_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Tier 2 Slurm-free launcher for 8-GPU / 4-GPU closed loop and 1-GPU Google Colab" + ) + parser.add_argument( + "--mode", + choices=("8gpu", "4gpu", "colab-1gpu"), + default="4gpu", + help="8gpu: 1 Train + 7 Rollout [TP=1,2,4]; 4gpu: 1 Train + 3 Rollout [TP=1,2]; colab-1gpu: co-located GPU", + ) + parser.add_argument( + "--policy", + default="auto", + help="Scheduling policy (8gpu/4gpu: round_robin/least_connections/cmlfq/cmlfq_cost/all; colab-1gpu: least_connections/round_robin/all)", + ) + parser.add_argument( + "--colab-tier", + choices=("auto", *COLAB_TIER_PRESETS.keys()), + default="auto", + help="GPU preset tier when --mode colab-1gpu (default: auto-detect VRAM/SM)", + ) + parser.add_argument("--model", default=None, help="Override HuggingFace/local model path") + parser.add_argument( + "--dataset", + type=Path, + default=DEFAULT_DATASET, + help="DAPO-Math JSONL or Parquet dataset path", + ) + parser.add_argument( + "--gpus", + default=None, + help="Comma-separated GPU IDs (defaults to CUDA_VISIBLE_DEVICES or 0..7 / 0..3 / 0)", + ) + parser.add_argument( + "--output-dir", + type=Path, + default=REPO_ROOT / "logs/tier2_closed_loop", + help="Directory for run configs, checkpoints, history, and summary.json", + ) + parser.add_argument("--steps", type=int, default=None, help="Training steps") + parser.add_argument("--batch-size", type=int, default=None, help="Trajectories per RL step") + parser.add_argument("--n-samples", type=int, default=2, help="Rollouts per prompt") + parser.add_argument("--sync-interval", type=int, default=None, help="Weight reload interval") + parser.add_argument("--seed", type=int, default=42, help="Random seed") + parser.add_argument("--base-port", type=int, default=18920, help="Starting vLLM port") + parser.add_argument( + "--kv-backend", + choices=("recompute", "cpu_offload"), + default="recompute", + help="KV movement backend for cmlfq/cmlfq_cost (default: recompute)", + ) + parser.add_argument("--gpu-memory-utilization", type=float, default=None) + parser.add_argument("--max-model-len", type=int, default=None) + parser.add_argument("--max-new-tokens", type=int, default=None) + parser.add_argument("--max-turns", type=int, default=None, help="Max rollout turns per episode") + parser.add_argument( + "--dry-run", + action="store_true", + help="Materialize and validate configs/commands without launching GPUs", + ) + return parser + + +def main(argv: list[str] | None = None) -> int: + parser = build_arg_parser() + args = parser.parse_args(argv) + + if not args.dataset.exists(): + raise FileNotFoundError(f"Dataset not found: {args.dataset}") + + gpus = parse_gpu_list(args.gpus, mode=args.mode) + policies = resolve_policies(args.policy, args.mode) + + plans = [ + build_run_plan( + mode=args.mode, + policy=pol, + gpus=gpus, + output_dir=args.output_dir, + dataset_path=args.dataset, + model_path=args.model, + colab_tier=args.colab_tier, + steps=args.steps, + batch_size=args.batch_size, + n_samples=args.n_samples, + sync_interval=args.sync_interval, + seed=args.seed, + base_port=args.base_port, + kv_backend=args.kv_backend, + gpu_memory_utilization=args.gpu_memory_utilization, + max_model_len=args.max_model_len, + max_new_tokens=args.max_new_tokens, + max_turns=args.max_turns, + ) + for pol in policies + ] + + if args.dry_run: + for plan in plans: + materialize_run_plan(plan) + _print_dry_run_summary(plans) + return 0 + + for plan in plans: + print(f"\n[Tier 2] Starting run: policy={plan['policy']} mode={plan['mode']} dir={plan['run_dir']}") + execute_run_plan(plan) + + try: + summary = summarize(args.output_dir.resolve()) + (args.output_dir / "summary.json").write_text( + json.dumps(summary, indent=2) + "\n", encoding="utf-8" + ) + print("\n=== Tier 2 Summary ===") + print(json.dumps(summary, indent=2)) + except ValueError as exc: + print(f"[Tier 2] Note: summary skipped ({exc})") + + history_glob = next(args.output_dir.glob("*/history/*.jsonl"), None) + if history_glob is not None: + tp_arg = "1,2,4" if args.mode == "8gpu" else "1,2" + print( + "\nReplay collected rollout trace on CPU (Tier 1):\n" + f" python repro/tier1_zero_gpu_replay/run_replay.py --trace {history_glob} --tp-layout {tp_arg}" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/repro/tier2_four_gpu_closed_loop/run_4gpu.sh b/repro/tier2_four_gpu_closed_loop/run_4gpu.sh new file mode 100755 index 0000000..10f3b95 --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/run_4gpu.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +exec python3 "$ROOT/repro/tier2_four_gpu_closed_loop/launch_4gpu.py" "$@" diff --git a/repro/tier2_four_gpu_closed_loop/run_8gpu.sh b/repro/tier2_four_gpu_closed_loop/run_8gpu.sh new file mode 100755 index 0000000..a69ae8d --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/run_8gpu.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +exec python3 "$ROOT/repro/tier2_four_gpu_closed_loop/launch_4gpu.py" --mode 8gpu "$@" diff --git a/repro/tier2_four_gpu_closed_loop/run_ehp.sh b/repro/tier2_four_gpu_closed_loop/run_ehp.sh new file mode 100755 index 0000000..0ae251d --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/run_ehp.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" +PYTHON_BIN="${PYTHON_BIN:-python3}" + +exec "${PYTHON_BIN}" "${SCRIPT_DIR}/benchmark_ehp.py" \ + --model "${MODEL:-/mnt/tidal-alsh-hilab/dataset/diandian/model/qwen3/Qwen3-4B}" \ + --dataset "${DATASET:-${SCRIPT_DIR}/sample_data/dapo_math_mini.jsonl}" \ + --output-dir "${OUTPUT_DIR:-/workspace/libra-tier2-eval/runs/h20_8gpu_ehp}" \ + --steps "${STEPS:-3}" \ + --warmup-steps "${WARMUP_STEPS:-1}" \ + --seq-len "${SEQ_LEN:-1536}" \ + --micro-batch-size "${MICRO_BATCH_SIZE:-2}" \ + "$@" diff --git a/repro/tier2_four_gpu_closed_loop/run_grp.sh b/repro/tier2_four_gpu_closed_loop/run_grp.sh new file mode 100755 index 0000000..7882155 --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/run_grp.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PYTHON_BIN="${PYTHON_BIN:-python3}" + +exec "${PYTHON_BIN}" "${SCRIPT_DIR}/benchmark_grp.py" \ + --model "${MODEL:-/mnt/tidal-alsh-hilab/dataset/diandian/model/qwen3/Qwen3-4B}" \ + --dataset "${DATASET:-${SCRIPT_DIR}/sample_data/dapo_math_mini.jsonl}" \ + --output-dir "${OUTPUT_DIR:-/workspace/libra-tier2-eval/runs/h20_8gpu_grp}" \ + --python-bin "${PYTHON_BIN}" \ + "$@" diff --git a/repro/tier2_four_gpu_closed_loop/sample_data/dapo_cost_profile.json b/repro/tier2_four_gpu_closed_loop/sample_data/dapo_cost_profile.json new file mode 100644 index 0000000..d37c8c6 --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/sample_data/dapo_cost_profile.json @@ -0,0 +1,19 @@ +{ + "decode_ms": { + "1": { + "short": 300.0, + "medium": 28000.0, + "long": 240000.0 + }, + "2": { + "short": 1200.0, + "medium": 2800.0, + "long": 90000.0 + }, + "4": { + "short": 1200.0, + "medium": 14000.0, + "long": 3200.0 + } + } +} diff --git a/repro/tier2_four_gpu_closed_loop/sample_data/dapo_math_mini.jsonl b/repro/tier2_four_gpu_closed_loop/sample_data/dapo_math_mini.jsonl new file mode 100644 index 0000000..52686d4 --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/sample_data/dapo_math_mini.jsonl @@ -0,0 +1,64 @@ +{"prompt_id": "dapo_mini_00", "question": "Solve for $x$: $2x + 7 = 13$.", "ground_truth": "3", "answer": "3", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_01", "question": "Find the remainder when $7^{2025}$ is divided by $1000$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "807", "answer": "807", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_02", "question": "Solve for $x$: $3x + 10 = 34$.", "ground_truth": "8", "answer": "8", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_03", "question": "Find the smallest positive integer $n$ such that $n \\equiv 3 \\pmod{7}$, $n \\equiv 5 \\pmod{11}$, and $n \\equiv 9 \\pmod{13}$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "269", "answer": "269", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32], "tool_status": "failure"} +{"prompt_id": "dapo_mini_04", "question": "Solve for $x$: $4x + 13 = 65$.", "ground_truth": "13", "answer": "13", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_05", "question": "Find the sum of all positive integers $n \\le 250$ that leave remainder $2$ when divided by $7$ and are divisible by neither $3$ nor $5$.", "ground_truth": "2448", "answer": "2448", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_06", "question": "Solve for $x$: $5x + 16 = 106$.", "ground_truth": "18", "answer": "18", "data_source": "dapo_math_mini", "archetype": "short_clean", "max_turns": 1, "turn_max_tokens": [32], "ignore_eos": true, "payload_size_class": "", "validator_hint": "", "tool_status": ""} +{"prompt_id": "dapo_mini_07", "question": "How many ordered triples of positive integers $(a, b, c)$ satisfy $a + b + c = 30$ with $a \\le 12$, $b \\le 14$, and $c \\le 16$? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "90", "answer": "90", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_08", "question": "Solve for $x$: $6x + 19 = 43$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "4", "answer": "4", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_09", "question": "How many lattice paths from $(0,0)$ to $(6,6)$ taking steps $(+1,0)$ or $(0,+1)$ avoid both $(2,3)$ and $(4,4)$? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "334", "answer": "334", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_10", "question": "Solve for $x$: $7x + 9 = 72$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "9", "answer": "9", "data_source": "dapo_math_mini", "archetype": "long_cascading", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_11", "question": "Let $r_1, r_2, r_3$ be the three roots of $x^3 - 7x^2 + 11x - 3 = 0$. Compute $r_1^3 + r_2^3 + r_3^3$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "121", "answer": "121", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_12", "question": "Solve for $x$: $8x + 12 = 124$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "14", "answer": "14", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_13", "question": "A sequence satisfies $a_0 = 1$, $a_1 = 3$, and $a_n = 5a_{n-1} - 6a_{n-2} + n$ for $n \\ge 2$. Find the remainder when $a_{10}$ is divided by $1000$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "795", "answer": "795", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_14", "question": "Solve for $x$: $9x + 15 = 186$.", "ground_truth": "19", "answer": "19", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_15", "question": "How many triples of non-negative integers $(x, y, z)$ satisfy $3x + 5y + 7z = 100$?", "ground_truth": "55", "answer": "55", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_16", "question": "An arithmetic sequence starts at $2$ with common difference $3$. Find the sum of its first $6$ terms. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "57", "answer": "57", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_17", "question": "Triangle $ABC$ has side lengths $AB = 13$, $AC = 14$, and $BC = 15$. The internal angle bisector of $\\angle BAC$ meets side $BC$ at $D$. Express the area of $\\triangle ABD$ as an irreducible fraction $\\frac{p}{q}$ and find $p + q$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "373", "answer": "373", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_18", "question": "An arithmetic sequence starts at $4$ with common difference $4$. Find the sum of its first $7$ terms.", "ground_truth": "112", "answer": "112", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_19", "question": "In a circle of radius $13$, chord $AB$ has length $24$ with midpoint $M$. Point $P$ lies on $AB$ at distance $4$ from $M$, and chord $CD$ passes through $P$ perpendicular to $AB$. Compute $CD^2$.", "ground_truth": "612", "answer": "612", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_20", "question": "An arithmetic sequence starts at $6$ with common difference $5$. Find the sum of its first $8$ terms. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "188", "answer": "188", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_21", "question": "Find the remainder when $\\binom{30}{15} + \\binom{30}{10}$ is divided by $1009$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "945", "answer": "945", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_22", "question": "An arithmetic sequence starts at $8$ with common difference $6$. Find the sum of its first $9$ terms. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "288", "answer": "288", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_23", "question": "How many $5$-digit positive integers (from $10000$ to $99999$) have digit sum equal to $23$ and every digit at most $6$? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "321", "answer": "321", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32], "tool_status": "failure"} +{"prompt_id": "dapo_mini_24", "question": "An arithmetic sequence starts at $10$ with common difference $7$. Find the sum of its first $10$ terms. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "415", "answer": "415", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_25", "question": "Three distinct integers are chosen uniformly at random from $\\{1, 2, \\dots, 20\\}$. The probability that their product is divisible by $4$ is $\\frac{p}{q}$ in lowest terms. Find $p + q$.", "ground_truth": "129", "answer": "129", "data_source": "dapo_math_mini", "archetype": "short_clean", "max_turns": 1, "turn_max_tokens": [32], "ignore_eos": true, "payload_size_class": "", "validator_hint": "", "tool_status": ""} +{"prompt_id": "dapo_mini_26", "question": "An arithmetic sequence starts at $12$ with common difference $3$. Find the sum of its first $11$ terms.", "ground_truth": "297", "answer": "297", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_27", "question": "Over all permutations $(a, b, c, d, e)$ of $\\{2, 5, 9, 14, 20\\}$, find the maximum possible value of $ab + bc + cd + de$.", "ground_truth": "548", "answer": "548", "data_source": "dapo_math_mini", "archetype": "short_clean", "max_turns": 1, "turn_max_tokens": [32], "ignore_eos": true, "payload_size_class": "", "validator_hint": "", "tool_status": ""} +{"prompt_id": "dapo_mini_28", "question": "An arithmetic sequence starts at $14$ with common difference $4$. Find the sum of its first $6$ terms. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "144", "answer": "144", "data_source": "dapo_math_mini", "archetype": "long_cascading", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_29", "question": "How many functions $f: \\{1, 2, 3, 4, 5\\} \\to \\{1, 2, 3, 4, 5\\}$ satisfy $f(f(f(x))) = x$ for every $x \\in \\{1, 2, 3, 4, 5\\}$? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "21", "answer": "21", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_30", "question": "An arithmetic sequence starts at $16$ with common difference $5$. Find the sum of its first $7$ terms. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "217", "answer": "217", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_31", "question": "In how many ways can the vertices of a labeled regular pentagon be colored using $4$ available colors such that no two adjacent vertices receive the same color? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "240", "answer": "240", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32], "tool_status": "failure"} +{"prompt_id": "dapo_mini_32", "question": "Compute the remainder when $5^{3}$ is divided by $7$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "6", "answer": "6", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_33", "question": "Compute the sum $\\sum_{k=1}^{40} \\lfloor \\sqrt{3k + 1} \\rfloor$.", "ground_truth": "284", "answer": "284", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_34", "question": "Compute the remainder when $6^{4}$ is divided by $8$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "0", "answer": "0", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_35", "question": "Find the largest integer $n$ such that $72^n$ divides $120!$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "29", "answer": "29", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32], "tool_status": "failure"} +{"prompt_id": "dapo_mini_36", "question": "Compute the remainder when $7^{5}$ is divided by $9$.", "ground_truth": "4", "answer": "4", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_37", "question": "Let $F_1 = 1$, $F_2 = 1$, and $F_n = F_{n-1} + F_{n-2}$ for $n \\ge 3$. Compute $\\sum_{k=1}^{15} F_k^2$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "602070", "answer": "602070", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_38", "question": "Compute the remainder when $8^{6}$ is divided by $10$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "4", "answer": "4", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_39", "question": "Let $\\omega = e^{2\\pi i / 7}$. Compute $\\prod_{k=1}^{6} (3 - 2\\omega^k)$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "2059", "answer": "2059", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_40", "question": "Compute the remainder when $9^{3}$ is divided by $11$.", "ground_truth": "3", "answer": "3", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_41", "question": "How many $6$-digit palindromic positive integers are divisible by $77$? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "140", "answer": "140", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_42", "question": "Compute the remainder when $10^{4}$ is divided by $7$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "4", "answer": "4", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_43", "question": "A token starts at integer position $2$ on the number line. Each second, it moves right ($+1$) with probability $\\frac{2}{3}$ and left ($-1$) with probability $\\frac{1}{3}$, stopping as soon as it reaches $0$ or $4$. The expected number of seconds until it stops equals $\\frac{p}{q}$ in lowest terms. Find $p + q$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "23", "answer": "23", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_44", "question": "Compute the remainder when $11^{5}$ is divided by $8$.", "ground_truth": "3", "answer": "3", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_45", "question": "A triangle has side lengths $10$, $17$, and $21$. Let $R$ be its circumradius and $r$ be its inradius. Express $\\frac{R}{r}$ as an irreducible fraction $\\frac{p}{q}$ and find $p + q$.", "ground_truth": "113", "answer": "113", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_46", "question": "Compute the remainder when $12^{6}$ is divided by $9$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "0", "answer": "0", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_47", "question": "How many non-empty subsets of $\\{1, 2, \\dots, 12\\}$ have the sum of their elements divisible by $5$? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "819", "answer": "819", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_48", "question": "In how many ways can we choose $2$ distinct items from $6$ distinct items? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "15", "answer": "15", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32], "tool_status": "failure"} +{"prompt_id": "dapo_mini_49", "question": "Compute the exact value of $\\sum_{k=1}^{12} k \\binom{12}{k} 2^k$.", "ground_truth": "4251528", "answer": "4251528", "data_source": "dapo_math_mini", "archetype": "short_clean", "max_turns": 1, "turn_max_tokens": [32], "ignore_eos": true, "payload_size_class": "", "validator_hint": "", "tool_status": ""} +{"prompt_id": "dapo_mini_50", "question": "In how many ways can we choose $3$ distinct items from $7$ distinct items? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "35", "answer": "35", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32], "tool_status": "failure"} +{"prompt_id": "dapo_mini_51", "question": "Find the sum of all integers $x \\in \\{1, 2, \\dots, 100\\}$ satisfying $x^2 + 5x + 3 \\equiv 0 \\pmod{43}$.", "ground_truth": "257", "answer": "257", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_52", "question": "In how many ways can we choose $4$ distinct items from $8$ distinct items? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "70", "answer": "70", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_53", "question": "How many ordered pairs of integers $(x, y)$ satisfy both $|x| + |y| \\le 10$ and $x^2 + y^2 \\ge 25$?", "ground_truth": "152", "answer": "152", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_54", "question": "In how many ways can we choose $2$ distinct items from $9$ distinct items? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "36", "answer": "36", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32], "tool_status": "failure"} +{"prompt_id": "dapo_mini_55", "question": "Two sequences are defined by $x_0 = 2$, $y_0 = 1$, and for all $n \\ge 0$, $x_{n+1} = 3x_n + 2y_n$ and $y_{n+1} = x_n + 4y_n$. Find the remainder when $x_8 + y_8$ is divided by $1000$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "752", "answer": "752", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32], "tool_status": "failure"} +{"prompt_id": "dapo_mini_56", "question": "A rectangle has width $4$ and height $7$. What is its perimeter? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "22", "answer": "22", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_57", "question": "How many distinct circular necklaces of length $6$ can be made using beads of up to $3$ colors, where two necklaces are considered identical if one can be rotated to match the other (without flipping)?", "ground_truth": "130", "answer": "130", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_58", "question": "Find the area of a trapezoid with parallel bases $7$ and $11$ and height $6$.", "ground_truth": "54", "answer": "54", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_59", "question": "When the polynomial $5x^{17} - 7x^{12} + 11x^7 - 13x^2 + 19$ is divided by $x^2 + 1$, the remainder is $ax + b$. Find $a^2 + b^2$. Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "661", "answer": "661", "data_source": "dapo_math_mini", "archetype": "medium", "max_turns": 2, "turn_max_tokens": [32, 1120], "ignore_eos": true, "payload_size_class": "medium", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure"} +{"prompt_id": "dapo_mini_60", "question": "A right triangle has legs of length $9$ and $12$. What is its area?", "ground_truth": "54", "answer": "54", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_61", "question": "In how many ways can a $2 \\times 10$ rectangle be completely tiled using $1 \\times 2$ dominoes (in either orientation) and $2 \\times 2$ squares? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "683", "answer": "683", "data_source": "dapo_math_mini", "archetype": "short_recover", "max_turns": 3, "turn_max_tokens": [32, 160, 160], "ignore_eos": true, "payload_size_class": "small", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "timeout"} +{"prompt_id": "dapo_mini_62", "question": "A rectangle has width $7$ and height $13$. What is its perimeter? Solve concisely and put the final answer in \\boxed{} immediately. /no_think", "ground_truth": "40", "answer": "40", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} +{"prompt_id": "dapo_mini_63", "question": "Find the last three digits (remainder when divided by $1000$) of $13^{17^{19}}$.", "ground_truth": "53", "answer": "53", "data_source": "dapo_math_mini", "archetype": "long_unambig", "max_turns": 3, "turn_max_tokens": [32, 1792, 1792], "ignore_eos": true, "payload_size_class": "large", "validator_hint": "Re-check intermediate arithmetic bounds and verify step-by-step before concluding.", "tool_status": "failure", "rollout1_max_turns": 1, "rollout1_turn_max_tokens": [32]} diff --git a/scripts/benchmark_scheduler_train.py b/scripts/benchmark_scheduler_train.py index b57975f..6bd32da 100644 --- a/scripts/benchmark_scheduler_train.py +++ b/scripts/benchmark_scheduler_train.py @@ -2,6 +2,7 @@ import json import os import random +import sys import time from pathlib import Path @@ -10,8 +11,15 @@ from datasets import load_dataset from transformers import AutoTokenizer +_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 import AsyncRLTrainer, parse_args_and_load_config -from RL_Framework.examples.dapo_math_async_rl import _preprocess +try: + from examples.dapo_math_async_rl import _preprocess +except ImportError: + from RL_Framework.examples.dapo_math_async_rl import _preprocess from RL_Framework.workflow.dapo_math import DAPOMathWorkflow OUT = Path(os.environ['BENCH_RUN_DIR']) @@ -41,7 +49,12 @@ async def generate(self, **kwargs): class MeasuredWorkflow(DAPOMathWorkflow): async def run_episode(self, engine, data, version=0, rollout_index=0): started = time.time() - result = await super().run_episode(MeasuredEngine(engine), data, version) + result = await super().run_episode( + MeasuredEngine(engine), + data, + version, + rollout_index=rollout_index, + ) append('episodes.jsonl', dict(start=started, end=time.time(), version=version, prompt_id=result['prompt_id'], input_tokens=result['input_len'], generated_tokens=result['output_len'], turns=result['n_turns'], @@ -50,8 +63,8 @@ async def run_episode(self, engine, data, version=0, rollout_index=0): class MeasuredTrainer(AsyncRLTrainer): - def _record_history_step(self, step, batch, stats, *args): - super()._record_history_step(step, batch, stats, *args) + def _record_history_step(self, step, batch, stats, *args, **kwargs): + super()._record_history_step(step, batch, stats, *args, **kwargs) append('steps.jsonl', dict(step=step, timestamp=time.time(), stats=stats, generated_tokens=sum(int(t['loss_mask'].sum()) for t in batch), sequence_tokens=sum(int(t['input_ids'].numel()) for t in batch), @@ -65,13 +78,26 @@ def main(): np.random.seed(config.seed) torch.manual_seed(config.seed) torch.cuda.manual_seed_all(config.seed) - dataset = load_dataset('json', data_files=os.environ['DAPO_MATH_PATH'], split='train') + data_path = os.environ['DAPO_MATH_PATH'] + data_format = 'parquet' if data_path.endswith('.parquet') else 'json' + dataset = load_dataset(data_format, data_files=data_path, split='train') dataset = dataset.map(_preprocess, with_indices=True) dataset = dataset.filter(lambda r: bool(r['question']) and bool(r['ground_truth'])) - tokenizer = AutoTokenizer.from_pretrained(config.model_path) - workflow = MeasuredWorkflow(tokenizer=tokenizer, max_turns=2, - max_new_tokens=config.max_new_tokens, max_seq_length=config.max_seq_length, - max_prompt_tokens=512, temperature=config.temperature, top_p=config.top_p) + tokenizer = AutoTokenizer.from_pretrained( + config.tokenizer_path or config.model_path, + trust_remote_code=True, + ) + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + workflow = MeasuredWorkflow( + tokenizer=tokenizer, + max_turns=int(os.environ.get('DAPO_MAX_TURNS', '2')), + max_new_tokens=config.max_new_tokens, + max_seq_length=config.max_seq_length, + max_prompt_tokens=int(os.environ.get('DAPO_MAX_PROMPT_TOKENS', '512')), + temperature=config.temperature, + top_p=config.top_p, + ) trainer = MeasuredTrainer(config) started = time.time() trainer.train(workflow, dataset) diff --git a/tests/test_r2e_1938329_entrypoint.py b/tests/test_r2e_1938329_entrypoint.py index 257cdac..ee31713 100644 --- a/tests/test_r2e_1938329_entrypoint.py +++ b/tests/test_r2e_1938329_entrypoint.py @@ -89,7 +89,7 @@ def evaluate(): def test_rank_zero_exception_reaches_every_rank(tmp_path): mp.start_processes( _describe_rank_zero_failure, args=(tmp_path / "store", tmp_path), - nprocs=2, start_method="fork", + nprocs=2, start_method="spawn", ) assert [(tmp_path / str(rank)).read_text() for rank in range(2)] == [ "OSError: heldout output unavailable", "OSError: heldout output unavailable", diff --git a/tests/test_tier2_closed_loop.py b/tests/test_tier2_closed_loop.py new file mode 100644 index 0000000..ce2bb9e --- /dev/null +++ b/tests/test_tier2_closed_loop.py @@ -0,0 +1,668 @@ +"""CPU-safe unit and dry-run tests for Tier 2 (8-GPU / 4-GPU closed loop & Google Colab).""" + +import asyncio +import importlib.util +import json +import os +import re +import subprocess +import sys +import types +from pathlib import Path + +import pytest +import torch + +from repro.tier2_four_gpu_closed_loop.launch_4gpu import ( + COLAB_TIER_PRESETS, + REPO_ROOT, + build_run_plan, + materialize_run_plan, +) +from RL_Framework.config import AsyncRLConfig +from RL_Framework.engine.train_engine import _resolve_train_dtype +from RL_Framework.infra.scheduling.cmlfq_cost_scheduler import CMLFQCostScheduler +from RL_Framework.infra.scheduling.factory import SchedulerFactory +from RL_Framework.infra.scheduling.load_balance import LoadBalanceScheduler + + +SAMPLE_DATASET = ( + REPO_ROOT / "repro/tier2_four_gpu_closed_loop/sample_data/dapo_math_mini.jsonl" +) +COST_PROFILE = ( + REPO_ROOT / "repro/tier2_four_gpu_closed_loop/sample_data/dapo_cost_profile.json" +) +CONFIG_8GPU = REPO_ROOT / "repro/tier2_four_gpu_closed_loop/config_8gpu_qwen3_4b.yaml" +CONFIG_4GPU = REPO_ROOT / "repro/tier2_four_gpu_closed_loop/config_4gpu_qwen3_4b.yaml" +CONFIG_COLAB = REPO_ROOT / "repro/tier2_four_gpu_closed_loop/config_colab_1gpu.yaml" +COLAB_NOTEBOOK = ( + REPO_ROOT / "repro/tier2_four_gpu_closed_loop/colab_quickstart.ipynb" +) +LAUNCH_SCRIPT = REPO_ROOT / "repro/tier2_four_gpu_closed_loop/launch_4gpu.py" +RUN_8GPU_SH = REPO_ROOT / "repro/tier2_four_gpu_closed_loop/run_8gpu.sh" + + +def test_dapo_math_mini_dataset(): + lines = SAMPLE_DATASET.read_text(encoding="utf-8").splitlines() + assert len(lines) == 64 + + prompt_ids: set[str] = set() + box_re = re.compile(r"\\boxed\s*\{(.*?)\}", re.DOTALL) + has_grader = importlib.util.find_spec("latex2sympy2") is not None + if has_grader: + from RL_Framework.env.dapo_math_reward import dapo_math_reward_fn + + for raw in lines: + row = json.loads(raw) + assert row["prompt_id"] + assert row["prompt_id"] not in prompt_ids + prompt_ids.add(row["prompt_id"]) + assert row["question"].strip() + assert row["ground_truth"] == row["answer"] + assert int(row["ground_truth"]) >= 0 + assert row["data_source"] == "dapo_math_mini" + completion = f"Let us solve carefully.\nFinal answer: \\boxed{{{row['ground_truth']}}}." + extracted = box_re.findall(completion) + assert extracted and extracted[-1] == row["ground_truth"] + if has_grader: + assert ( + dapo_math_reward_fn( + row["question"], + completion, + ground_truth=row["ground_truth"], + ) + == 1.0 + ) + + +def test_static_tier2_and_colab_yaml_configs(): + cfg_4gpu = AsyncRLConfig.from_yaml(str(CONFIG_4GPU)) + assert cfg_4gpu.train_gpus == 1 + assert cfg_4gpu.rollout_gpus == 3 + assert cfg_4gpu.rollout_weight_reload_method == "inplace" + instances_4gpu = cfg_4gpu.heterogeneous_rollout.instances + assert [(i.tp, i.port) for i in instances_4gpu] == [(1, 18920), (2, 18921)] + sched_4gpu = SchedulerFactory.create( + cfg_4gpu.heterogeneous_rollout.scheduling.scheduler_type, + cfg_4gpu.heterogeneous_rollout, + ) + assert isinstance(sched_4gpu, CMLFQCostScheduler) + + cfg_colab = AsyncRLConfig.from_yaml(str(CONFIG_COLAB)) + assert cfg_colab.train_gpus == 1 + assert cfg_colab.rollout_gpus == 1 + assert cfg_colab.rollout_weight_reload_method == "inplace" + assert len(cfg_colab.heterogeneous_rollout.instances) == 1 + assert cfg_colab.heterogeneous_rollout.instances[0].tp == 1 + sched_colab = SchedulerFactory.create( + cfg_colab.heterogeneous_rollout.scheduling.scheduler_type, + cfg_colab.heterogeneous_rollout, + ) + assert isinstance(sched_colab, LoadBalanceScheduler) + + +def test_launch_4gpu_dry_run_slurm_free(tmp_path: Path): + env = dict(os.environ) + env.pop("SLURM_JOB_ID", None) + + out_dir = tmp_path / "ab_runs" + proc = subprocess.run( + [ + sys.executable, + str(LAUNCH_SCRIPT), + "--mode", + "4gpu", + "--policy", + "all", + "--gpus", + "0,1,2,3", + "--output-dir", + str(out_dir), + "--dry-run", + ], + cwd=str(REPO_ROOT), + env=env, + capture_output=True, + text=True, + check=True, + ) + assert "Dry-Run Launch Plan" in proc.stdout + + for expected_dir in ("round_robin_42", "least_connections_42", "cmlfq_cost_42"): + run_dir = out_dir / expected_dir + assert (run_dir / "config.yaml").is_file() + assert (run_dir / "launch_plan.json").is_file() + loaded = AsyncRLConfig.from_yaml(str(run_dir / "config.yaml")) + assert loaded.train_gpus == 1 + assert loaded.rollout_gpus == 3 + + plan = json.loads((run_dir / "launch_plan.json").read_text(encoding="utf-8")) + assert plan["train_spec"]["cuda_visible_devices"] == "0" + assert plan["train_spec"]["env_overrides"] == { + "RANK": "0", + "LOCAL_RANK": "0", + "WORLD_SIZE": "1", + } + assert [s["cuda_visible_devices"] for s in plan["rollout_specs"]] == ["1", "2,3"] + assert [s["port"] for s in plan["rollout_specs"]] == [18920, 18921] + + offload_plan = build_run_plan( + mode="4gpu", + policy="cmlfq_cost", + gpus=[4, 5, 6, 7], + output_dir=tmp_path / "offload", + dataset_path=SAMPLE_DATASET, + kv_backend="cpu_offload", + ) + materialize_run_plan(offload_plan) + assert "LIBRA_KV_STORAGE_PATH" in offload_plan["env_overrides"] + assert offload_plan["train_spec"]["cuda_visible_devices"] == "4" + assert [s["cuda_visible_devices"] for s in offload_plan["rollout_specs"]] == [ + "5", + "6,7", + ] + assert "--kv-transfer-config" in offload_plan["rollout_specs"][0]["command"] + assert "LibraCPUOffloadConnector" in " ".join( + offload_plan["rollout_specs"][0]["command"] + ) + + +@pytest.mark.parametrize("tier", list(COLAB_TIER_PRESETS.keys())) +def test_launch_colab_1gpu_tiers_dry_run(tmp_path: Path, tier: str): + plan = build_run_plan( + mode="colab-1gpu", + policy="least_connections", + gpus=[0], + output_dir=tmp_path / tier, + dataset_path=SAMPLE_DATASET, + colab_tier=tier, + ) + materialize_run_plan(plan) + + loaded = AsyncRLConfig.from_yaml(plan["config_path"]) + assert loaded.train_gpus == 1 + assert loaded.rollout_gpus == 1 + assert len(plan["rollout_specs"]) == 1 + assert plan["rollout_specs"][0]["cuda_visible_devices"] == "0" + assert plan["train_spec"]["cuda_visible_devices"] == "0" + + if tier == "t4": + assert plan["vllm_dtype"] == "half" + assert plan["fsdp_dtype"] == "float32" + assert plan["env_overrides"]["FSDP_DTYPE"] == "float32" + assert plan["model"] == "Qwen/Qwen2.5-0.5B-Instruct" + assert loaded.heterogeneous_rollout.gpu_memory_utilization == 0.30 + else: + assert plan["vllm_dtype"] == "bfloat16" + assert plan["fsdp_dtype"] == "bfloat16" + + if tier == "t4": + proc = subprocess.run( + [ + sys.executable, + str(LAUNCH_SCRIPT), + "--mode", + "colab-1gpu", + "--colab-tier", + "t4", + "--output-dir", + str(tmp_path / "cli_t4"), + "--dry-run", + ], + cwd=str(REPO_ROOT), + capture_output=True, + text=True, + check=True, + ) + assert "colab-1gpu" in proc.stdout + + +def test_colab_notebook_structure(): + nb = json.loads(COLAB_NOTEBOOK.read_text(encoding="utf-8")) + assert nb["nbformat"] == 4 + cell_types = [c["cell_type"] for c in nb["cells"]] + assert "markdown" in cell_types + assert "code" in cell_types + + all_text = "\n".join("".join(c["source"]) for c in nb["cells"]) + assert "colab.research.google.com/github/NetX-lab/Libra/blob/main/repro/tier2_four_gpu_closed_loop/colab_quickstart.ipynb" in all_text + assert "repro/tier2_four_gpu_closed_loop/launch_4gpu.py" in all_text + assert "--mode colab-1gpu" in all_text + assert "repro/tier1_zero_gpu_replay/run_replay.py" in all_text + assert "latex2sympy2" in all_text + + +def test_resolve_train_dtype(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setenv("FSDP_DTYPE", "float32") + assert _resolve_train_dtype() is torch.float32 + + monkeypatch.setenv("FSDP_DTYPE", "float16") + assert _resolve_train_dtype() is torch.float16 + + monkeypatch.setenv("FSDP_DTYPE", "bf16") + assert _resolve_train_dtype() is torch.bfloat16 + + monkeypatch.setenv("FSDP_DTYPE", "auto") + monkeypatch.setattr(torch.cuda, "is_available", lambda: True) + monkeypatch.setattr(torch.cuda, "is_bf16_supported", lambda: False) + assert _resolve_train_dtype() is torch.float32 + + monkeypatch.setattr(torch.cuda, "is_bf16_supported", lambda: True) + assert _resolve_train_dtype() is torch.bfloat16 + + monkeypatch.setenv("FSDP_DTYPE", "invalid_precision") + with pytest.raises(ValueError, match="FSDP_DTYPE"): + _resolve_train_dtype() + + +def test_dapo_math_workflow_populates_cmlfq_cost_distribution( + monkeypatch: pytest.MonkeyPatch, +): + if importlib.util.find_spec("latex2sympy2") is None: + fake_l2s = types.ModuleType("latex2sympy2") + fake_l2s.latex2sympy = lambda expr: expr # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "latex2sympy2", fake_l2s) + if importlib.util.find_spec("word2number") is None: + fake_w2n_pkg = types.ModuleType("word2number") + fake_w2n = types.ModuleType("word2number.w2n") + fake_w2n.word_to_num = lambda text: int(text) # type: ignore[attr-defined] + fake_w2n_pkg.w2n = fake_w2n # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "word2number", fake_w2n_pkg) + monkeypatch.setitem(sys.modules, "word2number.w2n", fake_w2n) + + from RL_Framework.engine.heterogeneous_engine import HeterogeneousRolloutEngine + from RL_Framework.workflow.dapo_math import DAPOMathWorkflow + + class _CharTokenizer: + def encode(self, text: str, add_special_tokens: bool = False) -> list[int]: + del add_special_tokens + return [ord(ch) for ch in text] + + def decode(self, tokens: list[int], skip_special_tokens: bool = True) -> str: + del skip_special_tokens + return "".join(chr(tok) for tok in tokens) + + def apply_chat_template(self, messages, **kwargs) -> str: + del kwargs + return "\n".join(msg["content"] for msg in messages) + + class _MockVLLM: + def __init__(self, tokenizer: _CharTokenizer): + self.base_url = "http://127.0.0.1:0" + self._tokenizer = tokenizer + + async def generate(self, **kwargs): + prompt = kwargs.get("prompt", "") + # Fail Turn 1 ("DAPO-Math Validator" absent) -> succeed Turn 2 after feedback. + if "DAPO-Math Validator" in prompt: + text = "Revising the algebra step: $2x = 6$, so \\boxed{3}." + else: + text = "Initial attempt: $2x + 7 = 13$ gives \\boxed{999}." + toks = self._tokenizer.encode(text) + return { + "text": text, + "tokens": toks, + "logprobs": [-0.1] * len(toks), + "finish_reason": "stop", + } + + class _RecordingEngine: + def __init__(self, inner: HeterogeneousRolloutEngine): + self._inner = inner + self.route_infos: list[dict] = [] + + def __getattr__(self, name: str): + return getattr(self._inner, name) + + async def generate(self, **kwargs): + out = await self._inner.generate(**kwargs) + self.route_infos.append(dict(out.get("_schedule_info", {}))) + return out + + cfg = AsyncRLConfig.from_yaml(str(CONFIG_4GPU)) + cfg.heterogeneous_rollout.scheduling.cmlfq_tree_path = "" + cfg.heterogeneous_rollout.scheduling.cmlfq_kv_backend = "recompute" + + hetero = HeterogeneousRolloutEngine.from_config(cfg) + tok = _CharTokenizer() + hetero.engines = [_MockVLLM(tok), _MockVLLM(tok)] + recorder = _RecordingEngine(hetero) + + workflow = DAPOMathWorkflow( + tokenizer=tok, + max_turns=2, + max_new_tokens=512, + max_seq_length=2048, + max_prompt_tokens=256, + ) + row = { + "prompt_id": "dapo_mini_00", + "question": "Solve for $x$: $2x + 7 = 13$.", + "ground_truth": "3", + "answer": "3", + } + + async def _run_two(): + ep1 = await workflow.run_episode(recorder, row, version=0) + dist_after_ep1 = hetero.scheduler.prefix_tree.residual_distribution( + "dapo_mini_00", + [hetero.scheduler._tool_registry.extract(ep1["tool_returns"][0])], + hetero.scheduler._bucket_thresholds, + ) + ep2 = await workflow.run_episode(recorder, row, version=0) + return ep1, dist_after_ep1, ep2 + + ep1, dist_after_ep1, ep2 = asyncio.run(_run_two()) + assert ep1["n_turns"] == 2 + assert ep2["n_turns"] == 2 + assert hetero.scheduler.prefix_tree.remaining_unit == "model_generated_tokens" + assert dist_after_ep1, "Expected non-empty residual distribution after Episode 1" + # Episode 2 Turn 2 is the 4th generate() call overall (indices 0,1 = ep1; 2,3 = ep2). + assert len(recorder.route_infos) == 4 + assert recorder.route_infos[3]["reason"] == "distribution_cost" + assert recorder.route_infos[3]["estimated_decode_seconds"] > 0.0 + + +def test_static_tier2_8gpu_yaml_and_cost_profile(): + assert COST_PROFILE.is_file() + cfg_8gpu = AsyncRLConfig.from_yaml(str(CONFIG_8GPU)) + assert cfg_8gpu.train_gpus == 1 + assert cfg_8gpu.rollout_gpus == 7 + assert cfg_8gpu.rollout_weight_reload_method == "inplace" + instances_8gpu = cfg_8gpu.heterogeneous_rollout.instances + assert [(i.tp, i.port) for i in instances_8gpu] == [ + (1, 18920), + (2, 18921), + (4, 18922), + ] + sched_8gpu = SchedulerFactory.create( + cfg_8gpu.heterogeneous_rollout.scheduling.scheduler_type, + cfg_8gpu.heterogeneous_rollout, + ) + assert isinstance(sched_8gpu, CMLFQCostScheduler) + assert set(sched_8gpu._bucket_thresholds.keys()) == {"short", "medium", "long"} + + +def test_launch_8gpu_dry_run_and_seeded_trees(tmp_path: Path): + subprocess.run(["bash", "-n", str(RUN_8GPU_SH)], check=True) + + env = dict(os.environ) + env.pop("SLURM_JOB_ID", None) + out_dir = tmp_path / "ab_8gpu" + proc = subprocess.run( + [ + sys.executable, + str(LAUNCH_SCRIPT), + "--mode", + "8gpu", + "--policy", + "all", + "--gpus", + "0,1,2,3,4,5,6,7", + "--output-dir", + str(out_dir), + "--dry-run", + ], + cwd=str(REPO_ROOT), + env=env, + capture_output=True, + text=True, + check=True, + ) + assert "Mode: `8gpu`" in proc.stdout + + for expected_dir in ( + "round_robin_42", + "least_connections_42", + "cmlfq_42", + "cmlfq_cost_42", + ): + run_dir = out_dir / expected_dir + assert (run_dir / "config.yaml").is_file() + assert (run_dir / "launch_plan.json").is_file() + loaded = AsyncRLConfig.from_yaml(str(run_dir / "config.yaml")) + assert loaded.train_gpus == 1 + assert loaded.rollout_gpus == 7 + assert loaded.micro_batch_size == 1 + + plan = json.loads((run_dir / "launch_plan.json").read_text(encoding="utf-8")) + assert plan["train_spec"]["cuda_visible_devices"] == "0" + assert [s["cuda_visible_devices"] for s in plan["rollout_specs"]] == [ + "1", + "2,3", + "4,5,6,7", + ] + assert [s["port"] for s in plan["rollout_specs"]] == [18920, 18921, 18922] + assert "--enable-prefix-caching" in plan["rollout_specs"][0]["command"] + assert "--enforce-eager" not in plan["rollout_specs"][0]["command"] + + cmlfq_tree = json.loads((out_dir / "cmlfq_42" / "tree.json").read_text(encoding="utf-8")) + assert cmlfq_tree["remaining_unit"] == "context_tokens" + cost_tree = json.loads( + (out_dir / "cmlfq_cost_42" / "tree.json").read_text(encoding="utf-8") + ) + assert cost_tree["remaining_unit"] == "model_generated_tokens" + + +def test_8gpu_three_tier_routing_with_seeded_tree( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + if importlib.util.find_spec("latex2sympy2") is None: + fake_l2s = types.ModuleType("latex2sympy2") + fake_l2s.latex2sympy = lambda expr: expr # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "latex2sympy2", fake_l2s) + if importlib.util.find_spec("word2number") is None: + fake_w2n_pkg = types.ModuleType("word2number") + fake_w2n = types.ModuleType("word2number.w2n") + fake_w2n.word_to_num = lambda text: int(text) # type: ignore[attr-defined] + fake_w2n_pkg.w2n = fake_w2n # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "word2number", fake_w2n_pkg) + monkeypatch.setitem(sys.modules, "word2number.w2n", fake_w2n) + + from RL_Framework.engine.heterogeneous_engine import HeterogeneousRolloutEngine + from RL_Framework.workflow.dapo_math import DAPOMathWorkflow + + class _CharTokenizer: + def encode(self, text: str, add_special_tokens: bool = False) -> list[int]: + del add_special_tokens + return [ord(ch) for ch in text] + + def decode(self, tokens: list[int], skip_special_tokens: bool = True) -> str: + del skip_special_tokens + return "".join(chr(tok) for tok in tokens) + + def apply_chat_template(self, messages, **kwargs) -> str: + del kwargs + return "\n".join(msg["content"] for msg in messages) + + class _FixedMockVLLM: + def __init__(self, tokenizer: _CharTokenizer): + self.base_url = "http://127.0.0.1:0" + self._tokenizer = tokenizer + + async def generate(self, **kwargs): + text = "Reasoning without box yet." + toks = self._tokenizer.encode(text) + return { + "text": text, + "tokens": toks, + "logprobs": [-0.1] * len(toks), + "finish_reason": "length", + } + + class _RecordingEngine: + def __init__(self, inner: HeterogeneousRolloutEngine): + self._inner = inner + self.route_infos: list[dict] = [] + + def __getattr__(self, name: str): + return getattr(self._inner, name) + + async def generate(self, **kwargs): + out = await self._inner.generate(**kwargs) + self.route_infos.append(dict(out.get("_schedule_info", {}))) + return out + + rows_by_arch: dict[str, dict] = {} + for raw in SAMPLE_DATASET.read_text(encoding="utf-8").splitlines(): + row = json.loads(raw) + rows_by_arch.setdefault(row["archetype"], row) + assert set(rows_by_arch) == { + "short_clean", + "short_recover", + "medium", + "long_unambig", + "long_cascading", + } + + tok = _CharTokenizer() + workflow = DAPOMathWorkflow( + tokenizer=tok, + max_turns=3, + max_new_tokens=1792, + max_seq_length=6144, + max_prompt_tokens=512, + ) + + tp_routes_by_policy: dict[str, dict[str, list[int]]] = {} + for policy in ("cmlfq", "cmlfq_cost"): + plan = build_run_plan( + mode="8gpu", + policy=policy, + gpus=list(range(8)), + output_dir=tmp_path / policy, + dataset_path=SAMPLE_DATASET, + ) + materialize_run_plan(plan) + cfg = AsyncRLConfig.from_yaml(plan["config_path"]) + hetero = HeterogeneousRolloutEngine.from_config(cfg) + hetero.engines = [_FixedMockVLLM(tok) for _ in range(3)] + rec = _RecordingEngine(hetero) + + tp_routes: dict[str, list[int]] = {} + for arch in ( + "short_clean", + "short_recover", + "medium", + "long_unambig", + "long_cascading", + ): + before = len(rec.route_infos) + asyncio.run(workflow.run_episode(rec, rows_by_arch[arch], version=0)) + tp_routes[arch] = [r["tp_degree"] for r in rec.route_infos[before:]] + tp_routes_by_policy[policy] = tp_routes + + assert tp_routes_by_policy["cmlfq"]["short_clean"] == [1] + assert tp_routes_by_policy["cmlfq"]["short_recover"] == [1, 1, 1] + assert tp_routes_by_policy["cmlfq"]["medium"] == [1, 2] + assert tp_routes_by_policy["cmlfq"]["long_unambig"] == [1, 4, 4] + assert tp_routes_by_policy["cmlfq"]["long_cascading"] == [1, 1, 4] + + assert tp_routes_by_policy["cmlfq_cost"]["short_clean"] == [1] + assert tp_routes_by_policy["cmlfq_cost"]["short_recover"] == [1, 1, 1] + assert tp_routes_by_policy["cmlfq_cost"]["medium"] == [1, 2] + assert tp_routes_by_policy["cmlfq_cost"]["long_unambig"] == [1, 4, 4] + assert tp_routes_by_policy["cmlfq_cost"]["long_cascading"] == [1, 4, 4] + + +def test_benchmark_grp_dry_run_and_preflight_selection(tmp_path: Path) -> None: + """GRP benchmark Phase 1 + Phase 2 dry-run selects 1 train + TP=[4,2,1] on 8 GPUs.""" + from types import SimpleNamespace + + from repro.tier2_four_gpu_closed_loop import benchmark_grp, launch_4gpu + + args = SimpleNamespace( + model=benchmark_grp.DEFAULT_MODEL, + dataset=str(launch_4gpu.DEFAULT_DATASET), + output_dir=str(tmp_path / "grp_dry"), + steps=None, + batch_size=None, + n_samples=2, + sync_interval=None, + seed=42, + base_port=18920, + gpu_memory_utilization=None, + max_model_len=None, + max_new_tokens=None, + timeout_s=60.0, + python_bin=sys.executable, + plans=None, + force=False, + plan_only=False, + dry_run=True, + ) + summary = benchmark_grp.run_benchmark(args) + assert (tmp_path / "grp_dry" / "grp_summary.json").exists() + + phase1 = summary["phase1_preflight_planning"] + assert phase1["preflight_applied"] is True + assert phase1["best_plan"]["train"]["n_gpus"] == 1 + assert phase1["best_plan"]["rollout"]["tp_list"] == [4, 2, 1] + + evals = phase1["plan_evaluations"] + assert ( + evals["grp_optimal_1train_7rollout_hetero"]["predicted_t_global_s"] + < evals["fixed_2train_6rollout_tp2"]["predicted_t_global_s"] + < evals["fixed_4train_4rollout_tp1"]["predicted_t_global_s"] + ) + + plans = summary["phase2_materialized_plans"] + assert set(plans) == { + "fixed_4train_4rollout_tp1", + "fixed_2train_6rollout_tp2", + "grp_optimal_1train_7rollout_hetero", + } + assert plans["fixed_4train_4rollout_tp1"]["rollout_tp_list"] == [1, 1, 1, 1] + assert plans["fixed_4train_4rollout_tp1"]["prefix_affinity"] is True + assert plans["fixed_2train_6rollout_tp2"]["rollout_tp_list"] == [2, 2, 2] + assert plans["fixed_2train_6rollout_tp2"]["prefix_affinity"] is True + assert plans["grp_optimal_1train_7rollout_hetero"]["rollout_tp_list"] == [1, 2, 4] + assert plans["grp_optimal_1train_7rollout_hetero"]["prefix_affinity"] is False + assert all(p["config_validated"] for p in plans.values()) + + +def test_benchmark_ehp_dry_run_and_elastic_lifecycle(tmp_path: Path) -> None: + """EHP benchmark Phase 1 + Phase 2 + CPU Phase 3 dry-run checks lifecycle & gradient parity.""" + from types import SimpleNamespace + + from repro.tier2_four_gpu_closed_loop import benchmark_ehp + + args = SimpleNamespace( + model=benchmark_ehp.DEFAULT_MODEL, + dataset=str(benchmark_ehp.DEFAULT_DATASET), + output_dir=str(tmp_path / "ehp_dry"), + steps=2, + warmup_steps=0, + groups_per_batch=4, + group_size=4, + seq_len=64, + micro_batch_size=2, + lr=1e-4, + seed=42, + dry_run=True, + ) + summary = benchmark_ehp.run_benchmark(args) + assert (tmp_path / "ehp_dry" / "ehp_summary.json").exists() + + p1 = summary["phase1_cost_model"] + assert p1["passed"] is True + assert p1["lending_capacity_checks"]["borrow_3_from_tp1_tp2_reserve_4"] == 3 + assert p1["lending_capacity_checks"]["borrow_blocked_exceeds_reserve"] == 0 + assert ( + p1["bounded_update_time_estimates"]["borrow_3_gpus"]["bounded_update_time_s"] + < p1["bounded_update_time_estimates"]["borrow_0_gpus"]["bounded_update_time_s"] + ) + + p2 = summary["phase2_lifecycle_and_ipc"] + assert p2["passed"] is True + assert p2["zero_sync_guard_passed"] is True + assert p2["ipc_received_count"] == 3 + assert abs(p2["reduced_mean_verified"] - 2.5) < 1e-5 + + p3 = summary["phase3_elastic_training"] + assert p3["mode"] == "dry_run_cpu" + for mode_name in ("static_core_1gpu", "ehp_borrow_1gpu", "ehp_borrow_3gpus"): + assert p3["runs"][mode_name]["grad_norm_diff_vs_static"] < 1e-5 + assert p3["runs"]["ehp_borrow_1gpu"]["ipc_acks"] == 2 + assert p3["runs"]["ehp_borrow_3gpus"]["ipc_acks"] == 6 + diff --git a/workflow/dapo_math.py b/workflow/dapo_math.py index bf4bbfc..67c3e3e 100644 --- a/workflow/dapo_math.py +++ b/workflow/dapo_math.py @@ -125,7 +125,13 @@ def _clip(self, tokens: list[int], logprobs: list[float], used: int) -> tuple[li return tokens, logprobs return tokens[:remaining], logprobs[:remaining] - async def run_episode(self, engine: Any, data: dict[str, Any], version: int = 0) -> dict[str, torch.Tensor]: + async def run_episode( + self, + engine: Any, + data: dict[str, Any], + version: int = 0, + rollout_index: int = 0, + ) -> dict[str, torch.Tensor]: prompt_text = self._build_prompt(data) prompt_tokens = self._encode(prompt_text) answer = self._extract_answer(data) @@ -135,15 +141,45 @@ async def run_episode(self, engine: Any, data: dict[str, Any], version: int = 0) begin_cmlfq = getattr(engine, "begin_cmlfq_request", None) cmlfq_request_id = begin_cmlfq(prompt_id, len(prompt_tokens)) if callable(begin_cmlfq) else "" + use_rollout1 = int(rollout_index) == 1 and isinstance(data.get("rollout1_turn_max_tokens"), list) and bool(data.get("rollout1_turn_max_tokens")) + raw_turn_budgets = ( + data.get("rollout1_turn_max_tokens") + if use_rollout1 + else data.get("turn_max_tokens") + ) + row_turn_budgets = ( + [max(1, int(toks)) for toks in raw_turn_budgets] + if isinstance(raw_turn_budgets, list) and raw_turn_budgets + else None + ) + raw_max_turns = data.get("rollout1_max_turns") if use_rollout1 else data.get("max_turns") + if raw_max_turns is None: + raw_max_turns = len(row_turn_budgets) if row_turn_budgets is not None else self.max_turns + episode_max_turns = max(1, int(raw_max_turns)) + force_ignore_eos = bool(data.get("ignore_eos")) + validator_hint = str(data.get("validator_hint") or "").strip() + payload_size_spec = ( + data.get("rollout1_payload_size_class") + if use_rollout1 and "rollout1_payload_size_class" in data + else data.get("payload_size_class") + ) + raw_tool_status = ( + data.get("rollout1_tool_status") + if use_rollout1 and "rollout1_tool_status" in data + else data.get("tool_status") + ) + tool_status_override = str(raw_tool_status or "").strip() current_text = prompt_text final_completion = "" final_turn = 0 try: - for turn in range(self.max_turns): + for turn in range(episode_max_turns): final_turn = turn used = sum(len(toks) for toks, _, _ in segments) generation_prompt, prompt_len = self._fit_generation_prompt(current_text) max_tokens = self._generation_budget(prompt_len, used, turn) + if row_turn_budgets is not None and turn < len(row_turn_budgets): + max_tokens = min(max_tokens, row_turn_budgets[turn]) kwargs = { "prompt_id": prompt_id, "prompt": generation_prompt, @@ -155,6 +191,8 @@ async def run_episode(self, engine: Any, data: dict[str, Any], version: int = 0) # passing it skips the engine-side estimation encode. "input_tokens": prompt_len, } + if force_ignore_eos or (row_turn_budgets is not None and turn < episode_max_turns - 1): + kwargs["ignore_eos"] = True if cmlfq_request_id: kwargs.update({"request_id": cmlfq_request_id, "prompt_id": prompt_id}) response = await engine.generate(**kwargs) @@ -170,10 +208,15 @@ async def run_episode(self, engine: Any, data: dict[str, Any], version: int = 0) segments.append((output_tokens, output_logprobs, 1)) metrics = evaluate_math_completion(output_text, answer) - if turn >= self.max_turns - 1 or metrics["accuracy"] >= 1.0: + if row_turn_budgets is not None and len(row_turn_budgets) > 1: + if turn >= episode_max_turns - 1: + break + elif turn >= episode_max_turns - 1 or metrics["accuracy"] >= 1.0: break feedback = format_math_validator_feedback(metrics) + if validator_hint: + feedback = f"{feedback}\n{validator_hint}" feedback_tokens = self._encode(feedback) used_after_output = sum(len(toks) for toks, _, _ in segments) feedback_tokens, feedback_logprobs = self._clip( @@ -184,19 +227,34 @@ async def run_episode(self, engine: Any, data: dict[str, Any], version: int = 0) feedback = self.tokenizer.decode(feedback_tokens, skip_special_tokens=True) segments.append((feedback_tokens, feedback_logprobs, 0)) generated_tokens = sum(len(toks) for toks, _, _ in segments[1:]) + pure_generated_tokens = sum(len(toks) for toks, _, mask in segments if mask == 1) + resolved_status = ( + tool_status_override + if tool_status_override in ("success", "failure", "timeout") + else ("success" if metrics["accuracy"] >= 1.0 else "failure") + ) tool_event = { "tool_type": "dapo_math_validator", "output": feedback, - "status": "success" if metrics["accuracy"] >= 1.0 else "failure", + "status": resolved_status, "payload_tokens": len(feedback_tokens), "token_position": generated_tokens, + "generated_token_position": pure_generated_tokens, "turn": turn, "reward": metrics["reward"], "accuracy": metrics["accuracy"], } + if isinstance(payload_size_spec, list): + if turn < len(payload_size_spec) and payload_size_spec[turn]: + tool_event["payload_size_class"] = str(payload_size_spec[turn]) + elif payload_size_spec: + tool_event["payload_size_class"] = str(payload_size_spec) tool_returns.append(tool_event) + record_tool_return = getattr(engine, "record_cmlfq_tool_return", None) route_tool_return = getattr(engine, "route_cmlfq_tool_return", None) - if cmlfq_request_id and callable(route_tool_return): + if cmlfq_request_id and callable(record_tool_return): + record_tool_return(cmlfq_request_id, tool_event, generated_tokens) + elif cmlfq_request_id and callable(route_tool_return): route_tool_return(cmlfq_request_id, tool_event, generated_tokens) current_text += output_text + "\n" + feedback + "\n" except BaseException: @@ -226,7 +284,10 @@ async def run_episode(self, engine: Any, data: dict[str, Any], version: int = 0) tr["remaining_length"] = max(0, total_output_tokens - pos) finish_cmlfq = getattr(engine, "finish_cmlfq_request", None) if cmlfq_request_id and callable(finish_cmlfq): - finish_cmlfq(cmlfq_request_id, total_output_tokens) + try: + finish_cmlfq(cmlfq_request_id, total_output_tokens, generated_tokens=output_len) + except TypeError: + finish_cmlfq(cmlfq_request_id, total_output_tokens) reward = self.reward_fn(prompt=prompt_text, completion=final_completion, ground_truth=answer, answer=answer) seq = torch.tensor(input_ids, dtype=torch.long) return {