Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions engine/train_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
)
Expand All @@ -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),
Expand Down
6 changes: 4 additions & 2 deletions infra/execution/batch_dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
151 changes: 151 additions & 0 deletions repro/tier2_four_gpu_closed_loop/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
# Tier 2 — 8-GPU & 4-GPU Heterogeneous Closed-Loop RL & Google Colab Quickstart

Tier 2 provides **Slurm-free** real-GPU **end-to-end closed-loop RL** entry points (`AsyncRLTrainer` + `FSDPTrainEngine` + `DAPOMathWorkflow` + supervised `vllm_hot_reload_api_server.py` with confirmed in-place weight reloads):

1. **8-GPU Heterogeneous Closed Loop (`1 Train + 7 Rollout [TP=1, TP=2, TP=4]`)**: Real end-to-end GRPO closed-loop training across three heterogeneous serving tiers (`TP=1` on GPU 1, `TP=2` on GPUs 2–3, `TP=4` on GPUs 4–7) with confirmed in-place vLLM weight reloads.
2. **4-GPU Heterogeneous Closed Loop (`1 Train + 3 Rollout [TP=1, TP=2]`)**: Smaller 4-GPU heterogeneous closed-loop setup (`TP=1` on GPU 1, `TP=2` on GPUs 2–3).
3. **Google Colab 1-GPU Co-Located Startup**: Single-GPU closed-loop verification with automatic VRAM/SM tier detection (`T4 16GB`, `L4 24GB`, `A100 40GB`, `A100 80GB`).

> Looking for pure rollout scheduling policy comparison (`round_robin`, `least_connections`, `cmlfq`, `cmlfq_cost`)? See Tier 1 (`repro/tier1_zero_gpu_replay/`) in [../tier1_zero_gpu_replay/README.md](../tier1_zero_gpu_replay/README.md). Below, Tier 2 focuses on end-to-end closed-loop RL bring-up and the 8-GPU **GRP** and **EHP** system benchmarks.

---

## Mode 1: 8-GPU Heterogeneous Closed Loop (`1 Train + TP=1, 2, 4`)

Launch an 8-GPU end-to-end closed-loop RL run without Slurm (`1 × FSDPTrainEngine` on GPU `0` + `TP=1` on GPU `1` + `TP=2` on GPUs `2,3` + `TP=4` on GPUs `4..7`, `bfloat16`, `batch_size=16`, `micro_batch_size=1`, `max_model_len=6144`, `rollout_weight_reload_method=inplace`):

```bash
# Dry-run: validate topology, CostModel profile, seeded trees, and commands without GPUs
python3 repro/tier2_four_gpu_closed_loop/launch_4gpu.py \
--mode 8gpu \
--gpus 0,1,2,3,4,5,6,7 \
--dry-run

# End-to-end real-GPU closed-loop RL run on 8x H20-3e
bash repro/tier2_four_gpu_closed_loop/run_8gpu.sh \
--gpus 0,1,2,3,4,5,6,7 \
--model Qwen/Qwen3-4B \
--output-dir ./logs/tier2_8gpu
```

---

## Mode 2: 4-GPU Heterogeneous Closed Loop (No Slurm Required)

Runs 1 FSDP trainer on GPU 0 and 2 heterogeneous vLLM rollout instances on GPUs `1` (`TP=1`) and `2,3` (`TP=2`):

```bash
# Single policy run (default: cmlfq_cost on DAPO-Math mini + Qwen3-4B)
bash repro/tier2_four_gpu_closed_loop/run_4gpu.sh \
--model Qwen/Qwen3-4B \
--gpus 0,1,2,3

# Full policy sweep across round_robin, least_connections, and cmlfq_cost
bash repro/tier2_four_gpu_closed_loop/run_4gpu.sh \
--model Qwen/Qwen3-4B \
--policy all \
--gpus 0,1,2,3 \
--output-dir ./logs/tier2_ab

# Example: run on a 4-GPU slice of a multi-GPU H20/A800 server
CUDA_VISIBLE_DEVICES=0,1,2,3 bash repro/tier2_four_gpu_closed_loop/run_4gpu.sh \
--model /path/to/Qwen3-4B \
--steps 8 \
--output-dir ./logs/tier2_h20_4gpu
```

Validate configs and inspect exact commands without starting GPUs:

```bash
python3 repro/tier2_four_gpu_closed_loop/launch_4gpu.py --dry-run
```

---

## Mode 3: Google Colab 1-GPU Co-Located Startup

Open [colab_quickstart.ipynb](colab_quickstart.ipynb) directly in Google Colab:

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NetX-lab/Libra/blob/main/repro/tier2_four_gpu_closed_loop/colab_quickstart.ipynb)

Or launch locally on any single GPU (`T4` / `L4` / `A100` / `RTX`):

