From 22d4b8799be108dec49889f83323b6106be1c0ea Mon Sep 17 00:00:00 2001 From: "CHEN, Kaiwen" <80016929+kaiwenKevinn@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:29:11 +0800 Subject: [PATCH 1/5] feat(repro): add Tier 2 closed-loop RL, Colab quickstart, and rollout scheduling benchmark --- engine/train_engine.py | 31 +- repro/tier2_four_gpu_closed_loop/README.md | 139 ++ .../benchmark_rollout_scheduling.py | 1240 +++++++++++++++++ .../colab_quickstart.ipynb | 146 ++ .../config_4gpu_qwen3_4b.yaml | 95 ++ .../config_colab_1gpu.yaml | 77 + .../tier2_four_gpu_closed_loop/launch_4gpu.py | 827 +++++++++++ repro/tier2_four_gpu_closed_loop/run_4gpu.sh | 4 + .../run_rollout_ab.sh | 251 ++++ .../sample_data/dapo_math_mini.jsonl | 64 + scripts/benchmark_scheduler_train.py | 33 +- tests/test_tier2_closed_loop.py | 560 ++++++++ workflow/dapo_math.py | 12 +- 13 files changed, 3468 insertions(+), 11 deletions(-) create mode 100644 repro/tier2_four_gpu_closed_loop/README.md create mode 100644 repro/tier2_four_gpu_closed_loop/benchmark_rollout_scheduling.py create mode 100644 repro/tier2_four_gpu_closed_loop/colab_quickstart.ipynb create mode 100644 repro/tier2_four_gpu_closed_loop/config_4gpu_qwen3_4b.yaml create mode 100644 repro/tier2_four_gpu_closed_loop/config_colab_1gpu.yaml create mode 100755 repro/tier2_four_gpu_closed_loop/launch_4gpu.py create mode 100755 repro/tier2_four_gpu_closed_loop/run_4gpu.sh create mode 100755 repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh create mode 100644 repro/tier2_four_gpu_closed_loop/sample_data/dapo_math_mini.jsonl create mode 100644 tests/test_tier2_closed_loop.py 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/repro/tier2_four_gpu_closed_loop/README.md b/repro/tier2_four_gpu_closed_loop/README.md new file mode 100644 index 0000000..af443a8 --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/README.md @@ -0,0 +1,139 @@ +# Tier 2 — Small-Scale Heterogeneous Benchmarks, Closed-Loop RL & Google Colab Quickstart + +Tier 2 provides **Slurm-free** GPU entry points covering: + +1. **Mode A — Controlled Multi-Turn Heterogeneous Rollout Scheduling Benchmark (`4×TP=1 + 1×TP=4`)**: End-to-end 6-policy comparison (`round_robin`, `least_connections`, `length_aware`, `la_mlfq`, `cmlfq`, `cmlfq_cost`) against live `vLLM` servers with CUDA graphs, Automatic Prefix Caching (`--enable-prefix-caching`), and online H20-3e cold calibration. +2. **Mode B — 4-GPU Heterogeneous Closed Loop (`1 Train + 3 Rollout`)**: Slurm-free `AsyncRLTrainer` (`FSDPTrainEngine` + `DAPOMathWorkflow` + supervised `vllm_hot_reload_api_server.py` with confirmed in-place weight reloads) across `TP=1` + `TP=2`. +3. **Mode C — 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`). + +--- + +## Mode A: Controlled Multi-Turn Heterogeneous Rollout Scheduling Benchmark + +Reproduce the controlled heterogeneous rollout comparison cleanly on an 8-GPU node (`4×TP=1 + 1×TP=4` by default, configurable via `--topology`): + +```bash +# Dry-run: validate topology, unified thresholds, CostModel wiring, and launch commands without GPUs +bash repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh --dry-run + +# Full real-GPU 6-policy, 2-round counterbalanced benchmark on 8x H20-3e (Qwen3-14B) +bash repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh \ + --model Qwen/Qwen3-14B \ + --gpus 0,1,2,3,4,5,6,7 \ + --topology 1,1,1,1,4 \ + --output-dir ./logs/tier2_rollout_scheduling +``` + +### Experimental Setup + +- **Hardware & Topology**: Single node `8 × NVIDIA H20-3e (141 GiB)`, `Qwen/Qwen3-14B` (`bfloat16`), deployed as **`4 × TP=1` (GPUs 0–3) + `1 × TP=4` (GPUs 4–7)**. +- **vLLM Serving Configuration**: `vLLM 0.9.2` V1 engine with CUDA graphs and `--enable-prefix-caching`, `max_model_len=24576`, `gpu_memory_utilization=0.85`, `max_num_seqs=32`, and per-instance cache isolation (`VLLM_CACHE_ROOT`, `TORCHINDUCTOR_CACHE_DIR`, `TRITON_CACHE_DIR`). +- **Fair Isolation & Unified Thresholds**: + - Each `(round, policy, phase)` prepends a fixed-width session tag (`W01..W12` / `E01..E12`) at token 0 and fits `prompt0` to `1024` tokens, eliminating cross-policy/cross-round KV cache leakage while preserving real intra-trajectory multi-turn vLLM prefix caching. + - All bucketed/length-aware schedulers share Libra's default boundary `short = 5000` (`BUCKETS_2`: `short -> TP=1 <= 5000`, `long -> TP=4 <= 24576`; `length_thresholds = {short: 5000, medium: 12000, long: 24576}`). +- **Phase 1 Cold Calibration & Cost Model**: Unique token-0 trial prefixes measure cold prefill (`2048, 4096, 8192, 16384`) and decode (`b=1` / `b=8` at `ctx=2048, 6144`, `gen=1024`) on `TP=1` and `TP=4`, autofitting `CostModel` scales (`prefill_scale`, `decode_scale`) alongside measured `recompute_ms` migration costs (`decode_ms={}` uses continuous-batching makespan estimation). +- **Heavy-Tailed Multi-Turn Workload**: Warmup `13` trajectories (`6 short / 4 quick_fix / 2 deep_fail / 1 deep_timeout`) and Eval `60` trajectories (`48 short / 10 quick_fix / 1 deep_fail / 1 deep_timeout`), 100% randomly shuffled, submitted at full-batch concurrency (`60`) with `temperature=0.0` and natural EOS over 2 counterbalanced rounds (Forward + Reverse): + - `short`: 1 turn (`max_new_tokens=256`). + - `quick_fix`: Turn 0 (`96`) -> `test_runner:medium:failure` (`1000`-tok log) -> Turn 1 (`192`). + - `deep_fail` / `deep_timeout`: Turn 0 (`96`) -> 10 turns of `1000`-tok `test_runner` logs + `640` generated tokens/turn (peak context ~`17.5K`). + +### Verified Real-GPU Results (`8 × NVIDIA H20-3e`, `Qwen3-14B`) + +**Phase 1 Cold Micro-Calibration**: + +| Metric | `TP=1` | `TP=4` | `TP=4` Speedup | +| :--- | ---: | ---: | ---: | +| Prefill `ctx=2048` median | `430.4 ms` | `128.9 ms` | `3.34x` | +| Prefill `ctx=4096` median | `864.2 ms` | `251.5 ms` | `3.44x` | +| Prefill `ctx=8192` median | `1790.3 ms` | `513.9 ms` | `3.48x` | +| Prefill `ctx=16384` median | `3970.8 ms` | `1128.6 ms` | `3.52x` | +| Decode `ctx=2048, gen=1024` (`b=1` / `b=8`) | `10.81s` / `15.94s` | `5.95s` / `7.49s` | `1.82x` / `2.13x` | +| Decode `ctx=6144, gen=1024` (`b=1` / `b=8`) | `12.07s` / `26.38s` | `6.28s` / `11.19s` | `1.92x` / `2.36x` | + +Auto-fitted analytical `CostModel` scales: `TP=1: {prefill_scale: 0.6722, decode_scale: 1.4631}`, `TP=4: {prefill_scale: 0.7828, decode_scale: 2.6475}`. + +**Phase 2 Six-Policy Counterbalanced Results (Mean Across Forward Round 1 & Reverse Round 2)**: + +| Policy | Mean Makespan (R1 / R2) | Throughput (tok/s) | vs `round_robin` (tok/s) | Makespan Reduction | `deep_fail` / `deep_timeout` | Migrations | `TP=1 / TP=4` Calls | +| :--- | --- | ---: | ---: | ---: | --- | ---: | ---: | +| `la_mlfq` | `81.14s` (`81.09` / `81.18`) | `347.1` | `-4.0%` (`0.96x`) | `-4.2%` | `81.05s` / `81.13s` | `0` | `90 / 0` | +| `round_robin` | `77.88s` (`77.43` / `78.33`) | `361.6` | `+0.0%` (`1.00x`) | `+0.0%` | `77.78s` / `77.88s` | `0` | `72 / 18` | +| `least_connections` | `73.79s` (`73.48` / `74.09`) | `376.3` | `+4.1%` (`1.06x`) | `+5.3%` | `73.30s` / `70.02s` | `0` | `63 / 27` | +| `cmlfq` | `58.42s` (`58.66` / `58.18`) | `472.7` | `+30.7%` (`1.33x`) | `+25.0%` | `58.42s` / `53.83s` | `14` | `66 / 24` | +| `length_aware` | `52.61s` (`53.19` / `52.03`) | `532.6` | `+47.3%` (`1.48x`) | `+32.4%` | `52.60s` / `51.68s` | `0` | `74 / 16` | +| **`cmlfq_cost`** | **`45.08s`** (`45.09` / `45.08`) | **`624.6`** | **`+72.7%` (`1.73x`)** | **`+42.1%`** | **`45.08s` / `45.08s`** | **`15`** | **`60 / 30`** | + +- **`cmlfq_cost` net speedups**: **`+72.7%` tok/s vs `round_robin`** (`1.73x`), **`+66.0%` vs `least_connections`**, **`+32.1%` vs `cmlfq`**, and **`+17.3%` vs `length_aware`**. +- **Routing verification**: Across both rounds, `cmlfq_cost` generated all `28,160` expected tokens (`short=256`, `quick_fix=288`, `deep_fail=6496`, `deep_timeout=6496`), placed short requests cleanly across `4×TP=1` (`13,440` tokens), migrated deep bimodal/timeout tails proactively at Turn 1 to `TP=4` (`reasons={resume: 60, distribution_cost: 30}`, `paths={stay: 78, recompute: 12}`), and retained intra-episode vLLM APC residency (`tp_tokens={1: 13440, 4: 14720}`). + +--- + +## Mode B: 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, cmlfq, 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 C: 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`. + +--- + +## Bundled Sample Data, Scripts & Templates + +- [benchmark_rollout_scheduling.py](benchmark_rollout_scheduling.py) & [run_rollout_ab.sh](run_rollout_ab.sh): Controlled 6-policy multi-turn rollout benchmark with Phase 1 cold calibration, session-isolated vLLM APC, and unified `short=5000` thresholds. +- [launch_4gpu.py](launch_4gpu.py) & [run_4gpu.sh](run_4gpu.sh): Slurm-free 4-GPU closed-loop RL and 1-GPU Colab launcher. +- [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 (works offline out of the box; pass `--dataset /path/to/dapo-math-17k.parquet` for full DAPO-Math-17K). +- [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_rollout_scheduling.py b/repro/tier2_four_gpu_closed_loop/benchmark_rollout_scheduling.py new file mode 100644 index 0000000..637c877 --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/benchmark_rollout_scheduling.py @@ -0,0 +1,1240 @@ +#!/usr/bin/env python3 +"""Controlled multi-turn heterogeneous rollout scheduling benchmark (Tier 2). + +Runs Phase 1 cold micro-calibration across distinct tensor-parallel tiers to fit +analytical `CostModel` scaling factors and migration recompute costs, followed by +Phase 2 counterbalanced rounds comparing 6 Libra scheduling policies with live +vLLM Automatic Prefix Caching (`--enable-prefix-caching`) and session-isolated +prompts. +""" + +from __future__ import annotations + +import argparse +import asyncio +import importlib.util +import json +import random +import statistics +import sys +import tempfile +import time +from collections import Counter +from pathlib import Path +from typing import Any + +import yaml + + +def _ensure_rl_framework_importable() -> Path: + """Resolve the repository root and make `RL_Framework.*` importable.""" + repo_root = Path(__file__).resolve().parents[2] + if str(repo_root) not in sys.path: + sys.path.insert(0, str(repo_root)) + if repo_root.name == "RL_Framework": + parent = str(repo_root.parent) + if parent not in sys.path: + sys.path.insert(0, parent) + 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.engine.heterogeneous_engine import HeterogeneousRolloutEngine # noqa: E402 +from RL_Framework.infra.cost_model.model import CostModel, RequestInfo # noqa: E402 +from RL_Framework.infra.scheduling.cmlfq_cost import CMLFQRoutingCosts # noqa: E402 +from RL_Framework.infra.scheduling.cmlfq_cost_scheduler import CMLFQCostScheduler # noqa: E402 + +POLICIES_FORWARD: tuple[str, ...] = ( + "round_robin", + "least_connections", + "length_aware", + "la_mlfq", + "cmlfq", + "cmlfq_cost", +) + +DEFAULT_HW_CFG = REPO_ROOT / "configs/hardware_config/h20_3e_141g.yaml" +DEFAULT_ARCH_CFG = REPO_ROOT / "configs/model_arch_config/qwen3-14b.yaml" + + +def parse_topology( + topology_spec: str, + gpus: list[int] | None = None, + host: str = "127.0.0.1", + base_port: int = 19001, +) -> list[dict[str, Any]]: + """Parse a comma-separated TP layout into heterogeneous instance configs.""" + parts = [p.strip() for p in topology_spec.split(",") if p.strip()] + if not parts: + raise ValueError("topology specification must not be empty") + tp_degrees = [int(p) for p in parts] + if any(tp <= 0 for tp in tp_degrees): + raise ValueError(f"TP degrees must be positive: {tp_degrees}") + if len(tp_degrees) < 2 or len(set(tp_degrees)) != 2: + raise ValueError( + "cmlfq_cost requires >= 2 instances spanning exactly 2 distinct TP tiers, " + f"got {tp_degrees}" + ) + + total_gpus = sum(tp_degrees) + gpu_list = list(range(total_gpus)) if gpus is None else list(gpus) + if len(gpu_list) != total_gpus: + raise ValueError( + f"topology {tp_degrees} requires {total_gpus} GPUs, got {len(gpu_list)} ({gpu_list})" + ) + + instances: list[dict[str, Any]] = [] + tp_counts: Counter[int] = Counter() + cursor = 0 + for idx, tp in enumerate(tp_degrees): + assigned = gpu_list[cursor : cursor + tp] + cursor += tp + suffix = tp_counts[tp] + tp_counts[tp] += 1 + instances.append({ + "instance_id": f"tp{tp}_{suffix}", + "tp": tp, + "gpus": assigned, + "host": host, + "port": base_port + idx, + }) + return instances + + +def make_buckets_and_thresholds( + instances: list[dict[str, Any]], + *, + max_model_len: int = 24576, + short_threshold: int = 5000, + medium_threshold: int = 12000, +) -> tuple[dict[str, dict[str, Any]], dict[str, int]]: + """Build unified Libra two-bucket routing definitions and length thresholds.""" + tps = sorted({int(inst["tp"]) for inst in instances}) + if len(tps) != 2: + raise ValueError(f"Expected 2 distinct TP tiers, got {tps}") + min_tp, max_tp = tps[0], tps[1] + buckets = { + "short": {"tp_degrees": [min_tp], "max_tokens": short_threshold}, + "long": {"tp_degrees": [max_tp], "max_tokens": max_model_len}, + } + length_thresholds = { + "short": short_threshold, + "medium": medium_threshold, + "long": max_model_len, + } + return buckets, length_thresholds + + +def _make_padded_text(tokenizer, target_tokens: int, seed_text: str, filler_unit: str) -> str: + """Build exact-token-budget text using the configured tokenizer.""" + ids = tokenizer.encode(seed_text, add_special_tokens=False) + filler_ids = tokenizer.encode(filler_unit, add_special_tokens=False) + while len(ids) < target_tokens: + ids.extend(filler_ids) + ids = ids[:target_tokens] + return tokenizer.decode(ids, skip_special_tokens=True) + + +def _chat_prompt(tokenizer, system_msg: str, user_msg: str) -> tuple[str, int]: + messages = [ + {"role": "system", "content": system_msg}, + {"role": "user", "content": user_msg}, + ] + text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) + return text, len(tokenizer.encode(text, add_special_tokens=False)) + + +def _fit_chat_prompt_exact( + tokenizer, + system_msg: str, + user_head: str, + filler_unit: str, + target_tokens: int = 1024, +) -> tuple[str, int]: + """Pad user filler so apply_chat_template hits ~target_tokens across sessions.""" + _, base_len = _chat_prompt(tokenizer, system_msg, user_head) + filler_ids = tokenizer.encode(filler_unit, add_special_tokens=False) + filler_n = max(16, target_tokens - base_len) + pad_text = "" + for _ in range(3): + rep = (filler_n // max(1, len(filler_ids))) + 2 + pad_text = tokenizer.decode((filler_ids * rep)[: max(0, filler_n)], skip_special_tokens=True) + full_text, full_len = _chat_prompt(tokenizer, system_msg, user_head + pad_text) + diff = target_tokens - full_len + if diff == 0: + return full_text, full_len + filler_n = max(0, filler_n + diff) + return _chat_prompt(tokenizer, system_msg, user_head + pad_text) + + +def _interp_pf(pf_map: dict[int, float], ctx: int) -> float: + """Lookup or piecewise-linearly interpolate measured prefill latency (ms).""" + if ctx in pf_map: + return pf_map[ctx] + keys = sorted(pf_map) + if ctx <= keys[0]: + return pf_map[keys[0]] * (ctx / max(1, keys[0])) + if ctx >= keys[-1]: + return pf_map[keys[-1]] * (ctx / max(1, keys[-1])) + for lo, hi in zip(keys[:-1], keys[1:]): + if lo <= ctx <= hi: + alpha = (ctx - lo) / (hi - lo) + return pf_map[lo] * (1.0 - alpha) + pf_map[hi] * alpha + return pf_map[keys[-1]] + + +def fit_rollout_calibration( + prefill_ms: dict[str, dict[int, float]], + raw_decode_ms: dict[str, dict[str, dict[str, float]]], + prefill_specs: list[int], + decode_specs: list[tuple[str, int, int]], + hw_cfg_path: Path, + arch_cfg_path: Path, + model_path: str, +) -> dict[str, dict[str, float]]: + """Fit analytical CostModel prefill/decode scale factors against live cold measurements.""" + uncalib_raw = AsyncRLConfig(model_path=model_path, tokenizer_path=model_path).to_dict() + uncalib_raw["hardware"] = yaml.safe_load(hw_cfg_path.read_text(encoding="utf-8")) + uncalib_raw["model_arch"] = yaml.safe_load(arch_cfg_path.read_text(encoding="utf-8")) + uncalib_cfg = AsyncRLConfig.from_dict(uncalib_raw) + rm_uncalib = CostModel( + hardware=uncalib_cfg.hardware, + model_arch=uncalib_cfg.model_arch, + profiling=uncalib_cfg.profiling, + ).rollout_model + chunk = max(1, int(rm_uncalib.L_chunk)) + + rollout_calibration: dict[str, dict[str, float]] = {} + for tp_key in sorted(prefill_ms, key=lambda k: int(k)): + tp = int(tp_key) + pf_ratios = [] + for ctx in prefill_specs: + uncalib_pf_ms = (ctx / chunk) * rm_uncalib.compute_prefill_step_time(1, chunk, tp) * 1000.0 + pf_ratios.append(prefill_ms[tp_key][ctx] / max(1e-3, uncalib_pf_ms)) + pf_scale = max(0.2, min(5.0, statistics.median(pf_ratios))) + + dec_ratios = [] + for label, ctx, gen in decode_specs: + meas_dec_ms = max( + 1.0, + raw_decode_ms[tp_key][label]["b1_total_ms"] - _interp_pf(prefill_ms[tp_key], ctx), + ) + uncalib_pf_s = (ctx / chunk) * rm_uncalib.compute_prefill_step_time(1, chunk, tp) + uncalib_dec_ms = max( + 1.0, + (rm_uncalib.compute_instance_makespan([RequestInfo(ctx, gen)], tp) - uncalib_pf_s) + * 1000.0, + ) + dec_ratios.append(meas_dec_ms / uncalib_dec_ms) + dec_scale = max(0.2, min(5.0, statistics.median(dec_ratios))) + rollout_calibration[tp_key] = { + "prefill_scale": round(pf_scale, 4), + "decode_scale": round(dec_scale, 4), + } + return rollout_calibration + + +def _make_bare_engine( + policy: str, + instances: list[dict[str, Any]], + *, + model_path: str, + hw_cfg_path: Path, + arch_cfg_path: Path, + out_dir: Path, + max_model_len: int = 24576, + gpu_memory_utilization: float = 0.85, + short_threshold: int = 5000, + medium_threshold: int = 12000, + cost_profile_path: str = "", + rollout_calibration: dict[str, dict[str, float]] | None = None, +) -> HeterogeneousRolloutEngine: + """Instantiate a client-only HeterogeneousRolloutEngine pointing at running vLLM servers.""" + buckets, length_thresholds = make_buckets_and_thresholds( + instances, + max_model_len=max_model_len, + short_threshold=short_threshold, + medium_threshold=medium_threshold, + ) + tps = sorted({int(inst["tp"]) for inst in instances}) + min_tp, max_tp = tps[0], tps[1] + + raw = AsyncRLConfig( + model_path=model_path, + tokenizer_path=model_path, + sync_path=str(out_dir / "_unused_sync"), + log_dir=str(out_dir / "_unused_logs"), + ).to_dict() + raw["enable_history_collection"] = False + raw["hardware"] = yaml.safe_load(hw_cfg_path.read_text(encoding="utf-8")) + raw["model_arch"] = yaml.safe_load(arch_cfg_path.read_text(encoding="utf-8")) + if rollout_calibration and policy == "cmlfq_cost": + raw.setdefault("profiling", {})["calibration"] = {"rollout": rollout_calibration} + + hr = raw["heterogeneous_rollout"] + hr["enabled"] = True + hr["total_gpus"] = sum(int(inst["tp"]) for inst in instances) + hr["max_model_len"] = max_model_len + hr["gpu_memory_utilization"] = gpu_memory_utilization + hr["instances"] = [dict(inst) for inst in instances] + + sc = hr["scheduling"] + sc["max_queue_length"] = 64 + sc["enable_fallback"] = True + if policy in ("round_robin", "least_connections"): + sc["scheduler_type"] = "load_balance" + sc["load_balance_strategy"] = policy + elif policy == "length_aware": + sc["scheduler_type"] = "length_aware" + sc["load_balance_strategy"] = "least_connections" + sc["routing_rules"] = {"short": [min_tp], "medium": [max_tp], "long": [max_tp]} + sc["length_thresholds"] = length_thresholds + elif policy == "la_mlfq": + sc["scheduler_type"] = "la_mlfq" + sc["load_balance_strategy"] = "least_connections" + sc["la_mlfq_buckets"] = buckets + sc["length_thresholds"] = length_thresholds + sc["la_mlfq_history_ttl"] = 10 + elif policy == "cmlfq": + sc["scheduler_type"] = "cmlfq" + sc["cmlfq_buckets"] = buckets + sc["cmlfq_tree_path"] = "" + sc["cmlfq_rebuild_interval"] = 32 + sc["cmlfq_kv_backend"] = "recompute" + elif policy == "cmlfq_cost": + sc["scheduler_type"] = "cmlfq_cost" + sc["cmlfq_buckets"] = buckets + sc["cmlfq_tree_path"] = "" + sc["cmlfq_rebuild_interval"] = 32 + sc["cmlfq_kv_backend"] = "recompute" + sc["cmlfq_cost_profile_path"] = cost_profile_path + else: + raise ValueError(f"Unknown policy: {policy}") + + full_cfg = AsyncRLConfig.from_dict(raw) + engine = HeterogeneousRolloutEngine.from_config(full_cfg) + if isinstance(engine.scheduler, CMLFQCostScheduler): + cm = CostModel( + hardware=full_cfg.hardware, + model_arch=full_cfg.model_arch, + profiling=full_cfg.profiling, + ) + engine.scheduler.routing_costs = CMLFQRoutingCosts( + profile_path=cost_profile_path, + rollout_model=cm.rollout_model, + ) + return engine + + +async def run_phase1_calibration( + tokenizer, + instances: list[dict[str, Any]], + *, + model_path: str, + hw_cfg_path: Path, + arch_cfg_path: Path, + out_dir: Path, + max_model_len: int, + gpu_memory_utilization: float, + short_threshold: int, + medium_threshold: int, +) -> dict[str, Any]: + """Run live cold micro-calibration on the two distinct TP tiers.""" + print("=== PHASE 1: Live Cold Micro-Calibration (TP_short vs TP_long) ===", flush=True) + engine = _make_bare_engine( + "round_robin", + instances, + model_path=model_path, + hw_cfg_path=hw_cfg_path, + arch_cfg_path=arch_cfg_path, + out_dir=out_dir, + max_model_len=max_model_len, + gpu_memory_utilization=gpu_memory_utilization, + short_threshold=short_threshold, + medium_threshold=medium_threshold, + ) + try: + warm_prompt = _make_padded_text( + tokenizer, + 128, + "[calib_warmup_nonce_00] Solve 2x + 3 = 11 briefly. ", + "Verify each arithmetic step cleanly. ", + ) + await asyncio.gather(*( + sub.generate( + prompt=warm_prompt, + max_new_tokens=8, + temperature=0.0, + top_p=1.0, + n=1, + ignore_eos=True, + ) + for sub in engine.engines + )) + + tps = sorted({int(inst["tp"]) for inst in instances}) + min_tp, max_tp = tps[0], tps[1] + probe_indices = [ + next(i for i, inst in enumerate(instances) if int(inst["tp"]) == min_tp), + next(i for i, inst in enumerate(instances) if int(inst["tp"]) == max_tp), + ] + prefill_specs = [c for c in (2048, 4096, 8192, 16384) if c < max_model_len] + if not prefill_specs: + prefill_specs = [max(256, max_model_len // 2)] + + prefill_ms: dict[str, dict[int, float]] = {} + for idx in probe_indices: + tp_key = str(engine.instance_configs[idx]["tp_degree"]) + sub = engine.engines[idx] + prefill_ms[tp_key] = {} + for ctx in prefill_specs: + samples = [] + for trial in range(3): + # Unique token-0 prefix guarantees cold prefill even with vLLM APC enabled. + prompt = _make_padded_text( + tokenizer, + ctx, + f"[calib_pf_tp{tp_key}_L{ctx}_t{trial}] Analyze distributed KV state across {ctx} tokens:\n", + f"Block trace tp{tp_key}_L{ctx}_t{trial}: entry status ok, prefix alignment verified, worker nominal.\n", + ) + t0 = time.perf_counter() + await sub.generate( + prompt=prompt, + max_new_tokens=1, + temperature=0.0, + top_p=1.0, + n=1, + ignore_eos=True, + ) + samples.append((time.perf_counter() - t0) * 1000.0) + prefill_ms[tp_key][ctx] = statistics.median(samples) + print( + f" [Calib Prefill] tp={tp_key} ctx={ctx:5d} median={prefill_ms[tp_key][ctx]:7.1f}ms", + flush=True, + ) + + decode_specs = [ + (lbl, ctx, gen) + for lbl, ctx, gen in (("ctx2048_g1024", 2048, 1024), ("ctx6144_g1024", 6144, 1024)) + if ctx + gen <= max_model_len + ] + if not decode_specs: + ctx_fallback = max(256, max_model_len // 2) + gen_fallback = max(64, min(512, max_model_len - ctx_fallback - 16)) + decode_specs = [(f"ctx{ctx_fallback}_g{gen_fallback}", ctx_fallback, gen_fallback)] + + raw_decode_ms: dict[str, dict[str, dict[str, float]]] = {} + for idx in probe_indices: + tp_key = str(engine.instance_configs[idx]["tp_degree"]) + sub = engine.engines[idx] + raw_decode_ms[tp_key] = {} + for label, ctx, gen in decode_specs: + prompt_b1 = _make_padded_text( + tokenizer, + ctx, + f"[calib_dec_tp{tp_key}_{label}_b1] Derive a complete formal proof for variant {label}:\n", + f"Constraint {label}_b1: invariant A_i <= B_i + 1 preserved over state transitions.\n", + ) + t0 = time.perf_counter() + await sub.generate( + prompt=prompt_b1, + max_new_tokens=gen, + temperature=0.0, + top_p=1.0, + n=1, + ignore_eos=True, + ) + b1_total_ms = (time.perf_counter() - t0) * 1000.0 + + b8_prompts = [ + _make_padded_text( + tokenizer, + ctx, + f"[calib_dec_tp{tp_key}_{label}_b8_s{k}] Derive proof variant {label} sample {k}:\n", + f"Constraint {label}_b8_s{k}: invariant A_i <= B_i + 1 preserved over state transitions.\n", + ) + for k in range(8) + ] + t0 = time.perf_counter() + await asyncio.gather(*( + sub.generate( + prompt=p_k, + max_new_tokens=gen, + temperature=0.0, + top_p=1.0, + n=1, + ignore_eos=True, + ) + for p_k in b8_prompts + )) + b8_wall_ms = (time.perf_counter() - t0) * 1000.0 + raw_decode_ms[tp_key][label] = { + "b1_total_ms": round(b1_total_ms, 2), + "b8_wall_ms": round(b8_wall_ms, 2), + } + print( + f" [Calib Decode] tp={tp_key} {label:13s}: b1={b1_total_ms:.0f}ms, b8_wall={b8_wall_ms:.0f}ms", + flush=True, + ) + + rollout_calibration = fit_rollout_calibration( + prefill_ms, + raw_decode_ms, + prefill_specs, + decode_specs, + hw_cfg_path, + arch_cfg_path, + model_path, + ) + print(f" [Calib Fit] rollout_calibration={rollout_calibration}", flush=True) + + migrations = [] + host_min = instances[probe_indices[0]]["host"] + host_max = instances[probe_indices[1]]["host"] + for src_tp, dst_tp, src_host, dst_host in ( + (min_tp, max_tp, host_min, host_max), + (max_tp, min_tp, host_max, host_min), + ): + for ctx in prefill_specs: + migrations.append({ + "source_tp": src_tp, + "target_tp": dst_tp, + "source_host": src_host, + "target_host": dst_host, + "seq_len": ctx, + "recompute_ms": round(prefill_ms[str(dst_tp)][ctx], 2), + }) + + profile = { + "decode_ms": {}, + "migrations": migrations, + "rollout_calibration": rollout_calibration, + "raw_measurements": { + "prefill_ms": prefill_ms, + "decode": raw_decode_ms, + }, + } + profile_path = out_dir / "h20_rollout_profile.json" + profile_path.write_text(json.dumps(profile, indent=2) + "\n", encoding="utf-8") + return { + "profile_path": str(profile_path), + "profile": profile, + "rollout_calibration": rollout_calibration, + } + finally: + await engine.close() + + +def build_workload( + tokenizer, + session_tag: str, + *, + is_warmup: bool, + max_model_len: int = 24576, + seed: int = 42, +) -> list[dict[str, Any]]: + """Build session-isolated SWE multi-turn workload (zero cross-run APC leakage).""" + sys_short = ( + f"[session={session_tag}] You are a meticulous repository QA & math verification assistant. " + "Provide a clear step-by-step derivation, sanity check boundary values, and end with \\boxed{} (~220 words)." + ) + sys_agent = ( + f"[session={session_tag}] You are an analytical software verification & distributed systems engineer. " + "Always write thorough step-by-step reasoning, state invariants, and complete verification details." + ) + + def make_item(kind: str, tag: str, idx: int) -> dict[str, Any]: + pid = f"{kind}_{tag}_{idx:03d}" + filler = ( + f"def verify_{pid}(shard_id, seq_len, active_reqs): " + f"assert shard_id >= 0 and seq_len <= {max_model_len}; return active_reqs * 2 + shard_id\n" + ) + if kind == "short": + a = 5 + (idx % 11) + b = 9 + (idx % 17) + x = 3 + (idx % 13) + rhs = a * x + b + head = ( + f"[{pid}] Repository Verification Task:\n" + f"Solve for shard parameter $x$ where ${a}x + {b} = {rhs}$, verify uniqueness " + f"and overflow safety against `max_seq={max_model_len}`, explain each arithmetic check clearly " + "in ~200 words, and finish with \\boxed{}.\nSnapshot context:\n" + ) + p0, n0 = _fit_chat_prompt_exact(tokenizer, sys_short, head, filler, target_tokens=1024) + return { + "prompt_id": pid, + "kind": "short", + "prompt0": p0, + "input_tokens0": n0, + "turns": [{"max_new_tokens": 256}], + } + if kind == "quick_fix": + m = 7 + idx + head = ( + f"[{pid}] Repository Patch Triage:\n" + f"Inspect off-by-one boundary in ring buffer size {m}. Draft an initial hypothesis in 3 concise " + "bullet points before running the test suite.\nSnapshot context:\n" + ) + p0, n0 = _fit_chat_prompt_exact(tokenizer, sys_agent, head, filler, target_tokens=1024) + fb1 = _make_padded_text( + tokenizer, + 1000, + f"### test_runner ({pid})\nstatus=failure\nMinor IndexError in ring_buffer_pop at offset {m}. " + "Summarize the exact 1-line fix, state why surrounding callers stay valid, and provide a short unified diff.\n" + "--- pytest traceback ---\n", + f"FAILED tests/test_ring_{m % 5}.py::test_boundary_{idx} - IndexError: pop index {m} out of range\n", + ) + return { + "prompt_id": pid, + "kind": "quick_fix", + "prompt0": p0, + "input_tokens0": n0, + "turns": [ + {"max_new_tokens": 96}, + { + "tool_type": "test_runner", + "status": "failure", + "payload_tokens": 1000, + "feedback": fb1, + "max_new_tokens": 192, + }, + ], + } + if kind == "deep_fail": + m = 19 + idx + head = ( + f"[{pid}] Deep Distributed Consensus Bug:\n" + f"Inspect multi-shard state replication across {m} replicas for epoch fencepost & lock ordering bugs. " + "List initial diagnostic hypotheses before inspecting failure logs.\nSnapshot context:\n" + ) + p0, n0 = _fit_chat_prompt_exact(tokenizer, sys_agent, head, filler, target_tokens=1024) + turns: list[dict[str, Any]] = [{"max_new_tokens": 96}] + for t in range(1, 11): + fb = _make_padded_text( + tokenizer, + 1000, + f"### test_runner ({pid} phase {t}/10)\nstatus=failure\nDeep AssertionError in replica-{m} state machine " + f"(sub-case {t}/10)! Write a comprehensive mathematical invariant proof, full transition table, " + "edge-case analysis, and complete corrected Python implementation.\n--- state dump ---\n", + f"E AssertionError: epoch={t} replica={m} expected barrier commit <= snapshot_seq\n", + ) + turns.append({ + "tool_type": "test_runner", + "status": "failure", + "payload_tokens": 1000, + "feedback": fb, + "max_new_tokens": 640, + }) + return { + "prompt_id": pid, + "kind": "deep_fail", + "prompt0": p0, + "input_tokens0": n0, + "turns": turns, + } + + m = 31 + idx + head = ( + f"[{pid}] Deep Async Pipeline Tail-Latency Bug:\n" + f"Diagnose worst-case tail latency stall in a {m}-worker asynchronous pipeline with preemption and rollback. " + "State initial hypotheses before inspecting profiler logs.\nSnapshot context:\n" + ) + p0, n0 = _fit_chat_prompt_exact(tokenizer, sys_agent, head, filler, target_tokens=1024) + turns = [{"max_new_tokens": 96}] + for t in range(1, 11): + fb = _make_padded_text( + tokenizer, + 1000, + f"### test_runner ({pid} stress {t}/10)\nstatus=timeout\nPerformance regression timed out on {m}-worker " + f"stress harness (phase {t}/10)! Derive the complete asymptotic complexity proof, amortization " + "equations, step-by-step execution trace, and full async Python rewrite.\n--- profiler trace ---\n", + f"TIMEOUT worker={m} phase={t} queue_wait_ms=14820 stalling_barrier=commit_lock\n", + ) + turns.append({ + "tool_type": "test_runner", + "status": "timeout", + "payload_tokens": 1000, + "feedback": fb, + "max_new_tokens": 640, + }) + return { + "prompt_id": pid, + "kind": "deep_timeout", + "prompt0": p0, + "input_tokens0": n0, + "turns": turns, + } + + if is_warmup: + counts = {"short": 6, "quick_fix": 4, "deep_fail": 2, "deep_timeout": 1} + tag = "w" + rng_seed = seed + else: + counts = {"short": 48, "quick_fix": 10, "deep_fail": 1, "deep_timeout": 1} + tag = "e" + rng_seed = seed + 1 + + items: list[dict[str, Any]] = [] + for kind in ("short", "quick_fix", "deep_fail", "deep_timeout"): + for idx in range(counts[kind]): + items.append(make_item(kind, tag, idx)) + random.Random(rng_seed).shuffle(items) + return items + + +async def run_one_episode( + engine: HeterogeneousRolloutEngine, + tokenizer, + item: dict[str, Any], + *, + epoch: int, +) -> dict[str, Any]: + t_ep0 = time.perf_counter() + req_id = "" + if hasattr(engine.scheduler, "get_request_route"): + req_id = await engine.begin_cmlfq_request_when_available( + item["prompt_id"], item["input_tokens0"], epoch=epoch + ) + + cur_text = item["prompt0"] + cur_tokens = item["input_tokens0"] + pure_generated = 0 + total_output_tokens = 0 + calls = [] + try: + for turn_idx, turn_spec in enumerate(item["turns"]): + if turn_idx > 0: + fb = turn_spec["feedback"] + event = { + "tool_type": turn_spec["tool_type"], + "status": turn_spec["status"], + "payload_tokens": turn_spec["payload_tokens"], + "token_position": total_output_tokens, + "generated_token_position": pure_generated, + "turn": turn_idx - 1, + } + if req_id: + engine.record_cmlfq_tool_return(req_id, event, total_output_tokens) + cur_text += "\n" + fb + "\n" + cur_tokens = len(tokenizer.encode(cur_text, add_special_tokens=False)) + + kwargs: dict[str, Any] = { + "prompt": cur_text, + "max_new_tokens": turn_spec["max_new_tokens"], + "temperature": 0.0, + "top_p": 1.0, + "n": 1, + "prompt_id": item["prompt_id"], + "input_tokens": cur_tokens, + "epoch": epoch, + } + if req_id: + kwargs["request_id"] = req_id + + t_g0 = time.perf_counter() + resp = await engine.generate(**kwargs) + t_g1 = time.perf_counter() + out_text = resp.get("text", "") + out_toks = len(resp.get("tokens", [])) or len( + tokenizer.encode(out_text, add_special_tokens=False) + ) + pure_generated += out_toks + total_output_tokens += out_toks + ( + turn_spec.get("payload_tokens", 0) if turn_idx > 0 else 0 + ) + cur_text += out_text + info = resp.get("_schedule_info", {}) + calls.append({ + "turn": turn_idx, + "tp": info.get("tp_degree"), + "instance_id": info.get("instance_id"), + "reason": info.get("reason", ""), + "path": info.get("execution_path", ""), + "out_tokens": out_toks, + "dur_s": t_g1 - t_g0, + }) + + if req_id: + engine.finish_cmlfq_request( + req_id, total_output_tokens, generated_tokens=pure_generated + ) + except BaseException: + if req_id: + engine.cancel_cmlfq_request(req_id) + raise + + return { + "prompt_id": item["prompt_id"], + "kind": item["kind"], + "dur_s": time.perf_counter() - t_ep0, + "pure_generated_tokens": pure_generated, + "calls": calls, + } + + +async def eval_policy( + policy: str, + round_idx: int, + run_slot: int, + tokenizer, + instances: list[dict[str, Any]], + *, + model_path: str, + hw_cfg_path: Path, + arch_cfg_path: Path, + out_dir: Path, + max_model_len: int, + gpu_memory_utilization: float, + short_threshold: int, + medium_threshold: int, + cost_profile_path: str, + rollout_calibration: dict[str, dict[str, float]], + seed: int, +) -> dict[str, Any]: + w_tag = f"W{run_slot:02d}" + e_tag = f"E{run_slot:02d}" + warmup_items = build_workload( + tokenizer, w_tag, is_warmup=True, max_model_len=max_model_len, seed=seed + ) + eval_items = build_workload( + tokenizer, e_tag, is_warmup=False, max_model_len=max_model_len, seed=seed + ) + engine = _make_bare_engine( + policy, + instances, + model_path=model_path, + hw_cfg_path=hw_cfg_path, + arch_cfg_path=arch_cfg_path, + out_dir=out_dir, + max_model_len=max_model_len, + gpu_memory_utilization=gpu_memory_utilization, + short_threshold=short_threshold, + medium_threshold=medium_threshold, + cost_profile_path=cost_profile_path, + rollout_calibration=rollout_calibration, + ) + try: + async def _run_batch(items: list[dict[str, Any]], epoch: int) -> list[dict[str, Any]]: + sem = asyncio.Semaphore(len(items)) + + async def _bounded(it: dict[str, Any]) -> dict[str, Any]: + async with sem: + return await run_one_episode(engine, tokenizer, it, epoch=epoch) + + return await asyncio.gather(*(_bounded(it) for it in items)) + + engine.notify_epoch_start(0) + await _run_batch(warmup_items, 0) + engine.notify_epoch_end(0) + + engine.notify_epoch_start(1) + t0 = time.perf_counter() + ep_results = await _run_batch(eval_items, 1) + makespan_s = time.perf_counter() - t0 + engine.notify_epoch_end(1) + + durs = sorted(ep["dur_s"] for ep in ep_results) + p50 = durs[len(durs) // 2] + p90 = durs[min(len(durs) - 1, int(0.9 * len(durs)))] + total_gen_tokens = sum(ep["pure_generated_tokens"] for ep in ep_results) + tp_calls: Counter[str] = Counter() + tp_tokens: Counter[str] = Counter() + reasons: Counter[str] = Counter() + paths: Counter[str] = Counter() + for ep in ep_results: + for c in ep["calls"]: + tp_key = str(c["tp"]) + tp_calls[tp_key] += 1 + tp_tokens[tp_key] += c["out_tokens"] + reasons[c["reason"]] += 1 + if c["path"]: + paths[c["path"]] += 1 + + stats = engine.scheduler.get_stats().to_dict() + migrations = stats.get("migrated_routes", 0) + by_kind = { + k: round(statistics.mean(ep["dur_s"] for ep in ep_results if ep["kind"] == k), 3) + for k in ("short", "quick_fix", "deep_fail", "deep_timeout") + } + by_kind_gen = { + k: round( + statistics.mean( + ep["pure_generated_tokens"] for ep in ep_results if ep["kind"] == k + ), + 1, + ) + for k in ("short", "quick_fix", "deep_fail", "deep_timeout") + } + print( + f"[R{round_idx} {policy:18s}] makespan={makespan_s:6.2f}s | " + f"tok/s={total_gen_tokens / makespan_s:7.1f} | p50={p50:5.2f}s p90={p90:5.2f}s | " + f"tp_calls={dict(sorted(tp_calls.items()))} | mig={migrations} | " + f"gen_tok={total_gen_tokens} | gen_by_kind={by_kind_gen}", + flush=True, + ) + return { + "round": round_idx, + "session_tags": {"warmup": w_tag, "eval": e_tag}, + "policy": policy, + "makespan_s": makespan_s, + "total_generated_tokens": total_gen_tokens, + "tokens_per_second": total_gen_tokens / makespan_s, + "trajectories_per_second": len(ep_results) / makespan_s, + "latency_p50_s": p50, + "latency_p90_s": p90, + "latency_max_s": durs[-1], + "tp_calls": dict(sorted(tp_calls.items())), + "tp_tokens": dict(sorted(tp_tokens.items())), + "migrations": migrations, + "reasons": dict(reasons), + "paths": dict(paths), + "by_kind": by_kind, + "by_kind_gen_tokens": by_kind_gen, + } + finally: + await engine.close() + + +def _resolve_policies(raw_policies: str) -> list[str]: + if raw_policies.strip().lower() == "all": + return list(POLICIES_FORWARD) + selected = [p.strip() for p in raw_policies.split(",") if p.strip()] + unknown = [p for p in selected if p not in POLICIES_FORWARD] + if unknown: + raise ValueError(f"Unknown policies {unknown}; valid choices: {list(POLICIES_FORWARD)}") + if not selected: + raise ValueError("No policies selected") + return selected + + +def run_dry_run( + args: argparse.Namespace, + instances: list[dict[str, Any]], + selected_policies: list[str], +) -> dict[str, Any]: + """Instantiate all selected schedulers offline and verify CostModel wiring.""" + buckets, length_thresholds = make_buckets_and_thresholds( + instances, + max_model_len=args.max_model_len, + short_threshold=args.short_threshold, + medium_threshold=args.medium_threshold, + ) + tps = sorted({int(inst["tp"]) for inst in instances}) + min_tp, max_tp = tps[0], tps[1] + dummy_cal = { + str(min_tp): {"prefill_scale": 0.67, "decode_scale": 1.46}, + str(max_tp): {"prefill_scale": 0.78, "decode_scale": 2.65}, + } + hw_cfg_path = Path(args.hardware_config) + arch_cfg_path = Path(args.model_arch_config) + + with tempfile.TemporaryDirectory(prefix="libra_rollout_dryrun_") as tmpdir: + tmp_path = Path(tmpdir) + profile_path = tmp_path / "dummy_profile.json" + profile_path.write_text( + json.dumps({ + "decode_ms": {}, + "migrations": [ + { + "source_tp": min_tp, + "target_tp": max_tp, + "source_host": instances[0]["host"], + "target_host": instances[-1]["host"], + "seq_len": 2048, + "recompute_ms": 130.0, + }, + { + "source_tp": max_tp, + "target_tp": min_tp, + "source_host": instances[-1]["host"], + "target_host": instances[0]["host"], + "seq_len": 2048, + "recompute_ms": 430.0, + }, + ], + }), + encoding="utf-8", + ) + schedulers: dict[str, str] = {} + for policy in selected_policies: + eng = _make_bare_engine( + policy, + instances, + model_path=args.model, + hw_cfg_path=hw_cfg_path, + arch_cfg_path=arch_cfg_path, + out_dir=tmp_path, + max_model_len=args.max_model_len, + gpu_memory_utilization=args.gpu_memory_utilization, + short_threshold=args.short_threshold, + medium_threshold=args.medium_threshold, + cost_profile_path=str(profile_path), + rollout_calibration=dummy_cal, + ) + schedulers[policy] = type(eng.scheduler).__name__ + if policy == "cmlfq_cost": + rc = eng.scheduler.routing_costs + assert rc.decode_ms == {}, f"Expected empty decode_ms, got {rc.decode_ms}" + assert rc.rollout_model is not None + assert rc.rollout_model.calibration == dummy_cal + assert len(rc.migrations) == 2 + + payload = { + "dry_run": True, + "model": args.model, + "instances": instances, + "buckets": buckets, + "length_thresholds": length_thresholds, + "policies": schedulers, + "rounds": args.rounds, + } + print(json.dumps(payload, indent=2)) + return payload + + +async def run_benchmark(args: argparse.Namespace) -> dict[str, Any]: + gpus = ( + [int(g.strip()) for g in args.gpus.split(",") if g.strip()] + if args.gpus.strip() + else None + ) + instances = parse_topology(args.topology, gpus=gpus, host=args.host, base_port=args.base_port) + selected_policies = _resolve_policies(args.policies) + + if args.dry_run: + return run_dry_run(args, instances, selected_policies) + + from transformers import AutoTokenizer + + out_dir = Path(args.output_dir) + out_dir.mkdir(parents=True, exist_ok=True) + hw_cfg_path = Path(args.hardware_config) + arch_cfg_path = Path(args.model_arch_config) + buckets, length_thresholds = make_buckets_and_thresholds( + instances, + max_model_len=args.max_model_len, + short_threshold=args.short_threshold, + medium_threshold=args.medium_threshold, + ) + + tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True) + calib = await run_phase1_calibration( + tokenizer, + instances, + model_path=args.model, + hw_cfg_path=hw_cfg_path, + arch_cfg_path=arch_cfg_path, + out_dir=out_dir, + max_model_len=args.max_model_len, + gpu_memory_utilization=args.gpu_memory_utilization, + short_threshold=args.short_threshold, + medium_threshold=args.medium_threshold, + ) + + print( + f"=== PHASE 2: {len(selected_policies)}-Policy Comparison " + f"(warmup=13, eval=60, full-batch, vLLM APC ON, short={args.short_threshold}) ===", + flush=True, + ) + + runs = [] + slot = 0 + for round_idx in range(1, args.rounds + 1): + order = selected_policies if round_idx % 2 == 1 else list(reversed(selected_policies)) + print(f"--- Round {round_idx}: {order} ---", flush=True) + for policy in order: + slot += 1 + runs.append( + await eval_policy( + policy, + round_idx, + slot, + tokenizer, + instances, + model_path=args.model, + hw_cfg_path=hw_cfg_path, + arch_cfg_path=arch_cfg_path, + out_dir=out_dir, + max_model_len=args.max_model_len, + gpu_memory_utilization=args.gpu_memory_utilization, + short_threshold=args.short_threshold, + medium_threshold=args.medium_threshold, + cost_profile_path=calib["profile_path"], + rollout_calibration=calib["rollout_calibration"], + seed=args.seed, + ) + ) + + aggregate: dict[str, dict[str, Any]] = {} + for policy in selected_policies: + rows = [r for r in runs if r["policy"] == policy] + mean_mk = statistics.mean(r["makespan_s"] for r in rows) + mean_tps = statistics.mean(r["tokens_per_second"] for r in rows) + mean_p50 = statistics.mean(r["latency_p50_s"] for r in rows) + mean_p90 = statistics.mean(r["latency_p90_s"] for r in rows) + mean_mig = statistics.mean(r["migrations"] for r in rows) + aggregate[policy] = { + "rounds": len(rows), + "mean_makespan_s": mean_mk, + "mean_tokens_per_second": mean_tps, + "mean_latency_p50_s": mean_p50, + "mean_latency_p90_s": mean_p90, + "mean_migrations": mean_mig, + "round_makespans_s": [r["makespan_s"] for r in rows], + "total_generated_tokens": [r["total_generated_tokens"] for r in rows], + "tp_calls_per_round": [r["tp_calls"] for r in rows], + "by_kind_mean_s": { + k: round(statistics.mean(r["by_kind"][k] for r in rows), 3) + for k in ("short", "quick_fix", "deep_fail", "deep_timeout") + }, + "by_kind_gen_tokens": { + k: round(statistics.mean(r["by_kind_gen_tokens"][k] for r in rows), 1) + for k in ("short", "quick_fix", "deep_fail", "deep_timeout") + }, + } + + if "round_robin" in aggregate: + rr = aggregate["round_robin"] + for stats_d in aggregate.values(): + stats_d["speedup_vs_round_robin"] = rr["mean_makespan_s"] / stats_d["mean_makespan_s"] + stats_d["throughput_gain_vs_rr_pct"] = ( + stats_d["mean_tokens_per_second"] / rr["mean_tokens_per_second"] - 1.0 + ) * 100.0 + stats_d["makespan_reduction_vs_rr_pct"] = ( + 1.0 - stats_d["mean_makespan_s"] / rr["mean_makespan_s"] + ) * 100.0 + if "least_connections" in aggregate: + lc = aggregate["least_connections"] + for stats_d in aggregate.values(): + stats_d["speedup_vs_least_connections"] = ( + lc["mean_makespan_s"] / stats_d["mean_makespan_s"] + ) + stats_d["throughput_gain_vs_lc_pct"] = ( + stats_d["mean_tokens_per_second"] / lc["mean_tokens_per_second"] - 1.0 + ) * 100.0 + if "length_aware" in aggregate: + la = aggregate["length_aware"] + for stats_d in aggregate.values(): + stats_d["throughput_gain_vs_la_pct"] = ( + stats_d["mean_tokens_per_second"] / la["mean_tokens_per_second"] - 1.0 + ) * 100.0 + if "cmlfq" in aggregate: + cm = aggregate["cmlfq"] + for stats_d in aggregate.values(): + stats_d["throughput_gain_vs_cmlfq_pct"] = ( + stats_d["mean_tokens_per_second"] / cm["mean_tokens_per_second"] - 1.0 + ) * 100.0 + + summary = { + "topology": args.topology, + "instances": instances, + "model": args.model, + "thresholds": {"buckets": buckets, "length_thresholds": length_thresholds}, + "calibration": calib["profile"], + "workload": {"warmup": 13, "eval": 60, "concurrency": {"warmup": 13, "eval": 60}}, + "runs": runs, + "aggregate": aggregate, + } + (out_dir / "results.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") + + print("\n=== AGGREGATE SUMMARY ===", flush=True) + for policy in selected_policies: + s = aggregate[policy] + vs_rr = ( + f" | vs_RR={s['speedup_vs_round_robin']:.2f}x " + f"(tok/s {s['throughput_gain_vs_rr_pct']:+5.1f}%, mk {s['makespan_reduction_vs_rr_pct']:+5.1f}%)" + if "speedup_vs_round_robin" in s + else "" + ) + print( + f"{policy:18s}: makespan={s['mean_makespan_s']:6.2f}s | " + f"tok/s={s['mean_tokens_per_second']:7.1f} | p90={s['mean_latency_p90_s']:5.2f}s{vs_rr}", + flush=True, + ) + return summary + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Tier 2 controlled multi-turn heterogeneous rollout scheduling benchmark." + ) + parser.add_argument("--model", default="Qwen/Qwen3-14B", help="Model ID or local path") + parser.add_argument( + "--topology", + default="1,1,1,1,4", + help="Comma-separated TP degrees across instances (default: 1,1,1,1,4)", + ) + parser.add_argument( + "--gpus", + default="", + help="Comma-separated GPU IDs (default: 0..sum(topology)-1)", + ) + parser.add_argument("--host", default="127.0.0.1", help="vLLM server host") + parser.add_argument("--base-port", type=int, default=19001, help="Starting vLLM server port") + parser.add_argument( + "--hardware-config", + default=str(DEFAULT_HW_CFG), + help="Hardware config YAML for analytical CostModel", + ) + parser.add_argument( + "--model-arch-config", + default=str(DEFAULT_ARCH_CFG), + help="Model architecture config YAML for analytical CostModel", + ) + parser.add_argument( + "--output-dir", + default="./logs/tier2_rollout_scheduling", + help="Directory for calibration profile and results.json", + ) + parser.add_argument("--max-model-len", type=int, default=24576, help="Max sequence length") + parser.add_argument( + "--gpu-memory-utilization", type=float, default=0.85, help="vLLM GPU memory utilization" + ) + parser.add_argument( + "--short-threshold", + type=int, + default=5000, + help="Unified token threshold separating short vs long bucket (default: 5000)", + ) + parser.add_argument( + "--medium-threshold", + type=int, + default=12000, + help="Medium length threshold for length_aware/la_mlfq (default: 12000)", + ) + parser.add_argument("--rounds", type=int, default=2, help="Counterbalanced rounds (default: 2)") + parser.add_argument( + "--policies", + default="all", + help="Comma-separated policy names or 'all'", + ) + parser.add_argument("--seed", type=int, default=42, help="Random workload shuffle seed") + parser.add_argument( + "--dry-run", + action="store_true", + help="Verify topology, thresholds, and scheduler initialization without GPUs", + ) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + asyncio.run(run_benchmark(args)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(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_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..7d07e5d --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/launch_4gpu.py @@ -0,0 +1,827 @@ +#!/usr/bin/env python3 +"""Slurm-free Tier 2 launcher for 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.scripts.summarize_scheduler_rl import summarize # noqa: E402 + + +DEFAULT_DATASET = ( + REPO_ROOT / "repro/tier2_four_gpu_closed_loop/sample_data/dapo_math_mini.jsonl" +) + +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 = "0,1,2,3" if mode == "4gpu" else "0" + 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 = 4 if mode == "4gpu" else 1 + 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 == "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") + return { + "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": ( + [[1, 2], [2, 1]] if (is_causal and kv_backend == "cpu_offload") else [] + ), + "cmlfq_buckets": { + "short": {"tp_degrees": [1], "max_tokens": 512}, + "long": {"tp_degrees": [2], "max_tokens": max(2048, max_model_len)}, + }, + } + + +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, +) -> 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), + "--enforce-eager", + "--disable-log-requests", + "--no-enable-prefix-caching", + "--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 = 2, + 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 + + 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"] + 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_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 + else: + resolved_model = model_path or "Qwen/Qwen3-4B" + arch_yaml = "qwen3-4b.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_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/a800_80g.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": 1, + "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": 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": "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(max_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" + 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=max_num_seqs, + seed=seed, + kv_storage_dir=kv_storage_dir, + ), + } + ) + + 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 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) + + 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 = [] + + try: + health_urls = [] + for spec in plan["rollout_specs"]: + log_file = Path(spec["log_path"]).open("w", encoding="utf-8") + log_handles.append(log_file) + proc = subprocess.Popen( + spec["command"], + env=dict(env, CUDA_VISIBLE_DEVICES=spec["cuda_visible_devices"]), + 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() + 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 4-GPU closed loop and 1-GPU Google Colab" + ) + parser.add_argument( + "--mode", + choices=("4gpu", "colab-1gpu"), + default="4gpu", + help="4gpu: 1 Train + 3 heterogeneous Rollout; colab-1gpu: single co-located GPU", + ) + parser.add_argument( + "--policy", + default="auto", + help="Scheduling policy (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,1,2,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="Prompts 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=2, 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: + 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 1,2" + ) + 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_rollout_ab.sh b/repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh new file mode 100755 index 0000000..84e8f0e --- /dev/null +++ b/repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh @@ -0,0 +1,251 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +BENCH_SCRIPT="$ROOT/repro/tier2_four_gpu_closed_loop/benchmark_rollout_scheduling.py" + +MODEL="Qwen/Qwen3-14B" +GPUS="0,1,2,3,4,5,6,7" +TOPOLOGY="1,1,1,1,4" +BASE_PORT="19001" +HOST="127.0.0.1" +MAX_MODEL_LEN="24576" +GPU_MEM_UTIL="0.85" +MAX_NUM_SEQS="32" +OUTPUT_DIR="./logs/tier2_rollout_scheduling" +HARDWARE_CONFIG="$ROOT/configs/hardware_config/h20_3e_141g.yaml" +MODEL_ARCH_CONFIG="$ROOT/configs/model_arch_config/qwen3-14b.yaml" +ROUNDS="2" +POLICIES="all" +PYTHON="python3" +DRY_RUN=0 + +usage() { + cat <&2; usage >&2; exit 1 ;; + esac +done + +IFS=',' read -ra TP_ARR <<< "$TOPOLOGY" +if [[ ${#TP_ARR[@]} -lt 2 ]]; then + echo "ERROR: --topology requires at least 2 instances, got '$TOPOLOGY'" >&2 + exit 1 +fi + +TOTAL_NEEDED=0 +for tp in "${TP_ARR[@]}"; do + TOTAL_NEEDED=$((TOTAL_NEEDED + tp)) +done + +if [[ -z "$GPUS" ]]; then + GPU_ARR=() + for ((g=0; g&2 + exit 1 +fi + +if [[ -d /dev/shm && -w /dev/shm ]]; then + CACHE_BASE="/dev/shm" +else + CACHE_BASE="${TMPDIR:-/tmp}" +fi +RUN_TAG="$$" + +INST_NAMES=() +INST_GPUS=() +INST_TPS=() +INST_PORTS=() + +cursor=0 +for ((idx=0; idx<${#TP_ARR[@]}; idx++)); do + tp="${TP_ARR[$idx]}" + sub_gpus="" + for ((j=0; j/dev/null || kill -TERM "$pid" 2>/dev/null || true + done + if [[ ${#PIDS[@]} -gt 0 ]]; then + sleep 6 + fi + for pid in "${PIDS[@]:-}"; do + kill -KILL -- "-$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null || true + done + rm -rf "${CACHE_BASE}/libra_vllm_${RUN_TAG}_"* + exit "$rc" +} +trap 'exit 143' TERM +trap 'exit 130' INT +trap cleanup EXIT + +for ((i=0; i<${#INST_NAMES[@]}; i++)); do + name="${INST_NAMES[$i]}" + gpus="${INST_GPUS[$i]}" + tp="${INST_TPS[$i]}" + port="${INST_PORTS[$i]}" + cache_dir="${CACHE_BASE}/libra_vllm_${RUN_TAG}_${name}" + mkdir -p "${cache_dir}/vllm" "${cache_dir}/inductor" "${cache_dir}/triton" + env \ + CUDA_VISIBLE_DEVICES="$gpus" \ + VLLM_CACHE_ROOT="${cache_dir}/vllm" \ + TORCHINDUCTOR_CACHE_DIR="${cache_dir}/inductor" \ + TRITON_CACHE_DIR="${cache_dir}/triton" \ + setsid "$PYTHON" -m vllm.entrypoints.openai.api_server \ + --model "$MODEL" \ + --host "$HOST" \ + --port "$port" \ + --tensor-parallel-size "$tp" \ + --dtype bfloat16 \ + --max-model-len "$MAX_MODEL_LEN" \ + --gpu-memory-utilization "$GPU_MEM_UTIL" \ + --max-num-seqs "$MAX_NUM_SEQS" \ + --enable-prefix-caching \ + --disable-log-requests \ + --seed 42 \ + > "$OUTPUT_DIR/vllm_${name}.log" 2>&1 < /dev/null & + PIDS+=($!) + echo "Launched $name (gpus=$gpus, tp=$tp, port=$port, pid=${PIDS[-1]})" +done + +deadline=$((SECONDS + 600)) +for port in "${INST_PORTS[@]}"; do + while true; do + if "$PYTHON" -c "import urllib.request; r=urllib.request.urlopen('http://${HOST}:${port}/health', timeout=2); raise SystemExit(0 if r.status == 200 else 1)" 2>/dev/null; then + echo "Server on ${HOST}:${port} is healthy." + break + fi + for pid in "${PIDS[@]}"; do + if ! kill -0 "$pid" 2>/dev/null; then + echo "ERROR: vLLM server pid $pid exited early; inspect $OUTPUT_DIR/vllm_*.log" >&2 + exit 2 + fi + done + if [[ "$SECONDS" -ge "$deadline" ]]; then + echo "ERROR: Timed out waiting for vLLM server on ${HOST}:${port}" >&2 + exit 3 + fi + sleep 3 + done +done + +echo "All ${#INST_NAMES[@]} vLLM servers ready. Running rollout scheduling benchmark..." +"$PYTHON" -u "$BENCH_SCRIPT" \ + --model "$MODEL" \ + --topology "$TOPOLOGY" \ + --gpus "$GPUS" \ + --host "$HOST" \ + --base-port "$BASE_PORT" \ + --hardware-config "$HARDWARE_CONFIG" \ + --model-arch-config "$MODEL_ARCH_CONFIG" \ + --output-dir "$OUTPUT_DIR" \ + --max-model-len "$MAX_MODEL_LEN" \ + --gpu-memory-utilization "$GPU_MEM_UTIL" \ + --rounds "$ROUNDS" \ + --policies "$POLICIES" 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..8c3d84e --- /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"} +{"prompt_id": "dapo_mini_01", "question": "Find the remainder when $7^{2025}$ is divided by $1000$.", "ground_truth": "807", "answer": "807", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_02", "question": "Solve for $x$: $3x + 10 = 34$.", "ground_truth": "8", "answer": "8", "data_source": "dapo_math_mini"} +{"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}$.", "ground_truth": "269", "answer": "269", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_04", "question": "Solve for $x$: $4x + 13 = 65$.", "ground_truth": "13", "answer": "13", "data_source": "dapo_math_mini"} +{"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"} +{"prompt_id": "dapo_mini_06", "question": "Solve for $x$: $5x + 16 = 106$.", "ground_truth": "18", "answer": "18", "data_source": "dapo_math_mini"} +{"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$?", "ground_truth": "90", "answer": "90", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_08", "question": "Solve for $x$: $6x + 19 = 43$.", "ground_truth": "4", "answer": "4", "data_source": "dapo_math_mini"} +{"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)$?", "ground_truth": "334", "answer": "334", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_10", "question": "Solve for $x$: $7x + 9 = 72$.", "ground_truth": "9", "answer": "9", "data_source": "dapo_math_mini"} +{"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$.", "ground_truth": "121", "answer": "121", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_12", "question": "Solve for $x$: $8x + 12 = 124$.", "ground_truth": "14", "answer": "14", "data_source": "dapo_math_mini"} +{"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$.", "ground_truth": "795", "answer": "795", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_14", "question": "Solve for $x$: $9x + 15 = 186$.", "ground_truth": "19", "answer": "19", "data_source": "dapo_math_mini"} +{"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"} +{"prompt_id": "dapo_mini_16", "question": "An arithmetic sequence starts at $2$ with common difference $3$. Find the sum of its first $6$ terms.", "ground_truth": "57", "answer": "57", "data_source": "dapo_math_mini"} +{"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$.", "ground_truth": "373", "answer": "373", "data_source": "dapo_math_mini"} +{"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"} +{"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"} +{"prompt_id": "dapo_mini_20", "question": "An arithmetic sequence starts at $6$ with common difference $5$. Find the sum of its first $8$ terms.", "ground_truth": "188", "answer": "188", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_21", "question": "Find the remainder when $\\binom{30}{15} + \\binom{30}{10}$ is divided by $1009$.", "ground_truth": "945", "answer": "945", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_22", "question": "An arithmetic sequence starts at $8$ with common difference $6$. Find the sum of its first $9$ terms.", "ground_truth": "288", "answer": "288", "data_source": "dapo_math_mini"} +{"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$?", "ground_truth": "321", "answer": "321", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_24", "question": "An arithmetic sequence starts at $10$ with common difference $7$. Find the sum of its first $10$ terms.", "ground_truth": "415", "answer": "415", "data_source": "dapo_math_mini"} +{"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"} +{"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"} +{"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"} +{"prompt_id": "dapo_mini_28", "question": "An arithmetic sequence starts at $14$ with common difference $4$. Find the sum of its first $6$ terms.", "ground_truth": "144", "answer": "144", "data_source": "dapo_math_mini"} +{"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\\}$?", "ground_truth": "21", "answer": "21", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_30", "question": "An arithmetic sequence starts at $16$ with common difference $5$. Find the sum of its first $7$ terms.", "ground_truth": "217", "answer": "217", "data_source": "dapo_math_mini"} +{"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?", "ground_truth": "240", "answer": "240", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_32", "question": "Compute the remainder when $5^{3}$ is divided by $7$.", "ground_truth": "6", "answer": "6", "data_source": "dapo_math_mini"} +{"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"} +{"prompt_id": "dapo_mini_34", "question": "Compute the remainder when $6^{4}$ is divided by $8$.", "ground_truth": "0", "answer": "0", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_35", "question": "Find the largest integer $n$ such that $72^n$ divides $120!$.", "ground_truth": "29", "answer": "29", "data_source": "dapo_math_mini"} +{"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"} +{"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$.", "ground_truth": "602070", "answer": "602070", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_38", "question": "Compute the remainder when $8^{6}$ is divided by $10$.", "ground_truth": "4", "answer": "4", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_39", "question": "Let $\\omega = e^{2\\pi i / 7}$. Compute $\\prod_{k=1}^{6} (3 - 2\\omega^k)$.", "ground_truth": "2059", "answer": "2059", "data_source": "dapo_math_mini"} +{"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"} +{"prompt_id": "dapo_mini_41", "question": "How many $6$-digit palindromic positive integers are divisible by $77$?", "ground_truth": "140", "answer": "140", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_42", "question": "Compute the remainder when $10^{4}$ is divided by $7$.", "ground_truth": "4", "answer": "4", "data_source": "dapo_math_mini"} +{"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$.", "ground_truth": "23", "answer": "23", "data_source": "dapo_math_mini"} +{"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"} +{"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"} +{"prompt_id": "dapo_mini_46", "question": "Compute the remainder when $12^{6}$ is divided by $9$.", "ground_truth": "0", "answer": "0", "data_source": "dapo_math_mini"} +{"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$?", "ground_truth": "819", "answer": "819", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_48", "question": "In how many ways can we choose $2$ distinct items from $6$ distinct items?", "ground_truth": "15", "answer": "15", "data_source": "dapo_math_mini"} +{"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"} +{"prompt_id": "dapo_mini_50", "question": "In how many ways can we choose $3$ distinct items from $7$ distinct items?", "ground_truth": "35", "answer": "35", "data_source": "dapo_math_mini"} +{"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"} +{"prompt_id": "dapo_mini_52", "question": "In how many ways can we choose $4$ distinct items from $8$ distinct items?", "ground_truth": "70", "answer": "70", "data_source": "dapo_math_mini"} +{"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"} +{"prompt_id": "dapo_mini_54", "question": "In how many ways can we choose $2$ distinct items from $9$ distinct items?", "ground_truth": "36", "answer": "36", "data_source": "dapo_math_mini"} +{"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$.", "ground_truth": "752", "answer": "752", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_56", "question": "A rectangle has width $4$ and height $7$. What is its perimeter?", "ground_truth": "22", "answer": "22", "data_source": "dapo_math_mini"} +{"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"} +{"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"} +{"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$.", "ground_truth": "661", "answer": "661", "data_source": "dapo_math_mini"} +{"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"} +{"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?", "ground_truth": "683", "answer": "683", "data_source": "dapo_math_mini"} +{"prompt_id": "dapo_mini_62", "question": "A rectangle has width $7$ and height $13$. What is its perimeter?", "ground_truth": "40", "answer": "40", "data_source": "dapo_math_mini"} +{"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"} diff --git a/scripts/benchmark_scheduler_train.py b/scripts/benchmark_scheduler_train.py index b57975f..6c907f8 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']) @@ -65,13 +73,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_tier2_closed_loop.py b/tests/test_tier2_closed_loop.py new file mode 100644 index 0000000..8183680 --- /dev/null +++ b/tests/test_tier2_closed_loop.py @@ -0,0 +1,560 @@ +"""CPU-safe unit and dry-run tests for Tier 2 (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" +) +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" + + +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_rollout_benchmark_topology_and_schedulers(tmp_path: Path): + from repro.tier2_four_gpu_closed_loop import benchmark_rollout_scheduling as bench + + instances = bench.parse_topology("1,1,1,1,4") + assert [inst["instance_id"] for inst in instances] == [ + "tp1_0", "tp1_1", "tp1_2", "tp1_3", "tp4_0" + ] + assert instances[0]["gpus"] == [0] + assert instances[4]["gpus"] == [4, 5, 6, 7] + assert [inst["port"] for inst in instances] == [19001, 19002, 19003, 19004, 19005] + + with pytest.raises(ValueError, match="exactly 2 distinct TP tiers"): + bench.parse_topology("1,2,4") + with pytest.raises(ValueError, match="requires 8 GPUs"): + bench.parse_topology("1,1,1,1,4", gpus=[0, 1, 2, 3]) + + buckets, thresholds = bench.make_buckets_and_thresholds(instances) + assert buckets == { + "short": {"tp_degrees": [1], "max_tokens": 5000}, + "long": {"tp_degrees": [4], "max_tokens": 24576}, + } + assert thresholds == {"short": 5000, "medium": 12000, "long": 24576} + + profile_path = tmp_path / "profile.json" + profile_path.write_text( + json.dumps({ + "decode_ms": {}, + "migrations": [ + { + "source_tp": 1, + "target_tp": 4, + "source_host": "127.0.0.1", + "target_host": "127.0.0.1", + "seq_len": 2048, + "recompute_ms": 128.9, + }, + { + "source_tp": 4, + "target_tp": 1, + "source_host": "127.0.0.1", + "target_host": "127.0.0.1", + "seq_len": 2048, + "recompute_ms": 430.4, + }, + ], + }), + encoding="utf-8", + ) + cal = { + "1": {"prefill_scale": 0.6722, "decode_scale": 1.4631}, + "4": {"prefill_scale": 0.7828, "decode_scale": 2.6475}, + } + for policy in bench.POLICIES_FORWARD: + eng = bench._make_bare_engine( + policy, + instances, + model_path="Qwen/Qwen3-14B", + hw_cfg_path=bench.DEFAULT_HW_CFG, + arch_cfg_path=bench.DEFAULT_ARCH_CFG, + out_dir=tmp_path, + cost_profile_path=str(profile_path), + rollout_calibration=cal, + ) + if policy == "cmlfq_cost": + assert isinstance(eng.scheduler, CMLFQCostScheduler) + assert eng.scheduler.routing_costs.decode_ms == {} + assert eng.scheduler.routing_costs.rollout_model.calibration == cal + assert len(eng.scheduler.routing_costs.migrations) == 2 + + +def test_rollout_benchmark_calibration_fit_and_interp(): + from repro.tier2_four_gpu_closed_loop import benchmark_rollout_scheduling as bench + + prefill_specs = [2048, 4096, 8192, 16384] + decode_specs = [("ctx2048_g1024", 2048, 1024), ("ctx6144_g1024", 6144, 1024)] + prefill_ms = { + "1": {2048: 430.4, 4096: 864.2, 8192: 1790.3, 16384: 3970.8}, + "4": {2048: 128.9, 4096: 251.5, 8192: 513.9, 16384: 1128.6}, + } + raw_decode_ms = { + "1": { + "ctx2048_g1024": {"b1_total_ms": 10809.0, "b8_wall_ms": 15940.0}, + "ctx6144_g1024": {"b1_total_ms": 12069.0, "b8_wall_ms": 26381.0}, + }, + "4": { + "ctx2048_g1024": {"b1_total_ms": 5950.0, "b8_wall_ms": 7485.0}, + "ctx6144_g1024": {"b1_total_ms": 6283.0, "b8_wall_ms": 11185.0}, + }, + } + + assert bench._interp_pf(prefill_ms["1"], 2048) == pytest.approx(430.4) + assert bench._interp_pf(prefill_ms["1"], 6144) == pytest.approx(0.5 * (864.2 + 1790.3)) + + fitted = bench.fit_rollout_calibration( + prefill_ms, + raw_decode_ms, + prefill_specs, + decode_specs, + bench.DEFAULT_HW_CFG, + bench.DEFAULT_ARCH_CFG, + "Qwen/Qwen3-14B", + ) + assert fitted["1"]["prefill_scale"] == pytest.approx(0.6722, abs=1e-3) + assert fitted["1"]["decode_scale"] == pytest.approx(1.4631, abs=1e-3) + assert fitted["4"]["prefill_scale"] == pytest.approx(0.7828, abs=1e-3) + assert fitted["4"]["decode_scale"] == pytest.approx(2.6475, abs=1e-3) + + +def test_rollout_benchmark_workload_and_session_isolation(): + from collections import Counter + from repro.tier2_four_gpu_closed_loop import benchmark_rollout_scheduling as bench + + class _WordTokenizer: + def __init__(self): + self._tok2id: dict[str, int] = {} + self._id2tok: list[str] = [] + + def encode(self, text: str, add_special_tokens: bool = False) -> list[int]: + del add_special_tokens + ids = [] + for tok in text.split(): + if tok not in self._tok2id: + self._tok2id[tok] = len(self._id2tok) + self._id2tok.append(tok) + ids.append(self._tok2id[tok]) + return ids + + def decode(self, ids: list[int], skip_special_tokens: bool = True) -> str: + del skip_special_tokens + return " ".join(self._id2tok[i] for i in ids) + + def apply_chat_template( + self, messages, tokenize: bool = False, add_generation_prompt: bool = True + ) -> str: + del tokenize, add_generation_prompt + return " ".join(msg["content"] for msg in messages) + + tok = _WordTokenizer() + warmup = bench.build_workload(tok, "W01", is_warmup=True) + eval_a = bench.build_workload(tok, "E01", is_warmup=False) + eval_b = bench.build_workload(tok, "E02", is_warmup=False) + + assert len(warmup) == 13 + assert Counter(it["kind"] for it in warmup) == { + "short": 6, + "quick_fix": 4, + "deep_fail": 2, + "deep_timeout": 1, + } + assert len(eval_a) == 60 + assert Counter(it["kind"] for it in eval_a) == { + "short": 48, + "quick_fix": 10, + "deep_fail": 1, + "deep_timeout": 1, + } + + expected_turns = {"short": 1, "quick_fix": 2, "deep_fail": 11, "deep_timeout": 11} + for it_a, it_b in zip(eval_a, eval_b): + assert it_a["prompt_id"] == it_b["prompt_id"] + assert it_a["input_tokens0"] == 1024 + assert it_b["input_tokens0"] == 1024 + assert it_a["prompt0"].startswith("[session=E01] ") + assert it_b["prompt0"].startswith("[session=E02] ") + assert len(it_a["turns"]) == expected_turns[it_a["kind"]] + + +def test_rollout_benchmark_dry_run_and_shell_syntax(): + bench_py = ( + REPO_ROOT / "repro/tier2_four_gpu_closed_loop/benchmark_rollout_scheduling.py" + ) + bench_sh = REPO_ROOT / "repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh" + + proc_py = subprocess.run( + [sys.executable, str(bench_py), "--dry-run"], + capture_output=True, + text=True, + check=True, + ) + parsed = json.loads(proc_py.stdout) + assert parsed["dry_run"] is True + assert list(parsed["policies"].keys()) == [ + "round_robin", + "least_connections", + "length_aware", + "la_mlfq", + "cmlfq", + "cmlfq_cost", + ] + + subprocess.run(["bash", "-n", str(bench_sh)], check=True) + proc_sh = subprocess.run( + ["bash", str(bench_sh), "--dry-run", "--python", sys.executable], + capture_output=True, + text=True, + check=True, + ) + assert "[tp1_0] CUDA_VISIBLE_DEVICES=0" in proc_sh.stdout + assert "[tp4_0] CUDA_VISIBLE_DEVICES=4,5,6,7" in proc_sh.stdout + assert "--enable-prefix-caching" in proc_sh.stdout diff --git a/workflow/dapo_math.py b/workflow/dapo_math.py index bf4bbfc..19ff7cc 100644 --- a/workflow/dapo_math.py +++ b/workflow/dapo_math.py @@ -184,19 +184,24 @@ 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) tool_event = { "tool_type": "dapo_math_validator", "output": feedback, "status": "success" if metrics["accuracy"] >= 1.0 else "failure", "payload_tokens": len(feedback_tokens), "token_position": generated_tokens, + "generated_token_position": pure_generated_tokens, "turn": turn, "reward": metrics["reward"], "accuracy": metrics["accuracy"], } 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 +231,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 { From fd98e1da405e4311f242a334ad57cc52c6a12022 Mon Sep 17 00:00:00 2001 From: "CHEN, Kaiwen" <80016929+kaiwenKevinn@users.noreply.github.com> Date: Sat, 28 Nov 2026 11:31:00 +0800 Subject: [PATCH 2/5] feat(repro): upgrade Tier 2 to 8-GPU end-to-end closed-loop RL and remove redundant rollout-only benchmark --- infra/execution/batch_dispatcher.py | 6 +- repro/tier2_four_gpu_closed_loop/README.md | 102 +- .../benchmark_rollout_scheduling.py | 1240 ----------------- .../config_8gpu_qwen3_4b.yaml | 103 ++ .../tier2_four_gpu_closed_loop/launch_4gpu.py | 252 +++- repro/tier2_four_gpu_closed_loop/run_8gpu.sh | 4 + .../run_rollout_ab.sh | 251 ---- .../sample_data/dapo_cost_profile.json | 19 + .../sample_data/dapo_math_mini.jsonl | 128 +- scripts/benchmark_scheduler_train.py | 11 +- tests/test_tier2_closed_loop.py | 367 ++--- workflow/dapo_math.py | 61 +- 12 files changed, 709 insertions(+), 1835 deletions(-) delete mode 100644 repro/tier2_four_gpu_closed_loop/benchmark_rollout_scheduling.py create mode 100644 repro/tier2_four_gpu_closed_loop/config_8gpu_qwen3_4b.yaml create mode 100755 repro/tier2_four_gpu_closed_loop/run_8gpu.sh delete mode 100755 repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh create mode 100644 repro/tier2_four_gpu_closed_loop/sample_data/dapo_cost_profile.json 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 index af443a8..53e6a0a 100644 --- a/repro/tier2_four_gpu_closed_loop/README.md +++ b/repro/tier2_four_gpu_closed_loop/README.md @@ -1,74 +1,63 @@ -# Tier 2 — Small-Scale Heterogeneous Benchmarks, Closed-Loop RL & Google Colab Quickstart +# Tier 2 — 8-GPU & 4-GPU Heterogeneous Closed-Loop RL & Google Colab Quickstart -Tier 2 provides **Slurm-free** GPU entry points covering: +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. **Mode A — Controlled Multi-Turn Heterogeneous Rollout Scheduling Benchmark (`4×TP=1 + 1×TP=4`)**: End-to-end 6-policy comparison (`round_robin`, `least_connections`, `length_aware`, `la_mlfq`, `cmlfq`, `cmlfq_cost`) against live `vLLM` servers with CUDA graphs, Automatic Prefix Caching (`--enable-prefix-caching`), and online H20-3e cold calibration. -2. **Mode B — 4-GPU Heterogeneous Closed Loop (`1 Train + 3 Rollout`)**: Slurm-free `AsyncRLTrainer` (`FSDPTrainEngine` + `DAPOMathWorkflow` + supervised `vllm_hot_reload_api_server.py` with confirmed in-place weight reloads) across `TP=1` + `TP=2`. -3. **Mode C — 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`). +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) comparing `round_robin`, `least_connections`, `cmlfq`, and `cmlfq_cost`. +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 comparison (without FSDP training updates or weight sync)? See Tier 1 Pathway 2 (`Real-GPU Live vLLM Judge`) in [../tier1_zero_gpu_replay/README.md](../tier1_zero_gpu_replay/README.md). --- -## Mode A: Controlled Multi-Turn Heterogeneous Rollout Scheduling Benchmark +## Mode 1: 8-GPU Heterogeneous Closed Loop (`1 Train + TP=1, 2, 4`) -Reproduce the controlled heterogeneous rollout comparison cleanly on an 8-GPU node (`4×TP=1 + 1×TP=4` by default, configurable via `--topology`): +Reproduce the 8-GPU end-to-end closed-loop RL comparison without Slurm: ```bash -# Dry-run: validate topology, unified thresholds, CostModel wiring, and launch commands without GPUs -bash repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh --dry-run +# Dry-run: validate topology, CostModel profile, seeded trees, and commands without GPUs +python3 repro/tier2_four_gpu_closed_loop/launch_4gpu.py \ + --mode 8gpu \ + --policy all \ + --gpus 0,1,2,3,4,5,6,7 \ + --dry-run -# Full real-GPU 6-policy, 2-round counterbalanced benchmark on 8x H20-3e (Qwen3-14B) -bash repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh \ - --model Qwen/Qwen3-14B \ +# Full 4-policy real-GPU end-to-end closed-loop RL sweep on 8x H20-3e +bash repro/tier2_four_gpu_closed_loop/run_8gpu.sh \ + --policy all \ --gpus 0,1,2,3,4,5,6,7 \ - --topology 1,1,1,1,4 \ - --output-dir ./logs/tier2_rollout_scheduling + --model Qwen/Qwen3-4B \ + --output-dir ./logs/tier2_8gpu_ab ``` -### Experimental Setup - -- **Hardware & Topology**: Single node `8 × NVIDIA H20-3e (141 GiB)`, `Qwen/Qwen3-14B` (`bfloat16`), deployed as **`4 × TP=1` (GPUs 0–3) + `1 × TP=4` (GPUs 4–7)**. -- **vLLM Serving Configuration**: `vLLM 0.9.2` V1 engine with CUDA graphs and `--enable-prefix-caching`, `max_model_len=24576`, `gpu_memory_utilization=0.85`, `max_num_seqs=32`, and per-instance cache isolation (`VLLM_CACHE_ROOT`, `TORCHINDUCTOR_CACHE_DIR`, `TRITON_CACHE_DIR`). -- **Fair Isolation & Unified Thresholds**: - - Each `(round, policy, phase)` prepends a fixed-width session tag (`W01..W12` / `E01..E12`) at token 0 and fits `prompt0` to `1024` tokens, eliminating cross-policy/cross-round KV cache leakage while preserving real intra-trajectory multi-turn vLLM prefix caching. - - All bucketed/length-aware schedulers share Libra's default boundary `short = 5000` (`BUCKETS_2`: `short -> TP=1 <= 5000`, `long -> TP=4 <= 24576`; `length_thresholds = {short: 5000, medium: 12000, long: 24576}`). -- **Phase 1 Cold Calibration & Cost Model**: Unique token-0 trial prefixes measure cold prefill (`2048, 4096, 8192, 16384`) and decode (`b=1` / `b=8` at `ctx=2048, 6144`, `gen=1024`) on `TP=1` and `TP=4`, autofitting `CostModel` scales (`prefill_scale`, `decode_scale`) alongside measured `recompute_ms` migration costs (`decode_ms={}` uses continuous-batching makespan estimation). -- **Heavy-Tailed Multi-Turn Workload**: Warmup `13` trajectories (`6 short / 4 quick_fix / 2 deep_fail / 1 deep_timeout`) and Eval `60` trajectories (`48 short / 10 quick_fix / 1 deep_fail / 1 deep_timeout`), 100% randomly shuffled, submitted at full-batch concurrency (`60`) with `temperature=0.0` and natural EOS over 2 counterbalanced rounds (Forward + Reverse): - - `short`: 1 turn (`max_new_tokens=256`). - - `quick_fix`: Turn 0 (`96`) -> `test_runner:medium:failure` (`1000`-tok log) -> Turn 1 (`192`). - - `deep_fail` / `deep_timeout`: Turn 0 (`96`) -> 10 turns of `1000`-tok `test_runner` logs + `640` generated tokens/turn (peak context ~`17.5K`). - -### Verified Real-GPU Results (`8 × NVIDIA H20-3e`, `Qwen3-14B`) - -**Phase 1 Cold Micro-Calibration**: +### Experimental Setup (`8 × NVIDIA H20-3e`, `Qwen/Qwen3-4B`) -| Metric | `TP=1` | `TP=4` | `TP=4` Speedup | -| :--- | ---: | ---: | ---: | -| Prefill `ctx=2048` median | `430.4 ms` | `128.9 ms` | `3.34x` | -| Prefill `ctx=4096` median | `864.2 ms` | `251.5 ms` | `3.44x` | -| Prefill `ctx=8192` median | `1790.3 ms` | `513.9 ms` | `3.48x` | -| Prefill `ctx=16384` median | `3970.8 ms` | `1128.6 ms` | `3.52x` | -| Decode `ctx=2048, gen=1024` (`b=1` / `b=8`) | `10.81s` / `15.94s` | `5.95s` / `7.49s` | `1.82x` / `2.13x` | -| Decode `ctx=6144, gen=1024` (`b=1` / `b=8`) | `12.07s` / `26.38s` | `6.28s` / `11.19s` | `1.92x` / `2.36x` | +- **Hardware & Topology**: Single node `8 × NVIDIA H20-3e (141 GiB)`: + - **Training**: `1 × FSDPTrainEngine` on GPU `0` (`bfloat16`, `batch_size=16`, `micro_batch_size=1`, `recompute_logprobs=false`, `FSDP_GRADIENT_CHECKPOINTING=0`, `n_samples=2`, `ppo_epochs=1`, `sync_interval=4`). + - **Heterogeneous Rollout (`7` GPUs)**: `tp1` (`TP=1`, GPU `1`, `max_num_seqs=1`, port `18920`), `tp2` (`TP=2`, GPUs `2,3`, `max_num_seqs=2`, port `18921`), and `tp4` (`TP=4`, GPUs `4,5,6,7`, `max_num_seqs=16`, port `18922`). +- **vLLM Serving & Weight Reload**: `vLLM 0.9.2` V1 engine with CUDA graphs enabled, `--enable-prefix-caching`, `max_model_len=6144`, `gpu_memory_utilization=0.75`, per-instance isolated compile/KV caches, and verified parallel in-place disk weight reload (`rollout_weight_reload_method=inplace`, confirmed via `ack_tp1_4.json`, `ack_tp2_4.json`, `ack_tp4_4.json`). +- **Scheduling Policies & Calibration**: + - Baselines: `load_balance` (`round_robin`, `least_connections`). + - Causal schedulers: `cmlfq` and `cmlfq_cost` with unified three-tier buckets (`short -> TP=1 <= 400`, `medium -> TP=2 <= 1200`, `long -> TP=4 <= 6144`), pre-seeded `CausalPrefixTree` (`tree.json`), and empirical tier latency table (`sample_data/dapo_cost_profile.json`). +- **Multi-Turn Closed-Loop Workload (`sample_data/dapo_math_mini.jsonl`)**: `4` RL steps $\times$ `8` prompts/step $\times$ `2` rollouts (`64` trajectories total, `64` FSDP optimizer updates per policy), mixing `short_recover` (`3` turns `[32, 160, 160]`, `small:timeout`), `medium` (`2` turns `[32, 1120]`, `medium:failure`), `long_unambig` (`rollout 0` `[32, 1792, 1792]` + `rollout 1` `[32]`, `large:failure`), and `long_cascading` (Step 0 bimodal causal signal on `small:failure`, where `cmlfq` defers migration at Turn 1 due to `mean_p90_disagree` while `cmlfq_cost` eagerly promotes at Turn 1 via residual distribution + cost model). -Auto-fitted analytical `CostModel` scales: `TP=1: {prefill_scale: 0.6722, decode_scale: 1.4631}`, `TP=4: {prefill_scale: 0.7828, decode_scale: 2.6475}`. +### Verified Real-GPU Closed-Loop Results (`8 × NVIDIA H20-3e`, `Qwen/Qwen3-4B`) -**Phase 2 Six-Policy Counterbalanced Results (Mean Across Forward Round 1 & Reverse Round 2)**: +All 4 policies completed 4 RL steps (`64` samples, `64` FSDP optimizer updates, `152` generation calls, `3/3` confirmed in-place weight reload acks): -| Policy | Mean Makespan (R1 / R2) | Throughput (tok/s) | vs `round_robin` (tok/s) | Makespan Reduction | `deep_fail` / `deep_timeout` | Migrations | `TP=1 / TP=4` Calls | -| :--- | --- | ---: | ---: | ---: | --- | ---: | ---: | -| `la_mlfq` | `81.14s` (`81.09` / `81.18`) | `347.1` | `-4.0%` (`0.96x`) | `-4.2%` | `81.05s` / `81.13s` | `0` | `90 / 0` | -| `round_robin` | `77.88s` (`77.43` / `78.33`) | `361.6` | `+0.0%` (`1.00x`) | `+0.0%` | `77.78s` / `77.88s` | `0` | `72 / 18` | -| `least_connections` | `73.79s` (`73.48` / `74.09`) | `376.3` | `+4.1%` (`1.06x`) | `+5.3%` | `73.30s` / `70.02s` | `0` | `63 / 27` | -| `cmlfq` | `58.42s` (`58.66` / `58.18`) | `472.7` | `+30.7%` (`1.33x`) | `+25.0%` | `58.42s` / `53.83s` | `14` | `66 / 24` | -| `length_aware` | `52.61s` (`53.19` / `52.03`) | `532.6` | `+47.3%` (`1.48x`) | `+32.4%` | `52.60s` / `51.68s` | `0` | `74 / 16` | -| **`cmlfq_cost`** | **`45.08s`** (`45.09` / `45.08`) | **`624.6`** | **`+72.7%` (`1.73x`)** | **`+42.1%`** | **`45.08s` / `45.08s`** | **`15`** | **`60 / 30`** | +| Policy | End-to-End `loop_seconds` | `rollout_wait_seconds` | `train_seconds` | `sync_seconds` | `samples/s` | vs `round_robin` (`samples/s`) | `gen_tokens/s` | vs `round_robin` (`tok/s`) | Route Calls (`TP=1 / 2 / 4`) | +| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | :---: | +| `round_robin` | `168.60s` | `122.45s` | `29.94s` | `16.20s` | `0.3796` | `+0.0%` (`1.00x`) | `413.23` | `+0.0%` (`1.00x`) | `51 / 51 / 50` | +| `least_connections` | `121.69s` | `76.02s` | `29.40s` | `16.26s` | `0.5259` | `+38.5%` (`1.39x`) | `574.93` | `+39.1%` (`1.39x`) | `45 / 52 / 55` | +| `cmlfq` | `119.99s` | `73.57s` | `30.24s` | `16.15s` | `0.5334` | `+40.5%` (`1.41x`) | `580.13` | `+40.4%` (`1.40x`) | `113 / 16 / 23` | +| **`cmlfq_cost`** | **`115.38s`** | **`69.98s`** | **`29.35s`** | **`16.02s`** | **`0.5547`** | **`+46.1%` (`1.46x`)** | **`607.22`** | **`+46.9%` (`1.47x`)** | **`100 / 17 / 35`** | -- **`cmlfq_cost` net speedups**: **`+72.7%` tok/s vs `round_robin`** (`1.73x`), **`+66.0%` vs `least_connections`**, **`+32.1%` vs `cmlfq`**, and **`+17.3%` vs `length_aware`**. -- **Routing verification**: Across both rounds, `cmlfq_cost` generated all `28,160` expected tokens (`short=256`, `quick_fix=288`, `deep_fail=6496`, `deep_timeout=6496`), placed short requests cleanly across `4×TP=1` (`13,440` tokens), migrated deep bimodal/timeout tails proactively at Turn 1 to `TP=4` (`reasons={resume: 60, distribution_cost: 30}`, `paths={stay: 78, recompute: 12}`), and retained intra-episode vLLM APC residency (`tp_tokens={1: 13440, 4: 14720}`). +- **`cmlfq_cost` net end-to-end closed-loop RL speedups**: **`+46.1%` (`1.46x`) `samples/s`** and **`+46.9%` (`1.47x`) `generated_tokens/s`** vs `round_robin` (`1.75x` faster rollout collection), **`+5.5%` `samples/s` / `+5.6%` `tok/s`** vs `least_connections`, and **`+4.0%` `samples/s` / `+4.7%` `tok/s`** vs `cmlfq`. +- **Per-step stability & tier placement**: `cmlfq_cost` held steady rollout times across all 4 steps (`[16.97s, 17.73s, 17.62s, 17.66s]`), promoting all long trajectories at Turn 1 to `TP=4` (`35` calls, including Step 0 `long_cascading`), isolating `medium` on `TP=2` (`17` calls), and keeping short turns on `TP=1` (`100` calls), whereas `round_robin` stalled `tp1` with long/medium head-of-line queueing (`36.52s -> 24.93s` per step). --- -## Mode B: 4-GPU Heterogeneous Closed Loop (No Slurm Required) +## 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`): @@ -78,7 +67,7 @@ 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, cmlfq, and cmlfq_cost +# 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 \ @@ -100,7 +89,7 @@ python3 repro/tier2_four_gpu_closed_loop/launch_4gpu.py --dry-run --- -## Mode C: Google Colab 1-GPU Co-Located Startup +## Mode 3: Google Colab 1-GPU Co-Located Startup Open [colab_quickstart.ipynb](colab_quickstart.ipynb) directly in Google Colab: @@ -130,10 +119,11 @@ python3 repro/tier2_four_gpu_closed_loop/launch_4gpu.py \ ## Bundled Sample Data, Scripts & Templates -- [benchmark_rollout_scheduling.py](benchmark_rollout_scheduling.py) & [run_rollout_ab.sh](run_rollout_ab.sh): Controlled 6-policy multi-turn rollout benchmark with Phase 1 cold calibration, session-isolated vLLM APC, and unified `short=5000` thresholds. -- [launch_4gpu.py](launch_4gpu.py) & [run_4gpu.sh](run_4gpu.sh): Slurm-free 4-GPU closed-loop RL and 1-GPU Colab launcher. +- [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. - [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 (works offline out of the box; pass `--dataset /path/to/dapo-math-17k.parquet` for full DAPO-Math-17K). +- [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_rollout_scheduling.py b/repro/tier2_four_gpu_closed_loop/benchmark_rollout_scheduling.py deleted file mode 100644 index 637c877..0000000 --- a/repro/tier2_four_gpu_closed_loop/benchmark_rollout_scheduling.py +++ /dev/null @@ -1,1240 +0,0 @@ -#!/usr/bin/env python3 -"""Controlled multi-turn heterogeneous rollout scheduling benchmark (Tier 2). - -Runs Phase 1 cold micro-calibration across distinct tensor-parallel tiers to fit -analytical `CostModel` scaling factors and migration recompute costs, followed by -Phase 2 counterbalanced rounds comparing 6 Libra scheduling policies with live -vLLM Automatic Prefix Caching (`--enable-prefix-caching`) and session-isolated -prompts. -""" - -from __future__ import annotations - -import argparse -import asyncio -import importlib.util -import json -import random -import statistics -import sys -import tempfile -import time -from collections import Counter -from pathlib import Path -from typing import Any - -import yaml - - -def _ensure_rl_framework_importable() -> Path: - """Resolve the repository root and make `RL_Framework.*` importable.""" - repo_root = Path(__file__).resolve().parents[2] - if str(repo_root) not in sys.path: - sys.path.insert(0, str(repo_root)) - if repo_root.name == "RL_Framework": - parent = str(repo_root.parent) - if parent not in sys.path: - sys.path.insert(0, parent) - 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.engine.heterogeneous_engine import HeterogeneousRolloutEngine # noqa: E402 -from RL_Framework.infra.cost_model.model import CostModel, RequestInfo # noqa: E402 -from RL_Framework.infra.scheduling.cmlfq_cost import CMLFQRoutingCosts # noqa: E402 -from RL_Framework.infra.scheduling.cmlfq_cost_scheduler import CMLFQCostScheduler # noqa: E402 - -POLICIES_FORWARD: tuple[str, ...] = ( - "round_robin", - "least_connections", - "length_aware", - "la_mlfq", - "cmlfq", - "cmlfq_cost", -) - -DEFAULT_HW_CFG = REPO_ROOT / "configs/hardware_config/h20_3e_141g.yaml" -DEFAULT_ARCH_CFG = REPO_ROOT / "configs/model_arch_config/qwen3-14b.yaml" - - -def parse_topology( - topology_spec: str, - gpus: list[int] | None = None, - host: str = "127.0.0.1", - base_port: int = 19001, -) -> list[dict[str, Any]]: - """Parse a comma-separated TP layout into heterogeneous instance configs.""" - parts = [p.strip() for p in topology_spec.split(",") if p.strip()] - if not parts: - raise ValueError("topology specification must not be empty") - tp_degrees = [int(p) for p in parts] - if any(tp <= 0 for tp in tp_degrees): - raise ValueError(f"TP degrees must be positive: {tp_degrees}") - if len(tp_degrees) < 2 or len(set(tp_degrees)) != 2: - raise ValueError( - "cmlfq_cost requires >= 2 instances spanning exactly 2 distinct TP tiers, " - f"got {tp_degrees}" - ) - - total_gpus = sum(tp_degrees) - gpu_list = list(range(total_gpus)) if gpus is None else list(gpus) - if len(gpu_list) != total_gpus: - raise ValueError( - f"topology {tp_degrees} requires {total_gpus} GPUs, got {len(gpu_list)} ({gpu_list})" - ) - - instances: list[dict[str, Any]] = [] - tp_counts: Counter[int] = Counter() - cursor = 0 - for idx, tp in enumerate(tp_degrees): - assigned = gpu_list[cursor : cursor + tp] - cursor += tp - suffix = tp_counts[tp] - tp_counts[tp] += 1 - instances.append({ - "instance_id": f"tp{tp}_{suffix}", - "tp": tp, - "gpus": assigned, - "host": host, - "port": base_port + idx, - }) - return instances - - -def make_buckets_and_thresholds( - instances: list[dict[str, Any]], - *, - max_model_len: int = 24576, - short_threshold: int = 5000, - medium_threshold: int = 12000, -) -> tuple[dict[str, dict[str, Any]], dict[str, int]]: - """Build unified Libra two-bucket routing definitions and length thresholds.""" - tps = sorted({int(inst["tp"]) for inst in instances}) - if len(tps) != 2: - raise ValueError(f"Expected 2 distinct TP tiers, got {tps}") - min_tp, max_tp = tps[0], tps[1] - buckets = { - "short": {"tp_degrees": [min_tp], "max_tokens": short_threshold}, - "long": {"tp_degrees": [max_tp], "max_tokens": max_model_len}, - } - length_thresholds = { - "short": short_threshold, - "medium": medium_threshold, - "long": max_model_len, - } - return buckets, length_thresholds - - -def _make_padded_text(tokenizer, target_tokens: int, seed_text: str, filler_unit: str) -> str: - """Build exact-token-budget text using the configured tokenizer.""" - ids = tokenizer.encode(seed_text, add_special_tokens=False) - filler_ids = tokenizer.encode(filler_unit, add_special_tokens=False) - while len(ids) < target_tokens: - ids.extend(filler_ids) - ids = ids[:target_tokens] - return tokenizer.decode(ids, skip_special_tokens=True) - - -def _chat_prompt(tokenizer, system_msg: str, user_msg: str) -> tuple[str, int]: - messages = [ - {"role": "system", "content": system_msg}, - {"role": "user", "content": user_msg}, - ] - text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) - return text, len(tokenizer.encode(text, add_special_tokens=False)) - - -def _fit_chat_prompt_exact( - tokenizer, - system_msg: str, - user_head: str, - filler_unit: str, - target_tokens: int = 1024, -) -> tuple[str, int]: - """Pad user filler so apply_chat_template hits ~target_tokens across sessions.""" - _, base_len = _chat_prompt(tokenizer, system_msg, user_head) - filler_ids = tokenizer.encode(filler_unit, add_special_tokens=False) - filler_n = max(16, target_tokens - base_len) - pad_text = "" - for _ in range(3): - rep = (filler_n // max(1, len(filler_ids))) + 2 - pad_text = tokenizer.decode((filler_ids * rep)[: max(0, filler_n)], skip_special_tokens=True) - full_text, full_len = _chat_prompt(tokenizer, system_msg, user_head + pad_text) - diff = target_tokens - full_len - if diff == 0: - return full_text, full_len - filler_n = max(0, filler_n + diff) - return _chat_prompt(tokenizer, system_msg, user_head + pad_text) - - -def _interp_pf(pf_map: dict[int, float], ctx: int) -> float: - """Lookup or piecewise-linearly interpolate measured prefill latency (ms).""" - if ctx in pf_map: - return pf_map[ctx] - keys = sorted(pf_map) - if ctx <= keys[0]: - return pf_map[keys[0]] * (ctx / max(1, keys[0])) - if ctx >= keys[-1]: - return pf_map[keys[-1]] * (ctx / max(1, keys[-1])) - for lo, hi in zip(keys[:-1], keys[1:]): - if lo <= ctx <= hi: - alpha = (ctx - lo) / (hi - lo) - return pf_map[lo] * (1.0 - alpha) + pf_map[hi] * alpha - return pf_map[keys[-1]] - - -def fit_rollout_calibration( - prefill_ms: dict[str, dict[int, float]], - raw_decode_ms: dict[str, dict[str, dict[str, float]]], - prefill_specs: list[int], - decode_specs: list[tuple[str, int, int]], - hw_cfg_path: Path, - arch_cfg_path: Path, - model_path: str, -) -> dict[str, dict[str, float]]: - """Fit analytical CostModel prefill/decode scale factors against live cold measurements.""" - uncalib_raw = AsyncRLConfig(model_path=model_path, tokenizer_path=model_path).to_dict() - uncalib_raw["hardware"] = yaml.safe_load(hw_cfg_path.read_text(encoding="utf-8")) - uncalib_raw["model_arch"] = yaml.safe_load(arch_cfg_path.read_text(encoding="utf-8")) - uncalib_cfg = AsyncRLConfig.from_dict(uncalib_raw) - rm_uncalib = CostModel( - hardware=uncalib_cfg.hardware, - model_arch=uncalib_cfg.model_arch, - profiling=uncalib_cfg.profiling, - ).rollout_model - chunk = max(1, int(rm_uncalib.L_chunk)) - - rollout_calibration: dict[str, dict[str, float]] = {} - for tp_key in sorted(prefill_ms, key=lambda k: int(k)): - tp = int(tp_key) - pf_ratios = [] - for ctx in prefill_specs: - uncalib_pf_ms = (ctx / chunk) * rm_uncalib.compute_prefill_step_time(1, chunk, tp) * 1000.0 - pf_ratios.append(prefill_ms[tp_key][ctx] / max(1e-3, uncalib_pf_ms)) - pf_scale = max(0.2, min(5.0, statistics.median(pf_ratios))) - - dec_ratios = [] - for label, ctx, gen in decode_specs: - meas_dec_ms = max( - 1.0, - raw_decode_ms[tp_key][label]["b1_total_ms"] - _interp_pf(prefill_ms[tp_key], ctx), - ) - uncalib_pf_s = (ctx / chunk) * rm_uncalib.compute_prefill_step_time(1, chunk, tp) - uncalib_dec_ms = max( - 1.0, - (rm_uncalib.compute_instance_makespan([RequestInfo(ctx, gen)], tp) - uncalib_pf_s) - * 1000.0, - ) - dec_ratios.append(meas_dec_ms / uncalib_dec_ms) - dec_scale = max(0.2, min(5.0, statistics.median(dec_ratios))) - rollout_calibration[tp_key] = { - "prefill_scale": round(pf_scale, 4), - "decode_scale": round(dec_scale, 4), - } - return rollout_calibration - - -def _make_bare_engine( - policy: str, - instances: list[dict[str, Any]], - *, - model_path: str, - hw_cfg_path: Path, - arch_cfg_path: Path, - out_dir: Path, - max_model_len: int = 24576, - gpu_memory_utilization: float = 0.85, - short_threshold: int = 5000, - medium_threshold: int = 12000, - cost_profile_path: str = "", - rollout_calibration: dict[str, dict[str, float]] | None = None, -) -> HeterogeneousRolloutEngine: - """Instantiate a client-only HeterogeneousRolloutEngine pointing at running vLLM servers.""" - buckets, length_thresholds = make_buckets_and_thresholds( - instances, - max_model_len=max_model_len, - short_threshold=short_threshold, - medium_threshold=medium_threshold, - ) - tps = sorted({int(inst["tp"]) for inst in instances}) - min_tp, max_tp = tps[0], tps[1] - - raw = AsyncRLConfig( - model_path=model_path, - tokenizer_path=model_path, - sync_path=str(out_dir / "_unused_sync"), - log_dir=str(out_dir / "_unused_logs"), - ).to_dict() - raw["enable_history_collection"] = False - raw["hardware"] = yaml.safe_load(hw_cfg_path.read_text(encoding="utf-8")) - raw["model_arch"] = yaml.safe_load(arch_cfg_path.read_text(encoding="utf-8")) - if rollout_calibration and policy == "cmlfq_cost": - raw.setdefault("profiling", {})["calibration"] = {"rollout": rollout_calibration} - - hr = raw["heterogeneous_rollout"] - hr["enabled"] = True - hr["total_gpus"] = sum(int(inst["tp"]) for inst in instances) - hr["max_model_len"] = max_model_len - hr["gpu_memory_utilization"] = gpu_memory_utilization - hr["instances"] = [dict(inst) for inst in instances] - - sc = hr["scheduling"] - sc["max_queue_length"] = 64 - sc["enable_fallback"] = True - if policy in ("round_robin", "least_connections"): - sc["scheduler_type"] = "load_balance" - sc["load_balance_strategy"] = policy - elif policy == "length_aware": - sc["scheduler_type"] = "length_aware" - sc["load_balance_strategy"] = "least_connections" - sc["routing_rules"] = {"short": [min_tp], "medium": [max_tp], "long": [max_tp]} - sc["length_thresholds"] = length_thresholds - elif policy == "la_mlfq": - sc["scheduler_type"] = "la_mlfq" - sc["load_balance_strategy"] = "least_connections" - sc["la_mlfq_buckets"] = buckets - sc["length_thresholds"] = length_thresholds - sc["la_mlfq_history_ttl"] = 10 - elif policy == "cmlfq": - sc["scheduler_type"] = "cmlfq" - sc["cmlfq_buckets"] = buckets - sc["cmlfq_tree_path"] = "" - sc["cmlfq_rebuild_interval"] = 32 - sc["cmlfq_kv_backend"] = "recompute" - elif policy == "cmlfq_cost": - sc["scheduler_type"] = "cmlfq_cost" - sc["cmlfq_buckets"] = buckets - sc["cmlfq_tree_path"] = "" - sc["cmlfq_rebuild_interval"] = 32 - sc["cmlfq_kv_backend"] = "recompute" - sc["cmlfq_cost_profile_path"] = cost_profile_path - else: - raise ValueError(f"Unknown policy: {policy}") - - full_cfg = AsyncRLConfig.from_dict(raw) - engine = HeterogeneousRolloutEngine.from_config(full_cfg) - if isinstance(engine.scheduler, CMLFQCostScheduler): - cm = CostModel( - hardware=full_cfg.hardware, - model_arch=full_cfg.model_arch, - profiling=full_cfg.profiling, - ) - engine.scheduler.routing_costs = CMLFQRoutingCosts( - profile_path=cost_profile_path, - rollout_model=cm.rollout_model, - ) - return engine - - -async def run_phase1_calibration( - tokenizer, - instances: list[dict[str, Any]], - *, - model_path: str, - hw_cfg_path: Path, - arch_cfg_path: Path, - out_dir: Path, - max_model_len: int, - gpu_memory_utilization: float, - short_threshold: int, - medium_threshold: int, -) -> dict[str, Any]: - """Run live cold micro-calibration on the two distinct TP tiers.""" - print("=== PHASE 1: Live Cold Micro-Calibration (TP_short vs TP_long) ===", flush=True) - engine = _make_bare_engine( - "round_robin", - instances, - model_path=model_path, - hw_cfg_path=hw_cfg_path, - arch_cfg_path=arch_cfg_path, - out_dir=out_dir, - max_model_len=max_model_len, - gpu_memory_utilization=gpu_memory_utilization, - short_threshold=short_threshold, - medium_threshold=medium_threshold, - ) - try: - warm_prompt = _make_padded_text( - tokenizer, - 128, - "[calib_warmup_nonce_00] Solve 2x + 3 = 11 briefly. ", - "Verify each arithmetic step cleanly. ", - ) - await asyncio.gather(*( - sub.generate( - prompt=warm_prompt, - max_new_tokens=8, - temperature=0.0, - top_p=1.0, - n=1, - ignore_eos=True, - ) - for sub in engine.engines - )) - - tps = sorted({int(inst["tp"]) for inst in instances}) - min_tp, max_tp = tps[0], tps[1] - probe_indices = [ - next(i for i, inst in enumerate(instances) if int(inst["tp"]) == min_tp), - next(i for i, inst in enumerate(instances) if int(inst["tp"]) == max_tp), - ] - prefill_specs = [c for c in (2048, 4096, 8192, 16384) if c < max_model_len] - if not prefill_specs: - prefill_specs = [max(256, max_model_len // 2)] - - prefill_ms: dict[str, dict[int, float]] = {} - for idx in probe_indices: - tp_key = str(engine.instance_configs[idx]["tp_degree"]) - sub = engine.engines[idx] - prefill_ms[tp_key] = {} - for ctx in prefill_specs: - samples = [] - for trial in range(3): - # Unique token-0 prefix guarantees cold prefill even with vLLM APC enabled. - prompt = _make_padded_text( - tokenizer, - ctx, - f"[calib_pf_tp{tp_key}_L{ctx}_t{trial}] Analyze distributed KV state across {ctx} tokens:\n", - f"Block trace tp{tp_key}_L{ctx}_t{trial}: entry status ok, prefix alignment verified, worker nominal.\n", - ) - t0 = time.perf_counter() - await sub.generate( - prompt=prompt, - max_new_tokens=1, - temperature=0.0, - top_p=1.0, - n=1, - ignore_eos=True, - ) - samples.append((time.perf_counter() - t0) * 1000.0) - prefill_ms[tp_key][ctx] = statistics.median(samples) - print( - f" [Calib Prefill] tp={tp_key} ctx={ctx:5d} median={prefill_ms[tp_key][ctx]:7.1f}ms", - flush=True, - ) - - decode_specs = [ - (lbl, ctx, gen) - for lbl, ctx, gen in (("ctx2048_g1024", 2048, 1024), ("ctx6144_g1024", 6144, 1024)) - if ctx + gen <= max_model_len - ] - if not decode_specs: - ctx_fallback = max(256, max_model_len // 2) - gen_fallback = max(64, min(512, max_model_len - ctx_fallback - 16)) - decode_specs = [(f"ctx{ctx_fallback}_g{gen_fallback}", ctx_fallback, gen_fallback)] - - raw_decode_ms: dict[str, dict[str, dict[str, float]]] = {} - for idx in probe_indices: - tp_key = str(engine.instance_configs[idx]["tp_degree"]) - sub = engine.engines[idx] - raw_decode_ms[tp_key] = {} - for label, ctx, gen in decode_specs: - prompt_b1 = _make_padded_text( - tokenizer, - ctx, - f"[calib_dec_tp{tp_key}_{label}_b1] Derive a complete formal proof for variant {label}:\n", - f"Constraint {label}_b1: invariant A_i <= B_i + 1 preserved over state transitions.\n", - ) - t0 = time.perf_counter() - await sub.generate( - prompt=prompt_b1, - max_new_tokens=gen, - temperature=0.0, - top_p=1.0, - n=1, - ignore_eos=True, - ) - b1_total_ms = (time.perf_counter() - t0) * 1000.0 - - b8_prompts = [ - _make_padded_text( - tokenizer, - ctx, - f"[calib_dec_tp{tp_key}_{label}_b8_s{k}] Derive proof variant {label} sample {k}:\n", - f"Constraint {label}_b8_s{k}: invariant A_i <= B_i + 1 preserved over state transitions.\n", - ) - for k in range(8) - ] - t0 = time.perf_counter() - await asyncio.gather(*( - sub.generate( - prompt=p_k, - max_new_tokens=gen, - temperature=0.0, - top_p=1.0, - n=1, - ignore_eos=True, - ) - for p_k in b8_prompts - )) - b8_wall_ms = (time.perf_counter() - t0) * 1000.0 - raw_decode_ms[tp_key][label] = { - "b1_total_ms": round(b1_total_ms, 2), - "b8_wall_ms": round(b8_wall_ms, 2), - } - print( - f" [Calib Decode] tp={tp_key} {label:13s}: b1={b1_total_ms:.0f}ms, b8_wall={b8_wall_ms:.0f}ms", - flush=True, - ) - - rollout_calibration = fit_rollout_calibration( - prefill_ms, - raw_decode_ms, - prefill_specs, - decode_specs, - hw_cfg_path, - arch_cfg_path, - model_path, - ) - print(f" [Calib Fit] rollout_calibration={rollout_calibration}", flush=True) - - migrations = [] - host_min = instances[probe_indices[0]]["host"] - host_max = instances[probe_indices[1]]["host"] - for src_tp, dst_tp, src_host, dst_host in ( - (min_tp, max_tp, host_min, host_max), - (max_tp, min_tp, host_max, host_min), - ): - for ctx in prefill_specs: - migrations.append({ - "source_tp": src_tp, - "target_tp": dst_tp, - "source_host": src_host, - "target_host": dst_host, - "seq_len": ctx, - "recompute_ms": round(prefill_ms[str(dst_tp)][ctx], 2), - }) - - profile = { - "decode_ms": {}, - "migrations": migrations, - "rollout_calibration": rollout_calibration, - "raw_measurements": { - "prefill_ms": prefill_ms, - "decode": raw_decode_ms, - }, - } - profile_path = out_dir / "h20_rollout_profile.json" - profile_path.write_text(json.dumps(profile, indent=2) + "\n", encoding="utf-8") - return { - "profile_path": str(profile_path), - "profile": profile, - "rollout_calibration": rollout_calibration, - } - finally: - await engine.close() - - -def build_workload( - tokenizer, - session_tag: str, - *, - is_warmup: bool, - max_model_len: int = 24576, - seed: int = 42, -) -> list[dict[str, Any]]: - """Build session-isolated SWE multi-turn workload (zero cross-run APC leakage).""" - sys_short = ( - f"[session={session_tag}] You are a meticulous repository QA & math verification assistant. " - "Provide a clear step-by-step derivation, sanity check boundary values, and end with \\boxed{} (~220 words)." - ) - sys_agent = ( - f"[session={session_tag}] You are an analytical software verification & distributed systems engineer. " - "Always write thorough step-by-step reasoning, state invariants, and complete verification details." - ) - - def make_item(kind: str, tag: str, idx: int) -> dict[str, Any]: - pid = f"{kind}_{tag}_{idx:03d}" - filler = ( - f"def verify_{pid}(shard_id, seq_len, active_reqs): " - f"assert shard_id >= 0 and seq_len <= {max_model_len}; return active_reqs * 2 + shard_id\n" - ) - if kind == "short": - a = 5 + (idx % 11) - b = 9 + (idx % 17) - x = 3 + (idx % 13) - rhs = a * x + b - head = ( - f"[{pid}] Repository Verification Task:\n" - f"Solve for shard parameter $x$ where ${a}x + {b} = {rhs}$, verify uniqueness " - f"and overflow safety against `max_seq={max_model_len}`, explain each arithmetic check clearly " - "in ~200 words, and finish with \\boxed{}.\nSnapshot context:\n" - ) - p0, n0 = _fit_chat_prompt_exact(tokenizer, sys_short, head, filler, target_tokens=1024) - return { - "prompt_id": pid, - "kind": "short", - "prompt0": p0, - "input_tokens0": n0, - "turns": [{"max_new_tokens": 256}], - } - if kind == "quick_fix": - m = 7 + idx - head = ( - f"[{pid}] Repository Patch Triage:\n" - f"Inspect off-by-one boundary in ring buffer size {m}. Draft an initial hypothesis in 3 concise " - "bullet points before running the test suite.\nSnapshot context:\n" - ) - p0, n0 = _fit_chat_prompt_exact(tokenizer, sys_agent, head, filler, target_tokens=1024) - fb1 = _make_padded_text( - tokenizer, - 1000, - f"### test_runner ({pid})\nstatus=failure\nMinor IndexError in ring_buffer_pop at offset {m}. " - "Summarize the exact 1-line fix, state why surrounding callers stay valid, and provide a short unified diff.\n" - "--- pytest traceback ---\n", - f"FAILED tests/test_ring_{m % 5}.py::test_boundary_{idx} - IndexError: pop index {m} out of range\n", - ) - return { - "prompt_id": pid, - "kind": "quick_fix", - "prompt0": p0, - "input_tokens0": n0, - "turns": [ - {"max_new_tokens": 96}, - { - "tool_type": "test_runner", - "status": "failure", - "payload_tokens": 1000, - "feedback": fb1, - "max_new_tokens": 192, - }, - ], - } - if kind == "deep_fail": - m = 19 + idx - head = ( - f"[{pid}] Deep Distributed Consensus Bug:\n" - f"Inspect multi-shard state replication across {m} replicas for epoch fencepost & lock ordering bugs. " - "List initial diagnostic hypotheses before inspecting failure logs.\nSnapshot context:\n" - ) - p0, n0 = _fit_chat_prompt_exact(tokenizer, sys_agent, head, filler, target_tokens=1024) - turns: list[dict[str, Any]] = [{"max_new_tokens": 96}] - for t in range(1, 11): - fb = _make_padded_text( - tokenizer, - 1000, - f"### test_runner ({pid} phase {t}/10)\nstatus=failure\nDeep AssertionError in replica-{m} state machine " - f"(sub-case {t}/10)! Write a comprehensive mathematical invariant proof, full transition table, " - "edge-case analysis, and complete corrected Python implementation.\n--- state dump ---\n", - f"E AssertionError: epoch={t} replica={m} expected barrier commit <= snapshot_seq\n", - ) - turns.append({ - "tool_type": "test_runner", - "status": "failure", - "payload_tokens": 1000, - "feedback": fb, - "max_new_tokens": 640, - }) - return { - "prompt_id": pid, - "kind": "deep_fail", - "prompt0": p0, - "input_tokens0": n0, - "turns": turns, - } - - m = 31 + idx - head = ( - f"[{pid}] Deep Async Pipeline Tail-Latency Bug:\n" - f"Diagnose worst-case tail latency stall in a {m}-worker asynchronous pipeline with preemption and rollback. " - "State initial hypotheses before inspecting profiler logs.\nSnapshot context:\n" - ) - p0, n0 = _fit_chat_prompt_exact(tokenizer, sys_agent, head, filler, target_tokens=1024) - turns = [{"max_new_tokens": 96}] - for t in range(1, 11): - fb = _make_padded_text( - tokenizer, - 1000, - f"### test_runner ({pid} stress {t}/10)\nstatus=timeout\nPerformance regression timed out on {m}-worker " - f"stress harness (phase {t}/10)! Derive the complete asymptotic complexity proof, amortization " - "equations, step-by-step execution trace, and full async Python rewrite.\n--- profiler trace ---\n", - f"TIMEOUT worker={m} phase={t} queue_wait_ms=14820 stalling_barrier=commit_lock\n", - ) - turns.append({ - "tool_type": "test_runner", - "status": "timeout", - "payload_tokens": 1000, - "feedback": fb, - "max_new_tokens": 640, - }) - return { - "prompt_id": pid, - "kind": "deep_timeout", - "prompt0": p0, - "input_tokens0": n0, - "turns": turns, - } - - if is_warmup: - counts = {"short": 6, "quick_fix": 4, "deep_fail": 2, "deep_timeout": 1} - tag = "w" - rng_seed = seed - else: - counts = {"short": 48, "quick_fix": 10, "deep_fail": 1, "deep_timeout": 1} - tag = "e" - rng_seed = seed + 1 - - items: list[dict[str, Any]] = [] - for kind in ("short", "quick_fix", "deep_fail", "deep_timeout"): - for idx in range(counts[kind]): - items.append(make_item(kind, tag, idx)) - random.Random(rng_seed).shuffle(items) - return items - - -async def run_one_episode( - engine: HeterogeneousRolloutEngine, - tokenizer, - item: dict[str, Any], - *, - epoch: int, -) -> dict[str, Any]: - t_ep0 = time.perf_counter() - req_id = "" - if hasattr(engine.scheduler, "get_request_route"): - req_id = await engine.begin_cmlfq_request_when_available( - item["prompt_id"], item["input_tokens0"], epoch=epoch - ) - - cur_text = item["prompt0"] - cur_tokens = item["input_tokens0"] - pure_generated = 0 - total_output_tokens = 0 - calls = [] - try: - for turn_idx, turn_spec in enumerate(item["turns"]): - if turn_idx > 0: - fb = turn_spec["feedback"] - event = { - "tool_type": turn_spec["tool_type"], - "status": turn_spec["status"], - "payload_tokens": turn_spec["payload_tokens"], - "token_position": total_output_tokens, - "generated_token_position": pure_generated, - "turn": turn_idx - 1, - } - if req_id: - engine.record_cmlfq_tool_return(req_id, event, total_output_tokens) - cur_text += "\n" + fb + "\n" - cur_tokens = len(tokenizer.encode(cur_text, add_special_tokens=False)) - - kwargs: dict[str, Any] = { - "prompt": cur_text, - "max_new_tokens": turn_spec["max_new_tokens"], - "temperature": 0.0, - "top_p": 1.0, - "n": 1, - "prompt_id": item["prompt_id"], - "input_tokens": cur_tokens, - "epoch": epoch, - } - if req_id: - kwargs["request_id"] = req_id - - t_g0 = time.perf_counter() - resp = await engine.generate(**kwargs) - t_g1 = time.perf_counter() - out_text = resp.get("text", "") - out_toks = len(resp.get("tokens", [])) or len( - tokenizer.encode(out_text, add_special_tokens=False) - ) - pure_generated += out_toks - total_output_tokens += out_toks + ( - turn_spec.get("payload_tokens", 0) if turn_idx > 0 else 0 - ) - cur_text += out_text - info = resp.get("_schedule_info", {}) - calls.append({ - "turn": turn_idx, - "tp": info.get("tp_degree"), - "instance_id": info.get("instance_id"), - "reason": info.get("reason", ""), - "path": info.get("execution_path", ""), - "out_tokens": out_toks, - "dur_s": t_g1 - t_g0, - }) - - if req_id: - engine.finish_cmlfq_request( - req_id, total_output_tokens, generated_tokens=pure_generated - ) - except BaseException: - if req_id: - engine.cancel_cmlfq_request(req_id) - raise - - return { - "prompt_id": item["prompt_id"], - "kind": item["kind"], - "dur_s": time.perf_counter() - t_ep0, - "pure_generated_tokens": pure_generated, - "calls": calls, - } - - -async def eval_policy( - policy: str, - round_idx: int, - run_slot: int, - tokenizer, - instances: list[dict[str, Any]], - *, - model_path: str, - hw_cfg_path: Path, - arch_cfg_path: Path, - out_dir: Path, - max_model_len: int, - gpu_memory_utilization: float, - short_threshold: int, - medium_threshold: int, - cost_profile_path: str, - rollout_calibration: dict[str, dict[str, float]], - seed: int, -) -> dict[str, Any]: - w_tag = f"W{run_slot:02d}" - e_tag = f"E{run_slot:02d}" - warmup_items = build_workload( - tokenizer, w_tag, is_warmup=True, max_model_len=max_model_len, seed=seed - ) - eval_items = build_workload( - tokenizer, e_tag, is_warmup=False, max_model_len=max_model_len, seed=seed - ) - engine = _make_bare_engine( - policy, - instances, - model_path=model_path, - hw_cfg_path=hw_cfg_path, - arch_cfg_path=arch_cfg_path, - out_dir=out_dir, - max_model_len=max_model_len, - gpu_memory_utilization=gpu_memory_utilization, - short_threshold=short_threshold, - medium_threshold=medium_threshold, - cost_profile_path=cost_profile_path, - rollout_calibration=rollout_calibration, - ) - try: - async def _run_batch(items: list[dict[str, Any]], epoch: int) -> list[dict[str, Any]]: - sem = asyncio.Semaphore(len(items)) - - async def _bounded(it: dict[str, Any]) -> dict[str, Any]: - async with sem: - return await run_one_episode(engine, tokenizer, it, epoch=epoch) - - return await asyncio.gather(*(_bounded(it) for it in items)) - - engine.notify_epoch_start(0) - await _run_batch(warmup_items, 0) - engine.notify_epoch_end(0) - - engine.notify_epoch_start(1) - t0 = time.perf_counter() - ep_results = await _run_batch(eval_items, 1) - makespan_s = time.perf_counter() - t0 - engine.notify_epoch_end(1) - - durs = sorted(ep["dur_s"] for ep in ep_results) - p50 = durs[len(durs) // 2] - p90 = durs[min(len(durs) - 1, int(0.9 * len(durs)))] - total_gen_tokens = sum(ep["pure_generated_tokens"] for ep in ep_results) - tp_calls: Counter[str] = Counter() - tp_tokens: Counter[str] = Counter() - reasons: Counter[str] = Counter() - paths: Counter[str] = Counter() - for ep in ep_results: - for c in ep["calls"]: - tp_key = str(c["tp"]) - tp_calls[tp_key] += 1 - tp_tokens[tp_key] += c["out_tokens"] - reasons[c["reason"]] += 1 - if c["path"]: - paths[c["path"]] += 1 - - stats = engine.scheduler.get_stats().to_dict() - migrations = stats.get("migrated_routes", 0) - by_kind = { - k: round(statistics.mean(ep["dur_s"] for ep in ep_results if ep["kind"] == k), 3) - for k in ("short", "quick_fix", "deep_fail", "deep_timeout") - } - by_kind_gen = { - k: round( - statistics.mean( - ep["pure_generated_tokens"] for ep in ep_results if ep["kind"] == k - ), - 1, - ) - for k in ("short", "quick_fix", "deep_fail", "deep_timeout") - } - print( - f"[R{round_idx} {policy:18s}] makespan={makespan_s:6.2f}s | " - f"tok/s={total_gen_tokens / makespan_s:7.1f} | p50={p50:5.2f}s p90={p90:5.2f}s | " - f"tp_calls={dict(sorted(tp_calls.items()))} | mig={migrations} | " - f"gen_tok={total_gen_tokens} | gen_by_kind={by_kind_gen}", - flush=True, - ) - return { - "round": round_idx, - "session_tags": {"warmup": w_tag, "eval": e_tag}, - "policy": policy, - "makespan_s": makespan_s, - "total_generated_tokens": total_gen_tokens, - "tokens_per_second": total_gen_tokens / makespan_s, - "trajectories_per_second": len(ep_results) / makespan_s, - "latency_p50_s": p50, - "latency_p90_s": p90, - "latency_max_s": durs[-1], - "tp_calls": dict(sorted(tp_calls.items())), - "tp_tokens": dict(sorted(tp_tokens.items())), - "migrations": migrations, - "reasons": dict(reasons), - "paths": dict(paths), - "by_kind": by_kind, - "by_kind_gen_tokens": by_kind_gen, - } - finally: - await engine.close() - - -def _resolve_policies(raw_policies: str) -> list[str]: - if raw_policies.strip().lower() == "all": - return list(POLICIES_FORWARD) - selected = [p.strip() for p in raw_policies.split(",") if p.strip()] - unknown = [p for p in selected if p not in POLICIES_FORWARD] - if unknown: - raise ValueError(f"Unknown policies {unknown}; valid choices: {list(POLICIES_FORWARD)}") - if not selected: - raise ValueError("No policies selected") - return selected - - -def run_dry_run( - args: argparse.Namespace, - instances: list[dict[str, Any]], - selected_policies: list[str], -) -> dict[str, Any]: - """Instantiate all selected schedulers offline and verify CostModel wiring.""" - buckets, length_thresholds = make_buckets_and_thresholds( - instances, - max_model_len=args.max_model_len, - short_threshold=args.short_threshold, - medium_threshold=args.medium_threshold, - ) - tps = sorted({int(inst["tp"]) for inst in instances}) - min_tp, max_tp = tps[0], tps[1] - dummy_cal = { - str(min_tp): {"prefill_scale": 0.67, "decode_scale": 1.46}, - str(max_tp): {"prefill_scale": 0.78, "decode_scale": 2.65}, - } - hw_cfg_path = Path(args.hardware_config) - arch_cfg_path = Path(args.model_arch_config) - - with tempfile.TemporaryDirectory(prefix="libra_rollout_dryrun_") as tmpdir: - tmp_path = Path(tmpdir) - profile_path = tmp_path / "dummy_profile.json" - profile_path.write_text( - json.dumps({ - "decode_ms": {}, - "migrations": [ - { - "source_tp": min_tp, - "target_tp": max_tp, - "source_host": instances[0]["host"], - "target_host": instances[-1]["host"], - "seq_len": 2048, - "recompute_ms": 130.0, - }, - { - "source_tp": max_tp, - "target_tp": min_tp, - "source_host": instances[-1]["host"], - "target_host": instances[0]["host"], - "seq_len": 2048, - "recompute_ms": 430.0, - }, - ], - }), - encoding="utf-8", - ) - schedulers: dict[str, str] = {} - for policy in selected_policies: - eng = _make_bare_engine( - policy, - instances, - model_path=args.model, - hw_cfg_path=hw_cfg_path, - arch_cfg_path=arch_cfg_path, - out_dir=tmp_path, - max_model_len=args.max_model_len, - gpu_memory_utilization=args.gpu_memory_utilization, - short_threshold=args.short_threshold, - medium_threshold=args.medium_threshold, - cost_profile_path=str(profile_path), - rollout_calibration=dummy_cal, - ) - schedulers[policy] = type(eng.scheduler).__name__ - if policy == "cmlfq_cost": - rc = eng.scheduler.routing_costs - assert rc.decode_ms == {}, f"Expected empty decode_ms, got {rc.decode_ms}" - assert rc.rollout_model is not None - assert rc.rollout_model.calibration == dummy_cal - assert len(rc.migrations) == 2 - - payload = { - "dry_run": True, - "model": args.model, - "instances": instances, - "buckets": buckets, - "length_thresholds": length_thresholds, - "policies": schedulers, - "rounds": args.rounds, - } - print(json.dumps(payload, indent=2)) - return payload - - -async def run_benchmark(args: argparse.Namespace) -> dict[str, Any]: - gpus = ( - [int(g.strip()) for g in args.gpus.split(",") if g.strip()] - if args.gpus.strip() - else None - ) - instances = parse_topology(args.topology, gpus=gpus, host=args.host, base_port=args.base_port) - selected_policies = _resolve_policies(args.policies) - - if args.dry_run: - return run_dry_run(args, instances, selected_policies) - - from transformers import AutoTokenizer - - out_dir = Path(args.output_dir) - out_dir.mkdir(parents=True, exist_ok=True) - hw_cfg_path = Path(args.hardware_config) - arch_cfg_path = Path(args.model_arch_config) - buckets, length_thresholds = make_buckets_and_thresholds( - instances, - max_model_len=args.max_model_len, - short_threshold=args.short_threshold, - medium_threshold=args.medium_threshold, - ) - - tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True) - calib = await run_phase1_calibration( - tokenizer, - instances, - model_path=args.model, - hw_cfg_path=hw_cfg_path, - arch_cfg_path=arch_cfg_path, - out_dir=out_dir, - max_model_len=args.max_model_len, - gpu_memory_utilization=args.gpu_memory_utilization, - short_threshold=args.short_threshold, - medium_threshold=args.medium_threshold, - ) - - print( - f"=== PHASE 2: {len(selected_policies)}-Policy Comparison " - f"(warmup=13, eval=60, full-batch, vLLM APC ON, short={args.short_threshold}) ===", - flush=True, - ) - - runs = [] - slot = 0 - for round_idx in range(1, args.rounds + 1): - order = selected_policies if round_idx % 2 == 1 else list(reversed(selected_policies)) - print(f"--- Round {round_idx}: {order} ---", flush=True) - for policy in order: - slot += 1 - runs.append( - await eval_policy( - policy, - round_idx, - slot, - tokenizer, - instances, - model_path=args.model, - hw_cfg_path=hw_cfg_path, - arch_cfg_path=arch_cfg_path, - out_dir=out_dir, - max_model_len=args.max_model_len, - gpu_memory_utilization=args.gpu_memory_utilization, - short_threshold=args.short_threshold, - medium_threshold=args.medium_threshold, - cost_profile_path=calib["profile_path"], - rollout_calibration=calib["rollout_calibration"], - seed=args.seed, - ) - ) - - aggregate: dict[str, dict[str, Any]] = {} - for policy in selected_policies: - rows = [r for r in runs if r["policy"] == policy] - mean_mk = statistics.mean(r["makespan_s"] for r in rows) - mean_tps = statistics.mean(r["tokens_per_second"] for r in rows) - mean_p50 = statistics.mean(r["latency_p50_s"] for r in rows) - mean_p90 = statistics.mean(r["latency_p90_s"] for r in rows) - mean_mig = statistics.mean(r["migrations"] for r in rows) - aggregate[policy] = { - "rounds": len(rows), - "mean_makespan_s": mean_mk, - "mean_tokens_per_second": mean_tps, - "mean_latency_p50_s": mean_p50, - "mean_latency_p90_s": mean_p90, - "mean_migrations": mean_mig, - "round_makespans_s": [r["makespan_s"] for r in rows], - "total_generated_tokens": [r["total_generated_tokens"] for r in rows], - "tp_calls_per_round": [r["tp_calls"] for r in rows], - "by_kind_mean_s": { - k: round(statistics.mean(r["by_kind"][k] for r in rows), 3) - for k in ("short", "quick_fix", "deep_fail", "deep_timeout") - }, - "by_kind_gen_tokens": { - k: round(statistics.mean(r["by_kind_gen_tokens"][k] for r in rows), 1) - for k in ("short", "quick_fix", "deep_fail", "deep_timeout") - }, - } - - if "round_robin" in aggregate: - rr = aggregate["round_robin"] - for stats_d in aggregate.values(): - stats_d["speedup_vs_round_robin"] = rr["mean_makespan_s"] / stats_d["mean_makespan_s"] - stats_d["throughput_gain_vs_rr_pct"] = ( - stats_d["mean_tokens_per_second"] / rr["mean_tokens_per_second"] - 1.0 - ) * 100.0 - stats_d["makespan_reduction_vs_rr_pct"] = ( - 1.0 - stats_d["mean_makespan_s"] / rr["mean_makespan_s"] - ) * 100.0 - if "least_connections" in aggregate: - lc = aggregate["least_connections"] - for stats_d in aggregate.values(): - stats_d["speedup_vs_least_connections"] = ( - lc["mean_makespan_s"] / stats_d["mean_makespan_s"] - ) - stats_d["throughput_gain_vs_lc_pct"] = ( - stats_d["mean_tokens_per_second"] / lc["mean_tokens_per_second"] - 1.0 - ) * 100.0 - if "length_aware" in aggregate: - la = aggregate["length_aware"] - for stats_d in aggregate.values(): - stats_d["throughput_gain_vs_la_pct"] = ( - stats_d["mean_tokens_per_second"] / la["mean_tokens_per_second"] - 1.0 - ) * 100.0 - if "cmlfq" in aggregate: - cm = aggregate["cmlfq"] - for stats_d in aggregate.values(): - stats_d["throughput_gain_vs_cmlfq_pct"] = ( - stats_d["mean_tokens_per_second"] / cm["mean_tokens_per_second"] - 1.0 - ) * 100.0 - - summary = { - "topology": args.topology, - "instances": instances, - "model": args.model, - "thresholds": {"buckets": buckets, "length_thresholds": length_thresholds}, - "calibration": calib["profile"], - "workload": {"warmup": 13, "eval": 60, "concurrency": {"warmup": 13, "eval": 60}}, - "runs": runs, - "aggregate": aggregate, - } - (out_dir / "results.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") - - print("\n=== AGGREGATE SUMMARY ===", flush=True) - for policy in selected_policies: - s = aggregate[policy] - vs_rr = ( - f" | vs_RR={s['speedup_vs_round_robin']:.2f}x " - f"(tok/s {s['throughput_gain_vs_rr_pct']:+5.1f}%, mk {s['makespan_reduction_vs_rr_pct']:+5.1f}%)" - if "speedup_vs_round_robin" in s - else "" - ) - print( - f"{policy:18s}: makespan={s['mean_makespan_s']:6.2f}s | " - f"tok/s={s['mean_tokens_per_second']:7.1f} | p90={s['mean_latency_p90_s']:5.2f}s{vs_rr}", - flush=True, - ) - return summary - - -def parse_args(argv: list[str] | None = None) -> argparse.Namespace: - parser = argparse.ArgumentParser( - description="Tier 2 controlled multi-turn heterogeneous rollout scheduling benchmark." - ) - parser.add_argument("--model", default="Qwen/Qwen3-14B", help="Model ID or local path") - parser.add_argument( - "--topology", - default="1,1,1,1,4", - help="Comma-separated TP degrees across instances (default: 1,1,1,1,4)", - ) - parser.add_argument( - "--gpus", - default="", - help="Comma-separated GPU IDs (default: 0..sum(topology)-1)", - ) - parser.add_argument("--host", default="127.0.0.1", help="vLLM server host") - parser.add_argument("--base-port", type=int, default=19001, help="Starting vLLM server port") - parser.add_argument( - "--hardware-config", - default=str(DEFAULT_HW_CFG), - help="Hardware config YAML for analytical CostModel", - ) - parser.add_argument( - "--model-arch-config", - default=str(DEFAULT_ARCH_CFG), - help="Model architecture config YAML for analytical CostModel", - ) - parser.add_argument( - "--output-dir", - default="./logs/tier2_rollout_scheduling", - help="Directory for calibration profile and results.json", - ) - parser.add_argument("--max-model-len", type=int, default=24576, help="Max sequence length") - parser.add_argument( - "--gpu-memory-utilization", type=float, default=0.85, help="vLLM GPU memory utilization" - ) - parser.add_argument( - "--short-threshold", - type=int, - default=5000, - help="Unified token threshold separating short vs long bucket (default: 5000)", - ) - parser.add_argument( - "--medium-threshold", - type=int, - default=12000, - help="Medium length threshold for length_aware/la_mlfq (default: 12000)", - ) - parser.add_argument("--rounds", type=int, default=2, help="Counterbalanced rounds (default: 2)") - parser.add_argument( - "--policies", - default="all", - help="Comma-separated policy names or 'all'", - ) - parser.add_argument("--seed", type=int, default=42, help="Random workload shuffle seed") - parser.add_argument( - "--dry-run", - action="store_true", - help="Verify topology, thresholds, and scheduler initialization without GPUs", - ) - return parser.parse_args(argv) - - -def main(argv: list[str] | None = None) -> int: - args = parse_args(argv) - asyncio.run(run_benchmark(args)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) 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/launch_4gpu.py b/repro/tier2_four_gpu_closed_loop/launch_4gpu.py index 7d07e5d..af3e1df 100755 --- a/repro/tier2_four_gpu_closed_loop/launch_4gpu.py +++ b/repro/tier2_four_gpu_closed_loop/launch_4gpu.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Slurm-free Tier 2 launcher for 4-GPU heterogeneous and 1-GPU Colab closed-loop RL.""" +"""Slurm-free Tier 2 launcher for 8-GPU / 4-GPU heterogeneous and 1-GPU Colab closed-loop RL.""" from __future__ import annotations @@ -56,13 +56,23 @@ def _ensure_rl_framework_importable() -> Path: 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") @@ -137,14 +147,18 @@ def detect_colab_tier() -> str: def parse_gpu_list(raw: str | None, *, mode: str) -> list[int]: """Parse GPU indices from --gpus or CUDA_VISIBLE_DEVICES.""" - default_str = "0,1,2,3" if mode == "4gpu" else "0" + 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 = 4 if mode == "4gpu" else 1 + 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}" @@ -154,6 +168,17 @@ def parse_gpu_list(raw: str | None, *, mode: str) -> list[int]: 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"] @@ -194,7 +219,27 @@ def _scheduling_block( } is_causal = policy in ("cmlfq", "cmlfq_cost") - return { + 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" @@ -204,14 +249,12 @@ def _scheduling_block( "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": ( - [[1, 2], [2, 1]] if (is_causal and kv_backend == "cpu_offload") else [] - ), - "cmlfq_buckets": { - "short": {"tp_degrees": [1], "max_tokens": 512}, - "long": {"tp_degrees": [2], "max_tokens": max(2048, max_model_len)}, - }, + "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( @@ -229,6 +272,7 @@ def _vllm_supervisor_command( max_num_seqs: int, seed: int, kv_storage_dir: Path | None, + enable_cuda_graphs: bool = False, ) -> list[str]: vllm_cmd = [ python_bin, @@ -249,14 +293,21 @@ def _vllm_supervisor_command( str(gpu_memory_utilization), "--max-num-seqs", str(max_num_seqs), - "--enforce-eager", - "--disable-log-requests", - "--no-enable-prefix-caching", - "--seed", - str(seed), - "--worker-extension-cls", - "RL_Framework.vllm_hot_reload.InplaceReloadWorkerExtension", ] + 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( [ @@ -310,19 +361,22 @@ def build_run_plan( gpu_memory_utilization: float | None = None, max_model_len: int | None = None, max_new_tokens: int | None = None, - max_turns: int = 2, + 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 = ( @@ -333,6 +387,7 @@ def build_run_plan( 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"] @@ -341,15 +396,46 @@ def build_run_plan( 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 @@ -380,7 +466,7 @@ def build_run_plan( config_dict: dict[str, Any] = { "hardware_config": str( - (REPO_ROOT / "configs/hardware_config/a800_80g.yaml").resolve() + (REPO_ROOT / "configs/hardware_config" / hw_yaml).resolve() ), "model_arch_config": str( (REPO_ROOT / "configs/model_arch_config" / arch_yaml).resolve() @@ -395,7 +481,8 @@ def build_run_plan( "train_pp_size": 1, "train_dp_size": 1, "batch_size": resolved_batch, - "micro_batch_size": 1, + "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, @@ -408,7 +495,7 @@ def build_run_plan( "learning_rate": 1.0e-6, "ppo_epochs": 1, "seed": seed, - "recompute_logprobs": True, + "recompute_logprobs": False if mode == "8gpu" else True, "sync_interval": resolved_sync, "rollout_sync_drain_lead_steps": 1, "weight_sync_mode": "disk", @@ -447,12 +534,12 @@ def build_run_plan( "OMP_NUM_THREADS": "4", "TOKENIZERS_PARALLELISM": "false", "WANDB_MODE": "disabled", - "FSDP_GRADIENT_CHECKPOINTING": "1", + "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(max_turns), + "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", @@ -467,6 +554,11 @@ def build_run_plan( 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, @@ -487,9 +579,10 @@ def build_run_plan( vllm_dtype=vllm_dtype, max_model_len=resolved_max_len, gpu_memory_utilization=gpu_util, - max_num_seqs=max_num_seqs, + max_num_seqs=inst_max_num_seqs, seed=seed, kv_storage_dir=kv_storage_dir, + enable_cuda_graphs=enable_cuda_graphs, ), } ) @@ -529,6 +622,76 @@ def build_run_plan( } +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"]) @@ -539,6 +702,12 @@ def materialize_run_plan(plan: dict[str, Any]) -> None: 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" @@ -612,15 +781,27 @@ def execute_run_plan(plan: dict[str, Any], timeout_s: float = 2400.0) -> None: 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=dict(env, CUDA_VISIBLE_DEVICES=spec["cuda_visible_devices"]), + env=inst_env, stdout=log_file, stderr=subprocess.STDOUT, start_new_session=True, @@ -672,6 +853,8 @@ def execute_run_plan(plan: dict[str, Any], timeout_s: float = 2400.0) -> None: _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) @@ -699,18 +882,18 @@ def _print_dry_run_summary(plans: list[dict[str, Any]]) -> None: def build_arg_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( - description="Tier 2 Slurm-free launcher for 4-GPU closed loop and 1-GPU Google Colab" + description="Tier 2 Slurm-free launcher for 8-GPU / 4-GPU closed loop and 1-GPU Google Colab" ) parser.add_argument( "--mode", - choices=("4gpu", "colab-1gpu"), + choices=("8gpu", "4gpu", "colab-1gpu"), default="4gpu", - help="4gpu: 1 Train + 3 heterogeneous Rollout; colab-1gpu: single co-located GPU", + 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 (4gpu: round_robin/least_connections/cmlfq/cmlfq_cost/all; colab-1gpu: least_connections/round_robin/all)", + 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", @@ -728,7 +911,7 @@ def build_arg_parser() -> argparse.ArgumentParser: parser.add_argument( "--gpus", default=None, - help="Comma-separated GPU IDs (defaults to CUDA_VISIBLE_DEVICES or 0,1,2,3 / 0)", + help="Comma-separated GPU IDs (defaults to CUDA_VISIBLE_DEVICES or 0..7 / 0..3 / 0)", ) parser.add_argument( "--output-dir", @@ -737,7 +920,7 @@ def build_arg_parser() -> argparse.ArgumentParser: 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="Prompts per RL step") + 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") @@ -751,7 +934,7 @@ def build_arg_parser() -> argparse.ArgumentParser: 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=2, help="Max rollout turns per episode") + parser.add_argument("--max-turns", type=int, default=None, help="Max rollout turns per episode") parser.add_argument( "--dry-run", action="store_true", @@ -816,9 +999,10 @@ def main(argv: list[str] | None = None) -> int: 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 1,2" + f" python repro/tier1_zero_gpu_replay/run_replay.py --trace {history_glob} --tp-layout {tp_arg}" ) return 0 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_rollout_ab.sh b/repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh deleted file mode 100755 index 84e8f0e..0000000 --- a/repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh +++ /dev/null @@ -1,251 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -ROOT="$(cd "$(dirname "$0")/../.." && pwd)" -BENCH_SCRIPT="$ROOT/repro/tier2_four_gpu_closed_loop/benchmark_rollout_scheduling.py" - -MODEL="Qwen/Qwen3-14B" -GPUS="0,1,2,3,4,5,6,7" -TOPOLOGY="1,1,1,1,4" -BASE_PORT="19001" -HOST="127.0.0.1" -MAX_MODEL_LEN="24576" -GPU_MEM_UTIL="0.85" -MAX_NUM_SEQS="32" -OUTPUT_DIR="./logs/tier2_rollout_scheduling" -HARDWARE_CONFIG="$ROOT/configs/hardware_config/h20_3e_141g.yaml" -MODEL_ARCH_CONFIG="$ROOT/configs/model_arch_config/qwen3-14b.yaml" -ROUNDS="2" -POLICIES="all" -PYTHON="python3" -DRY_RUN=0 - -usage() { - cat <&2; usage >&2; exit 1 ;; - esac -done - -IFS=',' read -ra TP_ARR <<< "$TOPOLOGY" -if [[ ${#TP_ARR[@]} -lt 2 ]]; then - echo "ERROR: --topology requires at least 2 instances, got '$TOPOLOGY'" >&2 - exit 1 -fi - -TOTAL_NEEDED=0 -for tp in "${TP_ARR[@]}"; do - TOTAL_NEEDED=$((TOTAL_NEEDED + tp)) -done - -if [[ -z "$GPUS" ]]; then - GPU_ARR=() - for ((g=0; g&2 - exit 1 -fi - -if [[ -d /dev/shm && -w /dev/shm ]]; then - CACHE_BASE="/dev/shm" -else - CACHE_BASE="${TMPDIR:-/tmp}" -fi -RUN_TAG="$$" - -INST_NAMES=() -INST_GPUS=() -INST_TPS=() -INST_PORTS=() - -cursor=0 -for ((idx=0; idx<${#TP_ARR[@]}; idx++)); do - tp="${TP_ARR[$idx]}" - sub_gpus="" - for ((j=0; j/dev/null || kill -TERM "$pid" 2>/dev/null || true - done - if [[ ${#PIDS[@]} -gt 0 ]]; then - sleep 6 - fi - for pid in "${PIDS[@]:-}"; do - kill -KILL -- "-$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null || true - done - rm -rf "${CACHE_BASE}/libra_vllm_${RUN_TAG}_"* - exit "$rc" -} -trap 'exit 143' TERM -trap 'exit 130' INT -trap cleanup EXIT - -for ((i=0; i<${#INST_NAMES[@]}; i++)); do - name="${INST_NAMES[$i]}" - gpus="${INST_GPUS[$i]}" - tp="${INST_TPS[$i]}" - port="${INST_PORTS[$i]}" - cache_dir="${CACHE_BASE}/libra_vllm_${RUN_TAG}_${name}" - mkdir -p "${cache_dir}/vllm" "${cache_dir}/inductor" "${cache_dir}/triton" - env \ - CUDA_VISIBLE_DEVICES="$gpus" \ - VLLM_CACHE_ROOT="${cache_dir}/vllm" \ - TORCHINDUCTOR_CACHE_DIR="${cache_dir}/inductor" \ - TRITON_CACHE_DIR="${cache_dir}/triton" \ - setsid "$PYTHON" -m vllm.entrypoints.openai.api_server \ - --model "$MODEL" \ - --host "$HOST" \ - --port "$port" \ - --tensor-parallel-size "$tp" \ - --dtype bfloat16 \ - --max-model-len "$MAX_MODEL_LEN" \ - --gpu-memory-utilization "$GPU_MEM_UTIL" \ - --max-num-seqs "$MAX_NUM_SEQS" \ - --enable-prefix-caching \ - --disable-log-requests \ - --seed 42 \ - > "$OUTPUT_DIR/vllm_${name}.log" 2>&1 < /dev/null & - PIDS+=($!) - echo "Launched $name (gpus=$gpus, tp=$tp, port=$port, pid=${PIDS[-1]})" -done - -deadline=$((SECONDS + 600)) -for port in "${INST_PORTS[@]}"; do - while true; do - if "$PYTHON" -c "import urllib.request; r=urllib.request.urlopen('http://${HOST}:${port}/health', timeout=2); raise SystemExit(0 if r.status == 200 else 1)" 2>/dev/null; then - echo "Server on ${HOST}:${port} is healthy." - break - fi - for pid in "${PIDS[@]}"; do - if ! kill -0 "$pid" 2>/dev/null; then - echo "ERROR: vLLM server pid $pid exited early; inspect $OUTPUT_DIR/vllm_*.log" >&2 - exit 2 - fi - done - if [[ "$SECONDS" -ge "$deadline" ]]; then - echo "ERROR: Timed out waiting for vLLM server on ${HOST}:${port}" >&2 - exit 3 - fi - sleep 3 - done -done - -echo "All ${#INST_NAMES[@]} vLLM servers ready. Running rollout scheduling benchmark..." -"$PYTHON" -u "$BENCH_SCRIPT" \ - --model "$MODEL" \ - --topology "$TOPOLOGY" \ - --gpus "$GPUS" \ - --host "$HOST" \ - --base-port "$BASE_PORT" \ - --hardware-config "$HARDWARE_CONFIG" \ - --model-arch-config "$MODEL_ARCH_CONFIG" \ - --output-dir "$OUTPUT_DIR" \ - --max-model-len "$MAX_MODEL_LEN" \ - --gpu-memory-utilization "$GPU_MEM_UTIL" \ - --rounds "$ROUNDS" \ - --policies "$POLICIES" 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 index 8c3d84e..52686d4 100644 --- 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 @@ -1,64 +1,64 @@ -{"prompt_id": "dapo_mini_00", "question": "Solve for $x$: $2x + 7 = 13$.", "ground_truth": "3", "answer": "3", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_01", "question": "Find the remainder when $7^{2025}$ is divided by $1000$.", "ground_truth": "807", "answer": "807", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_02", "question": "Solve for $x$: $3x + 10 = 34$.", "ground_truth": "8", "answer": "8", "data_source": "dapo_math_mini"} -{"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}$.", "ground_truth": "269", "answer": "269", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_04", "question": "Solve for $x$: $4x + 13 = 65$.", "ground_truth": "13", "answer": "13", "data_source": "dapo_math_mini"} -{"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"} -{"prompt_id": "dapo_mini_06", "question": "Solve for $x$: $5x + 16 = 106$.", "ground_truth": "18", "answer": "18", "data_source": "dapo_math_mini"} -{"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$?", "ground_truth": "90", "answer": "90", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_08", "question": "Solve for $x$: $6x + 19 = 43$.", "ground_truth": "4", "answer": "4", "data_source": "dapo_math_mini"} -{"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)$?", "ground_truth": "334", "answer": "334", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_10", "question": "Solve for $x$: $7x + 9 = 72$.", "ground_truth": "9", "answer": "9", "data_source": "dapo_math_mini"} -{"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$.", "ground_truth": "121", "answer": "121", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_12", "question": "Solve for $x$: $8x + 12 = 124$.", "ground_truth": "14", "answer": "14", "data_source": "dapo_math_mini"} -{"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$.", "ground_truth": "795", "answer": "795", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_14", "question": "Solve for $x$: $9x + 15 = 186$.", "ground_truth": "19", "answer": "19", "data_source": "dapo_math_mini"} -{"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"} -{"prompt_id": "dapo_mini_16", "question": "An arithmetic sequence starts at $2$ with common difference $3$. Find the sum of its first $6$ terms.", "ground_truth": "57", "answer": "57", "data_source": "dapo_math_mini"} -{"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$.", "ground_truth": "373", "answer": "373", "data_source": "dapo_math_mini"} -{"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"} -{"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"} -{"prompt_id": "dapo_mini_20", "question": "An arithmetic sequence starts at $6$ with common difference $5$. Find the sum of its first $8$ terms.", "ground_truth": "188", "answer": "188", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_21", "question": "Find the remainder when $\\binom{30}{15} + \\binom{30}{10}$ is divided by $1009$.", "ground_truth": "945", "answer": "945", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_22", "question": "An arithmetic sequence starts at $8$ with common difference $6$. Find the sum of its first $9$ terms.", "ground_truth": "288", "answer": "288", "data_source": "dapo_math_mini"} -{"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$?", "ground_truth": "321", "answer": "321", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_24", "question": "An arithmetic sequence starts at $10$ with common difference $7$. Find the sum of its first $10$ terms.", "ground_truth": "415", "answer": "415", "data_source": "dapo_math_mini"} -{"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"} -{"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"} -{"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"} -{"prompt_id": "dapo_mini_28", "question": "An arithmetic sequence starts at $14$ with common difference $4$. Find the sum of its first $6$ terms.", "ground_truth": "144", "answer": "144", "data_source": "dapo_math_mini"} -{"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\\}$?", "ground_truth": "21", "answer": "21", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_30", "question": "An arithmetic sequence starts at $16$ with common difference $5$. Find the sum of its first $7$ terms.", "ground_truth": "217", "answer": "217", "data_source": "dapo_math_mini"} -{"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?", "ground_truth": "240", "answer": "240", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_32", "question": "Compute the remainder when $5^{3}$ is divided by $7$.", "ground_truth": "6", "answer": "6", "data_source": "dapo_math_mini"} -{"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"} -{"prompt_id": "dapo_mini_34", "question": "Compute the remainder when $6^{4}$ is divided by $8$.", "ground_truth": "0", "answer": "0", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_35", "question": "Find the largest integer $n$ such that $72^n$ divides $120!$.", "ground_truth": "29", "answer": "29", "data_source": "dapo_math_mini"} -{"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"} -{"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$.", "ground_truth": "602070", "answer": "602070", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_38", "question": "Compute the remainder when $8^{6}$ is divided by $10$.", "ground_truth": "4", "answer": "4", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_39", "question": "Let $\\omega = e^{2\\pi i / 7}$. Compute $\\prod_{k=1}^{6} (3 - 2\\omega^k)$.", "ground_truth": "2059", "answer": "2059", "data_source": "dapo_math_mini"} -{"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"} -{"prompt_id": "dapo_mini_41", "question": "How many $6$-digit palindromic positive integers are divisible by $77$?", "ground_truth": "140", "answer": "140", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_42", "question": "Compute the remainder when $10^{4}$ is divided by $7$.", "ground_truth": "4", "answer": "4", "data_source": "dapo_math_mini"} -{"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$.", "ground_truth": "23", "answer": "23", "data_source": "dapo_math_mini"} -{"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"} -{"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"} -{"prompt_id": "dapo_mini_46", "question": "Compute the remainder when $12^{6}$ is divided by $9$.", "ground_truth": "0", "answer": "0", "data_source": "dapo_math_mini"} -{"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$?", "ground_truth": "819", "answer": "819", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_48", "question": "In how many ways can we choose $2$ distinct items from $6$ distinct items?", "ground_truth": "15", "answer": "15", "data_source": "dapo_math_mini"} -{"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"} -{"prompt_id": "dapo_mini_50", "question": "In how many ways can we choose $3$ distinct items from $7$ distinct items?", "ground_truth": "35", "answer": "35", "data_source": "dapo_math_mini"} -{"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"} -{"prompt_id": "dapo_mini_52", "question": "In how many ways can we choose $4$ distinct items from $8$ distinct items?", "ground_truth": "70", "answer": "70", "data_source": "dapo_math_mini"} -{"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"} -{"prompt_id": "dapo_mini_54", "question": "In how many ways can we choose $2$ distinct items from $9$ distinct items?", "ground_truth": "36", "answer": "36", "data_source": "dapo_math_mini"} -{"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$.", "ground_truth": "752", "answer": "752", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_56", "question": "A rectangle has width $4$ and height $7$. What is its perimeter?", "ground_truth": "22", "answer": "22", "data_source": "dapo_math_mini"} -{"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"} -{"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"} -{"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$.", "ground_truth": "661", "answer": "661", "data_source": "dapo_math_mini"} -{"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"} -{"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?", "ground_truth": "683", "answer": "683", "data_source": "dapo_math_mini"} -{"prompt_id": "dapo_mini_62", "question": "A rectangle has width $7$ and height $13$. What is its perimeter?", "ground_truth": "40", "answer": "40", "data_source": "dapo_math_mini"} -{"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"} +{"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 6c907f8..6bd32da 100644 --- a/scripts/benchmark_scheduler_train.py +++ b/scripts/benchmark_scheduler_train.py @@ -49,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'], @@ -58,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), diff --git a/tests/test_tier2_closed_loop.py b/tests/test_tier2_closed_loop.py index 8183680..a151ec0 100644 --- a/tests/test_tier2_closed_loop.py +++ b/tests/test_tier2_closed_loop.py @@ -1,4 +1,4 @@ -"""CPU-safe unit and dry-run tests for Tier 2 (4-GPU closed loop & Google Colab).""" +"""CPU-safe unit and dry-run tests for Tier 2 (8-GPU / 4-GPU closed loop & Google Colab).""" import asyncio import importlib.util @@ -29,12 +29,17 @@ 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(): @@ -358,203 +363,203 @@ async def _run_two(): assert recorder.route_infos[3]["estimated_decode_seconds"] > 0.0 -def test_rollout_benchmark_topology_and_schedulers(tmp_path: Path): - from repro.tier2_four_gpu_closed_loop import benchmark_rollout_scheduling as bench - - instances = bench.parse_topology("1,1,1,1,4") - assert [inst["instance_id"] for inst in instances] == [ - "tp1_0", "tp1_1", "tp1_2", "tp1_3", "tp4_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), ] - assert instances[0]["gpus"] == [0] - assert instances[4]["gpus"] == [4, 5, 6, 7] - assert [inst["port"] for inst in instances] == [19001, 19002, 19003, 19004, 19005] - - with pytest.raises(ValueError, match="exactly 2 distinct TP tiers"): - bench.parse_topology("1,2,4") - with pytest.raises(ValueError, match="requires 8 GPUs"): - bench.parse_topology("1,1,1,1,4", gpus=[0, 1, 2, 3]) - - buckets, thresholds = bench.make_buckets_and_thresholds(instances) - assert buckets == { - "short": {"tp_degrees": [1], "max_tokens": 5000}, - "long": {"tp_degrees": [4], "max_tokens": 24576}, - } - assert thresholds == {"short": 5000, "medium": 12000, "long": 24576} - - profile_path = tmp_path / "profile.json" - profile_path.write_text( - json.dumps({ - "decode_ms": {}, - "migrations": [ - { - "source_tp": 1, - "target_tp": 4, - "source_host": "127.0.0.1", - "target_host": "127.0.0.1", - "seq_len": 2048, - "recompute_ms": 128.9, - }, - { - "source_tp": 4, - "target_tp": 1, - "source_host": "127.0.0.1", - "target_host": "127.0.0.1", - "seq_len": 2048, - "recompute_ms": 430.4, - }, - ], - }), - encoding="utf-8", + sched_8gpu = SchedulerFactory.create( + cfg_8gpu.heterogeneous_rollout.scheduling.scheduler_type, + cfg_8gpu.heterogeneous_rollout, ) - cal = { - "1": {"prefill_scale": 0.6722, "decode_scale": 1.4631}, - "4": {"prefill_scale": 0.7828, "decode_scale": 2.6475}, - } - for policy in bench.POLICIES_FORWARD: - eng = bench._make_bare_engine( - policy, - instances, - model_path="Qwen/Qwen3-14B", - hw_cfg_path=bench.DEFAULT_HW_CFG, - arch_cfg_path=bench.DEFAULT_ARCH_CFG, - out_dir=tmp_path, - cost_profile_path=str(profile_path), - rollout_calibration=cal, - ) - if policy == "cmlfq_cost": - assert isinstance(eng.scheduler, CMLFQCostScheduler) - assert eng.scheduler.routing_costs.decode_ms == {} - assert eng.scheduler.routing_costs.rollout_model.calibration == cal - assert len(eng.scheduler.routing_costs.migrations) == 2 + assert isinstance(sched_8gpu, CMLFQCostScheduler) + assert set(sched_8gpu._bucket_thresholds.keys()) == {"short", "medium", "long"} -def test_rollout_benchmark_calibration_fit_and_interp(): - from repro.tier2_four_gpu_closed_loop import benchmark_rollout_scheduling as bench +def test_launch_8gpu_dry_run_and_seeded_trees(tmp_path: Path): + subprocess.run(["bash", "-n", str(RUN_8GPU_SH)], check=True) - prefill_specs = [2048, 4096, 8192, 16384] - decode_specs = [("ctx2048_g1024", 2048, 1024), ("ctx6144_g1024", 6144, 1024)] - prefill_ms = { - "1": {2048: 430.4, 4096: 864.2, 8192: 1790.3, 16384: 3970.8}, - "4": {2048: 128.9, 4096: 251.5, 8192: 513.9, 16384: 1128.6}, - } - raw_decode_ms = { - "1": { - "ctx2048_g1024": {"b1_total_ms": 10809.0, "b8_wall_ms": 15940.0}, - "ctx6144_g1024": {"b1_total_ms": 12069.0, "b8_wall_ms": 26381.0}, - }, - "4": { - "ctx2048_g1024": {"b1_total_ms": 5950.0, "b8_wall_ms": 7485.0}, - "ctx6144_g1024": {"b1_total_ms": 6283.0, "b8_wall_ms": 11185.0}, - }, - } + 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 - assert bench._interp_pf(prefill_ms["1"], 2048) == pytest.approx(430.4) - assert bench._interp_pf(prefill_ms["1"], 6144) == pytest.approx(0.5 * (864.2 + 1790.3)) - - fitted = bench.fit_rollout_calibration( - prefill_ms, - raw_decode_ms, - prefill_specs, - decode_specs, - bench.DEFAULT_HW_CFG, - bench.DEFAULT_ARCH_CFG, - "Qwen/Qwen3-14B", + 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 fitted["1"]["prefill_scale"] == pytest.approx(0.6722, abs=1e-3) - assert fitted["1"]["decode_scale"] == pytest.approx(1.4631, abs=1e-3) - assert fitted["4"]["prefill_scale"] == pytest.approx(0.7828, abs=1e-3) - assert fitted["4"]["decode_scale"] == pytest.approx(2.6475, abs=1e-3) + assert cost_tree["remaining_unit"] == "model_generated_tokens" -def test_rollout_benchmark_workload_and_session_isolation(): - from collections import Counter - from repro.tier2_four_gpu_closed_loop import benchmark_rollout_scheduling as bench +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) - class _WordTokenizer: - def __init__(self): - self._tok2id: dict[str, int] = {} - self._id2tok: list[str] = [] + 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 - ids = [] - for tok in text.split(): - if tok not in self._tok2id: - self._tok2id[tok] = len(self._id2tok) - self._id2tok.append(tok) - ids.append(self._tok2id[tok]) - return ids - - def decode(self, ids: list[int], skip_special_tokens: bool = True) -> str: + 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(self._id2tok[i] for i in ids) - - def apply_chat_template( - self, messages, tokenize: bool = False, add_generation_prompt: bool = True - ) -> str: - del tokenize, add_generation_prompt - return " ".join(msg["content"] for msg in messages) - - tok = _WordTokenizer() - warmup = bench.build_workload(tok, "W01", is_warmup=True) - eval_a = bench.build_workload(tok, "E01", is_warmup=False) - eval_b = bench.build_workload(tok, "E02", is_warmup=False) - - assert len(warmup) == 13 - assert Counter(it["kind"] for it in warmup) == { - "short": 6, - "quick_fix": 4, - "deep_fail": 2, - "deep_timeout": 1, - } - assert len(eval_a) == 60 - assert Counter(it["kind"] for it in eval_a) == { - "short": 48, - "quick_fix": 10, - "deep_fail": 1, - "deep_timeout": 1, - } + return "".join(chr(tok) for tok in tokens) - expected_turns = {"short": 1, "quick_fix": 2, "deep_fail": 11, "deep_timeout": 11} - for it_a, it_b in zip(eval_a, eval_b): - assert it_a["prompt_id"] == it_b["prompt_id"] - assert it_a["input_tokens0"] == 1024 - assert it_b["input_tokens0"] == 1024 - assert it_a["prompt0"].startswith("[session=E01] ") - assert it_b["prompt0"].startswith("[session=E02] ") - assert len(it_a["turns"]) == expected_turns[it_a["kind"]] + 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 -def test_rollout_benchmark_dry_run_and_shell_syntax(): - bench_py = ( - REPO_ROOT / "repro/tier2_four_gpu_closed_loop/benchmark_rollout_scheduling.py" - ) - bench_sh = REPO_ROOT / "repro/tier2_four_gpu_closed_loop/run_rollout_ab.sh" + 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", + } - proc_py = subprocess.run( - [sys.executable, str(bench_py), "--dry-run"], - capture_output=True, - text=True, - check=True, - ) - parsed = json.loads(proc_py.stdout) - assert parsed["dry_run"] is True - assert list(parsed["policies"].keys()) == [ - "round_robin", - "least_connections", - "length_aware", - "la_mlfq", - "cmlfq", - "cmlfq_cost", - ] + class _RecordingEngine: + def __init__(self, inner: HeterogeneousRolloutEngine): + self._inner = inner + self.route_infos: list[dict] = [] - subprocess.run(["bash", "-n", str(bench_sh)], check=True) - proc_sh = subprocess.run( - ["bash", str(bench_sh), "--dry-run", "--python", sys.executable], - capture_output=True, - text=True, - check=True, + 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, ) - assert "[tp1_0] CUDA_VISIBLE_DEVICES=0" in proc_sh.stdout - assert "[tp4_0] CUDA_VISIBLE_DEVICES=4,5,6,7" in proc_sh.stdout - assert "--enable-prefix-caching" in proc_sh.stdout + + 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] diff --git a/workflow/dapo_math.py b/workflow/dapo_math.py index 19ff7cc..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( @@ -185,10 +228,15 @@ async def run_episode(self, engine: Any, data: dict[str, Any], version: int = 0) 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, @@ -196,6 +244,11 @@ async def run_episode(self, engine: Any, data: dict[str, Any], version: int = 0) "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) From c6a10f26fa183c22a1e4289dbe8dbdb194d80851 Mon Sep 17 00:00:00 2001 From: "CHEN, Kaiwen" <80016929+kaiwenKevinn@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:37:42 +0800 Subject: [PATCH 3/5] feat(repro): add 8-GPU GRP and EHP benchmarks with H20 verification --- repro/tier2_four_gpu_closed_loop/README.md | 49 + .../benchmark_ehp.py | 970 ++++++++++++++++++ .../benchmark_grp.py | 581 +++++++++++ repro/tier2_four_gpu_closed_loop/run_ehp.sh | 16 + repro/tier2_four_gpu_closed_loop/run_grp.sh | 12 + tests/test_tier2_closed_loop.py | 103 ++ 6 files changed, 1731 insertions(+) create mode 100644 repro/tier2_four_gpu_closed_loop/benchmark_ehp.py create mode 100644 repro/tier2_four_gpu_closed_loop/benchmark_grp.py create mode 100755 repro/tier2_four_gpu_closed_loop/run_ehp.sh create mode 100755 repro/tier2_four_gpu_closed_loop/run_grp.sh diff --git a/repro/tier2_four_gpu_closed_loop/README.md b/repro/tier2_four_gpu_closed_loop/README.md index 53e6a0a..e06beb4 100644 --- a/repro/tier2_four_gpu_closed_loop/README.md +++ b/repro/tier2_four_gpu_closed_loop/README.md @@ -117,9 +117,58 @@ python3 repro/tier2_four_gpu_closed_loop/launch_4gpu.py \ --- +## 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. 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/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/tests/test_tier2_closed_loop.py b/tests/test_tier2_closed_loop.py index a151ec0..ce2bb9e 100644 --- a/tests/test_tier2_closed_loop.py +++ b/tests/test_tier2_closed_loop.py @@ -563,3 +563,106 @@ async def generate(self, **kwargs): 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 + From bb6739cae87282e4099af180b3049eb430a8074b Mon Sep 17 00:00:00 2001 From: "CHEN, Kaiwen" <80016929+kaiwenKevinn@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:51:31 +0800 Subject: [PATCH 4/5] docs(repro): remove redundant closed-loop scheduling comparison from Tier 2 README --- repro/tier2_four_gpu_closed_loop/README.md | 37 +++------------------- 1 file changed, 5 insertions(+), 32 deletions(-) diff --git a/repro/tier2_four_gpu_closed_loop/README.md b/repro/tier2_four_gpu_closed_loop/README.md index e06beb4..38469f5 100644 --- a/repro/tier2_four_gpu_closed_loop/README.md +++ b/repro/tier2_four_gpu_closed_loop/README.md @@ -2,59 +2,32 @@ 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) comparing `round_robin`, `least_connections`, `cmlfq`, and `cmlfq_cost`. +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 comparison (without FSDP training updates or weight sync)? See Tier 1 Pathway 2 (`Real-GPU Live vLLM Judge`) in [../tier1_zero_gpu_replay/README.md](../tier1_zero_gpu_replay/README.md). +> 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`) -Reproduce the 8-GPU end-to-end closed-loop RL comparison without Slurm: +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 \ - --policy all \ --gpus 0,1,2,3,4,5,6,7 \ --dry-run -# Full 4-policy real-GPU end-to-end closed-loop RL sweep on 8x H20-3e +# End-to-end real-GPU closed-loop RL run on 8x H20-3e bash repro/tier2_four_gpu_closed_loop/run_8gpu.sh \ - --policy all \ --gpus 0,1,2,3,4,5,6,7 \ --model Qwen/Qwen3-4B \ - --output-dir ./logs/tier2_8gpu_ab + --output-dir ./logs/tier2_8gpu ``` -### Experimental Setup (`8 × NVIDIA H20-3e`, `Qwen/Qwen3-4B`) - -- **Hardware & Topology**: Single node `8 × NVIDIA H20-3e (141 GiB)`: - - **Training**: `1 × FSDPTrainEngine` on GPU `0` (`bfloat16`, `batch_size=16`, `micro_batch_size=1`, `recompute_logprobs=false`, `FSDP_GRADIENT_CHECKPOINTING=0`, `n_samples=2`, `ppo_epochs=1`, `sync_interval=4`). - - **Heterogeneous Rollout (`7` GPUs)**: `tp1` (`TP=1`, GPU `1`, `max_num_seqs=1`, port `18920`), `tp2` (`TP=2`, GPUs `2,3`, `max_num_seqs=2`, port `18921`), and `tp4` (`TP=4`, GPUs `4,5,6,7`, `max_num_seqs=16`, port `18922`). -- **vLLM Serving & Weight Reload**: `vLLM 0.9.2` V1 engine with CUDA graphs enabled, `--enable-prefix-caching`, `max_model_len=6144`, `gpu_memory_utilization=0.75`, per-instance isolated compile/KV caches, and verified parallel in-place disk weight reload (`rollout_weight_reload_method=inplace`, confirmed via `ack_tp1_4.json`, `ack_tp2_4.json`, `ack_tp4_4.json`). -- **Scheduling Policies & Calibration**: - - Baselines: `load_balance` (`round_robin`, `least_connections`). - - Causal schedulers: `cmlfq` and `cmlfq_cost` with unified three-tier buckets (`short -> TP=1 <= 400`, `medium -> TP=2 <= 1200`, `long -> TP=4 <= 6144`), pre-seeded `CausalPrefixTree` (`tree.json`), and empirical tier latency table (`sample_data/dapo_cost_profile.json`). -- **Multi-Turn Closed-Loop Workload (`sample_data/dapo_math_mini.jsonl`)**: `4` RL steps $\times$ `8` prompts/step $\times$ `2` rollouts (`64` trajectories total, `64` FSDP optimizer updates per policy), mixing `short_recover` (`3` turns `[32, 160, 160]`, `small:timeout`), `medium` (`2` turns `[32, 1120]`, `medium:failure`), `long_unambig` (`rollout 0` `[32, 1792, 1792]` + `rollout 1` `[32]`, `large:failure`), and `long_cascading` (Step 0 bimodal causal signal on `small:failure`, where `cmlfq` defers migration at Turn 1 due to `mean_p90_disagree` while `cmlfq_cost` eagerly promotes at Turn 1 via residual distribution + cost model). - -### Verified Real-GPU Closed-Loop Results (`8 × NVIDIA H20-3e`, `Qwen/Qwen3-4B`) - -All 4 policies completed 4 RL steps (`64` samples, `64` FSDP optimizer updates, `152` generation calls, `3/3` confirmed in-place weight reload acks): - -| Policy | End-to-End `loop_seconds` | `rollout_wait_seconds` | `train_seconds` | `sync_seconds` | `samples/s` | vs `round_robin` (`samples/s`) | `gen_tokens/s` | vs `round_robin` (`tok/s`) | Route Calls (`TP=1 / 2 / 4`) | -| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | :---: | -| `round_robin` | `168.60s` | `122.45s` | `29.94s` | `16.20s` | `0.3796` | `+0.0%` (`1.00x`) | `413.23` | `+0.0%` (`1.00x`) | `51 / 51 / 50` | -| `least_connections` | `121.69s` | `76.02s` | `29.40s` | `16.26s` | `0.5259` | `+38.5%` (`1.39x`) | `574.93` | `+39.1%` (`1.39x`) | `45 / 52 / 55` | -| `cmlfq` | `119.99s` | `73.57s` | `30.24s` | `16.15s` | `0.5334` | `+40.5%` (`1.41x`) | `580.13` | `+40.4%` (`1.40x`) | `113 / 16 / 23` | -| **`cmlfq_cost`** | **`115.38s`** | **`69.98s`** | **`29.35s`** | **`16.02s`** | **`0.5547`** | **`+46.1%` (`1.46x`)** | **`607.22`** | **`+46.9%` (`1.47x`)** | **`100 / 17 / 35`** | - -- **`cmlfq_cost` net end-to-end closed-loop RL speedups**: **`+46.1%` (`1.46x`) `samples/s`** and **`+46.9%` (`1.47x`) `generated_tokens/s`** vs `round_robin` (`1.75x` faster rollout collection), **`+5.5%` `samples/s` / `+5.6%` `tok/s`** vs `least_connections`, and **`+4.0%` `samples/s` / `+4.7%` `tok/s`** vs `cmlfq`. -- **Per-step stability & tier placement**: `cmlfq_cost` held steady rollout times across all 4 steps (`[16.97s, 17.73s, 17.62s, 17.66s]`), promoting all long trajectories at Turn 1 to `TP=4` (`35` calls, including Step 0 `long_cascading`), isolating `medium` on `TP=2` (`17` calls), and keeping short turns on `TP=1` (`100` calls), whereas `round_robin` stalled `tp1` with long/medium head-of-line queueing (`36.52s -> 24.93s` per step). - --- ## Mode 2: 4-GPU Heterogeneous Closed Loop (No Slurm Required) From d93a3dfa197a8286b699672259dd1218c5fcc673 Mon Sep 17 00:00:00 2001 From: "CHEN, Kaiwen" <80016929+kaiwenKevinn@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:20:39 +0800 Subject: [PATCH 5/5] test(ci): use spawn instead of fork in R2E rank-zero exception test --- tests/test_r2e_1938329_entrypoint.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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",