```bash
python3 repro/tier2_four_gpu_closed_loop/launch_4gpu.py \
--mode colab-1gpu \
--colab-tier auto \
--steps 4
```

### Automatic Colab Presets (`--colab-tier auto`)

| Preset | Trigger Condition | Model | vLLM / FSDP Dtype | KV Utilization | `max_model_len` |
| :--- | :--- | :--- | :--- | :---: | :---: |
| `t4` | `SM < 8.0` or `< 20 GiB` | `Qwen/Qwen2.5-0.5B-Instruct` | `half` / `float32` | `0.30` | `1024` |
| `l4` | `>= 20 GiB` (`SM >= 8.0`) | `Qwen/Qwen2.5-1.5B-Instruct` | `bfloat16` / `bfloat16` | `0.35` | `1536` |
| `a100-40g` | `>= 36 GiB` (`SM >= 8.0`) | `Qwen/Qwen3-1.7B` | `bfloat16` / `bfloat16` | `0.38` | `2048` |
| `a100-80g` | `>= 70 GiB` (`SM >= 8.0`) | `Qwen/Qwen3-4B` | `bfloat16` / `bfloat16` | `0.38` | `2048` |

> Why `float32` FSDP on T4? T4 (`sm_75`) lacks hardware `bfloat16` Tensor Cores. `engine/train_engine.py` reads `FSDP_DTYPE` (`auto` falls back to `float32` when `not torch.cuda.is_bf16_supported()`), while vLLM runs in `half`.

---

## GRP (Global Resource Planner) 8-GPU Benchmark

Evaluates `PreflightPlanner` / `TwoLevelNestedOptimizer` configuration selection and closed-loop multi-GPU allocation efficiency on `8 × NVIDIA H20-3e` (`Qwen/Qwen3-4B`, `4 steps × 16 trajectories`, `n_samples=2`, `max_new_tokens=1792`, `sync_interval=4`, `inplace` weight reload):

- **Phase 1 (Cost-Model Preflight Planning)**: Evaluates 8-GPU allocations against skewed DAPO length quartiles (`prompt=512`, `response=[128, 384, 1536, 4096]`). `PreflightPlanner` explores candidate training/rollout partitions in `15.0 ms` and selects **`1 Train (DP=1, GPU 0) + 7 Rollout (TP=[4, 2, 1], GPUs 1–7)`** (`-56.21%` predicted step time vs. fixed `4/4 TP=1`).
- **Phase 2 (Real `vLLM + FSDP` Closed-Loop Execution on `8 × H20-3e`)**:

| Allocation | Train GPUs (Active / Reserved) | Rollout Layout & Policy | Wall Time (`steps.jsonl`) | Rollout / Train / Sync (s) | Throughput | Reload ACKs | Speedup vs `4/4 TP=1` |
| :--- | :---: | :--- | :---: | :---: | :---: | :---: | :---: |
| `fixed_4train_4rollout_tp1` | `1 / 4` | `TP=[1,1,1,1]` (`round_robin + prefix_affinity`) | `222.275 s` | `176.315 / 29.538 / 16.404` | `17.276 rollouts/min` (`314.06 tok/s`) | `4/4` | `1.000x` |
| `fixed_2train_6rollout_tp2` | `1 / 2` | `TP=[2,2,2]` (`least_connections + prefix_affinity`) | `266.654 s` | `220.797 / 29.535 / 16.304` | `14.401 rollouts/min` (`262.03 tok/s`) | `3/3` | `0.834x` (`-19.97%`) |
| **`grp_optimal_1train_7rollout_hetero`** | **`1 / 1`** | **`TP=[1,2,4]` (`cmlfq_cost`)** | **`115.375 s`** | **`69.981 / 29.353 / 16.020`** | **`33.283 rollouts/min` (`607.22 tok/s`)** | **`3/3`** | **`1.927x` (`+48.09%`)** |

```bash
# CPU dry-run (Phase 1 planning + Phase 2 config validation without GPUs):
python3 repro/tier2_four_gpu_closed_loop/benchmark_grp.py --dry-run --output-dir /tmp/grp_dry

# Full 8 x H20 closed-loop benchmark:
bash repro/tier2_four_gpu_closed_loop/run_grp.sh
```

---

## EHP (Elastic Hybrid Parallelism) 8-GPU Benchmark

Verifies elastic GPU borrowing from the heterogeneous rollout pool to accelerate RL policy updates across three phases:

- **Phase 1 (Lending Capacity & Cost Horizon)**: Verifies `loan_replica_capacity` reserve guards across an 8-GPU GRP layout (`TP=[4, 2, 1]`: lends `0`, `1`, `3` GPUs with reserve satisfied, returns `0` when breaching reserve) and `bounded_update_time` (`111.2 s -> 104.2 s -> 101.2 s`).
- **Phase 2 (`ElasticHybridPool`, `ZERO_SYNC` Safety & Gradient IPC)**: Joins `hybrid_0..2` into `HYBRID_TRAINING / ACTIVE` state, confirms `ZERO_SYNC` placeholder rejection on `step >= 0` (`ValueError`), verifies loopback `ElasticGradientClient -> ElasticGradientServer` (`3/3` ACKs, `4.586 ms` mean latency on H20), and asserts exact weighted `InterReplicaGradientDomain.reduce_core_gradients` output (`2.500000`).
- **Phase 3 (Real `Qwen/Qwen3-4B` Elastic Data-Parallel Training on `8 × H20-3e`)**: Runs `partition_complete_grpo_groups` + `ThreadPoolExecutor` (`bf16`, `sdpa`, `16` trajectories × `seq_len=1536`, `micro_batch_size=2`, `warmup=1`, `steps=3`) + compact TCP norm IPC + GPU `in_place=True` NVLink `reduce_core_gradients` + Core `AdamW` step & parameter sync:

| Mode | Devices | Hybrid Activation | Avg Step (s) | Steady-State Step 1–2 (s) | Compute / IPC / Reduce / Opt+Sync (s) | Peak VRAM | Speedup vs `1 GPU` | `grad_norm` (Steps 0/1/2) |
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :--- |
| `static_core_1gpu` | `cuda:0` | `0.0001 s` | `8.3562 s` | `8.3562 s` | `8.2611 / 0.0000 / 0.0023 / 0.0895` | `60.322 GB` | `1.000x` | `1.460938 / 1.46875 / 1.476562` |
| `ehp_borrow_1gpu` | `cuda:0–1` | `0.2828 s` | `4.3236 s` | `4.3234 s` | `4.1505 / 0.0026 / 0.0508 / 0.1167` | `60.239 GB` | **`1.933x`** | `1.46875 / 1.46875 / 1.476562` |
| **`ehp_borrow_3gpus`** | **`cuda:0–3`** | **`0.8206 s`** | **`3.0834 s`** | **`2.4020 s` (`3.48x`)** | `2.7612 / 0.0039 / 0.1421 / 0.1719` | `60.195 GB` | **`2.710x`** | `1.46875 / 1.46875 / 1.476562` |

```bash
# CPU dry-run (Phase 1, Phase 2, and CPU gradient-parity verification):
python3 repro/tier2_four_gpu_closed_loop/benchmark_ehp.py --dry-run --output-dir /tmp/ehp_dry

# Full multi-GPU H20 EHP benchmark:
bash repro/tier2_four_gpu_closed_loop/run_ehp.sh
```

---

## Bundled Sample Data, Scripts & Templates

- [launch_4gpu.py](launch_4gpu.py), [run_8gpu.sh](run_8gpu.sh), & [run_4gpu.sh](run_4gpu.sh): Slurm-free 8-GPU (`--mode 8gpu`) and 4-GPU (`--mode 4gpu`) closed-loop RL and 1-GPU Colab (`--mode colab-1gpu`) launcher.
- [benchmark_grp.py](benchmark_grp.py) & [run_grp.sh](run_grp.sh): GRP `PreflightPlanner` cost-model verification and 3-way `8 × H20` closed-loop allocation benchmark.
- [benchmark_ehp.py](benchmark_ehp.py) & [run_ehp.sh](run_ehp.sh): EHP 3-phase rollout lending, `ElasticHybridPool` / `ZERO_SYNC` / IPC safety, and real `Qwen3-4B` multi-GPU elastic training benchmark.
- [colab_quickstart.ipynb](colab_quickstart.ipynb): End-to-end Google Colab notebook (Tier 1 replay + Tier 2 closed-loop RL).
- [sample_data/dapo_math_mini.jsonl](sample_data/dapo_math_mini.jsonl): 64 deterministic math verification problems with multi-turn rollout profiles (works offline out of the box; pass `--dataset /path/to/dapo-math-17k.parquet` for full DAPO-Math-17K).
- [sample_data/dapo_cost_profile.json](sample_data/dapo_cost_profile.json): Empirical H20-3e tier latency profile for `cmlfq_cost` in 8-GPU closed-loop evaluation.
- [config_8gpu_qwen3_4b.yaml](config_8gpu_qwen3_4b.yaml): Static 8-GPU configuration template (`1 Train + TP=1 + TP=2 + TP=4`).
- [config_4gpu_qwen3_4b.yaml](config_4gpu_qwen3_4b.yaml): Static 4-GPU configuration template (`1 Train + TP=1 + TP=2`).
- [config_colab_1gpu.yaml](config_colab_1gpu.yaml): Static 1-GPU Colab co-located configuration template.
- **Runtime dependencies**: In addition to CPU CI deps, GPU execution requires `vllm`, `transformers`, `datasets`, `sympy`, `regex`, `latex2sympy2`, and `word2number` (pre-installed by Colab notebook Cell 1).
Loading
Loading