Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f26eeeb52 | ||
|
|
90e9ae98bf | ||
|
|
67cdc55521 | ||
|
|
d3e478d732 | ||
|
|
d8698f4e53 | ||
|
|
845eb6e6f2 | ||
|
|
eaf95997f7 | ||
|
|
09e11c7527 | ||
|
|
03f7feff14 | ||
|
|
87ab84b666 | ||
|
|
0b37bc923e | ||
|
|
6591943919 | ||
|
|
4748472b9f | ||
|
|
8106bf0a02 | ||
|
|
46653c1d70 | ||
|
|
c5fb9591b2 | ||
|
|
b22e768fc4 | ||
|
|
ef8f459ca0 | ||
|
|
c3c6b70f11 | ||
|
|
f18297fd7d | ||
|
|
6d80c412b6 | ||
|
|
a166a8b8df | ||
|
|
66ff00d117 | ||
|
|
ae610d9dd8 |
@@ -18,7 +18,7 @@ jobs:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
- name: Install dependencies
|
||||
@@ -69,6 +69,12 @@ jobs:
|
||||
- test: reverse_text
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text.py"
|
||||
- test: reverse_text_rl_opd
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
|
||||
- test: reverse_text_rl_sft
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
|
||||
- test: alphabet_sort
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py"
|
||||
@@ -97,7 +103,7 @@ jobs:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
- name: Install dependencies
|
||||
|
||||
@@ -79,7 +79,7 @@ jobs:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
- name: Init public submodules
|
||||
run: |
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
|
||||
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: crazy-max/ghaction-docker-meta@v2
|
||||
|
||||
@@ -10,3 +10,6 @@
|
||||
[submodule "configs/private"]
|
||||
path = configs/private
|
||||
url = git@github.com:PrimeIntellect-ai/research-configs.git
|
||||
[submodule "pydantic-config"]
|
||||
path = deps/pydantic-config
|
||||
url = https://github.com/PrimeIntellect-ai/pydantic-config
|
||||
|
||||
@@ -2,6 +2,14 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **First-class `training_mode` + batch-driven loss dispatch** (collection of removals/renames). Loss selection is now driven by `TrainingSample.training_mode` (`rl` / `opd` / `sft`), set under `[orchestrator]`. The trainer is mode-agnostic and dispatches per batch.
|
||||
- **`orchestrator.use_sft_loss` removed**: replaced by `[orchestrator] training_mode = "sft"`. The orchestrator stamps each sample's `training_mode` and the trainer dispatches to `sft_loss_fn` per batch.
|
||||
- **`orchestrator.teacher_rollout_model` removed (no alias)**: configs must rename to `[orchestrator.teacher]` (`teacher_model` is also accepted as a back-compat alias for `teacher`). Used in both opd and sft modes; the role is determined by `training_mode`.
|
||||
- **`orchestrator.model` → `orchestrator.student`**: renamed for symmetry with `orchestrator.teacher`. Legacy `[orchestrator.model]` and a flat `[orchestrator.model.lora]`-style layout are aliased via a back-compat shim, so most existing configs still parse. New code should use `[orchestrator.student.*]`.
|
||||
- **`trainer.loss.type = "sft"` removed (`SFTLossConfig` deleted)**: zero-field discriminator that is now implied by `training_mode = "sft"`. `trainer.loss` collapsed to a `DefaultLossConfig | CustomLossConfig` union. Existing configs setting `[trainer.loss] type = "sft"` must remove that line; the orchestrator-level `training_mode = "sft"` is enough.
|
||||
- **`trainer.loss.teacher_tau` removed from `DefaultLossConfig`**: the teacher-KL term is now exclusive to `opd_loss_fn` (which inlines `teacher_tau = 1.0`). `default_loss_fn` only handles reward-driven RL and no longer accepts a `teacher_tau`. Configs that set `teacher_tau` on `[trainer.loss]` will fail validation — switch to `[orchestrator] training_mode = "opd"` (which uses `opd_loss_fn` with the value baked in).
|
||||
- **`trainer.loss` only applies to rl-mode batches**: opd and sft don't read `trainer.loss`. `opd_loss_fn`'s knobs (dppo_mask_*, kl_tau) are inlined as literals; tweak them by editing the function. `CustomLossConfig` overrides the rl-mode loss only — opd and sft always use their dedicated fns. (2026-05-19)
|
||||
- **`orchestrator.use_token_client` removed**: The server-tokenized TITO path has been deprecated end-to-end. The orchestrator-side config flag (`use_token_client`), the verifiers client_type (`openai_chat_completions_token`), and the inference server's `/v1/chat/completions/tokens` route (along with the `OpenAIServingChatWithTokens` wrapper) are all gone. The orchestrator now picks between renderer-backed TITO (`use_renderer = true`, default) and MITO (`use_renderer = false`, fallback). Existing configs with `use_token_client = true` must migrate to `use_renderer = true` (or `use_renderer = false` for MITO); configs with `use_token_client = false` can simply drop the field. (2026-05-19)
|
||||
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
|
||||
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
|
||||
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
|
||||
|
||||
@@ -94,7 +94,7 @@ cd prime-rl
|
||||
2. Initialize submodules
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
```
|
||||
|
||||
3. Install [uv](https://docs.astral.sh/uv/)
|
||||
|
||||
+16
-16
@@ -15,34 +15,34 @@
|
||||
"cp": 1,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "83c21ddac",
|
||||
"timestamp": "2026-02-26T02:07:06+00:00",
|
||||
"commit_sha": "0b37bc923",
|
||||
"timestamp": "2026-05-19T01:28:25+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 276.12556480802596
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 16.41977165630161,
|
||||
"std": 0.010586646038388221,
|
||||
"min": 16.407648988464405,
|
||||
"max": 16.42719598975201
|
||||
"mean": 22.77046832707997,
|
||||
"std": 0.03172890658906481,
|
||||
"min": 22.750797215697055,
|
||||
"max": 22.80707156937409
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 1960.9836648020673,
|
||||
"std": 1.2643440104327244,
|
||||
"min": 1959.5358764831926,
|
||||
"max": 1961.8703395331793
|
||||
"mean": 2719.4358949662887,
|
||||
"std": 3.7893259921987053,
|
||||
"min": 2717.086609671837,
|
||||
"max": 2723.8073540657224
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 65.87,
|
||||
"std": 0.13,
|
||||
"min": 65.74,
|
||||
"max": 66.0
|
||||
"mean": 48.285218452724315,
|
||||
"std": 0.06726350421944344,
|
||||
"min": 48.207625919021666,
|
||||
"max": 48.327002701349556
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 31.806640625,
|
||||
"pct": 67.03
|
||||
"gib": 24.248046875,
|
||||
"pct": 51.15428047554115
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-17
@@ -15,34 +15,34 @@
|
||||
"cp": 1,
|
||||
"docker_image": null,
|
||||
"device_name": "NVIDIA RTX A6000",
|
||||
"commit_sha": "83c21ddac",
|
||||
"timestamp": "2026-02-26T02:07:06+00:00",
|
||||
"commit_sha": "0b37bc923",
|
||||
"timestamp": "2026-05-19T01:32:27+00:00",
|
||||
"success": true,
|
||||
"error_reason": null,
|
||||
"time_taken": 291.91085167229176
|
||||
},
|
||||
"metrics": {
|
||||
"mfu": {
|
||||
"mean": 15.634260517326164,
|
||||
"std": 0.009817863071768202,
|
||||
"min": 15.622927380137481,
|
||||
"max": 15.640172924064188
|
||||
"mean": 21.824271379711288,
|
||||
"std": 0.07444985226850119,
|
||||
"min": 21.739369034306105,
|
||||
"max": 21.878404774433935
|
||||
},
|
||||
"throughput": {
|
||||
"mean": 7468.685954343421,
|
||||
"std": 4.690118598479809,
|
||||
"min": 7463.271969943842,
|
||||
"max": 7471.510386564679
|
||||
"mean": 10425.733211800512,
|
||||
"std": 35.565645418564436,
|
||||
"min": 10385.174276894972,
|
||||
"max": 10451.593425935866
|
||||
},
|
||||
"step_time": {
|
||||
"mean": 68.34095695288852,
|
||||
"std": 0.16054587555887065,
|
||||
"min": 68.16114284005016,
|
||||
"max": 68.46991707291454
|
||||
"mean": 50.39627862814814,
|
||||
"std": 0.1756523472528039,
|
||||
"min": 50.26670710090548,
|
||||
"max": 50.59620195720345
|
||||
},
|
||||
"peak_memory": {
|
||||
"gib": 23.25390625,
|
||||
"pct": 49.05701678145735
|
||||
"gib": 17.490234375,
|
||||
"pct": 36.897831788841806
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,4 +45,9 @@ rollouts_per_example = 32
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -46,4 +46,9 @@ rollouts_per_example = 32
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -4,7 +4,7 @@ seq_len = 2048
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
@@ -22,3 +22,8 @@ name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
|
||||
[inference]
|
||||
|
||||
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
|
||||
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
[orchestrator.renderer]
|
||||
preserve_all_thinking = true
|
||||
|
||||
@@ -20,4 +20,8 @@ max_completion_tokens = 128
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -19,4 +19,8 @@ max_completion_tokens = 128
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -31,4 +31,8 @@ id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
enable_lora = true
|
||||
gpu_memory_utilization = 0.7
|
||||
gpu_memory_utilization = 0.7
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -30,4 +30,8 @@ id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
enable_lora = true
|
||||
gpu_memory_utilization = 0.7
|
||||
gpu_memory_utilization = 0.7
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -27,3 +27,7 @@ gpu_memory_utilization = 0.7
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 2048
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -20,3 +20,7 @@ id = "reverse-text"
|
||||
[ckpt]
|
||||
interval = 10
|
||||
resume_step = -1
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# Smoke test for the RL-entrypoint OPD (on-policy distillation) training mode.
|
||||
# The student inference deployment is launched by the rl entrypoint on GPU 0;
|
||||
# the teacher inference server is started externally by the test fixture (see
|
||||
# tests/integration/test_reverse_text_rl_opd.py) on the same GPU. Trainer
|
||||
# takes GPU 1. Training config mirrors `reverse_text/start.toml`.
|
||||
|
||||
max_steps = 5
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-ci"
|
||||
name = "ci-rl-opd"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "opd"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 16
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.4
|
||||
@@ -0,0 +1,48 @@
|
||||
# Smoke test for the RL-entrypoint SFT (on-policy hard distillation) training
|
||||
# mode. The student inference deployment is launched by the rl entrypoint on
|
||||
# GPU 0; the teacher inference server is started externally by the test
|
||||
# fixture (see tests/integration/test_reverse_text_rl_sft.py) on the same GPU.
|
||||
# Trainer takes GPU 1. Training config mirrors `reverse_text/start.toml`.
|
||||
|
||||
max_steps = 5
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-ci"
|
||||
name = "ci-rl-sft"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 16
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.4
|
||||
@@ -28,4 +28,9 @@ args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", que
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference]
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -16,6 +16,7 @@ language_model_attr = "model.language_model"
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
use_renderer = false
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# Training Mode — Debug Configs
|
||||
|
||||
Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) against the `reverse-text` env, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the student.
|
||||
|
||||
| Config | Mode | Teacher | Notes |
|
||||
|---|---|---|---|
|
||||
| `rl.toml` | `rl` | none | |
|
||||
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
|
||||
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
|
||||
| `sft.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
|
||||
| `sft_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
|
||||
| `sft_external.toml` | `sft` | PI inference (`openai/gpt-5-mini`) | external OAI endpoint; no local teacher |
|
||||
|
||||
The student inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local teacher (used by everything except `rl.toml` and `sft_external.toml`) is **not** auto-launched — start it manually on GPU 1.
|
||||
|
||||
## Start the local teacher
|
||||
|
||||
Needed for `opd*.toml` and `sft.toml` / `sft_lora.toml`:
|
||||
|
||||
```bash
|
||||
CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
--server.port 8001 \
|
||||
--gpu-memory-utilization 0.5 \
|
||||
--model.enforce-eager
|
||||
```
|
||||
|
||||
## Run the debug configs
|
||||
|
||||
```bash
|
||||
# RL (no teacher)
|
||||
uv run rl @ configs/debug/training_modes/rl.toml
|
||||
|
||||
# OPD (needs teacher on port 8001)
|
||||
uv run rl @ configs/debug/training_modes/opd.toml
|
||||
uv run rl @ configs/debug/training_modes/opd_lora.toml
|
||||
|
||||
# SFT hard distill (needs teacher on port 8001)
|
||||
uv run rl @ configs/debug/training_modes/sft.toml
|
||||
uv run rl @ configs/debug/training_modes/sft_lora.toml
|
||||
|
||||
# SFT hard distill from openai/gpt-5-mini via PI inference
|
||||
# (requires PRIME_API_KEY + PRIME_TEAM_ID in env; no local teacher needed)
|
||||
uv run rl @ configs/debug/training_modes/sft_external.toml
|
||||
```
|
||||
|
||||
See [docs/training_modes.md](../../docs/training_modes.md) for what each mode does.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/opd.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-opd"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "opd"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,60 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/opd_lora.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-opd-lora"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "opd"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,41 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-rl"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "rl"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,51 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/sft.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-sft"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,55 @@
|
||||
# SFT from openai/gpt-5-mini via PI inference.
|
||||
# Requires PRIME_API_KEY + PRIME_TEAM_ID in the environment.
|
||||
#
|
||||
# Run with:
|
||||
# uv run rl @ configs/debug/training_modes/sft_external.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-sft-external"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
extra_body = { reasoning_effort = "minimal" }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "openai/gpt-5-mini"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["https://api.pinference.ai/api/v1"]
|
||||
api_key_var = "PRIME_API_KEY"
|
||||
|
||||
[orchestrator.teacher.client.headers_from_env]
|
||||
X-Prime-Team-ID = "PRIME_TEAM_ID"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,57 @@
|
||||
# Start the teacher inference server first (on a separate GPU):
|
||||
# CUDA_VISIBLE_DEVICES=1 uv run inference \
|
||||
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
|
||||
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
|
||||
# Then:
|
||||
# uv run rl @ configs/debug/training_modes/sft_lora.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-sft-lora"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 8
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -31,4 +31,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -32,4 +32,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -32,4 +32,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
|
||||
[trainer.model.ac]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
dp = 6
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -6,7 +6,7 @@ project = "gsm8k-debug"
|
||||
name = "gsm8k"
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
@@ -22,4 +22,9 @@ args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
[inference] # Default inference config
|
||||
[inference] # Default inference config
|
||||
|
||||
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
|
||||
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
[orchestrator.renderer]
|
||||
preserve_all_thinking = true
|
||||
|
||||
@@ -36,4 +36,9 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
max_model_len = 8192
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
level = "debug"
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -52,4 +52,8 @@ temperature = 0.5
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference] # Default inference config
|
||||
[inference] # Default inference config
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -11,6 +11,7 @@ language_model_attr = "model.language_model"
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
use_renderer = false
|
||||
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
|
||||
@@ -12,6 +12,7 @@ language_model_attr = "model.language_model"
|
||||
[orchestrator]
|
||||
batch_size = 16
|
||||
rollouts_per_example = 2
|
||||
use_renderer = false
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 32
|
||||
|
||||
+1
Submodule deps/pydantic-config added at 94d71ecdec
Vendored
+1
-1
Submodule deps/renderers updated: 17d0584f87...8704f9d502
Vendored
+1
-1
Submodule deps/verifiers updated: 711a7c705e...58b119fa1b
@@ -8,7 +8,7 @@ Checkpointing is non-standard due to trainer/orchestrator separation and natural
|
||||
|
||||
The default checkpoint directory is `checkpoints` and each checkpoint step will live in a step subdirectory, i.e. `checkpoints/step_{step}`.
|
||||
|
||||
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronoously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
|
||||
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
|
||||
|
||||
## SFT
|
||||
|
||||
@@ -54,4 +54,4 @@ uv run rl \
|
||||
--orchestrator @ path/to/orch.toml \
|
||||
--max-steps 20 \
|
||||
--ckpt.resume-step 10
|
||||
```
|
||||
```
|
||||
|
||||
+1
-1
@@ -30,4 +30,4 @@ name = "Qwen/Qwen-14B"
|
||||
PRIME_MODEL__NAME=Qwen/Qwen3-4B uv run ... @ qwen8b.toml @ qwen14b.toml --model.name Qwen/Qwen3-32B
|
||||
```
|
||||
|
||||
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precedence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
|
||||
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precedence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen3-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ For more details on multi-node deployment options, see the [deployment](deployme
|
||||
|
||||
## SFT
|
||||
|
||||
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seemless post-training workflow.
|
||||
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seamless post-training workflow.
|
||||
|
||||
To start an SFT training, you need to prepare a conversational dataset in either [prompt-completion format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion) or raw `messages` format. If `messages` is provided, the trainer interprets the full conversation as a single sample with an empty prompt and applies role-based loss masking across the whole chat. If both `messages` and `prompt` / `completion` are present, `messages` takes precedence. Single-turn fine-tuning should be compatible with the chat templates of most models. However, to properly handle loss masking, we require that the tokenizer's chat template satisfies a prefix property: the tokenization of any conversation prefix must be a prefix of the tokenization of the full conversation. For instance, tokenizing message 1 should yield a token sequence that forms a prefix of tokenizing messages 1 and 2, which in turn should be a prefix of tokenizing messages 1, 2, 3, and so forth. An example of a chat template that *does not* satisfy this property is Qwen3's chat template, as it strips away past think sections.
|
||||
|
||||
|
||||
+3
-1
@@ -7,6 +7,7 @@
|
||||
"index",
|
||||
"entrypoints",
|
||||
"configs",
|
||||
"training_modes",
|
||||
"environments",
|
||||
"async",
|
||||
"logging",
|
||||
@@ -15,8 +16,9 @@
|
||||
"benchmarking",
|
||||
"deployment",
|
||||
"kubernetes",
|
||||
"testing-moe-at-small-scale",
|
||||
"troubleshooting"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
# On-Policy Distillation
|
||||
|
||||
On-policy distillation uses a teacher model to provide dense token-level feedback during RL training. The student generates rollouts, and the teacher's logprobs guide the student to stay close to stronger behavior while still learning from rewards.
|
||||
|
||||
For more details, see [On-Policy Distillation](https://thinkingmachines.ai/blog/on-policy-distillation/) by Thinking Machines.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Add `num_teacher_gpus` to `[deployment]` and set `teacher_tau > 0`:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
num_teacher_gpus = 2
|
||||
|
||||
[trainer.loss]
|
||||
teacher_tau = 0.5
|
||||
```
|
||||
|
||||
This automatically starts a teacher inference server using the same model as inference. To use a different teacher model:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
num_teacher_gpus = 2
|
||||
|
||||
[teacher_inference.model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
|
||||
[trainer.loss]
|
||||
teacher_tau = 0.5
|
||||
```
|
||||
|
||||
## Using an External Teacher Server
|
||||
|
||||
If the teacher is already running elsewhere:
|
||||
|
||||
```toml
|
||||
[trainer.loss]
|
||||
teacher_tau = 0.5
|
||||
|
||||
[orchestrator.teacher_model.client]
|
||||
base_url = ["http://teacher-server:8000/v1"]
|
||||
|
||||
[orchestrator.teacher_model.model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
|
||||
```
|
||||
|
||||
## Pure Distillation (No Verification)
|
||||
|
||||
For agentic environments where verification is expensive (code execution, tool use, multi-turn interactions), you can skip verification entirely and use only the teacher signal:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
num_teacher_gpus = 2
|
||||
|
||||
[trainer.loss]
|
||||
teacher_tau = 1.0
|
||||
adv_tau = 0.0 # Disable reward-based learning
|
||||
|
||||
[orchestrator.verification]
|
||||
enabled = false # Skip expensive verification
|
||||
```
|
||||
|
||||
This runs pure on-policy distillation: the student learns to match the teacher without needing any reward signal.
|
||||
|
||||
## SFT Distillation ("Hard Distillation") From Teacher Rollouts
|
||||
|
||||
Use this mode when you want to train from teacher-generated completions directly (hard distillation), without teacher token-level logprobs.
|
||||
|
||||
```toml
|
||||
[trainer.loss]
|
||||
type = "sft"
|
||||
|
||||
[orchestrator]
|
||||
use_token_client = false
|
||||
|
||||
[orchestrator.teacher_rollout_model.client]
|
||||
base_url = ["https://your-openai-compatible-endpoint/v1"]
|
||||
skip_model_check = true
|
||||
|
||||
[orchestrator.teacher_rollout_model.model]
|
||||
name = "teacher-model-name"
|
||||
```
|
||||
|
||||
In this mode:
|
||||
- Rollouts are generated from `orchestrator.teacher_rollout_model`
|
||||
- The orchestrator uses text-level reconstruction with the student tokenizer
|
||||
- The RL trainer optimizes masked NLL (`trainer.loss.type = "sft"`)
|
||||
- Omit `[inference]` (no local inference server required)
|
||||
|
||||
### Image Input (VLM) Support
|
||||
|
||||
Yes, image input is supported in SFT/hard-distillation mode when the student model is multimodal (VLM).
|
||||
|
||||
- Prompts can include OpenAI-style image items in `message.content`, e.g. `{"type": "image_url", "image_url": {"url": "data:image/..."}}`
|
||||
- The orchestrator extracts and preprocesses images from trajectory prompts and attaches `pixel_values`/`image_grid_thw` to training samples
|
||||
- No teacher token IDs/logprobs are required; reconstruction still happens from messages
|
||||
|
||||
Notes:
|
||||
- This path currently expects `data:image/...` payloads in message content
|
||||
- The teacher rollout endpoint still needs to be able to handle the same multimodal prompts during generation
|
||||
|
||||
Reference configs:
|
||||
- `configs/alphabet_sort/sft_distill_hard_qwen4b_lora_prime_teacher.toml`
|
||||
- `examples/alphabet_sort/sft_distill_hard.toml`
|
||||
|
||||
## Parameters
|
||||
|
||||
| Parameter | Default | Description |
|
||||
|-----------|---------|-------------|
|
||||
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for teacher server. Auto-starts server when set. |
|
||||
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Set `> 0` to enable. |
|
||||
| `trainer.loss.adv_tau` | `1.0` | Weight for RL advantage signal. Set `0` for pure distillation. |
|
||||
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
|
||||
|
||||
## Monitoring
|
||||
|
||||
The `teacher_kl` metric shows the KL divergence from teacher to student. Lower values mean the student is closer to the teacher.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Training Modes
|
||||
|
||||
PRIME-RL supports three training modes through our RL trainer, selected via `training_mode`:
|
||||
|
||||
- **`rl`** — reinforcement learning: student generates rollouts, no teacher
|
||||
- **`opd`** — [on-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): students generates rollouts, train to minimize the KL divergence between the student and teacher's logprobs for each token in the rollout
|
||||
- **`sft`** — supervised fine-tuning on teacher-generated rollouts
|
||||
|
||||
> Note: PRIME-RL also has a dedicated `sft` entrypoint for more traditional supervised fine-tuning from a HF dataset. When using the `sft` training mode on the orchestrator, teacher rollouts are generated on-the-fly and used for training.
|
||||
|
||||
The mode determines who generates rollouts, what role the teacher plays, and what must be configured.
|
||||
|
||||
| Mode | Student | Teacher |
|
||||
|---|---|---|
|
||||
| `rl` | required | forbidden |
|
||||
| `opd` | required | required (local vLLM) |
|
||||
| `sft` | required | required (any OAI-compatible endpoint) |
|
||||
|
||||
**SFT vs OPD teachers** differ in what the orchestrator asks of them. SFT only calls `/v1/chat/completions` to generate rollouts — any OpenAI-compatible endpoint works (PI inference, OpenAI, Anthropic, a local vLLM). OPD additionally needs token-level logprobs scored over the student's tokens, which today only vLLM's `/inference/v1/generate` with `prompt_logprobs` exposes — so the OPD teacher must be a vLLM server.
|
||||
|
||||
### Reference configs
|
||||
|
||||
Debug-scale configs for all three modes (and LoRA variants) live in [`configs/debug/training_modes/`](../configs/debug/training_modes/):
|
||||
|
||||
- `rl.toml` / `opd.toml` / `opd_lora.toml`
|
||||
- `sft.toml` / `sft_lora.toml` (local vLLM teacher)
|
||||
- `sft_external.toml` (PI inference teacher)
|
||||
|
||||
See [`configs/debug/training_modes/README.md`](../configs/debug/training_modes/README.md) for run commands.
|
||||
|
||||
## Parameter reference
|
||||
|
||||
| Parameter | Default | Description |
|
||||
|-----------|---------|-------------|
|
||||
| `training_mode` | `"rl"` | One of `rl`, `opd`, `sft`. Propagates to `orchestrator.training_mode` and (for sft) `trainer.loss.type`. |
|
||||
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for the teacher vLLM server. Auto-starts when set. OPD only. |
|
||||
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Must be `> 0` in OPD. |
|
||||
| `trainer.loss.adv_tau` | `1.0` | Weight for the RL advantage signal. Set `0` for pure distillation. |
|
||||
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
|
||||
@@ -39,7 +39,7 @@ Interleaving enforces a strict invariant:
|
||||
|
||||
> The prompt at turn $t$ must be the exact concatenation of prior messages exactly as the LLM originally generated them
|
||||
|
||||
We call this the "exact prefix" invariant. For example, at turn 2, the LLM should see U1,A1,U2 as the prompt, where U1 exactly matches the user message in turn 1 and A1 exactly matches the produced assistant message in turn 1. Any violation to this invariant will result in downstream problems when computing the importance sampling ratio during training.
|
||||
We call this the "exact prefix" invariant. For example, at turn 2, the LLM should see U1,A1,U2 as the prompt, where U1 exactly matches the user message in turn 1 and A1 exactly matches the produced assistant message in turn 1. Any violation of this invariant will result in downstream problems when computing the importance sampling ratio during training.
|
||||
|
||||
For example, assume that at turn 2 the prompt is U1,A1',U2 where A1' varies from A1. In this scenario it is not clear whether to add A1 or A1' to the interleaved rollout:
|
||||
- If we add A1', the logprobs from turn 1 might be off because the inference LLM produced A1 but the trainer LLM is computing logprobs for A1'
|
||||
|
||||
@@ -12,7 +12,7 @@ ulimit -n 32000
|
||||
|
||||
Assuming this is happening on the RL or SFT trainer, you can try the following:
|
||||
- Use full activation checkpointing (`--model.ac`)
|
||||
- Reduce the the micro batch size (`--data.micro-batch-size`) and sequence length (`--data.seq-len`)
|
||||
- Reduce the micro batch size (`--data.micro-batch-size`) and sequence length (`--data.seq-len`)
|
||||
- (*Experimental*) Use context parallelism with `--model.cp`
|
||||
|
||||
> I cannot pass my TOML config file
|
||||
|
||||
@@ -94,4 +94,8 @@ args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200
|
||||
id = "aime2025"
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
tp = 8
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
max_steps = 24
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
type = "single_node"
|
||||
gpus_per_node = 2
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 0
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[wandb]
|
||||
project = "alphabet-sort-sft-distill"
|
||||
name = "qwen3-4b-hard-distill"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 16
|
||||
alpha = 32
|
||||
|
||||
[trainer.ckpt.weights]
|
||||
save_adapter_separately = true
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 4
|
||||
use_token_client = false
|
||||
use_sft_loss = true
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
temperature = 0.7
|
||||
|
||||
[orchestrator.teacher_rollout_model.client]
|
||||
base_url = ["https://api.pinference.ai/api/v1"]
|
||||
api_key_var = "PRIME_API_KEY"
|
||||
|
||||
[orchestrator.teacher_rollout_model.model]
|
||||
name = "qwen/qwen3-235b-a22b-instruct-2507"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
|
||||
@@ -34,4 +34,9 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
seq_len = 16384
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 8192
|
||||
max_model_len = 8192
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
|
||||
@@ -68,4 +68,8 @@ hard_threshold = 0.0
|
||||
seed = 42
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
tp = 8
|
||||
|
||||
# PrimeIntellect/MiniMax-M2.5-bf16 — template-identical to MiniMaxAI/MiniMax-M2.5 (mapped).
|
||||
[orchestrator.renderer]
|
||||
name = "minimax-m2"
|
||||
|
||||
@@ -23,4 +23,8 @@ lr = 3e-6
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference]
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
|
||||
@@ -29,3 +29,10 @@ max_completion_tokens = 1024
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
# Qwen3 finetune with the standard PI template patch (byte-identical to
|
||||
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
|
||||
# Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
preserve_all_thinking = true
|
||||
|
||||
@@ -9,7 +9,7 @@ name = "PrimeIntellect/Qwen3-1.7B"
|
||||
name = "willcb/V3-wordle"
|
||||
seq_len = 1024
|
||||
batch_size = 64
|
||||
micro-batch-size = 1
|
||||
micro_batch_size = 1
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
@@ -6,10 +6,13 @@ readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
dependencies = [
|
||||
"pydantic>=1.10.13",
|
||||
# The PyPI package named `pydantic-config` is a different project that
|
||||
# doesn't expose `BaseConfig` / `cli`. Pin to samsja's fork so plain
|
||||
# `pip install prime-rl-configs` (no uv workspace context) resolves it.
|
||||
"pydantic-config @ git+https://github.com/samsja/pydantic_config.git",
|
||||
"prime-pydantic-config>=0.3.0.dev82",
|
||||
# OrchestratorConfig validates renderer.name='auto' against
|
||||
# renderers.base.MODEL_RENDERER_MAP. Renderers itself is light; its only
|
||||
# weighty transitive (transformers) is lazy-imported via the validator,
|
||||
# so plain `from prime_rl.configs.orchestrator import OrchestratorConfig`
|
||||
# still doesn't pull it into sys.modules.
|
||||
"renderers>=0.1.8.dev4",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
]
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic import model_validator
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
@@ -9,18 +8,15 @@ from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class EnvServerConfig(BaseConfig):
|
||||
"""Configures an environment server."""
|
||||
|
||||
env: EnvConfig = EnvConfig()
|
||||
log: LogConfig = LogConfig()
|
||||
env_install_prerelease: bool = False
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
Field(
|
||||
description="Directory to write outputs to. Will be populated with checkpoints, weights, rollouts and logs as subdirectories. Should be set to a persistent directory with enough disk space. This value should be distinct across experiments running on a single node. See the README for more details."
|
||||
),
|
||||
] = Path("outputs")
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
env_install_prerelease: bool = False
|
||||
"""Allow pre-release versions when installing environments. Passes ``--prerelease`` to ``prime env install``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_num_workers(self):
|
||||
|
||||
@@ -2,7 +2,7 @@ from argparse import Namespace
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic_config import BaseConfig
|
||||
|
||||
from prime_rl.configs.shared import BaseModelConfig, SlurmConfig
|
||||
@@ -12,122 +12,61 @@ from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
|
||||
|
||||
|
||||
class ServerConfig(BaseConfig):
|
||||
"""Configures the inference server."""
|
||||
host: str | None = None
|
||||
"""Host to bind to."""
|
||||
|
||||
host: Annotated[str | None, Field(description="The host to bind to.")] = None
|
||||
port: Annotated[int, Field(description="The port to bind to.")] = 8000
|
||||
liveness_timeout_seconds: Annotated[
|
||||
float,
|
||||
Field(
|
||||
gt=0,
|
||||
description=(
|
||||
"Timeout in seconds for the /liveness endpoint's internal vLLM worker RPC. "
|
||||
"If Kubernetes liveness probes are enabled, keep the probe timeoutSeconds at least this high."
|
||||
),
|
||||
),
|
||||
] = 30.0
|
||||
port: int = 8000
|
||||
"""Port to bind to."""
|
||||
|
||||
liveness_timeout_seconds: float = Field(30.0, gt=0)
|
||||
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. With Kubernetes liveness probes, keep the probe ``timeoutSeconds`` at least this high."""
|
||||
|
||||
|
||||
class ParallelConfig(BaseConfig):
|
||||
"""Configures multi-node and multi-GPU setups through different types of parallelism (TP, DP, PP)."""
|
||||
tp: int = 1
|
||||
"""Tensor parallel size. Forwarded to vLLM as ``--tensor-parallel-size``."""
|
||||
|
||||
tp: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="The tensor parallel size. It is passed to vLLM as `--tensor-parallel-size`",
|
||||
),
|
||||
] = 1
|
||||
|
||||
dp: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="The data parallel size. It is passed to vLLM as `--data-parallel-size`",
|
||||
),
|
||||
] = 1
|
||||
dp: int = Field(1, ge=1)
|
||||
"""Data parallel size. Forwarded to vLLM as ``--data-parallel-size``."""
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"tp={self.tp} dp={self.dp}"
|
||||
|
||||
|
||||
class ModelConfig(BaseModelConfig):
|
||||
"""Configures the inference model. Most arguments are passed directly to the vLLM LLM class (https://docs.vllm.ai/en/latest/api/vllm.LLM.html)."""
|
||||
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
|
||||
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models. Forwarded as ``--dtype``."""
|
||||
|
||||
dtype: Annotated[
|
||||
Literal["auto", "float16", "bfloat16", "float32"],
|
||||
Field(
|
||||
description="Data type for model weights and activations. If 'auto' will use FP16 precision for FP32 and FP16 models, and BF16 precision for BF16 models. Passed to vLLM as `--dtype`",
|
||||
),
|
||||
] = "auto"
|
||||
max_model_len: int | None = None
|
||||
"""Maximum model context length. If None, uses the model config's value. Forwarded as ``--max-model-len``."""
|
||||
|
||||
max_model_len: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Maximum model context length. If None, will use the maximum context length from model config. Passed to vLLM as `--max-model-len`",
|
||||
),
|
||||
] = None
|
||||
enforce_eager: bool = False
|
||||
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance. Forwarded as ``--enforce-eager``."""
|
||||
|
||||
enforce_eager: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to enforce eager mode. If False, will use PyTorch eager and cuda graphs in hybrid for maximal performance. Passed to vLLM as `--enforce-eager`",
|
||||
),
|
||||
] = False
|
||||
trust_remote_code: bool = False
|
||||
"""Trust remote code. Forwarded to vLLM engine init."""
|
||||
|
||||
trust_remote_code: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to trust remote code. Passed to vLLM engine init",
|
||||
),
|
||||
] = False
|
||||
chat_template: str | None = None
|
||||
"""Chat template — a Jinja2 template string or path to a template file. Forwarded as ``--chat-template``. If None, uses the model's default."""
|
||||
|
||||
chat_template: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Chat template to use. Can be a Jinja2 template string or a path to a template file. "
|
||||
"Passed to vLLM as `--chat-template`. If None, uses the model's default.",
|
||||
),
|
||||
] = None
|
||||
tool_call_parser: str | None = "auto"
|
||||
"""Tool-call parser. Forwarded as ``--tool-call-parser``. Set to ``auto`` to infer from the model name."""
|
||||
|
||||
tool_call_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
|
||||
'Set to "auto" to infer from the model name.',
|
||||
),
|
||||
] = "auto"
|
||||
reasoning_parser: str | None = None
|
||||
"""Parser for extracting reasoning content from model outputs. Forwarded as ``--reasoning-parser``. Setting this enables reasoning mode."""
|
||||
|
||||
reasoning_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Parser for extracting reasoning content from model outputs. Passed to vLLM as `--reasoning-parser`. Setting this enables reasoning mode.",
|
||||
),
|
||||
] = None
|
||||
|
||||
rope_scaling: Annotated[
|
||||
dict[str, Any] | str | None,
|
||||
Field(
|
||||
description='RoPE scaling configuration as a dict. For YaRN, use: {rope_type="yarn", factor=4.0, original_max_position_embeddings=32768} or. Passed to vLLM as `--rope-scaling`.',
|
||||
),
|
||||
] = None
|
||||
rope_scaling: dict[str, Any] | str | None = None
|
||||
"""RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``). Forwarded as ``--rope-scaling``."""
|
||||
|
||||
|
||||
class WeightBroadcastConfig(BaseConfig):
|
||||
"""Configures weight broadcast settings."""
|
||||
|
||||
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
|
||||
"filesystem"
|
||||
)
|
||||
type: Literal["nccl", "filesystem"] = "filesystem"
|
||||
"""Weight broadcast transport."""
|
||||
|
||||
|
||||
class KVCacheOffloadConfig(BaseModel):
|
||||
"""CPU KV cache offloading for vLLM inference workers."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
cpu_bytes: Annotated[int, Field(gt=0, description="CPU bytes available for KV cache offloading per worker.")] = (
|
||||
1_000_000_000
|
||||
)
|
||||
class KVCacheOffloadConfig(BaseConfig):
|
||||
cpu_bytes: int = Field(1_000_000_000, gt=0)
|
||||
"""CPU bytes available for KV cache offloading per worker."""
|
||||
|
||||
|
||||
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
|
||||
@@ -144,81 +83,70 @@ All2AllBackend = Literal[
|
||||
]
|
||||
|
||||
|
||||
class BaseInferenceDeploymentConfig(BaseModel):
|
||||
"""Base deployment config for inference."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
|
||||
class BaseInferenceDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
|
||||
|
||||
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
"""Configures a single-node inference deployment."""
|
||||
|
||||
type: Literal["single_node"] = "single_node"
|
||||
|
||||
|
||||
# Multi-node inference: each node runs an independent vLLM replica.
|
||||
class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
"""Configures a multi-node inference deployment. Each node runs an independent vLLM replica."""
|
||||
|
||||
type: Literal["multi_node"] = "multi_node"
|
||||
|
||||
num_nodes: Annotated[int, Field(ge=1, description="Number of inference nodes.")] = 2
|
||||
num_nodes: int = Field(2, ge=1)
|
||||
"""Inference nodes."""
|
||||
|
||||
router_port: Annotated[int, Field(description="Port for the vllm-router.")] = 8000
|
||||
backend_port: Annotated[int, Field(description="Port for vLLM backend instances.")] = 8100
|
||||
router_policy: Annotated[
|
||||
str, Field(description="Routing policy for the vllm-router (e.g. 'consistent_hash', 'round_robin').")
|
||||
] = "consistent_hash"
|
||||
router_port: int = 8000
|
||||
"""Port for the vllm-router."""
|
||||
|
||||
backend_port: int = 8100
|
||||
"""Port for vLLM backend instances."""
|
||||
|
||||
router_policy: str = "consistent_hash"
|
||||
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
|
||||
|
||||
|
||||
# Disaggregated prefill/decode inference. Each replica is split into separate
|
||||
# prefill and decode node groups. Requires NIXL for KV transfer and a vllm-router
|
||||
# for request routing. Multi-replica: set ``num_prefill_replicas`` /
|
||||
# ``num_decode_replicas`` to run multiple independent vLLM instances within the
|
||||
# prefill / decode node groups. E.g. ``num_prefill_nodes=4, num_prefill_replicas=2``
|
||||
# creates two prefill vLLM instances each spanning 2 nodes (EP16 with 8 GPUs/node).
|
||||
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
"""Configures a disaggregated prefill/decode inference deployment.
|
||||
|
||||
Each inference replica is split into separate prefill and decode node groups.
|
||||
Requires NIXL for KV transfer and a vllm-router for request routing.
|
||||
|
||||
Multi-replica support: set ``num_prefill_replicas`` / ``num_decode_replicas``
|
||||
to run multiple independent vLLM instances within the prefill / decode node
|
||||
groups. For example, ``num_prefill_nodes=4, num_prefill_replicas=2`` creates
|
||||
two prefill vLLM instances each spanning 2 nodes (EP16 with 8 GPUs/node).
|
||||
"""
|
||||
|
||||
type: Literal["disaggregated"] = "disaggregated"
|
||||
|
||||
num_prefill_nodes: Annotated[int, Field(ge=1, description="Total number of prefill nodes.")] = 1
|
||||
num_decode_nodes: Annotated[int, Field(ge=1, description="Total number of decode nodes.")] = 1
|
||||
num_prefill_nodes: int = Field(1, ge=1)
|
||||
"""Total prefill nodes."""
|
||||
|
||||
num_prefill_replicas: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Number of independent prefill vLLM instances. Must evenly divide num_prefill_nodes.",
|
||||
),
|
||||
] = 1
|
||||
num_decode_replicas: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Number of independent decode vLLM instances. Must evenly divide num_decode_nodes.",
|
||||
),
|
||||
] = 1
|
||||
num_decode_nodes: int = Field(1, ge=1)
|
||||
"""Total decode nodes."""
|
||||
|
||||
router_port: Annotated[int, Field(description="Port for the vllm-router on each replica.")] = 8000
|
||||
prefill_port: Annotated[int, Field(description="Port for prefill vLLM instances.")] = 8100
|
||||
decode_port: Annotated[int, Field(description="Port for decode vLLM instances.")] = 8200
|
||||
router_policy: Annotated[
|
||||
str, Field(description="Routing policy for the vllm-router (e.g. 'consistent_hash', 'round_robin').")
|
||||
] = "consistent_hash"
|
||||
num_prefill_replicas: int = Field(1, ge=1)
|
||||
"""Independent prefill vLLM instances. Must evenly divide ``num_prefill_nodes``."""
|
||||
|
||||
prefill_env_overrides: Annotated[
|
||||
dict[str, str],
|
||||
Field(description="Extra environment variables exported only on prefill nodes."),
|
||||
] = {}
|
||||
decode_env_overrides: Annotated[
|
||||
dict[str, str],
|
||||
Field(description="Extra environment variables exported only on decode nodes."),
|
||||
] = {}
|
||||
num_decode_replicas: int = Field(1, ge=1)
|
||||
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
|
||||
|
||||
router_port: int = 8000
|
||||
"""Port for the vllm-router on each replica."""
|
||||
|
||||
prefill_port: int = 8100
|
||||
"""Port for prefill vLLM instances."""
|
||||
|
||||
decode_port: int = 8200
|
||||
"""Port for decode vLLM instances."""
|
||||
|
||||
router_policy: str = "consistent_hash"
|
||||
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
|
||||
|
||||
prefill_env_overrides: dict[str, str] = {}
|
||||
"""Extra environment variables exported only on prefill nodes."""
|
||||
|
||||
decode_env_overrides: dict[str, str] = {}
|
||||
"""Extra environment variables exported only on decode nodes."""
|
||||
|
||||
@property
|
||||
def num_nodes(self) -> int:
|
||||
@@ -246,200 +174,96 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
|
||||
|
||||
class InferenceExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for inference."""
|
||||
pass
|
||||
|
||||
|
||||
class InferenceConfig(BaseConfig):
|
||||
"""Configures inference."""
|
||||
|
||||
# The server configuration
|
||||
server: ServerConfig = ServerConfig()
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = Field(default_factory=ModelConfig)
|
||||
|
||||
# The parallel configuration
|
||||
parallel: ParallelConfig = ParallelConfig()
|
||||
"""Multi-node and multi-GPU parallelism (TP, DP, PP)."""
|
||||
|
||||
enable_lora: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to enable LORA. Passed to vLLM as `--enable-lora`",
|
||||
),
|
||||
] = False
|
||||
enable_lora: bool = False
|
||||
"""Enable LoRA. Forwarded as ``--enable-lora``."""
|
||||
|
||||
max_loras: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="The maximum number of LoRAs to use. Passed to vLLM as `--max-loras`",
|
||||
),
|
||||
] = 8
|
||||
max_loras: int = 8
|
||||
"""Maximum number of LoRAs. Forwarded as ``--max-loras``."""
|
||||
|
||||
# TODO: The default value is very high because our areal impl for lora isn't ideal
|
||||
# We add a lora with the same name instead of changing weights inplace
|
||||
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
|
||||
max_cpu_loras: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="The maximum number of LoRAs to use on CPU. Passed to vLLM as `--max-cpu-loras`",
|
||||
),
|
||||
] = 100
|
||||
max_cpu_loras: int = 100
|
||||
"""Maximum number of LoRAs on CPU. Forwarded as ``--max-cpu-loras``."""
|
||||
|
||||
max_lora_rank: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="The maximum LoRA rank to use. Passed to vLLM as `--max-lora-rank`",
|
||||
),
|
||||
] = None
|
||||
max_lora_rank: int | None = None
|
||||
"""Maximum LoRA rank. Forwarded as ``--max-lora-rank``."""
|
||||
|
||||
lora_target_modules: Annotated[
|
||||
list[str] | None,
|
||||
Field(
|
||||
description="The target modules for LoRA. Passed to vLLM as `--lora-target-modules`.",
|
||||
),
|
||||
] = None
|
||||
lora_target_modules: list[str] | None = None
|
||||
"""LoRA target modules. Forwarded as ``--lora-target-modules``."""
|
||||
|
||||
enable_prefix_caching: Annotated[
|
||||
bool | None,
|
||||
Field(
|
||||
description="Whether to enable prefix caching. Passed to vLLM as `--enable-prefix-caching`",
|
||||
),
|
||||
] = None
|
||||
enable_prefix_caching: bool | None = None
|
||||
"""Enable prefix caching. Forwarded as ``--enable-prefix-caching``."""
|
||||
|
||||
gpu_memory_utilization: Annotated[
|
||||
float,
|
||||
Field(
|
||||
description="The GPU memory utilization to use. Passed to vLLM as `--gpu-memory-utilization`",
|
||||
),
|
||||
] = 0.9
|
||||
gpu_memory_utilization: float = 0.9
|
||||
"""GPU memory utilization. Forwarded as ``--gpu-memory-utilization``."""
|
||||
|
||||
api_server_count: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=0,
|
||||
description="The number of API servers to use. Passed to vLLM as `--api-server-count`. Set to 0 for headless mode.",
|
||||
),
|
||||
] = 1
|
||||
api_server_count: int = Field(1, ge=0)
|
||||
"""API servers to run. Forwarded as ``--api-server-count``. Set to 0 for headless mode."""
|
||||
|
||||
data_parallel_size_local: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Number of data parallel replicas to run on this node. Passed to vLLM as `--data-parallel-size-local`.",
|
||||
),
|
||||
] = None
|
||||
data_parallel_size_local: int | None = Field(None, ge=1)
|
||||
"""Data parallel replicas to run on this node. Forwarded as ``--data-parallel-size-local``."""
|
||||
|
||||
data_parallel_rpc_port: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
le=65535,
|
||||
description="RPC port for data parallel communication. Passed to vLLM as `--data-parallel-rpc-port`.",
|
||||
),
|
||||
] = 13345
|
||||
data_parallel_rpc_port: int = Field(13345, ge=1, le=65535)
|
||||
"""RPC port for data parallel communication. Forwarded as ``--data-parallel-rpc-port``."""
|
||||
|
||||
seed: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Seed the inference components. Passed to vLLM as `--seed`",
|
||||
),
|
||||
] = 0
|
||||
seed: int = 0
|
||||
"""Seed the inference components. Forwarded as ``--seed``."""
|
||||
|
||||
enable_expert_parallel: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Enable expert parallelism for MoE models. Passed to vLLM as `--enable-expert-parallel`.",
|
||||
),
|
||||
] = False
|
||||
enable_expert_parallel: bool = False
|
||||
"""Enable expert parallelism for MoE models. Forwarded as ``--enable-expert-parallel``."""
|
||||
|
||||
all2all_backend: Annotated[
|
||||
All2AllBackend,
|
||||
Field(
|
||||
description="All-to-all backend for expert parallel communication. Passed to vLLM as `--all2all-backend`.",
|
||||
),
|
||||
] = "allgather_reducescatter"
|
||||
all2all_backend: All2AllBackend = "allgather_reducescatter"
|
||||
"""All-to-all backend for expert-parallel communication. Forwarded as ``--all2all-backend``."""
|
||||
|
||||
enable_eplb: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Enable expert parallel load balancer (EPLB). Passed to vLLM as `--enable-eplb`.",
|
||||
),
|
||||
] = False
|
||||
enable_eplb: bool = False
|
||||
"""Enable expert parallel load balancer (EPLB). Forwarded as ``--enable-eplb``."""
|
||||
|
||||
enable_dbo: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Enable dual batch overlap (DBO). Passed to vLLM as `--enable-dbo`.",
|
||||
),
|
||||
] = False
|
||||
enable_dbo: bool = False
|
||||
"""Enable dual batch overlap (DBO). Forwarded as ``--enable-dbo``."""
|
||||
|
||||
use_deep_gemm: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Force DeepGEMM FP8 kernels via VLLM_USE_DEEP_GEMM=1. Only works with per-tensor FP8 quantization (e.g. GLM-5-FP8).",
|
||||
),
|
||||
] = False
|
||||
use_deep_gemm: bool = False
|
||||
"""Force DeepGEMM FP8 kernels via ``VLLM_USE_DEEP_GEMM=1``. Only works with per-tensor FP8 quantization (e.g. GLM-5-FP8)."""
|
||||
|
||||
weight_broadcast: Annotated[WeightBroadcastConfig, Field(description="The weight broadcast config.")] = (
|
||||
WeightBroadcastConfig()
|
||||
)
|
||||
weight_broadcast: WeightBroadcastConfig = WeightBroadcastConfig()
|
||||
|
||||
kv_cache_offload: Annotated[
|
||||
KVCacheOffloadConfig | None,
|
||||
Field(
|
||||
description=(
|
||||
"CPU KV cache offload config for inference workers. Standard inference uses vLLM's "
|
||||
"OffloadingConnector. Disaggregated P/D deployments combine it with NIXL through "
|
||||
"MultiConnector in the SLURM launcher."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
kv_cache_offload: KVCacheOffloadConfig | None = None
|
||||
"""CPU KV cache offload for inference workers. Standard inference uses vLLM's ``OffloadingConnector``. Disaggregated P/D deployments combine it with NIXL through ``MultiConnector`` in the SLURM launcher."""
|
||||
|
||||
enable_return_routed_experts: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts`",
|
||||
),
|
||||
] = False
|
||||
enable_return_routed_experts: bool = False
|
||||
"""Return routed experts in responses. Forwarded as ``--enable-return-routed-experts``."""
|
||||
|
||||
enable_fp32_lm_head: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Run the lm_head projection in fp32 via a native bf16xbf16 -> fp32 GEMM (`torch.mm` with `out_dtype=torch.float32`). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's `--enable-fp32-lm-head`. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting `additional_config[\"fp32_lm_head\"] = True` on the vLLM config.",
|
||||
),
|
||||
] = False
|
||||
enable_fp32_lm_head: bool = False
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
|
||||
|
||||
vllm_extra: Annotated[
|
||||
dict[str, Any],
|
||||
Field(
|
||||
description="Extra arguments to pass to vLLM. These are applied as attributes on the vLLM namespace after config translation.",
|
||||
),
|
||||
] = {}
|
||||
vllm_extra: dict[str, Any] = {}
|
||||
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
|
||||
|
||||
# Launcher-only fields
|
||||
|
||||
deployment: Annotated[
|
||||
InferenceDeploymentConfig,
|
||||
Field(
|
||||
description="Deployment configuration for inference.",
|
||||
),
|
||||
] = SingleNodeInferenceDeploymentConfig()
|
||||
deployment: InferenceDeploymentConfig = SingleNodeInferenceDeploymentConfig()
|
||||
|
||||
slurm: Annotated[
|
||||
SlurmConfig | None,
|
||||
Field(
|
||||
description="SLURM configuration. If set, the run will be submitted as a SLURM job instead of running locally.",
|
||||
),
|
||||
] = None
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
|
||||
|
||||
output_dir: Annotated[Path, Field(description="Directory for SLURM logs and generated scripts.")] = Path("outputs")
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory for SLURM logs and generated scripts."""
|
||||
|
||||
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: Annotated[
|
||||
InferenceExperimentalConfig,
|
||||
Field(description="Experimental features for inference."),
|
||||
] = InferenceExperimentalConfig()
|
||||
experimental: InferenceExperimentalConfig = InferenceExperimentalConfig()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_multi_node_requires_slurm(self):
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,7 @@ import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
@@ -53,47 +53,38 @@ from prime_rl.utils.validation import (
|
||||
|
||||
|
||||
class RLExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for RL training."""
|
||||
pass
|
||||
|
||||
|
||||
class SharedLogConfig(BaseConfig):
|
||||
"""Configures shared logging."""
|
||||
level: str | None = None
|
||||
"""Log level for trainer and orchestrator. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
|
||||
|
||||
level: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The log level to use. When unset, the trainer and orchestrator log levels are used as-is (which themselves default to the PRIME_LOG_LEVEL env var if set, else 'info').",
|
||||
),
|
||||
] = None
|
||||
|
||||
json_logging: Annotated[
|
||||
bool,
|
||||
Field(description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.)."),
|
||||
] = False
|
||||
json_logging: bool = False
|
||||
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
|
||||
|
||||
|
||||
class SharedWandbConfig(BaseConfig):
|
||||
"""Configures shared W&B configs."""
|
||||
project: str | None = "prime-rl"
|
||||
"""W&B project."""
|
||||
|
||||
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
|
||||
entity: str | None = None
|
||||
"""W&B entity."""
|
||||
|
||||
entity: Annotated[str | None, Field(description="The W&B entity to use.")] = None
|
||||
name: str | None = None
|
||||
"""W&B run name."""
|
||||
|
||||
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
|
||||
group: str | None = None
|
||||
"""W&B group."""
|
||||
|
||||
group: Annotated[str | None, Field(description="The W&B group to use.")] = None
|
||||
tags: list[str] | None = None
|
||||
"""W&B tags attached to the run."""
|
||||
|
||||
tags: Annotated[list[str] | None, Field(description="The W&B tags to attach to the run.")] = None
|
||||
offline: bool | None = False
|
||||
"""Run W&B in offline mode."""
|
||||
|
||||
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
|
||||
|
||||
shared: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Use shared W&B mode to log trainer and orchestrator metrics to a single run. "
|
||||
"Requires wandb SDK >= 0.19.9. Incompatible with offline mode.",
|
||||
),
|
||||
] = True
|
||||
shared: bool = True
|
||||
"""Log trainer and orchestrator metrics to a single shared W&B run. Requires wandb SDK ≥ 0.19.9. Incompatible with offline mode."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_shared_not_offline(self):
|
||||
@@ -103,88 +94,60 @@ class SharedWandbConfig(BaseConfig):
|
||||
|
||||
|
||||
class SharedCheckpointConfig(BaseConfig):
|
||||
"""Configures shared checkpoint configs."""
|
||||
output_dir: Path | None = None
|
||||
"""Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer ``output_dir``."""
|
||||
|
||||
output_dir: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer output_dir.",
|
||||
),
|
||||
] = None
|
||||
interval: int | None = None
|
||||
"""Interval at which to save checkpoints."""
|
||||
|
||||
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
|
||||
resume_step: int | None = None
|
||||
"""Step to resume from. If None, does not resume from a checkpoint."""
|
||||
|
||||
resume_step: Annotated[
|
||||
int | None, Field(description="The step to resume from. If None, will not resume from a checkpoint.")
|
||||
] = None
|
||||
keep_last: int | None = Field(None, ge=1)
|
||||
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
|
||||
|
||||
keep_last: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency.",
|
||||
),
|
||||
] = None
|
||||
|
||||
keep_interval: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Keep checkpoints at every N steps permanently (e.g., keep_interval=100 keeps step 100, 200, ...). If None, no interval-based keeping.",
|
||||
),
|
||||
] = None
|
||||
keep_interval: int | None = Field(None, ge=1)
|
||||
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
|
||||
|
||||
|
||||
class SharedModelConfig(BaseConfig):
|
||||
"""Configures shared model settings."""
|
||||
name: str = "Qwen/Qwen3-0.6B"
|
||||
"""HF model name or local path."""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
Field(description="The name of the model to use."),
|
||||
] = "Qwen/Qwen3-0.6B"
|
||||
|
||||
vlm: Annotated[
|
||||
"VLMConfig | None",
|
||||
Field(description="VLM configuration. Set to enable vision-language model support."),
|
||||
] = None
|
||||
vlm: "VLMConfig | None" = None
|
||||
"""VLM configuration. Set this to enable vision-language model support."""
|
||||
|
||||
|
||||
class SharedWeightBroadcastConfig(BaseConfig):
|
||||
"""Configures shared weight broadcast settings."""
|
||||
type: Literal["nccl", "filesystem"] = "filesystem"
|
||||
"""Weight broadcast transport."""
|
||||
|
||||
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
|
||||
"filesystem"
|
||||
)
|
||||
port: int = 29501
|
||||
"""Port for NCCL weight broadcast."""
|
||||
|
||||
port: Annotated[int, Field(description="The port to use for NCCL weight broadcast.")] = 29501
|
||||
timeout: Annotated[int, Field(description="The timeout in seconds for NCCL weight broadcast.")] = 1200
|
||||
quantize_in_weight_transfer: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"Use kernel-format FP8 quantized NCCL transfer for weight updates. "
|
||||
"When disabled, uses default HF checkpoint-format transfer."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for NCCL weight broadcast."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
|
||||
|
||||
|
||||
class BaseDeploymentConfig(BaseModel):
|
||||
"""Configures a base deployment."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
|
||||
class BaseDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
|
||||
|
||||
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
"""Configures a single node deployment."""
|
||||
|
||||
type: Literal["single_node"] = "single_node"
|
||||
|
||||
num_train_gpus: Annotated[int, Field(description="Number of training GPUs")] = 1
|
||||
num_infer_gpus: Annotated[int, Field(description="Number of inference GPUs")] = 1
|
||||
num_teacher_gpus: Annotated[int | None, Field(description="Number of teacher inference GPUs")] = None
|
||||
num_train_gpus: int = 1
|
||||
"""GPUs allocated to the trainer."""
|
||||
|
||||
num_infer_gpus: int = 1
|
||||
"""GPUs allocated to inference."""
|
||||
|
||||
num_teacher_gpus: int | None = None
|
||||
"""GPUs allocated to teacher inference (None disables the teacher server)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_gpu_count(self):
|
||||
@@ -198,33 +161,22 @@ class SingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
|
||||
|
||||
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
"""Configures a multi node deployment."""
|
||||
|
||||
type: Literal["multi_node"] = "multi_node"
|
||||
|
||||
num_train_nodes: Annotated[int, Field(description="Number of training nodes.")]
|
||||
num_infer_nodes: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=0,
|
||||
description="Number of inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data).",
|
||||
),
|
||||
]
|
||||
num_infer_replicas: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Number of independent inference replicas. Total inference nodes = num_infer_nodes * num_infer_replicas.",
|
||||
),
|
||||
] = 1
|
||||
num_teacher_nodes: Annotated[int | None, Field(description="Number of teacher inference nodes.")] = None
|
||||
num_train_nodes: int
|
||||
"""Training nodes."""
|
||||
|
||||
nodes_per_fsdp_group: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Number of training nodes per FSDP island. Auto-sets trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group."
|
||||
),
|
||||
] = None
|
||||
num_infer_nodes: int = Field(ge=0)
|
||||
"""Inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data)."""
|
||||
|
||||
num_infer_replicas: int = Field(1, ge=1)
|
||||
"""Independent inference replicas. Total inference nodes = ``num_infer_nodes * num_infer_replicas``."""
|
||||
|
||||
num_teacher_nodes: int | None = None
|
||||
"""Teacher inference nodes."""
|
||||
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Training nodes per FSDP island. Auto-sets ``trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
|
||||
|
||||
@property
|
||||
def total_infer_nodes(self) -> int:
|
||||
@@ -243,130 +195,89 @@ DeploymentConfig: TypeAlias = Annotated[
|
||||
|
||||
|
||||
class RLConfig(BaseConfig):
|
||||
"""Configures an RL training run."""
|
||||
|
||||
trainer: TrainerConfig
|
||||
|
||||
orchestrator: OrchestratorConfig
|
||||
inference: Annotated[
|
||||
InferenceConfig | None,
|
||||
Field(
|
||||
description="The inference config. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."
|
||||
),
|
||||
] = None
|
||||
|
||||
teacher_inference: Annotated[
|
||||
InferenceConfig | None,
|
||||
Field(
|
||||
description="Teacher inference config. If None, will use the same config as inference or a default config. Only used when teacher GPUs or nodes are set."
|
||||
),
|
||||
] = None
|
||||
inference: InferenceConfig | None = None
|
||||
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."""
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
Field(
|
||||
description="The directory to store the outputs. Should be set to a unique directory identifying the experiment."
|
||||
),
|
||||
] = Path("outputs")
|
||||
teacher_inference: InferenceConfig | None = None
|
||||
"""Teacher inference server configuration. If None, falls back to the same config as ``inference`` (or a default). Only used when teacher GPUs/nodes are set."""
|
||||
|
||||
clean_output_dir: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
|
||||
),
|
||||
] = False
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Output directory. Should be unique per experiment."""
|
||||
|
||||
clean_output_dir: bool = False
|
||||
"""Delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming."""
|
||||
|
||||
### Shared configurations
|
||||
|
||||
log: Annotated[
|
||||
SharedLogConfig,
|
||||
Field(
|
||||
description="Shared log configs. If None, will fallback to the log configs specified on submodule configs."
|
||||
),
|
||||
] = SharedLogConfig()
|
||||
log: SharedLogConfig = SharedLogConfig()
|
||||
"""Shared log config. Propagated to trainer and orchestrator."""
|
||||
|
||||
ckpt: Annotated[
|
||||
SharedCheckpointConfig | None,
|
||||
Field(
|
||||
description="Shared checkpoint configs. If None, will fallback to the checkpoint configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
ckpt: SharedCheckpointConfig | None = None
|
||||
"""Shared checkpoint config. If None, falls back to the sub-config checkpoint settings."""
|
||||
|
||||
wandb: Annotated[
|
||||
SharedWandbConfig | None,
|
||||
Field(
|
||||
description="Shared W&B configs. If None, will fallback to the W&B configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
wandb: SharedWandbConfig | None = None
|
||||
"""Shared W&B config. If None, falls back to the sub-config W&B settings."""
|
||||
|
||||
model: Annotated[
|
||||
SharedModelConfig | None,
|
||||
Field(
|
||||
description="Shared model configs. If None, will fallback to the model configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
model: SharedModelConfig | None = None
|
||||
"""Shared model config. If None, falls back to the sub-config model settings."""
|
||||
|
||||
tokenizer: Annotated[
|
||||
TokenizerConfig | None,
|
||||
Field(
|
||||
description="Shared tokenizer config. Propagated to trainer, orchestrator, and inference. "
|
||||
"If None, each component uses its own tokenizer config (defaulting to model name).",
|
||||
),
|
||||
] = None
|
||||
tokenizer: TokenizerConfig | None = None
|
||||
"""Shared tokenizer config. Propagated to trainer, orchestrator, and inference. If None, each component uses its own tokenizer config (defaulting to model name)."""
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="The maximum number of steps to train for. If None, will fallback to the max steps specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
max_steps: int | None = None
|
||||
"""Shared maximum training steps. If None, falls back to the sub-config ``max_steps``."""
|
||||
|
||||
max_model_len: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="The maximum model length to use. If None, will fallback to the max model length specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
max_model_len: int | None = None
|
||||
"""Shared maximum model context length. If None, falls back to the sub-config ``max_model_len``."""
|
||||
|
||||
seq_len: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Shared sequence length. Propagates to trainer.model.seq_len and orchestrator.seq_len, "
|
||||
"but only for those not explicitly set in the config. "
|
||||
"Explicitly set per-component values always take precedence."
|
||||
),
|
||||
] = None
|
||||
seq_len: int | None = None
|
||||
"""Shared sequence length. Propagates to ``trainer.model.seq_len`` and ``orchestrator.seq_len`` only when those values were not explicitly set; explicit per-component values always win."""
|
||||
|
||||
max_async_level: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="The async level to use. If None, will fallback to the async level specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
max_async_level: int | None = None
|
||||
"""Shared async level. If None, falls back to the sub-config ``max_async_level``."""
|
||||
|
||||
weight_broadcast: Annotated[
|
||||
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
|
||||
] = None
|
||||
weight_broadcast: SharedWeightBroadcastConfig | None = None
|
||||
|
||||
bench: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to run in benchmark mode. Automatically sets the trainer and orchestrator to benchmark mode and, if present, suffixes the W&B project with `-bench`.",
|
||||
),
|
||||
] = False
|
||||
bench: bool = False
|
||||
"""Benchmark mode. Sets trainer and orchestrator to benchmark mode and, when set, suffixes the W&B project with ``-bench``."""
|
||||
|
||||
deployment: DeploymentConfig = SingleNodeDeploymentConfig()
|
||||
|
||||
slurm: Annotated[SlurmConfig | None, Field(description="SLURM configuration. If None, will run locally.")] = None
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. If None, runs locally."""
|
||||
|
||||
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: Annotated[
|
||||
RLExperimentalConfig,
|
||||
Field(description="Experimental features for RL training."),
|
||||
] = RLExperimentalConfig()
|
||||
experimental: RLExperimentalConfig = RLExperimentalConfig()
|
||||
|
||||
### Validate configs (e.g. raise for unsupported (combinations of) configs)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _stub_orchestrator_teacher_for_auto_setup(cls, data):
|
||||
"""When `deployment.num_teacher_gpus > 0` and the user didn't write an
|
||||
`[orchestrator.teacher]` block, inject an empty one so
|
||||
`OrchestratorConfig.validate_training_mode` (which fires during nested
|
||||
validation) doesn't reject `training_mode = "opd"` for "missing teacher".
|
||||
`auto_setup_teacher_inference` (after) then fills in client.base_url and
|
||||
model.name from the auto-launched teacher_inference server."""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
deployment = data.get("deployment")
|
||||
if not isinstance(deployment, dict):
|
||||
return data
|
||||
if not deployment.get("num_teacher_gpus"):
|
||||
return data
|
||||
orch = data.setdefault("orchestrator", {})
|
||||
if isinstance(orch, dict) and "teacher" not in orch and "teacher_model" not in orch:
|
||||
orch["teacher"] = {}
|
||||
return data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_deployment(self):
|
||||
if self.deployment.type == "multi_node":
|
||||
@@ -422,32 +333,6 @@ class RLConfig(BaseConfig):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_teacher_model(self):
|
||||
if (
|
||||
self.trainer.loss.type == "default" and self.trainer.loss.teacher_tau > 0
|
||||
) and not self.orchestrator.teacher_model:
|
||||
raise ValueError(
|
||||
"teacher_model must be configured when teacher_tau > 0. "
|
||||
"Either set teacher_tau = 0, set deployment.num_teacher_gpus, or configure teacher_model manually."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_external_rollout_inference(self):
|
||||
"""Forbid configuring a local inference server when rollouts come from an external teacher.
|
||||
|
||||
Orchestrator-only invariants (``use_sft_loss`` paired with ``teacher_rollout_model``,
|
||||
and ``use_token_client`` coupling) live on ``OrchestratorConfig`` so the hosted
|
||||
orchestrator entrypoint also enforces them.
|
||||
"""
|
||||
if self.orchestrator.teacher_rollout_model is not None and self.inference is not None:
|
||||
raise ValueError(
|
||||
"inference must be omitted when orchestrator.teacher_rollout_model is configured. "
|
||||
"External rollout mode does not use the local inference server."
|
||||
)
|
||||
return self
|
||||
|
||||
### Auto-setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -564,13 +449,13 @@ class RLConfig(BaseConfig):
|
||||
inference_model_explicitly_set = "name" in self.inference.model.model_fields_set
|
||||
if not inference_model_explicitly_set:
|
||||
self.inference.model.name = self.model.name
|
||||
self.orchestrator.model.name = self.inference.model.name
|
||||
self.orchestrator.student.model.name = self.inference.model.name
|
||||
else:
|
||||
self.orchestrator.model.name = self.model.name
|
||||
self.orchestrator.student.model.name = self.model.name
|
||||
|
||||
if self.model.vlm is not None:
|
||||
self.trainer.model.vlm = self.model.vlm
|
||||
self.orchestrator.model.vlm = self.model.vlm
|
||||
self.orchestrator.student.model.vlm = self.model.vlm
|
||||
if self.inference is not None:
|
||||
self.inference.model.vlm = self.model.vlm
|
||||
|
||||
@@ -586,17 +471,21 @@ class RLConfig(BaseConfig):
|
||||
# in name/trust_remote_code from model config where still unset.
|
||||
self.trainer.tokenizer = self.tokenizer.model_copy()
|
||||
self.orchestrator.tokenizer = self.tokenizer.model_copy()
|
||||
for component in (self.trainer, self.orchestrator):
|
||||
if component.tokenizer.name is None:
|
||||
component.tokenizer.name = component.model.name
|
||||
if component.tokenizer.trust_remote_code is None:
|
||||
component.tokenizer.trust_remote_code = component.model.trust_remote_code
|
||||
if self.trainer.tokenizer.name is None:
|
||||
self.trainer.tokenizer.name = self.trainer.model.name
|
||||
if self.trainer.tokenizer.trust_remote_code is None:
|
||||
self.trainer.tokenizer.trust_remote_code = self.trainer.model.trust_remote_code
|
||||
if self.orchestrator.tokenizer.name is None:
|
||||
self.orchestrator.tokenizer.name = self.orchestrator.student.model.name
|
||||
if self.orchestrator.tokenizer.trust_remote_code is None:
|
||||
self.orchestrator.tokenizer.trust_remote_code = self.orchestrator.student.model.trust_remote_code
|
||||
else:
|
||||
# No shared tokenizer: re-derive from (now-correct) model names,
|
||||
# since auto_setup_tokenizer on sub-configs already ran with defaults.
|
||||
for component in (self.trainer, self.orchestrator):
|
||||
component.tokenizer.name = component.model.name
|
||||
component.tokenizer.trust_remote_code = component.model.trust_remote_code
|
||||
self.trainer.tokenizer.name = self.trainer.model.name
|
||||
self.trainer.tokenizer.trust_remote_code = self.trainer.model.trust_remote_code
|
||||
self.orchestrator.tokenizer.name = self.orchestrator.student.model.name
|
||||
self.orchestrator.tokenizer.trust_remote_code = self.orchestrator.student.model.trust_remote_code
|
||||
|
||||
# Propagate chat_template to inference (vLLM --chat-template)
|
||||
if self.inference is not None:
|
||||
@@ -720,40 +609,40 @@ class RLConfig(BaseConfig):
|
||||
if self.trainer.weight_broadcast.type == "nccl":
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
|
||||
if self.orchestrator.model.lora is None:
|
||||
if self.orchestrator.student.model.lora is None:
|
||||
from prime_rl.configs.orchestrator import LoRAConfig
|
||||
|
||||
self.orchestrator.model.lora = LoRAConfig()
|
||||
self.orchestrator.student.model.lora = LoRAConfig()
|
||||
|
||||
if (
|
||||
self.orchestrator.model.lora.rank is not None
|
||||
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
|
||||
self.orchestrator.student.model.lora.rank is not None
|
||||
and self.orchestrator.student.model.lora.rank != self.trainer.model.lora.rank
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
|
||||
f"orchestrator.student.model.lora.rank ({self.orchestrator.student.model.lora.rank}) conflicts with "
|
||||
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
|
||||
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
|
||||
f"Remove orchestrator.student.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
|
||||
)
|
||||
|
||||
if (
|
||||
self.orchestrator.model.lora.alpha is not None
|
||||
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
|
||||
self.orchestrator.student.model.lora.alpha is not None
|
||||
and self.orchestrator.student.model.lora.alpha != self.trainer.model.lora.alpha
|
||||
):
|
||||
raise ValueError(
|
||||
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
|
||||
f"orchestrator.student.model.lora.alpha ({self.orchestrator.student.model.lora.alpha}) conflicts with "
|
||||
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
|
||||
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
|
||||
f"Remove orchestrator.student.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
|
||||
)
|
||||
|
||||
if self.orchestrator.model.lora.rank is None:
|
||||
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
|
||||
if self.orchestrator.student.model.lora.rank is None:
|
||||
self.orchestrator.student.model.lora.rank = self.trainer.model.lora.rank
|
||||
|
||||
if self.orchestrator.model.lora.alpha is None:
|
||||
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
|
||||
if self.orchestrator.student.model.lora.alpha is None:
|
||||
self.orchestrator.student.model.lora.alpha = self.trainer.model.lora.alpha
|
||||
|
||||
if self.orchestrator.model.lora.name is None:
|
||||
self.orchestrator.model.lora.name = (
|
||||
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
|
||||
if self.orchestrator.student.model.lora.name is None:
|
||||
self.orchestrator.student.model.lora.name = (
|
||||
f"r{self.orchestrator.student.model.lora.rank}-a{self.orchestrator.student.model.lora.alpha}"
|
||||
)
|
||||
|
||||
if self.inference is not None:
|
||||
@@ -771,7 +660,7 @@ class RLConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_session_headers(self):
|
||||
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
|
||||
self.orchestrator.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
|
||||
self.orchestrator.student.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -917,17 +806,23 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_dp_rank_count(self):
|
||||
"""Auto-set orchestrator client dp_rank_count from inference DP size.
|
||||
def auto_setup_inference_client(self):
|
||||
"""Auto-configure orchestrator student client from the inference server config.
|
||||
|
||||
Uses data_parallel_size_local (per-node DP) when set, since each base URL
|
||||
points to a single node whose API server only knows about its local ranks.
|
||||
Falls back to the global parallel.dp for single-node setups.
|
||||
For all modes, sets dp_rank_count from inference DP size. For SFT mode,
|
||||
also sets base_url - rl/opd rely on the ClientConfig default
|
||||
(``["http://localhost:8000/v1"]``) which already matches the auto-launched
|
||||
student vLLM at inference.server.port = 8000.
|
||||
"""
|
||||
if self.inference is not None and "dp_rank_count" not in self.orchestrator.client.model_fields_set:
|
||||
self.orchestrator.client.dp_rank_count = (
|
||||
self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
)
|
||||
if self.inference is None:
|
||||
return self
|
||||
client = self.orchestrator.student.client
|
||||
if "dp_rank_count" not in client.model_fields_set:
|
||||
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
if self.orchestrator.training_mode == "sft" and "base_url" not in client.model_fields_set:
|
||||
host = self.inference.server.host or "localhost"
|
||||
port = self.inference.server.port
|
||||
client.base_url = [f"http://{host}:{port}/v1"]
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -940,7 +835,7 @@ class RLConfig(BaseConfig):
|
||||
|
||||
import copy
|
||||
|
||||
from prime_rl.configs.orchestrator import TeacherModelConfig
|
||||
from prime_rl.configs.orchestrator import RolloutModelConfig
|
||||
|
||||
if self.teacher_inference is None:
|
||||
if self.inference is None:
|
||||
@@ -962,12 +857,12 @@ class RLConfig(BaseConfig):
|
||||
assert num_teacher_gpus > 0, "num_teacher_gpus cannot be zero"
|
||||
self.teacher_inference.parallel.dp = num_teacher_gpus // tp
|
||||
|
||||
if self.orchestrator.teacher_model is None:
|
||||
self.orchestrator.teacher_model = TeacherModelConfig()
|
||||
if self.orchestrator.teacher is None:
|
||||
self.orchestrator.teacher = RolloutModelConfig()
|
||||
host = self.teacher_inference.server.host or "localhost"
|
||||
port = self.teacher_inference.server.port
|
||||
self.orchestrator.teacher_model.client.base_url = [f"http://{host}:{port}/v1"]
|
||||
self.orchestrator.teacher_model.model.name = self.teacher_inference.model.name
|
||||
self.orchestrator.teacher.client.base_url = [f"http://{host}:{port}/v1"]
|
||||
self.orchestrator.teacher.model.name = self.teacher_inference.model.name
|
||||
|
||||
return self
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
HeartbeatConfig,
|
||||
@@ -25,13 +25,18 @@ from prime_rl.configs.trainer import (
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
|
||||
|
||||
class BaseDataConfig(BaseModel):
|
||||
"""Base config for SFT data."""
|
||||
class BaseDataConfig(BaseConfig):
|
||||
batch_size: int = Field(128, ge=1)
|
||||
"""Global batch size."""
|
||||
|
||||
seq_len: int = Field(128, ge=1)
|
||||
"""Sequence length."""
|
||||
|
||||
batch_size: Annotated[int, Field(ge=1)] = 128
|
||||
seq_len: Annotated[int, Field(ge=1)] = 128
|
||||
pack_function: Literal["cat", "stack"] = "cat"
|
||||
micro_batch_size: Annotated[int, Field(ge=1)] = 1
|
||||
"""Sample packing strategy. ``cat`` concatenates; ``stack`` requires ``seq_len`` divisible by 256."""
|
||||
|
||||
micro_batch_size: int = Field(1, ge=1)
|
||||
"""Per-step micro batch size. ``batch_size`` must be divisible by this."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_batch_size(self):
|
||||
@@ -43,50 +48,56 @@ class BaseDataConfig(BaseModel):
|
||||
|
||||
|
||||
class FakeDataConfig(BaseDataConfig):
|
||||
"""Configures fake data used for debugging."""
|
||||
|
||||
type: Literal["fake"] = "fake"
|
||||
|
||||
length: Literal["fixed", "variable"] = "fixed"
|
||||
"""Use fixed-length samples or variable-length samples."""
|
||||
|
||||
input_ids: Literal["increasing", "random"] = "increasing"
|
||||
"""Token id generator: ``increasing`` for deterministic sequences, ``random`` for random ids."""
|
||||
|
||||
|
||||
class LossMaskConfig(BaseConfig):
|
||||
"""Configures which message types contribute to the loss. If True, the loss_mask will be True and the message type will contribute to the loss."""
|
||||
system: bool = False
|
||||
"""System messages contribute to the loss."""
|
||||
|
||||
system: Annotated[bool, Field(description="Whether system messages contribute to the loss.")] = False
|
||||
user: Annotated[bool, Field(description="Whether user messages contribute to the loss.")] = False
|
||||
assistant: Annotated[bool, Field(description="Whether assistant messages contribute to the loss.")] = True
|
||||
tool: Annotated[bool, Field(description="Whether tool messages contribute to the loss.")] = False
|
||||
user: bool = False
|
||||
"""User messages contribute to the loss."""
|
||||
|
||||
assistant: bool = True
|
||||
"""Assistant messages contribute to the loss."""
|
||||
|
||||
tool: bool = False
|
||||
"""Tool messages contribute to the loss."""
|
||||
|
||||
|
||||
class SFTDataConfig(BaseDataConfig):
|
||||
"""Configures the data used for training."""
|
||||
|
||||
type: Literal["sft"] = "sft"
|
||||
|
||||
name: Annotated[str, Field(description="Name or path of the HF dataset to use.")] = (
|
||||
"PrimeIntellect/Reverse-Text-SFT"
|
||||
)
|
||||
subsets: Annotated[list[str] | None, Field(description="Subsets to use from the HF dataset.")] = None
|
||||
splits: Annotated[list[str] | None, Field(description="Splits to use from the HF dataset.")] = None
|
||||
probabilities: Annotated[list[float] | None, Field(description="Probabilities to use for each subset/split.")] = (
|
||||
None
|
||||
)
|
||||
stopping_strategy: Annotated[
|
||||
Literal["first_exhausted", "all_exhausted"],
|
||||
Field(description=""),
|
||||
] = "all_exhausted"
|
||||
shuffle: Annotated[bool, Field(description="Whether to shuffle the dataset at the beginning of each epoch.")] = True
|
||||
seed: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Random seed to use for shuffling the dataset. We also shuffle at the end of each epoch by adding epoch count to the seed."
|
||||
),
|
||||
] = 0
|
||||
name: str = "PrimeIntellect/Reverse-Text-SFT"
|
||||
"""HF dataset name or path."""
|
||||
|
||||
subsets: list[str] | None = None
|
||||
"""Subsets to load from the HF dataset."""
|
||||
|
||||
splits: list[str] | None = None
|
||||
"""Splits to load from the HF dataset."""
|
||||
|
||||
probabilities: list[float] | None = None
|
||||
"""Sampling probabilities for each subset/split."""
|
||||
|
||||
stopping_strategy: Literal["first_exhausted", "all_exhausted"] = "all_exhausted"
|
||||
"""Stopping strategy when interleaving multiple subsets/splits."""
|
||||
|
||||
shuffle: bool = True
|
||||
"""Shuffle the dataset at the start of each epoch."""
|
||||
|
||||
seed: int = 0
|
||||
"""Random seed for shuffling. Re-shuffled per epoch by adding the epoch count to the seed."""
|
||||
|
||||
# Configuring
|
||||
loss_mask: LossMaskConfig = LossMaskConfig()
|
||||
"""Which message types contribute to the loss."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_subsets_and_splits(self):
|
||||
@@ -110,28 +121,28 @@ class SFTDataConfig(BaseDataConfig):
|
||||
|
||||
|
||||
class SFTValConfig(BaseConfig):
|
||||
interval: Annotated[int, Field(ge=1, description="Run validation every N training steps.")] = 50
|
||||
eval_on_start: Annotated[bool, Field(description="Run validation before the first training step.")] = False
|
||||
interval: int = Field(50, ge=1)
|
||||
"""Run validation every N training steps."""
|
||||
|
||||
eval_on_start: bool = False
|
||||
"""Run validation before the first training step."""
|
||||
|
||||
data: SFTDataConfig
|
||||
|
||||
|
||||
DataConfig: TypeAlias = Annotated[FakeDataConfig | SFTDataConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class BaseDeploymentConfig(BaseModel):
|
||||
"""Base deployment config for SFT."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
|
||||
class BaseDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
|
||||
|
||||
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
"""Configures a single-node SFT deployment."""
|
||||
|
||||
type: Literal["single_node"] = "single_node"
|
||||
|
||||
num_gpus: Annotated[int, Field(description="Number of GPUs.")] = 1
|
||||
num_gpus: int = 1
|
||||
"""GPUs to use."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_gpu_count(self):
|
||||
@@ -141,18 +152,13 @@ class SingleNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
|
||||
|
||||
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
|
||||
"""Configures a multi-node SFT deployment."""
|
||||
|
||||
type: Literal["multi_node"] = "multi_node"
|
||||
|
||||
num_nodes: Annotated[int, Field(description="Number of training nodes.")] = 2
|
||||
num_nodes: int = 2
|
||||
"""Training nodes."""
|
||||
|
||||
nodes_per_fsdp_group: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="Number of nodes per FSDP island. Auto-sets model.dp_replicate = num_nodes / nodes_per_fsdp_group."
|
||||
),
|
||||
] = None
|
||||
nodes_per_fsdp_group: int | None = None
|
||||
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_nodes / nodes_per_fsdp_group``."""
|
||||
|
||||
|
||||
SFTDeploymentConfig: TypeAlias = Annotated[
|
||||
@@ -161,139 +167,77 @@ SFTDeploymentConfig: TypeAlias = Annotated[
|
||||
|
||||
|
||||
class SFTExperimentalConfig(BaseConfig):
|
||||
"""Experimental features for SFT training."""
|
||||
pass
|
||||
|
||||
|
||||
class SFTConfig(BaseConfig):
|
||||
"""Configures the SFT trainer"""
|
||||
|
||||
# The model configuration
|
||||
model: ModelConfig = ModelConfig()
|
||||
|
||||
# The tokenizer configuration
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
# The renderer configuration (only used when use_renderer=True)
|
||||
renderer: RendererConfig = RendererConfig()
|
||||
"""Client-side renderer configuration. Only consumed when ``use_renderer=true``."""
|
||||
|
||||
use_renderer: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description=(
|
||||
"If True, tokenize SFT samples through the `renderers` library "
|
||||
"(single render() + message_indices mask) instead of the default "
|
||||
"`build_incremental_token_mask` path. Required for chat templates "
|
||||
"that render position-dependently (e.g. Qwen3, Qwen3.5)."
|
||||
),
|
||||
),
|
||||
] = False
|
||||
use_renderer: bool = False
|
||||
"""Tokenize SFT samples through the ``renderers`` library (single ``render()`` + ``message_indices`` mask) instead of the default ``build_incremental_token_mask`` path. Required for chat templates that render position-dependently (e.g. Qwen3, Qwen3.5)."""
|
||||
|
||||
# The data configuration
|
||||
data: DataConfig = SFTDataConfig()
|
||||
|
||||
# Optional validation configuration
|
||||
val: SFTValConfig | None = None
|
||||
"""Validation configuration. If None, no validation runs."""
|
||||
|
||||
# The optimizer configuration
|
||||
optim: OptimizerConfig = AdamWConfig()
|
||||
|
||||
# The learning rate scheduler configuration
|
||||
scheduler: SchedulerConfig = ConstantSchedulerConfig()
|
||||
|
||||
# The checkpoint configuration
|
||||
ckpt: CheckpointConfig | None = None
|
||||
|
||||
# The logging configuration
|
||||
log: TrainerLogConfig = TrainerLogConfig()
|
||||
|
||||
# The wandb configuration
|
||||
wandb: WandbConfig | None = None
|
||||
|
||||
output_dir: Annotated[
|
||||
Path,
|
||||
Field(
|
||||
description="Directory to write outputs to. Will be populated with checkpoints and logs as subdirectories. Should be set to a persistent directory with enough disk space. This value should be distinct across experiments running on a single node. See the README for more details."
|
||||
),
|
||||
] = Path("outputs")
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
|
||||
clean_output_dir: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
|
||||
),
|
||||
] = False
|
||||
clean_output_dir: bool = False
|
||||
"""Delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming."""
|
||||
|
||||
matmul_precision: Annotated[
|
||||
Literal["highest", "high", "medium"],
|
||||
Field(
|
||||
description=(
|
||||
"Precision for float32 matrix multiplications. "
|
||||
"Use 'highest' for full FP32 (required on ROCm/AMD GPUs to avoid "
|
||||
"catastrophic precision loss in softmax over large vocabularies). "
|
||||
"Use 'high' to enable TF32 on NVIDIA GPUs for a speedup with minor "
|
||||
"precision tradeoff. See torch.set_float32_matmul_precision docs."
|
||||
),
|
||||
),
|
||||
] = "high"
|
||||
matmul_precision: Literal["highest", "high", "medium"] = "high"
|
||||
"""Precision for float32 matrix multiplications. ``highest`` is full FP32 (required on ROCm/AMD GPUs to avoid catastrophic precision loss in softmax over large vocabularies). ``high`` enables TF32 on NVIDIA GPUs for a speedup with minor precision tradeoff. See ``torch.set_float32_matmul_precision``."""
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(description="Maximum number of steps to run training for. If None, will run indefinitely."),
|
||||
] = None
|
||||
max_steps: int | None = None
|
||||
"""Maximum training steps. If None, runs indefinitely."""
|
||||
|
||||
memory_profiler_path: Annotated[Path | None, Field(description="Path to write memory profile to.")] = None
|
||||
memory_profiler_path: Path | None = None
|
||||
"""Path to write the memory profile to."""
|
||||
|
||||
bench: Annotated[
|
||||
BenchConfig | None,
|
||||
Field(
|
||||
description="Whether to run in benchmark mode. It will automatically set the maximum number of steps to run to 4 and use fake data.",
|
||||
),
|
||||
] = None
|
||||
bench: BenchConfig | None = None
|
||||
"""Benchmark-mode configuration. When set, ``max_steps`` is forced to 4 and fake data is used."""
|
||||
|
||||
gc: Annotated[
|
||||
GCConfig | None,
|
||||
Field(
|
||||
description="Garbage collection config. Disables automatic GC and runs deterministic collections every N steps to avoid stragglers. Set to null to use Python's default GC behavior.",
|
||||
),
|
||||
] = GCConfig()
|
||||
gc: GCConfig | None = GCConfig()
|
||||
"""Garbage collection config. Disables automatic GC and runs deterministic collections every N steps to avoid stragglers. Set to null to use Python's default GC behavior."""
|
||||
|
||||
trace_path: Annotated[Path | None, Field(description="Path to write pytorch profiler trace to.")] = None
|
||||
trace_path: Path | None = None
|
||||
"""Path to write the PyTorch profiler trace to."""
|
||||
|
||||
dist_timeout_seconds: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Timeout in seconds for torch distributed ops. Defaults to 600 seconds.",
|
||||
),
|
||||
] = 600
|
||||
dist_timeout_seconds: int = 600
|
||||
"""Timeout in seconds for torch distributed ops."""
|
||||
|
||||
loss_impl: Annotated[
|
||||
Literal["liger", "torch", "liger_fused", "quack_fused"],
|
||||
Field(
|
||||
description="Implementation of the cross entropy loss function to use. "
|
||||
"'liger_fused' fuses the lm_head projection with the CE loss to avoid materializing full logits. "
|
||||
"'quack_fused' uses quack-kernels for chunked linear + CE with CuTe DSL CUDA kernels."
|
||||
),
|
||||
] = "torch"
|
||||
loss_impl: Literal["liger", "torch", "liger_fused", "quack_fused"] = "torch"
|
||||
"""Cross-entropy loss implementation. ``liger_fused`` fuses the lm_head projection with the CE loss to avoid materializing full logits. ``quack_fused`` uses quack-kernels for chunked linear + CE with CuTe DSL CUDA kernels."""
|
||||
|
||||
heartbeat: Annotated[
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
deployment: SFTDeploymentConfig = SingleNodeDeploymentConfig()
|
||||
|
||||
slurm: Annotated[
|
||||
SlurmConfig | None,
|
||||
Field(
|
||||
description="SLURM configuration. If set, the run will be submitted as a SLURM job instead of running locally.",
|
||||
),
|
||||
] = None
|
||||
slurm: SlurmConfig | None = None
|
||||
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
|
||||
|
||||
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
|
||||
dry_run: bool = False
|
||||
"""Only validate and dump resolved configs, then exit early."""
|
||||
|
||||
experimental: Annotated[
|
||||
SFTExperimentalConfig,
|
||||
Field(description="Experimental features for SFT training."),
|
||||
] = SFTExperimentalConfig()
|
||||
experimental: SFTExperimentalConfig = SFTExperimentalConfig()
|
||||
|
||||
### Pre-validation normalization
|
||||
|
||||
@@ -414,6 +358,12 @@ class SFTConfig(BaseConfig):
|
||||
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
|
||||
if self.renderer.reasoning_parser is not None:
|
||||
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
|
||||
if self.renderer.preserve_all_thinking:
|
||||
renderer_args_set.append(f"renderer.preserve_all_thinking={self.renderer.preserve_all_thinking!r}")
|
||||
if self.renderer.preserve_thinking_between_tool_calls:
|
||||
renderer_args_set.append(
|
||||
f"renderer.preserve_thinking_between_tool_calls={self.renderer.preserve_thinking_between_tool_calls!r}"
|
||||
)
|
||||
|
||||
if renderer_args_set:
|
||||
raise ValueError(
|
||||
|
||||
@@ -2,61 +2,38 @@ import os
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class SlurmConfig(BaseConfig):
|
||||
"""Configures SLURM scheduling."""
|
||||
job_name: str = "prime-rl"
|
||||
"""SLURM job name."""
|
||||
|
||||
job_name: Annotated[str, Field(description="The SLURM job name.")] = "prime-rl"
|
||||
project_dir: Path = Path(".")
|
||||
"""Path to the project root, used to source .env, activate .venv, and run uv sync."""
|
||||
|
||||
project_dir: Annotated[
|
||||
Path,
|
||||
Field(description="Path to the project root. Used to source .env, activate .venv, and run uv sync."),
|
||||
] = Path(".")
|
||||
template_path: Path | None = None
|
||||
"""SLURM template file. If None, uses the bundled single-node or multi-node template."""
|
||||
|
||||
template_path: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
description="The path to the SLURM template file. If None, will use the default single-node/multi-node template."
|
||||
),
|
||||
] = None
|
||||
partition: str = "cluster"
|
||||
"""SLURM partition (#SBATCH --partition)."""
|
||||
|
||||
partition: Annotated[
|
||||
str, Field(description="The SLURM partition to use. Will be passed as #SBATCH --partition.")
|
||||
] = "cluster"
|
||||
nodelist: str | None = None
|
||||
"""Comma-separated list of specific nodes to run on (#SBATCH --nodelist)."""
|
||||
|
||||
nodelist: Annotated[
|
||||
str | None,
|
||||
Field(description="Comma-separated list of specific nodes to run on. Passed as #SBATCH --nodelist."),
|
||||
] = None
|
||||
exclude: str | None = None
|
||||
"""Comma-separated list of nodes to exclude (#SBATCH --exclude)."""
|
||||
|
||||
exclude: Annotated[
|
||||
str | None,
|
||||
Field(description="Comma-separated list of nodes to exclude. Passed as #SBATCH --exclude."),
|
||||
] = None
|
||||
account: str | None = None
|
||||
"""SLURM account to charge (#SBATCH --account)."""
|
||||
|
||||
account: Annotated[
|
||||
str | None,
|
||||
Field(description="SLURM account to charge. Passed as #SBATCH --account."),
|
||||
] = None
|
||||
time: str | None = None
|
||||
"""Maximum wall time, e.g. '24:00:00' or '7-00:00:00' (#SBATCH --time)."""
|
||||
|
||||
time: Annotated[
|
||||
str | None,
|
||||
Field(description="Maximum wall time (e.g. '24:00:00', '7-00:00:00'). Passed as #SBATCH --time."),
|
||||
] = None
|
||||
|
||||
pre_run_command: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Shell command to run on the head node before starting the job. "
|
||||
"Runs after cd into project dir, .env sourcing, and venv activation. "
|
||||
"Useful for cleanup routines like 'sudo pkill -f vllm'. "
|
||||
"To run on all nodes, wrap with srun: 'srun bash -c \"pkill -f vllm || true\"'.",
|
||||
),
|
||||
] = None
|
||||
pre_run_command: str | None = None
|
||||
"""Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes."""
|
||||
|
||||
@property
|
||||
def template_vars(self) -> dict:
|
||||
@@ -82,247 +59,101 @@ ServerType = Literal["vllm", "openai"]
|
||||
|
||||
|
||||
class VLMConfig(BaseConfig):
|
||||
"""Configures vision-language model support.
|
||||
vision_encoder_attr: str
|
||||
"""Dotted attribute path to the vision encoder module (e.g. ``model.visual``)."""
|
||||
|
||||
Presence of this config enables VLM mode. You must specify where the
|
||||
vision encoder and language model live on the model object.
|
||||
language_model_attr: str
|
||||
"""Dotted attribute path to the language model module (e.g. ``model.language_model``)."""
|
||||
|
||||
Usage:
|
||||
[model.vlm]
|
||||
vision_encoder_attr = "model.visual"
|
||||
language_model_attr = "model.language_model"
|
||||
"""
|
||||
|
||||
vision_encoder_attr: Annotated[
|
||||
str,
|
||||
Field(description="Dotted attribute path to the vision encoder module (e.g. 'model.visual')."),
|
||||
]
|
||||
|
||||
language_model_attr: Annotated[
|
||||
str,
|
||||
Field(description="Dotted attribute path to the language model module (e.g. 'model.language_model')."),
|
||||
]
|
||||
|
||||
freeze_vision_encoder: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to freeze the vision encoder. When False, the vision encoder is trainable "
|
||||
"and FSDP-sharded per-block. Has no effect with LoRA (LoRA freezes all non-adapter parameters).",
|
||||
),
|
||||
] = True
|
||||
freeze_vision_encoder: bool = True
|
||||
"""Freeze the vision encoder. When False, it is trainable and FSDP-sharded per-block. No effect with LoRA (LoRA freezes all non-adapter parameters)."""
|
||||
|
||||
|
||||
class BaseModelConfig(BaseConfig):
|
||||
"""Configures the model."""
|
||||
name: str = "Qwen/Qwen3-0.6B"
|
||||
"""HF model name or local path."""
|
||||
|
||||
name: Annotated[str, Field(description="Name or path of the HF model to use.")] = "Qwen/Qwen3-0.6B"
|
||||
trust_remote_code: bool = False
|
||||
"""Trust remote code when initializing the tokenizer."""
|
||||
|
||||
trust_remote_code: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to trust remote code for tokenizer initialization.",
|
||||
),
|
||||
] = False
|
||||
vlm: "VLMConfig | None" = None
|
||||
"""VLM configuration. Setting this enables vision-language model support."""
|
||||
|
||||
vlm: Annotated[
|
||||
"VLMConfig | None",
|
||||
Field(
|
||||
description="VLM configuration. Set this to enable vision-language model support.",
|
||||
),
|
||||
] = None
|
||||
@property
|
||||
def is_vlm(self) -> bool:
|
||||
return self.vlm is not None
|
||||
|
||||
|
||||
class RendererConfig(BaseConfig):
|
||||
"""Configures the client-side renderer (chat-template + response parsing).
|
||||
name: str = "auto"
|
||||
"""Renderer used for chat-template tokenization. One of: ``auto`` (detect from tokenizer), ``qwen3``, ``qwen3_vl``, ``qwen3.5``, ``glm5``, ``glm4.5``, ``minimax-m2``, ``deepseek_v3``, ``kimi_k2``, ``kimi_k25``, ``nemotron3``, ``gpt_oss``, ``default``."""
|
||||
|
||||
Only consumed when ``orchestrator.use_renderer = true``. The renderer
|
||||
owns both directions: render messages → token ids on the client, and
|
||||
parse model output tokens → structured ``content`` / ``reasoning_content``
|
||||
/ ``tool_calls``.
|
||||
"""
|
||||
tool_parser: str | None = None
|
||||
"""Tool parser from ``renderers.parsers``. Only consumed by DefaultRenderer; model-specific renderers bake their own parsing in. Options: ``qwen3``, ``qwen3.5``, ``glm``, ``deepseek_v3``."""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description=(
|
||||
"Renderer to use for chat template tokenization. "
|
||||
"Options: 'auto' (detect from tokenizer), 'qwen3', 'qwen3_vl', "
|
||||
"'qwen3.5', 'glm5', 'glm4.5', 'minimax-m2', 'deepseek_v3', "
|
||||
"'kimi_k2', 'kimi_k25', 'nemotron3', 'gpt_oss', 'default'."
|
||||
),
|
||||
),
|
||||
] = "auto"
|
||||
reasoning_parser: str | None = None
|
||||
"""Reasoning parser from ``renderers.parsers``. Only consumed by DefaultRenderer. Options: ``think``."""
|
||||
|
||||
tool_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description=(
|
||||
"Name of a tool parser in renderers.parsers. Only consumed by "
|
||||
"DefaultRenderer (model-specific renderers bake their own parsing "
|
||||
"in). Options today: 'qwen3', 'qwen3.5', 'glm', 'deepseek_v3'."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
pool_size: int | None = Field(None, ge=1)
|
||||
"""Number of renderer slots shared across concurrent rollouts. Bump for long multi-turn prompts where client-side jinja tokenization serializes."""
|
||||
|
||||
reasoning_parser: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description=(
|
||||
"Name of a reasoning parser in renderers.parsers. Only consumed "
|
||||
"by DefaultRenderer. Options today: 'think'."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
preserve_all_thinking: bool = False
|
||||
"""Re-emit every past-assistant turn's ``reasoning_content`` between ``<think>``/``</think>`` (or the model's equivalent), even when the chat template would drop it. Strict superset of preserve_thinking_between_tool_calls."""
|
||||
|
||||
pool_size: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Number of renderer slots shared across concurrent rollouts. "
|
||||
"None keeps the verifiers default (1). Bump for long multi-turn "
|
||||
"prompts where client-side jinja tokenization serializes."
|
||||
),
|
||||
),
|
||||
] = None
|
||||
preserve_thinking_between_tool_calls: bool = False
|
||||
"""Preserve past-assistant ``reasoning_content`` only inside the current tool cycle — the contiguous assistant→tool→…→assistant block after the most recent user message, when that block contains at least one tool response. A new user turn closes the block."""
|
||||
|
||||
|
||||
class ElasticConfig(BaseConfig):
|
||||
"""Configures elastic inference pool with DNS-based service discovery.
|
||||
hostname: str
|
||||
"""DNS hostname that resolves to inference server IPs."""
|
||||
|
||||
Works with any DNS hostname that resolves to multiple IP addresses.
|
||||
"""
|
||||
port: int = 8000
|
||||
"""Port that inference servers listen on."""
|
||||
|
||||
hostname: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="DNS hostname that resolves to inference server IPs.",
|
||||
),
|
||||
]
|
||||
|
||||
port: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Port that inference servers listen on.",
|
||||
),
|
||||
] = 8000
|
||||
|
||||
sync_interval: Annotated[
|
||||
float,
|
||||
Field(
|
||||
description="Interval in seconds between server discovery checks.",
|
||||
),
|
||||
] = 5.0
|
||||
sync_interval: float = 5.0
|
||||
"""Seconds between server discovery checks."""
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
"""Configures the OAI client.
|
||||
timeout: int = 1200
|
||||
"""Request timeout in seconds."""
|
||||
|
||||
Supports two modes:
|
||||
- Static mode (default): Uses fixed base_url list
|
||||
- Elastic mode: Uses DNS-based service discovery via hostname
|
||||
connect_timeout: float = 30.0
|
||||
"""TCP connect timeout in seconds for inference API requests."""
|
||||
|
||||
If elastic config is provided, base_url is ignored and servers are discovered dynamically.
|
||||
"""
|
||||
wait_for_ready_timeout: int = 1800
|
||||
"""Seconds to wait at startup for the inference pool to become ready. Applies to both the static health check and elastic DNS-based discovery."""
|
||||
|
||||
timeout: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Timeout in seconds. By default, it is set to 1200 seconds.",
|
||||
),
|
||||
] = 1200
|
||||
base_url: list[str] = ["http://localhost:8000/v1"]
|
||||
"""Base URLs for the OpenAI API. With more than one URL, the client round-robins (chat) completion requests across all servers. Ignored when ``elastic`` is set."""
|
||||
|
||||
connect_timeout: Annotated[
|
||||
float,
|
||||
Field(
|
||||
description="TCP connect timeout in seconds for inference API requests.",
|
||||
),
|
||||
] = 30.0
|
||||
api_key_var: str = "VLLM_API_KEY"
|
||||
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
|
||||
|
||||
wait_for_ready_timeout: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Timeout in seconds for waiting for the inference pool to become ready at startup. "
|
||||
"Applies to both the static health check and elastic DNS-based discovery. Defaults to 1800 seconds.",
|
||||
),
|
||||
] = 1800
|
||||
headers: dict[str, str] = {}
|
||||
"""Static headers sent with every request."""
|
||||
|
||||
base_url: Annotated[
|
||||
list[str],
|
||||
Field(
|
||||
description="Base URLs to use for the OpenAI API. By default, it is set to a single server on localhost at port 8000 which matches the default local vLLM server configuration. If you specify more than one URL, the client will round-robin (chat) completion requests across all servers. Ignored if elastic config is provided.",
|
||||
),
|
||||
] = ["http://localhost:8000/v1"]
|
||||
headers_from_env: dict[str, str] = {}
|
||||
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
|
||||
|
||||
api_key_var: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="Name of environment variable containing the API key to use for the inference API. Will parse using `os.getenv(client_config.api_key_var)`. Can be set to an arbitrary string if the inference server is not protected by an API key. If multiple URLs are specified, the same API key will be used for all servers.",
|
||||
),
|
||||
] = "VLLM_API_KEY"
|
||||
extra_headers_from_state: dict[str, str] = {}
|
||||
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "example_id"}`` enables sticky routing at the inference router."""
|
||||
|
||||
headers: Annotated[
|
||||
dict[str, str],
|
||||
Field(
|
||||
description="Headers to use for the OpenAI API. By default, it is set to an empty dictionary.",
|
||||
),
|
||||
] = {}
|
||||
skip_model_check: bool = False
|
||||
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
|
||||
|
||||
extra_headers_from_state: Annotated[
|
||||
dict[str, str],
|
||||
Field(
|
||||
description="Maps HTTP header names to state field names. For each inference request, "
|
||||
"the header value is dynamically read from the rollout state dict. "
|
||||
'e.g. {"X-Session-ID": "example_id"} enables sticky routing at the inference router.',
|
||||
),
|
||||
] = {}
|
||||
dp_rank_count: int = Field(1, ge=1)
|
||||
"""Number of data-parallel ranks behind each base URL. When > 1, each URL is expanded into ``dp_rank_count`` logical clients pinned via the ``X-data-parallel-rank`` header, so every request within a rollout hits the same DP engine and reuses KV cache. Auto-set from the inference config when using the RL entrypoint."""
|
||||
|
||||
skip_model_check: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to skip checking if the model is available in the inference pool. Useful for external APIs or API Keys that don't support the /models endpoint.",
|
||||
),
|
||||
] = False
|
||||
admin_base_url: list[str] | None = None
|
||||
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in disaggregated P/D deployments where the router must not handle admin traffic."""
|
||||
|
||||
dp_rank_count: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description=(
|
||||
"Number of data-parallel ranks behind each base URL. When > 1, "
|
||||
"each URL is expanded into dp_rank_count logical clients, each "
|
||||
"pinned to a specific DP rank via the X-data-parallel-rank header. "
|
||||
"This ensures all requests within a multi-turn rollout hit the same "
|
||||
"DP engine, maximizing KV cache reuse. Auto-set from "
|
||||
"inference.data_parallel_size_local (or inference.parallel.dp) "
|
||||
"when using the RL entrypoint."
|
||||
),
|
||||
),
|
||||
] = 1
|
||||
elastic: ElasticConfig | None = None
|
||||
"""Elastic inference pool config for DNS-based service discovery. When set, ``base_url`` is ignored and inference servers are discovered dynamically via DNS."""
|
||||
|
||||
admin_base_url: Annotated[
|
||||
list[str] | None,
|
||||
Field(
|
||||
description="Separate base URLs for admin operations (weight updates, health checks). "
|
||||
"When set, admin clients use these URLs instead of base_url, allowing weight "
|
||||
"updates to bypass routers and hit each server directly. Used in disaggregated "
|
||||
"P/D deployments where the inference router should not handle admin traffic.",
|
||||
),
|
||||
] = None
|
||||
|
||||
elastic: Annotated[
|
||||
ElasticConfig | None,
|
||||
Field(
|
||||
description="Elastic inference pool configuration for DNS-based service discovery. If provided, base_url is ignored and inference servers are discovered dynamically via DNS.",
|
||||
),
|
||||
] = None
|
||||
|
||||
router_url: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="URL of a vllm-router for load-aware inference routing. When set with elastic mode, inference requests go through the router while admin operations (weight updates, LoRA loading) still go directly to discovered pods.",
|
||||
),
|
||||
] = None
|
||||
router_url: str | None = None
|
||||
"""vllm-router URL for load-aware inference routing. With elastic mode, inference requests go through the router while admin ops still hit discovered pods directly."""
|
||||
|
||||
@property
|
||||
def is_elastic(self) -> bool:
|
||||
@@ -331,225 +162,116 @@ class ClientConfig(BaseConfig):
|
||||
|
||||
|
||||
class LogConfig(BaseConfig):
|
||||
"""Configures the logger."""
|
||||
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
|
||||
"""Log level for the process. Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
|
||||
|
||||
level: Annotated[
|
||||
str,
|
||||
Field(
|
||||
default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"),
|
||||
description="Logging level for the process. Will determine the logging verbosity and format. Defaults to the PRIME_LOG_LEVEL env var if set, else 'info'.",
|
||||
),
|
||||
]
|
||||
vf_level: str = Field(default_factory=lambda: os.environ.get("PRIME_VF_LOG_LEVEL", "info"))
|
||||
"""Log level for the verifiers package. Defaults to ``$PRIME_VF_LOG_LEVEL`` if set, else ``info``."""
|
||||
|
||||
vf_level: Annotated[
|
||||
str,
|
||||
Field(
|
||||
default_factory=lambda: os.environ.get("PRIME_VF_LOG_LEVEL", "info"),
|
||||
description="Logging level for the verifiers package. Will determine the logging verbosity and format. Defaults to the PRIME_VF_LOG_LEVEL env var if set, else 'info'.",
|
||||
),
|
||||
]
|
||||
json_logging: bool = False
|
||||
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
|
||||
|
||||
json_logging: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.).",
|
||||
),
|
||||
] = False
|
||||
|
||||
log_data: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to log the first data sample to the logger.",
|
||||
),
|
||||
] = False
|
||||
log_data: bool = False
|
||||
"""Log the first data sample at startup."""
|
||||
|
||||
|
||||
class TrainerLogConfig(LogConfig):
|
||||
"""Trainer-specific log config."""
|
||||
|
||||
ranks_filter: Annotated[
|
||||
list[int],
|
||||
Field(description="Which trainer ranks to show in console output. Passed to torchrun's --local-ranks-filter."),
|
||||
] = [0]
|
||||
ranks_filter: list[int] = [0]
|
||||
"""Trainer ranks to show in console output. Passed to ``torchrun --local-ranks-filter``."""
|
||||
|
||||
|
||||
class LogExtrasConfig(BaseConfig):
|
||||
"""Configures extra logging for monitoring platforms."""
|
||||
samples: bool = True
|
||||
"""Log prompt/response samples."""
|
||||
|
||||
samples: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to log prompt/response samples.",
|
||||
),
|
||||
] = True
|
||||
distributions: bool = True
|
||||
"""Log distributions (rewards, advantages, etc.)."""
|
||||
|
||||
distributions: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to log distributions (like rewards, advantages, etc.).",
|
||||
),
|
||||
] = True
|
||||
interval: int = Field(10, ge=1)
|
||||
"""Step interval between extras logs."""
|
||||
|
||||
interval: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Step interval at which to log extras.",
|
||||
),
|
||||
] = 10
|
||||
|
||||
sample_ratio: Annotated[
|
||||
float | None,
|
||||
Field(
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Fraction of rollouts to log per step (0.0–1.0). "
|
||||
"When set, the effective sample cap is len(rollouts) * sample_ratio. "
|
||||
"1.0 = all rollouts, 0.5 = half, 0.0 = none. "
|
||||
"None (default)",
|
||||
),
|
||||
] = None
|
||||
sample_ratio: float | None = Field(None, ge=0.0, le=1.0)
|
||||
"""Fraction of rollouts to log per step. The effective cap is ``len(rollouts) * sample_ratio``; 1.0 = all, 0.5 = half, 0.0 = none."""
|
||||
|
||||
|
||||
class WandbConfig(BaseConfig):
|
||||
"""Configures logging to Weights and Biases."""
|
||||
|
||||
# Shared configs (May be overwritten by WandbConfig from `rl.py`)
|
||||
project: Annotated[str, Field(description="The W&B project to log to.")] = "prime-rl"
|
||||
project: str = "prime-rl"
|
||||
"""W&B project to log to."""
|
||||
|
||||
entity: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The W&B entity to log to.",
|
||||
),
|
||||
] = None
|
||||
entity: str | None = None
|
||||
"""W&B entity to log to."""
|
||||
|
||||
name: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The W&B name to to use for logging.",
|
||||
),
|
||||
] = None
|
||||
name: str | None = None
|
||||
"""W&B run name."""
|
||||
|
||||
group: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="The W&B group to use for logging.",
|
||||
),
|
||||
] = None
|
||||
group: str | None = None
|
||||
"""W&B group."""
|
||||
|
||||
tags: Annotated[
|
||||
list[str] | None,
|
||||
Field(
|
||||
description="The W&B tags to attach to the run.",
|
||||
),
|
||||
] = None
|
||||
tags: list[str] | None = None
|
||||
"""W&B tags attached to the run."""
|
||||
|
||||
offline: Annotated[bool, Field(description="Whether to run W&B in offline mode.")] = False
|
||||
offline: bool = False
|
||||
"""Run W&B in offline mode."""
|
||||
|
||||
|
||||
class WandbWithExtrasConfig(WandbConfig):
|
||||
"""Configures logging to Weights and Biases with extras."""
|
||||
|
||||
log_extras: Annotated[
|
||||
LogExtrasConfig | None,
|
||||
Field(
|
||||
description="Configuration for logging extras. If None, no extras are logged.",
|
||||
),
|
||||
] = LogExtrasConfig()
|
||||
log_extras: LogExtrasConfig | None = LogExtrasConfig()
|
||||
"""Extras logging configuration. If None, no extras are logged."""
|
||||
|
||||
|
||||
class PrimeMonitorConfig(BaseConfig):
|
||||
"""Configures logging to Prime Intellect API."""
|
||||
base_url: str = "https://api.primeintellect.ai/api/v1/rft"
|
||||
"""Base URL for the Prime Intellect monitoring API."""
|
||||
|
||||
base_url: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="The base URL for Prime Intellect monitoring API.",
|
||||
),
|
||||
] = "https://api.primeintellect.ai/api/v1/rft"
|
||||
api_key_var: str = "PRIME_API_KEY"
|
||||
"""Environment variable name containing the Prime Intellect API key, resolved via ``os.getenv``."""
|
||||
|
||||
api_key_var: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="Name of environment variable containing the API key for Prime Intellect API. Will parse using `os.getenv(config.api_key_var)`.",
|
||||
),
|
||||
] = "PRIME_API_KEY"
|
||||
log_extras: LogExtrasConfig | None = LogExtrasConfig()
|
||||
"""Extras logging configuration. If None, no extras are logged."""
|
||||
|
||||
log_extras: Annotated[
|
||||
LogExtrasConfig | None,
|
||||
Field(
|
||||
description="Configuration for logging extras. If None, no extras are logged.",
|
||||
),
|
||||
] = LogExtrasConfig()
|
||||
run_name: str | None = None
|
||||
"""Run name shown on the platform. Defaults to the W&B run name when set, otherwise the platform auto-generates one."""
|
||||
|
||||
run_name: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Name for the run shown on the platform. Defaults to the W&B run name if set, otherwise auto-generated by the platform.",
|
||||
),
|
||||
] = None
|
||||
team_id: str | None = None
|
||||
"""Team ID to associate the run with."""
|
||||
|
||||
team_id: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Team ID to associate the run with.",
|
||||
),
|
||||
] = None
|
||||
|
||||
frontend_url: Annotated[
|
||||
str | None,
|
||||
Field(
|
||||
description="Frontend base URL used for the dashboard link shown after registration. Defaults to the Prime CLI frontend URL when unset.",
|
||||
),
|
||||
] = None
|
||||
frontend_url: str | None = None
|
||||
"""Frontend base URL used for the dashboard link printed after registration. Defaults to the Prime CLI frontend URL when unset."""
|
||||
|
||||
|
||||
class HeartbeatConfig(BaseConfig):
|
||||
"""Configures the heartbeat for BetterStack."""
|
||||
|
||||
url: Annotated[str, Field(description="The URL to send the heartbeat to.")]
|
||||
url: str
|
||||
"""URL to send the heartbeat to."""
|
||||
|
||||
|
||||
class MetricsServerConfig(BaseConfig):
|
||||
"""Configures the Prometheus metrics server for trainer observability."""
|
||||
port: int = Field(8000, ge=1, le=65535)
|
||||
"""Port to expose metrics and health endpoints on."""
|
||||
|
||||
port: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
le=65535,
|
||||
description="Port to expose metrics and health endpoints. Defaults to 8000.",
|
||||
),
|
||||
] = 8000
|
||||
|
||||
host: Annotated[
|
||||
str,
|
||||
Field(
|
||||
description="Host to bind the server to. Defaults to 0.0.0.0.",
|
||||
),
|
||||
] = "0.0.0.0"
|
||||
host: str = "0.0.0.0"
|
||||
"""Host to bind the server to."""
|
||||
|
||||
|
||||
class BaseTransportConfig(BaseModel):
|
||||
"""Base configuration for transport."""
|
||||
|
||||
class BaseTransportConfig(BaseConfig):
|
||||
pass
|
||||
|
||||
|
||||
class FileSystemTransportConfig(BaseTransportConfig):
|
||||
"""Configures filesystem-based transport for training examples."""
|
||||
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
|
||||
class ZMQTransportConfig(BaseTransportConfig):
|
||||
"""Configures ZMQ-based transport for training examples."""
|
||||
|
||||
type: Literal["zmq"] = "zmq"
|
||||
host: Annotated[str, Field(description="The host address for ZMQ transport.")] = "localhost"
|
||||
port: Annotated[int, Field(description="The base port for ZMQ transport.")] = 5555
|
||||
hwm: Annotated[int, Field(description="High water mark (max messages in queue) for ZMQ sockets.")] = 10
|
||||
|
||||
host: str = "localhost"
|
||||
"""Host address for ZMQ transport."""
|
||||
|
||||
port: int = 5555
|
||||
"""Base port for ZMQ transport."""
|
||||
|
||||
hwm: int = 10
|
||||
"""High-water mark (max in-flight messages per ZMQ socket)."""
|
||||
|
||||
|
||||
TransportConfig: TypeAlias = Annotated[FileSystemTransportConfig | ZMQTransportConfig, Field(discriminator="type")]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -36,18 +36,18 @@ def validate_shared_model_name(
|
||||
) -> None:
|
||||
# Orchestrator must match inference (it queries the inference server)
|
||||
if inference is not None:
|
||||
if inference.model.name != orchestrator.model.name:
|
||||
if inference.model.name != orchestrator.student.model.name:
|
||||
raise ValueError(
|
||||
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
|
||||
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. "
|
||||
"The orchestrator queries the inference server and must use the same model name."
|
||||
)
|
||||
return
|
||||
|
||||
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
|
||||
return
|
||||
if trainer.model.name != orchestrator.model.name:
|
||||
if trainer.model.name != orchestrator.student.model.name:
|
||||
raise ValueError(
|
||||
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
|
||||
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. Please specify the same model name for both."
|
||||
)
|
||||
|
||||
|
||||
|
||||
+9
-8
@@ -18,7 +18,7 @@ dependencies = [
|
||||
"torchaudio",
|
||||
"torchdata>=0.11.0",
|
||||
"transformers",
|
||||
"vllm>=0.20.2",
|
||||
"vllm>=0.21.0",
|
||||
"wandb>=0.26.1",
|
||||
"ring-flash-attn>=0.1.8",
|
||||
"prime>=0.6.4",
|
||||
@@ -42,8 +42,8 @@ dependencies = [
|
||||
rl = "prime_rl.entrypoints.rl:main"
|
||||
sft = "prime_rl.entrypoints.sft:main"
|
||||
inference = "prime_rl.entrypoints.inference:main"
|
||||
trainer = "prime_rl.trainer.rl.train:main"
|
||||
orchestrator = "prime_rl.orchestrator.orchestrator:main"
|
||||
trainer = "prime_rl.entrypoints.trainer:main"
|
||||
orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
@@ -98,7 +98,7 @@ gpt-oss = [
|
||||
"kernels",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.3.3",
|
||||
"quack-kernels>=0.4.1",
|
||||
]
|
||||
all = [
|
||||
"prime-rl[flash-attn]",
|
||||
@@ -124,6 +124,7 @@ dev = [
|
||||
[tool.uv.workspace]
|
||||
members = [
|
||||
"packages/prime-rl-configs",
|
||||
"deps/pydantic-config",
|
||||
"deps/verifiers",
|
||||
"deps/renderers",
|
||||
"deps/verifiers/environments/alphabet_sort",
|
||||
@@ -176,6 +177,7 @@ override-dependencies = [
|
||||
[tool.uv.exclude-newer-package]
|
||||
# we want latest vllm, remove next patch
|
||||
vllm = false
|
||||
tokenspeed-mla = false
|
||||
flash_attn_3 = false
|
||||
# PrimeIntellect-published on PyPI (trusted publisher)
|
||||
prime = false
|
||||
@@ -185,7 +187,6 @@ prime-evals = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
vllm-router = false
|
||||
dion = false
|
||||
pydantic-config = false
|
||||
deep-ep = false
|
||||
deep-gemm = false
|
||||
nixl-cu12 = false
|
||||
@@ -228,11 +229,11 @@ torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
|
||||
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
|
||||
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
|
||||
prime-pydantic-config = { workspace = true }
|
||||
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
|
||||
|
||||
+15
-1
@@ -116,6 +116,14 @@ id = "math-env"
|
||||
|
||||
On the CLI, list items are indexed: `--env.0.id reverse-text --env.1.id math-env`.
|
||||
|
||||
When composing multiple TOML files, list fields are replaced wholesale by the later file. To change one
|
||||
`orchestrator.filters` entry in an overlay, include the full desired filter list in that overlay.
|
||||
|
||||
For quick KL smoke runs with very small rollout batches, enforced `zero_advantage` filtering can remove
|
||||
every rollout and stop the orchestrator. If the goal is only trainer/inference mismatch KL, keep the
|
||||
filter present but set `enforce = false` in a temporary overlay and call out that the run is not a reward
|
||||
learning validation.
|
||||
|
||||
### Dict fields
|
||||
|
||||
In TOML, use a section:
|
||||
@@ -155,7 +163,13 @@ If you wish to configure values of the default variant, you don't need to set th
|
||||
|
||||
### SFT hard distill override
|
||||
|
||||
For hosted multi-tenant runs where the trainer image's `trainer.loss.type` is fixed, the orchestrator exposes a per-run override that forces SFT loss on every micro-batch without rebuilding the trainer. Set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; both must be configured together (the orchestrator validator enforces this). The orchestrator stamps each `TrainingSample.sft_loss = True`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch — independent of the trainer's configured default loss.
|
||||
Set `orchestrator.training_mode = "sft"` (or top-level `training_mode = "sft"`, which auto-propagates) and configure `orchestrator.teacher` with the teacher endpoint. The orchestrator stamps each `TrainingSample.sft_loss = True` and the shared `training_mode` validator sets `trainer.loss.type = "sft"`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch.
|
||||
|
||||
`[inference]` is required (same as rl/opd) — it starts the student inference server and auto-configures `orchestrator.student.client.base_url`. The student pool is used for online evals and policy weight sync. For externally started student inference, set `orchestrator.student.client.base_url` explicitly instead.
|
||||
|
||||
### RL rollout client defaults
|
||||
|
||||
For text-only RL rollouts, the orchestrator defaults to renderer-backed TITO (`use_renderer = true`). VLM configs must explicitly fall back to MITO (`use_renderer = false`) so image preprocessing and chat templating stay server-side. External teacher rollouts must also set `use_renderer = false`.
|
||||
|
||||
### Model fields
|
||||
|
||||
|
||||
@@ -49,7 +49,6 @@ uv run inference --model.name Qwen/Qwen3-0.6B --model.enforce-eager
|
||||
Always use the `inference` entrypoint — never `vllm serve` directly.
|
||||
|
||||
Custom endpoints beyond standard OpenAI API:
|
||||
- `/v1/chat/completions/tokens` — accepts token IDs as prompt input
|
||||
- `/update_weights` — hot-reload model weights from the trainer
|
||||
- `/load_lora_adapter` — load LoRA adapters at runtime
|
||||
- `/init_broadcaster` — initialize weight broadcast for distributed training
|
||||
|
||||
@@ -12,18 +12,18 @@ prime-rl is a monorepo with submodules. Clone the repo first, then initialize su
|
||||
```bash
|
||||
git clone git@github.com:PrimeIntellect-ai/prime-rl.git
|
||||
cd prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
```
|
||||
|
||||
For an existing clone, initialize the public submodules by passing explicit paths:
|
||||
|
||||
```bash
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
|
||||
```
|
||||
|
||||
Do **not** use `git submodule update --init --recursive` without explicit paths — it will also attempt to clone `configs/private` (a private submodule) and fail with "Repository not found" for users without access. Git will retry the clone once internally before aborting, which is expected behavior.
|
||||
|
||||
The public submodules live under `deps/`: `deps/verifiers/`, `deps/renderers/`, and `deps/research-environments/`. Each is also a uv workspace member, so source edits inside them apply to the prime-rl venv without re-sync.
|
||||
The public submodules live under `deps/`: `deps/verifiers/`, `deps/renderers/`, `deps/research-environments/`, and `deps/pydantic-config/`. The uv workspace members among them apply source edits to the prime-rl venv without re-sync.
|
||||
|
||||
The install script (`scripts/install.sh`) handles the private submodule gracefully — it iterates each submodule individually so a failed `configs/private` init does not abort the rest.
|
||||
|
||||
@@ -36,6 +36,8 @@ uv sync --all-extras # recommended: includes envs, flash-attn, flash-attn-cute,
|
||||
|
||||
The `envs` extra installs the env packages listed in `pyproject.toml > [tool.uv.workspace] members`. Adding a new env means adding it there, in the `envs` extra, and in `[tool.uv.sources]`.
|
||||
|
||||
When intentionally bumping a package to a release newer than the workspace-wide `exclude-newer = "7 days"` window, add that package and any newly required transitive packages to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
|
||||
## Advanced
|
||||
|
||||
### Mamba-SSM (NemotronH models)
|
||||
|
||||
@@ -143,8 +143,8 @@ These tell you whether training is healthy or diverging.
|
||||
|
||||
| Metric | Source | Description |
|
||||
|--------|--------|-------------|
|
||||
| `mismatch_kl/mean` | trainer | KL divergence between trainer and (old) inference policy |
|
||||
| `entropy/mean` | trainer | policy entropy |
|
||||
| `mismatch_kl/{all,env}/{mean,std,max}` | trainer | KL divergence between trainer and (old) inference policy over trainable tokens (W&B) |
|
||||
| `entropy/{all,env}/{mean,std,max}` | trainer | policy entropy over trainable tokens (W&B) |
|
||||
| `masked_advantage_positive/mean` | trainer | fraction of DPPO-masked trainable tokens with positive advantage (W&B) |
|
||||
| `masked_advantage_negative/mean` | trainer | fraction of DPPO-masked trainable tokens with negative advantage (W&B) |
|
||||
| `optim/grad_norm` | trainer | gradient norm — spikes may precede divergence |
|
||||
@@ -253,4 +253,3 @@ PRIME-RL::Launcher
|
||||
```
|
||||
|
||||
For multi-node runs, trainer and inference processes are distributed across separate nodes. Use `srun` or `ssh` to inspect processes on other nodes directly.
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Lightweight launcher for the orchestrator.
|
||||
|
||||
Defers heavy ML imports (verifiers, transformers, pandas, prime_rl.trainer.*)
|
||||
until after ``cli()`` parses CLI args, so ``orchestrator --help`` short-circuits
|
||||
in ``cli()`` and returns in ~0.5 s instead of ~9 s.
|
||||
|
||||
The actual orchestrator implementation lives in
|
||||
``prime_rl.orchestrator.orchestrator``, which is also runnable as
|
||||
``python -m prime_rl.orchestrator.orchestrator``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Orchestrator")
|
||||
config = cli(OrchestratorConfig)
|
||||
from prime_rl.orchestrator.orchestrator import orchestrate
|
||||
|
||||
asyncio.run(orchestrate(config))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -12,23 +12,18 @@ from threading import Event, Thread
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
format_log_message,
|
||||
get_ckpt_dir,
|
||||
get_log_dir,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_output_dir,
|
||||
)
|
||||
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process, set_proc_title
|
||||
from prime_rl.utils.utils import (
|
||||
get_free_port,
|
||||
get_log_dir,
|
||||
)
|
||||
|
||||
RL_TOML = "rl.toml"
|
||||
RL_SBATCH = "rl.sbatch"
|
||||
@@ -78,26 +73,6 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
tomli_w.dump(teacher_inference.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
|
||||
def check_gpus_available(gpu_ids: list[int]) -> None:
|
||||
"""Raise error if there are existing processes on the specified GPUs."""
|
||||
pynvml.nvmlInit()
|
||||
|
||||
occupied = []
|
||||
for gpu_id in gpu_ids:
|
||||
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
|
||||
processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
|
||||
if processes:
|
||||
pids = [p.pid for p in processes]
|
||||
occupied.append((gpu_id, pids))
|
||||
|
||||
if occupied:
|
||||
msg = "Existing processes found on GPUs:\n"
|
||||
for gpu_id, pids in occupied:
|
||||
msg += f" GPU {gpu_id}: PIDs {pids}\n"
|
||||
msg += "Kill these processes or use different GPUs."
|
||||
raise RuntimeError(msg)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
assert config.deployment.type == "single_node"
|
||||
|
||||
@@ -148,21 +123,17 @@ def rl_local(config: RLConfig):
|
||||
wandb_shared_env["WANDB_SHARED_MODE"] = "1"
|
||||
wandb_shared_env["WANDB_SHARED_RUN_ID"] = os.environ.get("WANDB_SHARED_RUN_ID", uuid.uuid4().hex)
|
||||
|
||||
# Check for existing processes on GPUs
|
||||
all_gpu_ids = list(set(infer_gpu_ids + trainer_gpu_ids + teacher_gpu_ids))
|
||||
check_gpus_available(all_gpu_ids)
|
||||
|
||||
# Validate client port matches inference server port
|
||||
if config.inference is not None and not config.orchestrator.client.is_elastic:
|
||||
if config.inference is not None and not config.orchestrator.student.client.is_elastic:
|
||||
from urllib.parse import urlparse
|
||||
|
||||
base_url = config.orchestrator.client.base_url[0]
|
||||
base_url = config.orchestrator.student.client.base_url[0]
|
||||
parsed = urlparse(base_url)
|
||||
client_port = parsed.port
|
||||
expected_port = config.inference.server.port
|
||||
if client_port != expected_port:
|
||||
raise ValueError(
|
||||
f"orchestrator.client.base_url port ({client_port}) does not match "
|
||||
f"orchestrator.student.client.base_url port ({client_port}) does not match "
|
||||
f"inference.server.port ({expected_port}). "
|
||||
f"Update the base_url to use port {expected_port} to match the inference server."
|
||||
)
|
||||
@@ -215,14 +186,13 @@ def rl_local(config: RLConfig):
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
else:
|
||||
if config.orchestrator.teacher_rollout_model is None:
|
||||
logger.warning(
|
||||
"No inference config specified, skipping starting inference server. Make sure your inference server is running."
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"No inference config specified, using orchestrator.teacher_rollout_model for rollout generation."
|
||||
)
|
||||
logger.warning(
|
||||
"No [inference] block configured - the student inference server will not be started here. "
|
||||
"All training modes (rl/opd/sft) require a student inference pool for evals + weight sync; "
|
||||
"make sure one is running at orchestrator.student.client.base_url "
|
||||
f"({', '.join(config.orchestrator.student.client.base_url)}), otherwise the orchestrator "
|
||||
"will hang waiting for it."
|
||||
)
|
||||
|
||||
# Optionally, start teacher inference process
|
||||
if config.teacher_inference:
|
||||
@@ -230,7 +200,7 @@ def rl_local(config: RLConfig):
|
||||
raise ValueError(
|
||||
"teacher_inference is configured but deployment.num_teacher_gpus is not set. "
|
||||
"Either set deployment.num_teacher_gpus to start a teacher inference server, "
|
||||
"or omit teacher_inference and configure orchestrator.teacher_model to use an existing server."
|
||||
"or omit teacher_inference and configure orchestrator.teacher to use an existing server."
|
||||
)
|
||||
|
||||
teacher_inference_cmd = ["inference", "@", (config_dir / TEACHER_INFERENCE_TOML).as_posix()]
|
||||
@@ -258,12 +228,10 @@ def rl_local(config: RLConfig):
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
elif (
|
||||
config.trainer.loss.type == "default" and config.trainer.loss.teacher_tau > 0
|
||||
) or config.orchestrator.teacher_model:
|
||||
elif config.orchestrator.teacher:
|
||||
logger.warning(
|
||||
"No teacher_inference config specified, skipping starting teacher inference server. "
|
||||
"Is your teacher inference server running? Make sure orchestrator.teacher_model is configured."
|
||||
"Is your teacher inference server running? Make sure orchestrator.teacher is configured."
|
||||
)
|
||||
|
||||
# Start orchestrator process
|
||||
@@ -302,6 +270,8 @@ def rl_local(config: RLConfig):
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
# Start training process
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
trainer_cmd = [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
@@ -571,6 +541,8 @@ def rl(config: RLConfig):
|
||||
clean_future_steps(config.output_dir, -1)
|
||||
|
||||
if not config.dry_run:
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
|
||||
pre_download_model(config.trainer.model.name)
|
||||
|
||||
if config.slurm is not None:
|
||||
|
||||
@@ -8,14 +8,11 @@ from threading import Event, Thread
|
||||
|
||||
import tomli_w
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir, validate_output_dir
|
||||
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process, set_proc_title
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
SFT_TOML = "sft.toml"
|
||||
SFT_SBATCH = "sft.sbatch"
|
||||
@@ -115,6 +112,8 @@ def sft_local(config: SFTConfig):
|
||||
log_dir = config.output_dir / "logs"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
|
||||
trainer_cmd = [
|
||||
"torchrun",
|
||||
"--role=trainer",
|
||||
@@ -199,6 +198,8 @@ def sft(config: SFTConfig):
|
||||
config.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if not config.dry_run:
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
|
||||
pre_download_model(config.model.name)
|
||||
|
||||
if config.slurm is not None:
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Lightweight launcher for the RL trainer.
|
||||
|
||||
Defers heavy ML imports (torch, transformers, torchtitan, ring_flash_attn,
|
||||
prime_rl.trainer.*) until after ``cli()`` parses CLI args, so ``trainer --help``
|
||||
short-circuits in ``cli()`` and returns in ~0.5 s instead of ~10 s.
|
||||
|
||||
The actual training implementation lives in ``prime_rl.trainer.rl.train``,
|
||||
which is also runnable as ``python -m prime_rl.trainer.rl.train`` (used by
|
||||
the ``rl`` launcher under torchrun).
|
||||
"""
|
||||
|
||||
from prime_rl.configs.trainer import TrainerConfig
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Trainer")
|
||||
config = cli(TrainerConfig)
|
||||
from prime_rl.trainer.rl.train import train
|
||||
|
||||
train(config)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +1,6 @@
|
||||
import torch
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
|
||||
|
||||
|
||||
def transformers_v5_compat():
|
||||
@@ -15,10 +16,9 @@ def transformers_v5_compat():
|
||||
|
||||
_patch_qwen35_lora()
|
||||
_patch_lora_key_prefix()
|
||||
monkey_patch_deep_gemm_ep_scatter()
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
monkey_patch_dp_engine_core_pause_resume_deadlock()
|
||||
monkey_patch_vllm_layerwise_reload_alias_buffers()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
|
||||
|
||||
def monkey_patch_vllm_layerwise_reload_alias_buffers():
|
||||
@@ -29,6 +29,8 @@ def monkey_patch_vllm_layerwise_reload_alias_buffers():
|
||||
# storage *after* the parameter has been correctly reloaded. Skip the copy
|
||||
# for any buffer that shares storage with a parameter; _place_kernel_tensors
|
||||
# re-registers the original view, which trivially reflects the parameter.
|
||||
# Remove this patch once https://github.com/vllm-project/vllm/pull/42481 is
|
||||
# included in the vLLM release we pin/use.
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import layerwise as reload_layerwise
|
||||
|
||||
@@ -51,294 +53,6 @@ def monkey_patch_vllm_layerwise_reload_alias_buffers():
|
||||
logger.warning("Enabled vLLM layerwise reload alias-buffer patch.")
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _apply_expert_map_triton(expert_id, expert_map):
|
||||
if expert_id != -1:
|
||||
expert_id = tl.load(expert_map + expert_id).to(expert_id.dtype)
|
||||
return expert_id
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _fwd_kernel_ep_scatter_2_int64(
|
||||
total_token_num,
|
||||
expert_start_loc,
|
||||
recv_x,
|
||||
recv_x_stride0,
|
||||
recv_x_stride1,
|
||||
recv_x_scale,
|
||||
recv_x_scale_stride0,
|
||||
recv_x_scale_stride1,
|
||||
recv_topk,
|
||||
recv_topk_stride0,
|
||||
recv_topk_stride1,
|
||||
output_tensor,
|
||||
output_tensor_stride0,
|
||||
output_tensor_stride1,
|
||||
output_tensor_scale,
|
||||
output_tensor_scale_stride0,
|
||||
output_tensor_scale_stride1,
|
||||
output_index,
|
||||
output_index_stride0,
|
||||
output_index_stride1,
|
||||
topk_num: tl.constexpr,
|
||||
expert_map,
|
||||
HAS_EXPERT_MAP: tl.constexpr,
|
||||
HIDDEN_SIZE: tl.constexpr,
|
||||
HIDDEN_SIZE_PAD: tl.constexpr,
|
||||
SCALE_HIDDEN_SIZE: tl.constexpr,
|
||||
SCALE_HIDDEN_SIZE_PAD: tl.constexpr,
|
||||
):
|
||||
start_token_id = tl.program_id(0)
|
||||
grid_num = tl.num_programs(0)
|
||||
|
||||
offset_in = tl.arange(0, HIDDEN_SIZE_PAD)
|
||||
mask = offset_in < HIDDEN_SIZE
|
||||
|
||||
offset_in_s = tl.arange(0, SCALE_HIDDEN_SIZE_PAD)
|
||||
mask_s = offset_in_s < SCALE_HIDDEN_SIZE
|
||||
|
||||
output_tensor_stride0 = output_tensor_stride0.to(tl.int64)
|
||||
|
||||
for token_id in range(start_token_id, total_token_num, grid_num):
|
||||
to_copy = tl.load(recv_x + token_id * recv_x_stride0 + offset_in, mask=mask)
|
||||
to_copy_s = tl.load(
|
||||
recv_x_scale + token_id * recv_x_scale_stride0 + offset_in_s,
|
||||
mask=mask_s,
|
||||
)
|
||||
|
||||
for topk_index in tl.range(0, topk_num, 1, num_stages=4):
|
||||
expert_id = tl.load(recv_topk + token_id * recv_topk_stride0 + topk_index)
|
||||
|
||||
if HAS_EXPERT_MAP:
|
||||
expert_id = _apply_expert_map_triton(expert_id, expert_map)
|
||||
|
||||
if expert_id >= 0:
|
||||
dest_token_index = tl.atomic_add(expert_start_loc + expert_id, 1)
|
||||
dest_token_index_i64 = dest_token_index.to(tl.int64)
|
||||
|
||||
tl.store(
|
||||
output_index + token_id * output_index_stride0 + topk_index,
|
||||
dest_token_index,
|
||||
)
|
||||
|
||||
output_tensor_ptr = output_tensor + dest_token_index_i64 * output_tensor_stride0
|
||||
output_tensor_scale_ptr = output_tensor_scale + dest_token_index * output_tensor_scale_stride0
|
||||
tl.store(output_tensor_ptr + offset_in, to_copy, mask=mask)
|
||||
tl.store(output_tensor_scale_ptr + offset_in_s, to_copy_s, mask=mask_s)
|
||||
|
||||
|
||||
def _triton_ep_scatter_int64(
|
||||
recv_x: torch.Tensor,
|
||||
recv_x_scale: torch.Tensor,
|
||||
recv_topk: torch.Tensor,
|
||||
num_recv_tokens_per_expert: torch.Tensor,
|
||||
expert_map: torch.Tensor | None,
|
||||
expert_start_loc: torch.Tensor,
|
||||
output_tensor: torch.Tensor,
|
||||
output_tensor_scale: torch.Tensor,
|
||||
m_indices: torch.Tensor,
|
||||
output_index: torch.Tensor,
|
||||
) -> None:
|
||||
from vllm.model_executor.layers.fused_moe import deep_gemm_utils
|
||||
|
||||
block_e = 128
|
||||
num_warps = 8
|
||||
num_experts = num_recv_tokens_per_expert.shape[0]
|
||||
hidden_size = recv_x.shape[1]
|
||||
|
||||
assert m_indices.shape[0] % block_e == 0
|
||||
assert expert_start_loc.shape[0] == num_experts
|
||||
|
||||
deep_gemm_utils._fwd_kernel_ep_scatter_1[(num_experts,)](
|
||||
num_recv_tokens_per_expert,
|
||||
expert_start_loc,
|
||||
m_indices,
|
||||
num_experts=num_experts,
|
||||
num_warps=num_warps,
|
||||
BLOCK_E=block_e,
|
||||
BLOCK_EXPERT_NUM=triton.next_power_of_2(num_experts),
|
||||
)
|
||||
|
||||
grid = min(recv_topk.shape[0], 1024 * 8)
|
||||
_fwd_kernel_ep_scatter_2_int64[(grid,)](
|
||||
recv_topk.shape[0],
|
||||
expert_start_loc,
|
||||
recv_x,
|
||||
recv_x.stride(0),
|
||||
recv_x.stride(1),
|
||||
recv_x_scale,
|
||||
recv_x_scale.stride(0),
|
||||
recv_x_scale.stride(1),
|
||||
recv_topk,
|
||||
recv_topk.stride(0),
|
||||
recv_topk.stride(1),
|
||||
output_tensor,
|
||||
output_tensor.stride(0),
|
||||
output_tensor.stride(1),
|
||||
output_tensor_scale,
|
||||
output_tensor_scale.stride(0),
|
||||
output_tensor_scale.stride(1),
|
||||
output_index,
|
||||
output_index.stride(0),
|
||||
output_index.stride(1),
|
||||
topk_num=recv_topk.shape[1],
|
||||
expert_map=expert_map,
|
||||
HAS_EXPERT_MAP=expert_map is not None,
|
||||
num_warps=num_warps,
|
||||
HIDDEN_SIZE=hidden_size,
|
||||
HIDDEN_SIZE_PAD=triton.next_power_of_2(hidden_size),
|
||||
SCALE_HIDDEN_SIZE=recv_x_scale.shape[1],
|
||||
SCALE_HIDDEN_SIZE_PAD=triton.next_power_of_2(recv_x_scale.shape[1]),
|
||||
)
|
||||
|
||||
|
||||
def monkey_patch_deep_gemm_ep_scatter():
|
||||
# Temporary local carry of the upstream fix while it is under review:
|
||||
# issue: https://github.com/vllm-project/vllm/issues/39211
|
||||
# PR: https://github.com/vllm-project/vllm/pull/39213
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe import deep_gemm_utils
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
deep_gemm_utils.ep_scatter = torch.no_grad()(_triton_ep_scatter_int64)
|
||||
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM ep_scatter.")
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel(
|
||||
y_ptr,
|
||||
y_q_ptr,
|
||||
y_s_ptr,
|
||||
M: tl.int64,
|
||||
N: tl.int64,
|
||||
y_s_col_stride: tl.int64,
|
||||
eps,
|
||||
fp8_min: tl.constexpr,
|
||||
fp8_max: tl.constexpr,
|
||||
use_ue8m0: tl.constexpr,
|
||||
GROUP_SIZE: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
pid_m = tl.program_id(0)
|
||||
pid_n = tl.program_id(1)
|
||||
N_2 = N // 2
|
||||
|
||||
m_offset = (pid_m * BLOCK_M).to(tl.int64)
|
||||
n_offset = (pid_n * BLOCK_N).to(tl.int64)
|
||||
if m_offset >= M:
|
||||
return
|
||||
|
||||
offs_n = tl.arange(0, BLOCK_N).to(tl.int64)
|
||||
offs_m = tl.arange(0, BLOCK_M).to(tl.int64)
|
||||
|
||||
base_y_ptr = y_ptr + m_offset * N + n_offset
|
||||
act_in_ptrs = base_y_ptr + offs_m[:, None] * N + offs_n[None, :]
|
||||
|
||||
act_in = tl.load(act_in_ptrs)
|
||||
mul_in = tl.load(act_in_ptrs + N_2)
|
||||
|
||||
act_in = act_in.to(tl.float32)
|
||||
one_f32 = tl.cast(1, tl.float32)
|
||||
silu_out = (act_in / (one_f32 + tl.exp(-act_in))).to(y_ptr.dtype.element_ty)
|
||||
y = (silu_out * mul_in).to(tl.float32)
|
||||
|
||||
absmax = tl.maximum(tl.max(tl.abs(y), axis=1), eps)
|
||||
scale_raw = absmax * (1.0 / fp8_max)
|
||||
y_s = tl.math.exp2(tl.ceil(tl.log2(scale_raw))) if use_ue8m0 else scale_raw
|
||||
y_s = tl.reshape(y_s, (BLOCK_M, 1))
|
||||
y_q = tl.clamp(y / y_s, fp8_min, fp8_max).to(y_q_ptr.dtype.element_ty)
|
||||
|
||||
base_y_q_ptr = y_q_ptr + m_offset * N_2 + n_offset
|
||||
y_q_ptrs = base_y_q_ptr + offs_m[:, None] * N_2 + offs_n[None, :]
|
||||
tl.store(y_q_ptrs, y_q)
|
||||
|
||||
group_id = n_offset // GROUP_SIZE
|
||||
base_y_s_ptr = y_s_ptr + group_id * y_s_col_stride + m_offset
|
||||
y_s_ptrs = base_y_s_ptr + offs_m
|
||||
y_s = tl.reshape(y_s, (BLOCK_M,))
|
||||
tl.store(y_s_ptrs, y_s)
|
||||
|
||||
|
||||
def _silu_mul_per_token_group_quant_fp8_colmajor_int64(
|
||||
input: torch.Tensor,
|
||||
output: torch.Tensor | None = None,
|
||||
use_ue8m0: bool | None = None,
|
||||
eps: float = 1e-10,
|
||||
):
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.deep_gemm import is_deep_gemm_e8m0_used
|
||||
|
||||
group_size = 128
|
||||
assert input.ndim == 2
|
||||
if output is not None:
|
||||
assert output.ndim == 2
|
||||
assert input.size(0) % group_size == 0
|
||||
assert input.size(1) % (group_size * 2) == 0
|
||||
|
||||
if use_ue8m0 is None:
|
||||
use_ue8m0 = is_deep_gemm_e8m0_used()
|
||||
|
||||
M, N = input.size()
|
||||
N_2 = N // 2
|
||||
|
||||
fp8_dtype = current_platform.fp8_dtype()
|
||||
if output is None:
|
||||
output = torch.empty((M, N_2), dtype=fp8_dtype, device=input.device)
|
||||
|
||||
output_scales = torch.empty(((N_2 // group_size), M), dtype=torch.float32, device=input.device).transpose(0, 1)
|
||||
|
||||
block_m = 8
|
||||
block_n = group_size
|
||||
assert M % block_m == 0
|
||||
assert N_2 % block_n == 0
|
||||
|
||||
finfo = torch.finfo(fp8_dtype)
|
||||
fp8_min = -224.0 if current_platform.is_fp8_fnuz() else finfo.min
|
||||
fp8_max = 224.0 if current_platform.is_fp8_fnuz() else finfo.max
|
||||
|
||||
grid = (M // block_m, N_2 // block_n)
|
||||
_silu_mul_per_token_group_quant_fp8_colmajor_int64_kernel[grid](
|
||||
input,
|
||||
output,
|
||||
output_scales,
|
||||
M,
|
||||
N,
|
||||
output_scales.stride(-1),
|
||||
eps,
|
||||
fp8_min,
|
||||
fp8_max,
|
||||
use_ue8m0,
|
||||
group_size,
|
||||
block_m,
|
||||
block_n,
|
||||
)
|
||||
|
||||
return output, output_scales
|
||||
|
||||
|
||||
def monkey_patch_deep_gemm_silu_mul_quant_int64():
|
||||
# Temporary local carry for large DeepGEMM profile shapes whose row offsets
|
||||
# exceed signed int32 address arithmetic in vLLM's Triton kernel.
|
||||
import sys
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils import fp8_utils
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
fp8_utils.silu_mul_per_token_group_quant_fp8_colmajor = _silu_mul_per_token_group_quant_fp8_colmajor_int64
|
||||
|
||||
deep_gemm_moe_module = sys.modules.get("vllm.model_executor.layers.fused_moe.experts.deep_gemm_moe")
|
||||
if deep_gemm_moe_module is not None:
|
||||
deep_gemm_moe_module.silu_mul_per_token_group_quant_fp8_colmajor = (
|
||||
_silu_mul_per_token_group_quant_fp8_colmajor_int64
|
||||
)
|
||||
|
||||
logger.warning("Enabled int64-addressing Triton patch for vLLM DeepGEMM SiLU/mul FP8 quant.")
|
||||
|
||||
|
||||
def _patch_qwen35_lora():
|
||||
"""Fix Qwen3.5 LoRA: align packed_modules_mapping with output_sizes.
|
||||
|
||||
@@ -897,9 +611,9 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
- on resume, wake every DP rank and force an immediate global unfinished
|
||||
sync instead of waiting for the normal 32-step cadence
|
||||
|
||||
This keeps the upstream pause-side fix from
|
||||
https://github.com/vllm-project/vllm/pull/37024 and extends it with the
|
||||
resume-side wave-state fix.
|
||||
This also bypasses vLLM's two-phase DP pause implementation
|
||||
(https://github.com/vllm-project/vllm/pull/39366), which makes resume
|
||||
reject states that our weight-update flow can validly hit.
|
||||
"""
|
||||
from vllm.config import ParallelConfig
|
||||
from vllm.v1.core.sched.interface import PauseState
|
||||
@@ -909,7 +623,8 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
|
||||
_base_add_request = EngineCore.add_request
|
||||
_base_handle_client_request = EngineCoreProc._handle_client_request
|
||||
_base_resume_scheduler = DPEngineCoreProc.resume_scheduler
|
||||
_base_pause_complete = EngineCoreProc._pause_complete
|
||||
_base_resume_scheduler = EngineCoreProc.resume_scheduler
|
||||
|
||||
def _patched_add_request(self, request: Request, request_wave: int = 0):
|
||||
_base_add_request(self, request, request_wave)
|
||||
@@ -930,8 +645,15 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
else:
|
||||
_base_handle_client_request(self, request_type, request)
|
||||
|
||||
def _patched_pause_complete(self) -> bool:
|
||||
self.pending_pause = False
|
||||
self.ignore_start_dp_wave = False
|
||||
return _base_pause_complete(self)
|
||||
|
||||
def _patched_resume_scheduler(self):
|
||||
was_paused = self.scheduler.pause_state != PauseState.UNPAUSED
|
||||
self.pending_pause = False
|
||||
self.ignore_start_dp_wave = False
|
||||
_base_resume_scheduler(self)
|
||||
if was_paused:
|
||||
self.engines_running = True
|
||||
@@ -948,6 +670,7 @@ def monkey_patch_dp_engine_core_pause_resume_deadlock():
|
||||
|
||||
DPEngineCoreProc.add_request = _patched_add_request
|
||||
DPEngineCoreProc._handle_client_request = _patched_handle_client_request
|
||||
DPEngineCoreProc._pause_complete = _patched_pause_complete
|
||||
DPEngineCoreProc.resume_scheduler = _patched_resume_scheduler
|
||||
DPEngineCoreProc._has_global_unfinished_reqs = _patched_has_global_unfinished_reqs
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_INSTALL_LOCK = threading.Lock()
|
||||
_INSTALLED = False
|
||||
|
||||
|
||||
def monkey_patch_vllm_padded_input_scrub() -> None:
|
||||
"""Zero vLLM's padded model inputs before graph replay.
|
||||
|
||||
vLLM pads decode batches up to CUDA graph capture sizes. Some kernels read
|
||||
model-input tensors past the scheduled-token prefix, so stale values in the
|
||||
padded tail can affect replayed decode graphs. Keep this shim until the
|
||||
vLLM-side fix is available in the pinned runtime.
|
||||
|
||||
Remove this patch once https://github.com/vllm-project/vllm/pull/42779 is
|
||||
included in the vLLM release we pin/use.
|
||||
"""
|
||||
global _INSTALLED
|
||||
with _INSTALL_LOCK:
|
||||
if _INSTALLED:
|
||||
return
|
||||
|
||||
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
|
||||
|
||||
if getattr(GPUModelRunner, "_prime_rl_padded_input_scrub", False):
|
||||
_INSTALLED = True
|
||||
return
|
||||
|
||||
original_preprocess = GPUModelRunner._preprocess
|
||||
|
||||
def _patched_preprocess(
|
||||
self: Any,
|
||||
scheduler_output: Any,
|
||||
num_input_tokens: int,
|
||||
intermediate_tensors: Any | None = None,
|
||||
) -> tuple[Any, ...]:
|
||||
result = original_preprocess(
|
||||
self,
|
||||
scheduler_output,
|
||||
num_input_tokens,
|
||||
intermediate_tensors,
|
||||
)
|
||||
|
||||
num_scheduled_tokens = int(scheduler_output.total_num_scheduled_tokens)
|
||||
_zero_padded_model_inputs(
|
||||
result,
|
||||
num_scheduled_tokens,
|
||||
int(num_input_tokens),
|
||||
)
|
||||
return result
|
||||
|
||||
GPUModelRunner._preprocess = _patched_preprocess
|
||||
GPUModelRunner._prime_rl_padded_input_scrub = True
|
||||
_INSTALLED = True
|
||||
|
||||
logger.warning("Enabled vLLM padded model-input scrub.")
|
||||
|
||||
|
||||
def _zero_padded_model_inputs(
|
||||
preprocess_result: Sequence[Any],
|
||||
num_scheduled_tokens: int,
|
||||
num_input_tokens: int,
|
||||
) -> None:
|
||||
"""Zero the model-input tail beyond scheduled tokens in-place."""
|
||||
if num_input_tokens <= num_scheduled_tokens:
|
||||
return
|
||||
|
||||
input_ids = preprocess_result[0]
|
||||
inputs_embeds = preprocess_result[1]
|
||||
positions = preprocess_result[2]
|
||||
pad_slice = slice(num_scheduled_tokens, num_input_tokens)
|
||||
|
||||
if input_ids is not None:
|
||||
input_ids[pad_slice].zero_()
|
||||
if inputs_embeds is not None:
|
||||
inputs_embeds[pad_slice].zero_()
|
||||
if positions is not None:
|
||||
if positions.ndim == 1:
|
||||
positions[pad_slice].zero_()
|
||||
else:
|
||||
positions[..., pad_slice].zero_()
|
||||
@@ -1,22 +1,17 @@
|
||||
import asyncio
|
||||
from argparse import Namespace
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
|
||||
import uvloop
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.datastructures import State
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.entrypoints.openai.api_server import init_app_state
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionResponse
|
||||
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.openai.engine.serving import OpenAIServing
|
||||
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
|
||||
from vllm.entrypoints.openai.utils import validate_json_request
|
||||
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
|
||||
from vllm.entrypoints.utils import load_aware_call, with_cancellation
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
|
||||
@@ -139,10 +134,7 @@ from prime_rl.inference.patches import (
|
||||
monkey_patch_harmony_stop_token_propagation,
|
||||
monkey_patch_load_lora_adapter,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
)
|
||||
from prime_rl.inference.vllm.serving_chat_with_tokens import (
|
||||
ChatCompletionRequestWithTokens,
|
||||
OpenAIServingChatWithTokens,
|
||||
monkey_patch_vllm_padded_input_scrub,
|
||||
)
|
||||
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models
|
||||
@@ -154,6 +146,9 @@ monkey_patch_load_lora_adapter()
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
|
||||
# is available in our pinned runtime.
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.openai.api_server")
|
||||
|
||||
@@ -165,10 +160,6 @@ def engine_client(request: Request) -> EngineClient:
|
||||
return request.app.state.engine_client
|
||||
|
||||
|
||||
def base(request: Request) -> OpenAIServing:
|
||||
return request.app.state.openai_serving_tokenization
|
||||
|
||||
|
||||
def models(request: Request) -> OpenAIServingModels:
|
||||
return request.app.state.openai_serving_models
|
||||
|
||||
@@ -179,36 +170,6 @@ WORKER_EXTENSION_CLS = {
|
||||
}
|
||||
|
||||
|
||||
def chat_with_tokens(request: Request) -> OpenAIServingChatWithTokens | None:
|
||||
return request.app.state.openai_serving_chat_with_tokens
|
||||
|
||||
|
||||
@router.post(
|
||||
"/v1/chat/completions/tokens",
|
||||
dependencies=[Depends(validate_json_request)],
|
||||
responses={
|
||||
HTTPStatus.OK.value: {"content": {"text/event-stream": {}}},
|
||||
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
|
||||
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
|
||||
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
|
||||
},
|
||||
)
|
||||
@with_cancellation
|
||||
@load_aware_call
|
||||
async def _chat_with_tokens(request: ChatCompletionRequestWithTokens, raw_request: Request):
|
||||
handler = chat_with_tokens(raw_request)
|
||||
if handler is None:
|
||||
return base(raw_request).create_error_response(message="The model does not support Chat Completions API")
|
||||
generator = await handler.create_chat_completion_with_tokens(request, raw_request)
|
||||
if isinstance(generator, ErrorResponse):
|
||||
return JSONResponse(content=generator.model_dump(), status_code=generator.error.code)
|
||||
|
||||
elif isinstance(generator, ChatCompletionResponse):
|
||||
return JSONResponse(content=generator.model_dump())
|
||||
|
||||
return StreamingResponse(content=generator, media_type="text/event-stream")
|
||||
|
||||
|
||||
@router.post("/pause")
|
||||
async def pause(request: Request):
|
||||
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
|
||||
@@ -277,10 +238,7 @@ async def custom_init_app_state(
|
||||
Modifies init_app_state:
|
||||
1. Call the original init_app_state to set up standard state, including
|
||||
vLLM 0.20's ``serving_tokens`` for ``/inference/v1/generate``.
|
||||
2. Replace ``serving_chat`` with our ``OpenAIServingChatWithTokens`` wrapper
|
||||
so the ``/v1/chat/completions/tokens`` (TITO) endpoint can stream
|
||||
token IDs alongside the rendered chat completion.
|
||||
3. Replace ``serving_tokens`` with ``PrimeRlServingTokens`` so DP-rank
|
||||
2. Replace ``serving_tokens`` with ``PrimeRlServingTokens`` so DP-rank
|
||||
routing and ``routed_experts`` export survive the migration off the
|
||||
legacy ``/v1/generate`` endpoint.
|
||||
"""
|
||||
@@ -289,16 +247,6 @@ async def custom_init_app_state(
|
||||
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
|
||||
state.liveness_timeout_seconds = args.liveness_timeout_seconds
|
||||
|
||||
# TITO: server-side chat templating + token IDs.
|
||||
if "generate" in supported_tasks and state.openai_serving_chat is not None:
|
||||
original_chat = state.openai_serving_chat
|
||||
serving_chat = object.__new__(OpenAIServingChatWithTokens)
|
||||
serving_chat.__dict__.update(original_chat.__dict__)
|
||||
state.openai_serving_chat = serving_chat
|
||||
state.openai_serving_chat_with_tokens = serving_chat
|
||||
else:
|
||||
state.openai_serving_chat_with_tokens = None
|
||||
|
||||
# Swap in our ServingTokens subclass for /inference/v1/generate so the
|
||||
# X-data-parallel-rank header and routed_experts response field — both
|
||||
# used by prime-RL's renderer / router-replay paths — keep working.
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
from collections.abc import AsyncGenerator, AsyncIterator
|
||||
from typing import ClassVar, Optional, Union
|
||||
|
||||
from fastapi import Request
|
||||
from pydantic import Field
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest, ChatCompletionResponse
|
||||
from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, RequestResponseMetadata
|
||||
from vllm.entrypoints.openai.engine.serving import GenerationError
|
||||
from vllm.entrypoints.utils import get_max_tokens
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.logger import init_logger
|
||||
from vllm.outputs import RequestOutput
|
||||
from vllm.reasoning import ReasoningParser
|
||||
from vllm.sampling_params import BeamSearchParams, SamplingParams
|
||||
|
||||
from prime_rl.inference.vllm.serving_tokens import _RoutedExpertsCaptureBase
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class _RoutedExpertsCapture(_RoutedExpertsCaptureBase):
|
||||
"""Chat-endpoint variant: mutates choices in-place because
|
||||
``ChatCompletionResponseChoice`` is ``extra='allow'``, so an extra
|
||||
``routed_experts`` attribute survives serialization."""
|
||||
|
||||
def post_process(self, response: ChatCompletionResponse) -> None:
|
||||
for choice in response.choices:
|
||||
if choice.index in self.routed_experts:
|
||||
choice.routed_experts = self.routed_experts[choice.index]
|
||||
|
||||
|
||||
class ChatCompletionRequestWithTokens(ChatCompletionRequest):
|
||||
field_names: ClassVar[Optional[set[str]]] = None
|
||||
tokens: list[int] = Field(description=("Prompt tokens to use for the request."))
|
||||
|
||||
|
||||
class OpenAIServingChatWithTokens(OpenAIServingChat):
|
||||
"""OpenAI-compatible generate API that allows token-in and routed experts capture."""
|
||||
|
||||
async def chat_completion_full_generator(
|
||||
self,
|
||||
request: ChatCompletionRequest,
|
||||
result_generator: AsyncIterator[RequestOutput],
|
||||
request_id: str,
|
||||
model_name: str,
|
||||
conversation,
|
||||
tokenizer,
|
||||
request_metadata: RequestResponseMetadata,
|
||||
reasoning_parser: ReasoningParser | None = None,
|
||||
) -> ErrorResponse | ChatCompletionResponse:
|
||||
# We need to override the full_generator to be able to capture the routed experts
|
||||
# By default, VLLM does not save the routed experts into ChatCompletionResponse.choices, so we need to capture them manually
|
||||
# How this works:
|
||||
# 1. We create a custom generator that encapsulates the original result_generator in self._generator
|
||||
# 2. We override it's __aiter__ method to also capture the routed experts as an extra field in ChatCompletionResponse.choices
|
||||
# 3. We override the full_generator method to use the custom generator instead of the original one if expert routing is enabled
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
capture = _RoutedExpertsCapture(result_generator)
|
||||
result_generator = capture
|
||||
else:
|
||||
capture = None
|
||||
|
||||
response = await super().chat_completion_full_generator(
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
conversation,
|
||||
tokenizer,
|
||||
request_metadata,
|
||||
reasoning_parser,
|
||||
)
|
||||
|
||||
if capture and isinstance(response, ChatCompletionResponse):
|
||||
capture.post_process(response)
|
||||
|
||||
return response
|
||||
|
||||
async def create_chat_completion_with_tokens(
|
||||
self,
|
||||
request: ChatCompletionRequestWithTokens,
|
||||
raw_request: Optional[Request] = None,
|
||||
) -> Union[AsyncGenerator[str, None], ChatCompletionResponse, ErrorResponse]:
|
||||
"""
|
||||
Chat Completion API similar to OpenAI's API.
|
||||
|
||||
See https://platform.openai.com/docs/api-reference/chat/create
|
||||
for the API specification. This API mimics the OpenAI
|
||||
Chat Completion API.
|
||||
"""
|
||||
# Streaming response
|
||||
tokenizer = self.renderer.tokenizer
|
||||
assert tokenizer is not None
|
||||
reasoning_parser: ReasoningParser | None = None
|
||||
try:
|
||||
if self.reasoning_parser_cls:
|
||||
# Pass the same chat template kwargs as used in tokenization
|
||||
chat_template_kwargs = self._prepare_extra_chat_template_kwargs(
|
||||
request.chat_template_kwargs,
|
||||
self.default_chat_template_kwargs,
|
||||
)
|
||||
reasoning_parser = self.reasoning_parser_cls(
|
||||
tokenizer,
|
||||
chat_template_kwargs=chat_template_kwargs, # type: ignore[call-arg]
|
||||
)
|
||||
except RuntimeError as e:
|
||||
logger.exception("Error in reasoning parser creation.")
|
||||
return self.create_error_response(str(e))
|
||||
result = await self.render_chat_request(request)
|
||||
if isinstance(result, ErrorResponse):
|
||||
return result
|
||||
|
||||
conversation, engine_prompts = result
|
||||
|
||||
# We override prompt tokens directly.
|
||||
# VLM conversations use MITO (message-based) instead of TITO, so
|
||||
# multi_modal_data is not expected here.
|
||||
engine_prompts[0]["prompt_token_ids"] = request.tokens # type: ignore
|
||||
|
||||
request_id = f"chatcmpl-{self._base_request_id(raw_request, request.request_id)}"
|
||||
|
||||
request_metadata = RequestResponseMetadata(request_id=request_id)
|
||||
if raw_request:
|
||||
raw_request.state.request_metadata = request_metadata
|
||||
|
||||
try:
|
||||
lora_request = self._maybe_get_adapters(request, supports_default_mm_loras=True)
|
||||
|
||||
model_name = self.models.model_name(lora_request)
|
||||
except (ValueError, TypeError, RuntimeError) as e:
|
||||
logger.exception("Error preparing request components")
|
||||
return self.create_error_response(e)
|
||||
|
||||
# Extract data_parallel_rank from header (router can inject it)
|
||||
data_parallel_rank = self._get_data_parallel_rank(raw_request)
|
||||
|
||||
# Schedule the request and get the result generator.
|
||||
max_model_len = self.model_config.max_model_len
|
||||
generators: list[AsyncGenerator[RequestOutput, None]] = []
|
||||
try:
|
||||
for i, engine_prompt in enumerate(engine_prompts):
|
||||
prompt_token_ids = self._extract_prompt_components(engine_prompt).token_ids
|
||||
|
||||
# If we are creating sub requests for multiple prompts, ensure that they
|
||||
# have unique request ids.
|
||||
sub_request_id = request_id if len(engine_prompts) == 1 else f"{request_id}_{i}"
|
||||
|
||||
prompt_len = self._extract_prompt_len(engine_prompt)
|
||||
if prompt_len >= max_model_len:
|
||||
raise VLLMValidationError(
|
||||
f"This model's maximum context length is "
|
||||
f"{max_model_len} tokens. However, your request has "
|
||||
f"{prompt_len} input tokens. Please reduce the length of "
|
||||
"the input messages.",
|
||||
parameter="input_tokens",
|
||||
value=prompt_len,
|
||||
)
|
||||
|
||||
max_tokens = get_max_tokens(
|
||||
max_model_len,
|
||||
request.max_completion_tokens if request.max_completion_tokens is not None else request.max_tokens,
|
||||
self._extract_prompt_len(engine_prompt),
|
||||
self.default_sampling_params,
|
||||
self.override_max_tokens,
|
||||
)
|
||||
|
||||
sampling_params: SamplingParams | BeamSearchParams
|
||||
if request.use_beam_search:
|
||||
sampling_params = request.to_beam_search_params(max_tokens, self.default_sampling_params)
|
||||
else:
|
||||
sampling_params = request.to_sampling_params(
|
||||
max_tokens,
|
||||
self.default_sampling_params,
|
||||
)
|
||||
|
||||
self._log_inputs(
|
||||
sub_request_id,
|
||||
engine_prompt,
|
||||
params=sampling_params,
|
||||
lora_request=lora_request,
|
||||
)
|
||||
|
||||
trace_headers = None if raw_request is None else await self._get_trace_headers(raw_request.headers)
|
||||
|
||||
if isinstance(sampling_params, BeamSearchParams):
|
||||
generator = self.beam_search(
|
||||
prompt=engine_prompt,
|
||||
request_id=sub_request_id,
|
||||
params=sampling_params,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
)
|
||||
else:
|
||||
reasoning_ended = (
|
||||
reasoning_parser.is_reasoning_end(prompt_token_ids or []) if reasoning_parser else None
|
||||
)
|
||||
|
||||
generator = self.engine_client.generate(
|
||||
engine_prompt,
|
||||
sampling_params,
|
||||
sub_request_id,
|
||||
lora_request=lora_request,
|
||||
trace_headers=trace_headers,
|
||||
priority=request.priority,
|
||||
data_parallel_rank=data_parallel_rank,
|
||||
reasoning_ended=reasoning_ended,
|
||||
)
|
||||
|
||||
generators.append(generator)
|
||||
except ValueError as e:
|
||||
return self.create_error_response(e)
|
||||
|
||||
assert len(generators) == 1
|
||||
(result_generator,) = generators
|
||||
|
||||
if request.stream:
|
||||
return self.chat_completion_stream_generator(
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
conversation,
|
||||
tokenizer,
|
||||
request_metadata,
|
||||
reasoning_parser,
|
||||
)
|
||||
|
||||
try:
|
||||
return await self.chat_completion_full_generator(
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
conversation,
|
||||
tokenizer,
|
||||
request_metadata,
|
||||
reasoning_parser,
|
||||
)
|
||||
except GenerationError:
|
||||
raise # Let FastAPI's global generation_error_handler handle it
|
||||
except ValueError as e:
|
||||
return self.create_error_response(e)
|
||||
@@ -226,10 +226,8 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
# but never threads it into the engine, so PD disagg never fires on
|
||||
# ``/inference/v1/generate`` — decode receives an empty NIXL handshake
|
||||
# and ends up re-prefilling the prompt locally (~100× slower under
|
||||
# concurrency). The chat path bridges this via
|
||||
# ``ChatCompletionRequestWithTokens.to_sampling_params``; we mirror that
|
||||
# bridge here so the engine's KV connector picks the params up out of
|
||||
# ``sampling_params.extra_args``.
|
||||
# concurrency). Bridge it through ``sampling_params.extra_args`` so the
|
||||
# engine's KV connector picks the params up.
|
||||
#
|
||||
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
|
||||
# this block once we pin a vLLM version that includes it.
|
||||
@@ -300,12 +298,11 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
model_name: str,
|
||||
request_metadata: RequestResponseMetadata,
|
||||
) -> ErrorResponse | GenerateResponse:
|
||||
# Mirror serving_chat_with_tokens: wrap the result generator to capture
|
||||
# routed_experts as it streams, defer the rest to upstream, then post-
|
||||
# process the response into our PrimeRlGenerateResponse subclass so the
|
||||
# encoded experts surface in the JSON. Skipping the wrapper when the
|
||||
# engine isn't producing routed experts keeps us a no-op subclass on
|
||||
# the common path.
|
||||
# Wrap the result generator to capture routed_experts as it streams,
|
||||
# defer the rest to upstream, then post-process the response into our
|
||||
# PrimeRlGenerateResponse subclass so the encoded experts surface in
|
||||
# the JSON. Skipping the wrapper when the engine isn't producing routed
|
||||
# experts keeps us a no-op subclass on the common path.
|
||||
capture: _RoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
capture = _RoutedExpertsCapture(result_generator)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import ctypes
|
||||
import gc
|
||||
import os
|
||||
import time
|
||||
@@ -46,7 +47,6 @@ from prime_rl.orchestrator.utils import (
|
||||
get_weight_dir,
|
||||
print_benchmark,
|
||||
set_default_executor,
|
||||
setup_external_rollout_model,
|
||||
)
|
||||
from prime_rl.orchestrator.vf_utils import (
|
||||
get_seq_len,
|
||||
@@ -92,9 +92,10 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
intercept_vf_logging(logger="verifiers.serve", level="WARN") # show logs from env clients
|
||||
logger.info("Starting orchestrator")
|
||||
set_default_executor()
|
||||
|
||||
logger.info(f"Starting orchestrator ({config.training_mode})")
|
||||
|
||||
set_default_executor()
|
||||
event_loop_lag_monitor = EventLoopLagMonitor()
|
||||
event_loop_lag_monitor_task = asyncio.create_task(event_loop_lag_monitor.run())
|
||||
|
||||
@@ -117,45 +118,43 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id, prerelease=config.env_install_prerelease)
|
||||
|
||||
# Setup rollout inference pool (handles both static and elastic modes)
|
||||
rollout_client_config, rollout_model_name, enable_policy_updates = setup_external_rollout_model(config, logger)
|
||||
|
||||
# Setup teacher inference pool if configured
|
||||
if config.teacher_model:
|
||||
logger.info(
|
||||
f"Initializing teacher inference pool (base_url={', '.join(config.teacher_model.client.base_url)}, "
|
||||
f"model={config.teacher_model.model.name})"
|
||||
)
|
||||
teacher_inference_pool = await setup_inference_pool(
|
||||
config.teacher_model.client,
|
||||
model_name=config.teacher_model.model.name,
|
||||
train_client_type="openai_chat_completions",
|
||||
)
|
||||
else:
|
||||
teacher_inference_pool = None
|
||||
|
||||
# Check if this is a vision-language model (used throughout for VLM-specific paths)
|
||||
is_vlm = config.model.vlm is not None
|
||||
|
||||
# Load tokenizer and processor (processor only for VLM models)
|
||||
logger.info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
processor = None
|
||||
if is_vlm:
|
||||
logger.info(f"Loading VLM processor for {config.model.name}")
|
||||
if config.student.model.is_vlm:
|
||||
logger.info(f"Loading VLM processor for {config.student.model.name}")
|
||||
processor = AutoProcessor.from_pretrained(
|
||||
config.model.name, trust_remote_code=config.model.trust_remote_code, use_fast=True
|
||||
config.student.model.name, trust_remote_code=config.student.model.trust_remote_code, use_fast=True
|
||||
)
|
||||
|
||||
renderer, inference_pool = await setup_rollout_inference_pool(
|
||||
# Set up student inference pool (required for all training modes).
|
||||
logger.info(
|
||||
f"Initializing student inference pool (base_url={', '.join(config.student.client.base_url)}, "
|
||||
f"model={config.student.model.name})"
|
||||
)
|
||||
renderer, student_inference = await setup_student_inference_pool(
|
||||
config=config,
|
||||
rollout_client_config=rollout_client_config,
|
||||
rollout_model_name=rollout_model_name,
|
||||
tokenizer=tokenizer,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
# Set up teacher inference pool (configured for opd or sft). Always MITO for
|
||||
# simplicity - this also keeps external OAI-compatible teachers (PI inference,
|
||||
# OpenAI) working as drop-in endpoints.
|
||||
teacher_inference = None
|
||||
if config.teacher is not None:
|
||||
logger.info(
|
||||
f"Initializing teacher inference pool (base_url={', '.join(config.teacher.client.base_url)}, "
|
||||
f"model={config.teacher.model.name})"
|
||||
)
|
||||
teacher_inference = await setup_inference_pool(
|
||||
config.teacher.client,
|
||||
model_name=config.teacher.model.name,
|
||||
train_client_type="openai_chat_completions",
|
||||
)
|
||||
|
||||
# Setup monitor (may register the run and set RUN_ID in the environment)
|
||||
logger.info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
|
||||
monitor = setup_monitor(
|
||||
@@ -195,6 +194,12 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Load environments
|
||||
logger.info("Loading training environments")
|
||||
train_envs = TrainEnvs(config.train.env)
|
||||
if config.training_mode == "sft":
|
||||
# Teacher rollouts don't need inference-side logprobs (the trainer
|
||||
# reconstructs teacher tokens), and some external reasoning-model
|
||||
# endpoints (e.g. openai/gpt-5*) reject the parameter.
|
||||
for env in train_envs:
|
||||
env.sampling_args.pop("logprobs", None)
|
||||
logger.info(f"Loaded {len(train_envs)} training environment(s) ({', '.join(train_envs.names)})")
|
||||
|
||||
await train_envs.start(
|
||||
@@ -235,54 +240,44 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
scheduler = Scheduler(
|
||||
train_envs=train_envs,
|
||||
buffer=buffer,
|
||||
inference_pool=inference_pool,
|
||||
student_inference=student_inference,
|
||||
teacher_inference=teacher_inference,
|
||||
max_inflight_rollouts=config.max_inflight_rollouts,
|
||||
max_async_level=config.max_async_level,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
strict_async_level=config.strict_async_level,
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
enable_policy_updates=enable_policy_updates,
|
||||
lora_name=config.model.lora.name if config.model.lora else None,
|
||||
lora_name=config.student.model.lora.name if config.student.model.lora else None,
|
||||
config=config,
|
||||
)
|
||||
scheduler.model_name = rollout_model_name
|
||||
|
||||
if checkpoint_step is not None and config.model.lora is not None and enable_policy_updates:
|
||||
assert config.model.lora.name is not None
|
||||
scheduler.model_name = config.model.lora.name
|
||||
|
||||
# Check health of the inference pool
|
||||
logger.info("Waiting for inference pool to be ready")
|
||||
await inference_pool.wait_for_ready(rollout_model_name)
|
||||
|
||||
logger.success("Inference pool ready")
|
||||
# Wait for pools to be ready
|
||||
logger.info("Waiting for student inference pool to be ready")
|
||||
await student_inference.wait_for_ready(config.student.model.name)
|
||||
logger.success("Student inference pool ready")
|
||||
if teacher_inference is not None:
|
||||
assert config.teacher is not None
|
||||
logger.info("Waiting for teacher inference pool to be ready")
|
||||
await teacher_inference.wait_for_ready(config.teacher.model.name)
|
||||
logger.success("Teacher inference pool ready")
|
||||
|
||||
# Start inference metrics collector (requires W&B)
|
||||
inference_metrics_collector = None
|
||||
if config.wandb is not None and config.collect_inference_metrics:
|
||||
inference_metrics_collector = InferenceMetricsCollector(inference_pool.admin_clients)
|
||||
inference_metrics_collector = InferenceMetricsCollector(student_inference.admin_clients)
|
||||
await inference_metrics_collector.start()
|
||||
|
||||
# Check health of teacher inference server if configured
|
||||
if config.teacher_model and teacher_inference_pool:
|
||||
logger.info("Waiting for teacher inference pool to be ready")
|
||||
await teacher_inference_pool.wait_for_ready(config.teacher_model.model.name)
|
||||
logger.success("Teacher inference pool ready")
|
||||
|
||||
# Set up weight broadcast backend
|
||||
if enable_policy_updates:
|
||||
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
if config.weight_broadcast.type == "nccl":
|
||||
await init_nccl_broadcast(
|
||||
inference_pool.admin_clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
inference_world_size=config.weight_broadcast.inference_world_size,
|
||||
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
else:
|
||||
logger.info("Skipping weight broadcast initialization (SFT distillation mode)")
|
||||
# Set up weight broadcast backend (targets student inference)
|
||||
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
if config.weight_broadcast.type == "nccl":
|
||||
await init_nccl_broadcast(
|
||||
student_inference.admin_clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
inference_world_size=config.weight_broadcast.inference_world_size,
|
||||
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
|
||||
# Setup training batch sender for sending training examples to trainer
|
||||
logger.info(f"Initializing training batch sender ({config.rollout_transport})")
|
||||
@@ -308,15 +303,18 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Allow eval at resumed step by setting prev_ckpt_step one behind
|
||||
prev_ckpt_step = scheduler.ckpt_step - 1
|
||||
|
||||
if enable_policy_updates:
|
||||
# In NCCL mode, skip existence check - weights are broadcasted, not stored on disk
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, scheduler.ckpt_step, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
lora_name = config.model.lora.name if config.model.lora else None
|
||||
await inference_pool.update_weights(weights_path, lora_name=lora_name, step=scheduler.ckpt_step)
|
||||
# In NCCL mode, skip existence check - weights are broadcasted, not stored on disk
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, scheduler.ckpt_step, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
lora_name = config.student.model.lora.name if config.student.model.lora else None
|
||||
await student_inference.update_weights(weights_path, lora_name=lora_name, step=scheduler.ckpt_step)
|
||||
if lora_name is not None:
|
||||
student_inference.update_model_name(lora_name)
|
||||
if scheduler.rollout_inference is student_inference:
|
||||
scheduler.model_name = lora_name
|
||||
else:
|
||||
logger.info("Training from scratch")
|
||||
|
||||
@@ -332,7 +330,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
raise RuntimeError(f"Run evicted by trainer: {reason}")
|
||||
|
||||
# Capture ckpt_step once for consistency (it's updated inside the scheduler)
|
||||
ckpt_step = scheduler.ckpt_step if enable_policy_updates else progress.step
|
||||
ckpt_step = scheduler.ckpt_step
|
||||
scheduler.ckpt_step = ckpt_step
|
||||
|
||||
# Save checkpoint (if we are at an interval step and not at the first or last step)
|
||||
@@ -390,8 +388,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
eval_results = await asyncio.gather(
|
||||
*[
|
||||
eval_env.evaluate(
|
||||
model_name=scheduler.model_name,
|
||||
get_client=inference_pool.get_eval_client,
|
||||
model_name=student_inference.model_name,
|
||||
get_client=student_inference.get_eval_client,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
cache_salt=str(ckpt_step),
|
||||
@@ -471,7 +469,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
)
|
||||
|
||||
# VLM: offload base64 images to disk immediately to free memory
|
||||
if is_vlm:
|
||||
if config.student.model.is_vlm:
|
||||
offload_start = time.perf_counter()
|
||||
num_offloaded = offload_images_to_disk(train_rollouts, config.output_dir)
|
||||
if num_offloaded:
|
||||
@@ -503,7 +501,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
)
|
||||
)
|
||||
|
||||
if is_vlm:
|
||||
if config.student.model.is_vlm:
|
||||
mm_token_type_ids_mapping = {}
|
||||
if hasattr(processor, "image_token_id") and processor.image_token_id is not None:
|
||||
mm_token_type_ids_mapping[processor.image_token_id] = 1
|
||||
@@ -552,8 +550,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
for sample in samples:
|
||||
sample.advantage = rollout["advantage"]
|
||||
sample.reward = rollout["reward"]
|
||||
if config.use_sft_loss:
|
||||
sample.sft_loss = True
|
||||
sample.env_name = rollout["env_name"]
|
||||
sample.training_mode = config.training_mode
|
||||
sample_decode_tokens = sum(sample.completion_mask)
|
||||
sample_prefill_tokens = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode_tokens
|
||||
rollout_decode_tokens += sample_decode_tokens
|
||||
@@ -571,14 +569,15 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
f"to {len(train_examples)} training examples"
|
||||
)
|
||||
|
||||
# Compute teacher logprobs if teacher model is configured
|
||||
# Compute teacher logprobs (opd only - sft trains on teacher tokens directly)
|
||||
teacher_logprobs_time = 0
|
||||
if config.teacher_model and teacher_inference_pool:
|
||||
if config.training_mode == "opd" and teacher_inference is not None:
|
||||
assert config.teacher is not None
|
||||
logger.info(f"Computing teacher logprobs for {len(train_examples)} training examples")
|
||||
teacher_logprobs_start_time = time.perf_counter()
|
||||
teacher_logprobs_list = await compute_teacher_logprobs(
|
||||
clients=teacher_inference_pool.train_clients,
|
||||
model_name=config.teacher_model.model.name,
|
||||
clients=teacher_inference.train_clients,
|
||||
model_name=config.teacher.model.name,
|
||||
samples=train_examples,
|
||||
)
|
||||
for train_example, teacher_logprobs in zip(train_examples, teacher_logprobs_list):
|
||||
@@ -797,6 +796,13 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
del train_rollouts, train_examples, training_batch, vlm_cache
|
||||
del results_df, metrics_df
|
||||
gc.collect()
|
||||
# Return free glibc heap pages to the OS. numpy/pandas allocate array data
|
||||
# via malloc (outside Python's allocator), so gc.collect() alone doesn't
|
||||
# reclaim the RSS. malloc_trim(0) forces glibc to return freed pages.
|
||||
try:
|
||||
ctypes.CDLL("libc.so.6").malloc_trim(0)
|
||||
except Exception as e:
|
||||
logger.warning(f"malloc_trim(0) failed - RSS may grow unboundedly: {e}")
|
||||
|
||||
event_loop_lag_monitor.reset()
|
||||
|
||||
@@ -809,8 +815,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
eval_results = await asyncio.gather(
|
||||
*[
|
||||
eval_env.evaluate(
|
||||
model_name=scheduler.model_name,
|
||||
get_client=inference_pool.get_eval_client,
|
||||
model_name=student_inference.model_name,
|
||||
get_client=student_inference.get_eval_client,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
cache_salt=str(ckpt_step),
|
||||
@@ -846,9 +852,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
await scheduler.stop()
|
||||
if inference_metrics_collector is not None:
|
||||
await inference_metrics_collector.stop()
|
||||
await inference_pool.stop()
|
||||
if teacher_inference_pool is not None:
|
||||
await teacher_inference_pool.stop()
|
||||
await student_inference.stop()
|
||||
if teacher_inference is not None:
|
||||
await teacher_inference.stop()
|
||||
event_loop_lag_monitor_task.cancel()
|
||||
# Shutdown env processes (also registered as atexit handler for crash safety)
|
||||
train_envs.shutdown()
|
||||
@@ -886,39 +892,27 @@ def main():
|
||||
asyncio.run(orchestrate(cli(OrchestratorConfig)))
|
||||
|
||||
|
||||
async def setup_rollout_inference_pool(
|
||||
async def setup_student_inference_pool(
|
||||
*,
|
||||
config: OrchestratorConfig,
|
||||
rollout_client_config,
|
||||
rollout_model_name: str,
|
||||
tokenizer,
|
||||
logger,
|
||||
):
|
||||
"""Set up rollout inference.
|
||||
"""Set up the student inference pool (rollouts when rl/opd, evals + weight sync always).
|
||||
|
||||
Routing policy is driven by ``config.use_token_client`` and
|
||||
``config.use_renderer`` (mutually exclusive — config-level validators
|
||||
block both being True):
|
||||
Routing policy is driven by ``config.use_renderer``:
|
||||
|
||||
- external teacher rollout → MITO (``openai_chat_completions``),
|
||||
forced regardless of the toggles (config-level validator
|
||||
rejects ``use_token_client`` / ``use_renderer`` in that case)
|
||||
- ``use_renderer=True`` → renderer client (``/v1/generate``).
|
||||
Not allowed for VLMs (validated at config time).
|
||||
- ``use_token_client=True`` → TITO
|
||||
(``openai_chat_completions_token``, ``/v1/chat/completions/tokens``).
|
||||
Default. VLMs land here too.
|
||||
- both False → MITO (``openai_chat_completions``).
|
||||
- ``use_renderer=True`` → renderer-backed TITO client (``/v1/generate``).
|
||||
Default for text-only rollouts. Not allowed for VLMs (validated at
|
||||
config time).
|
||||
- ``use_renderer=False`` → MITO (``openai_chat_completions``). VLMs
|
||||
land here too.
|
||||
|
||||
Eval clients always use MITO. In sft mode ``use_renderer`` is forced off
|
||||
by a config validator, so the student pool is plain MITO end-to-end.
|
||||
"""
|
||||
if config.teacher_rollout_model is not None:
|
||||
logger.info("Using external rollout model (MITO) without renderer client")
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
train_client_type="openai_chat_completions",
|
||||
eval_client_type="openai_chat_completions",
|
||||
)
|
||||
return None, inference_pool
|
||||
client_config = config.student.client
|
||||
model_name = config.student.model.name
|
||||
|
||||
if config.use_renderer:
|
||||
renderer = create_renderer(
|
||||
@@ -926,30 +920,30 @@ async def setup_rollout_inference_pool(
|
||||
renderer=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
preserve_all_thinking=config.renderer.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=config.renderer.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
logger.info(f"Initialized {type(renderer).__name__} for {config.model.name}")
|
||||
logger.info(f"Initialized {type(renderer).__name__} for {model_name}")
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_name=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
renderer_pool_size=config.renderer.pool_size,
|
||||
preserve_all_thinking=config.renderer.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=config.renderer.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
logger.info("Using direct renderer rollout client")
|
||||
return renderer, inference_pool
|
||||
|
||||
train_client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
|
||||
if config.use_token_client:
|
||||
logger.info("Using token client (TITO) for rollouts — server-side templating, /v1/chat/completions/tokens")
|
||||
else:
|
||||
logger.info("Using MITO (openai_chat_completions) for rollouts")
|
||||
logger.info("Using MITO (openai_chat_completions) for rollouts")
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
train_client_type=train_client_type,
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type="openai_chat_completions",
|
||||
eval_client_type="openai_chat_completions",
|
||||
)
|
||||
return None, inference_pool
|
||||
|
||||
@@ -73,7 +73,8 @@ class Scheduler:
|
||||
def __init__(
|
||||
self,
|
||||
train_envs: TrainEnvs,
|
||||
inference_pool: InferencePool,
|
||||
student_inference: InferencePool,
|
||||
teacher_inference: InferencePool | None,
|
||||
buffer: Buffer,
|
||||
config: OrchestratorConfig,
|
||||
max_inflight_rollouts: int,
|
||||
@@ -81,7 +82,6 @@ class Scheduler:
|
||||
max_off_policy_steps: int,
|
||||
strict_async_level: bool,
|
||||
tasks_per_minute: int | None,
|
||||
enable_policy_updates: bool = True,
|
||||
lora_name: str | None = None,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
@@ -99,13 +99,21 @@ class Scheduler:
|
||||
self.max_async_level = max_async_level
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
self.strict_async_level = strict_async_level
|
||||
self.enable_policy_updates = enable_policy_updates
|
||||
self.lora_name = lora_name
|
||||
self.model_name = self.config.model.name
|
||||
self.json_logging = config.log.json_logging
|
||||
|
||||
# Inference pool - used for admin operations (adapter sync) and metrics
|
||||
self.inference_pool = inference_pool
|
||||
# student_inference is the weight-sync target. teacher_inference is set
|
||||
# in opd (for logprobs) and sft (for rollouts). rollout_inference is
|
||||
# whichever pool serves train rollouts for this mode.
|
||||
self.student_inference = student_inference
|
||||
self.teacher_inference = teacher_inference
|
||||
if config.training_mode == "sft":
|
||||
assert teacher_inference is not None
|
||||
self.rollout_inference = teacher_inference
|
||||
else:
|
||||
self.rollout_inference = student_inference
|
||||
# model_name is the name to send on rollout requests - matches the rollout pool
|
||||
self.model_name = self.rollout_inference.model_name
|
||||
|
||||
group_scoring_envs = [env.name for env in train_envs if env.requires_group_scoring]
|
||||
if group_scoring_envs:
|
||||
@@ -175,10 +183,10 @@ class Scheduler:
|
||||
Uses (api_base_url, dp_rank) as identity rather than client_idx so that
|
||||
load tracking survives elastic pool refreshes (which reassign indices).
|
||||
"""
|
||||
clients = self.inference_pool.train_clients
|
||||
clients = self.rollout_inference.train_clients
|
||||
while not clients:
|
||||
await asyncio.sleep(1)
|
||||
clients = self.inference_pool.train_clients
|
||||
clients = self.rollout_inference.train_clients
|
||||
inflight = Counter(self._client_identity(info.client_config) for info in self.inflight_requests.values())
|
||||
return min(clients, key=lambda c: inflight[self._client_identity(c)])
|
||||
|
||||
@@ -320,14 +328,18 @@ class Scheduler:
|
||||
|
||||
update_weights_start_time = time.perf_counter()
|
||||
weights_path = get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step)
|
||||
await self.inference_pool.update_weights(weights_path, lora_name=self.lora_name, step=next_ckpt_step)
|
||||
await self.student_inference.update_weights(weights_path, lora_name=self.lora_name, step=next_ckpt_step)
|
||||
self.update_weights_time = time.perf_counter() - update_weights_start_time
|
||||
self.logger.debug(f"Updated weights to step {next_ckpt_step} in {self.update_weights_time:.2f}s")
|
||||
|
||||
self.ckpt_step = next_ckpt_step
|
||||
if self.lora_name is not None:
|
||||
self.model_name = self.lora_name
|
||||
self.inference_pool.update_model_name(self.model_name)
|
||||
self.student_inference.update_model_name(self.lora_name)
|
||||
# Only redirect rollout requests to the new LoRA when rollouts come from
|
||||
# student inference (rl/opd). In sft, rollouts go to the teacher and
|
||||
# the student's LoRA name is irrelevant to them.
|
||||
if self.rollout_inference is self.student_inference:
|
||||
self.model_name = self.lora_name
|
||||
|
||||
self.checkpoint_ready.set()
|
||||
await self._update_off_policy()
|
||||
@@ -350,11 +362,6 @@ class Scheduler:
|
||||
|
||||
async def maybe_update_policy(self):
|
||||
"""Updates the policy to the latest available checkpoint. Aborts rollout requests that are older than the max retention steps."""
|
||||
if not self.enable_policy_updates:
|
||||
self.ckpt_step = self.step
|
||||
self.checkpoint_ready.set()
|
||||
return
|
||||
|
||||
while True:
|
||||
next_ckpt_step = self._compute_next_ckpt_step()
|
||||
if next_ckpt_step <= self.ckpt_step:
|
||||
@@ -394,18 +401,14 @@ class Scheduler:
|
||||
"""Continuously generates a batch of rollouts."""
|
||||
self.step = step
|
||||
|
||||
if self.enable_policy_updates:
|
||||
# Cancel the previous update policy task to avoid concurrent updates
|
||||
if self.update_policy_task is not None:
|
||||
await safe_cancel(self.update_policy_task)
|
||||
# Cancel the previous update policy task to avoid concurrent updates
|
||||
if self.update_policy_task is not None:
|
||||
await safe_cancel(self.update_policy_task)
|
||||
|
||||
# Manually check the async barrier before starting the step, then re-create the update policy loop
|
||||
# This ensures that we respect max_async_level, while still listening for policy updates mid-step
|
||||
await self.maybe_update_policy()
|
||||
self.update_policy_task = asyncio.create_task(self.update_policy_loop())
|
||||
else:
|
||||
self.ckpt_step = step
|
||||
self.checkpoint_ready.set()
|
||||
# Manually check the async barrier before starting the step, then re-create the update policy loop
|
||||
# This ensures that we respect max_async_level, while still listening for policy updates mid-step
|
||||
await self.maybe_update_policy()
|
||||
self.update_policy_task = asyncio.create_task(self.update_policy_loop())
|
||||
|
||||
batch_start_time = time.perf_counter()
|
||||
|
||||
@@ -598,7 +601,7 @@ class Scheduler:
|
||||
self.total_rollouts_by_env.clear()
|
||||
self.dropped_groups_by_env.clear()
|
||||
|
||||
# Add inference pool metrics (e.g. elastic pool server counts)
|
||||
metrics.update(self.inference_pool.get_metrics())
|
||||
# Add train pool metrics (e.g. elastic pool server counts)
|
||||
metrics.update(self.rollout_inference.get_metrics())
|
||||
|
||||
return metrics
|
||||
|
||||
@@ -337,6 +337,7 @@ def interleave_rollout(
|
||||
completion_temperatures=[temperature] * len(completion_ids),
|
||||
teacher_logprobs=None,
|
||||
advantage=None,
|
||||
env_name=output["env_name"],
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=None,
|
||||
)
|
||||
|
||||
@@ -11,7 +11,6 @@ from rich.console import Console
|
||||
from rich.table import Table
|
||||
from verifiers.utils.client_utils import setup_openai_client
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import (
|
||||
@@ -177,21 +176,3 @@ def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_
|
||||
return broadcast_weight_dir
|
||||
|
||||
raise FileNotFoundError(f"No weight directory found for checkpoint step {step}")
|
||||
|
||||
|
||||
def setup_external_rollout_model(config: OrchestratorConfig, logger) -> tuple[Any, str, bool]:
|
||||
"""Resolve rollout client/model and whether policy updates should be enabled."""
|
||||
rollout_client_config = config.client
|
||||
rollout_model_name = config.model.name
|
||||
enable_policy_updates = True
|
||||
|
||||
if config.teacher_rollout_model is not None:
|
||||
rollout_client_config = config.teacher_rollout_model.client
|
||||
rollout_model_name = config.teacher_rollout_model.model.name
|
||||
enable_policy_updates = False
|
||||
logger.info(
|
||||
f"Using external teacher rollout model (base_url={', '.join(rollout_client_config.base_url)}, "
|
||||
f"model={rollout_model_name})"
|
||||
)
|
||||
|
||||
return rollout_client_config, rollout_model_name, enable_policy_updates
|
||||
|
||||
@@ -14,6 +14,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
advantages = [training_example.advantage] * len(input_ids)
|
||||
position_ids = list(range(len(input_ids)))
|
||||
mm_token_type_ids = training_example.mm_token_type_ids
|
||||
assert training_example.env_name != "all", "env_name='all' is reserved for aggregate metric keys"
|
||||
env_names = [training_example.env_name] * len(input_ids)
|
||||
|
||||
# Per-token temperatures: prompt tokens use first completion temp (masked out anyway)
|
||||
# Default to 1.0 if completion is empty (e.g., model generated only tool calls with no text)
|
||||
@@ -38,6 +40,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
routed_experts = routed_experts[:seq_len]
|
||||
if mm_token_type_ids is not None:
|
||||
mm_token_type_ids = mm_token_type_ids[:seq_len]
|
||||
env_names = env_names[:seq_len]
|
||||
|
||||
assert (
|
||||
len(input_ids)
|
||||
@@ -61,6 +64,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
assert len(mm_token_type_ids) == len(input_ids), (
|
||||
f"mm_token_type_ids: {len(mm_token_type_ids)}, input_ids: {len(input_ids)}"
|
||||
)
|
||||
assert len(env_names) == len(input_ids), f"env_names: {len(env_names)}, input_ids: {len(input_ids)}"
|
||||
|
||||
return MicroBatch(
|
||||
input_ids=input_ids,
|
||||
@@ -72,11 +76,12 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
temperatures=temperatures,
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
# Multimodal fields (Qwen3-VL) - passed through without modification
|
||||
pixel_values=training_example.pixel_values,
|
||||
pixel_values_shape=training_example.pixel_values_shape,
|
||||
image_grid_thw=training_example.image_grid_thw,
|
||||
sft_loss=training_example.sft_loss,
|
||||
training_mode=training_example.training_mode,
|
||||
)
|
||||
|
||||
|
||||
@@ -118,7 +123,7 @@ def packed_samples_into_micro_bs(
|
||||
# Check if sequence fits in this bin
|
||||
if (
|
||||
len(bin_content.input_ids) + len(sample.input_ids) <= max_seq_len
|
||||
and bin_content.sft_loss == sample.sft_loss
|
||||
and bin_content.training_mode == sample.training_mode
|
||||
):
|
||||
bin_content.input_ids.extend(sample.input_ids)
|
||||
bin_content.loss_mask.extend(sample.loss_mask)
|
||||
@@ -137,6 +142,7 @@ def packed_samples_into_micro_bs(
|
||||
if bin_content.mm_token_type_ids is None:
|
||||
bin_content.mm_token_type_ids = []
|
||||
bin_content.mm_token_type_ids.extend(sample.mm_token_type_ids)
|
||||
bin_content.env_names.extend(sample.env_names)
|
||||
bin_content.position_ids.extend(sample.position_ids)
|
||||
bin_content.lora_num_tokens[idx] += len(sample.input_ids)
|
||||
break
|
||||
@@ -161,6 +167,12 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
|
||||
|
||||
padding_size = (pad_to_multiple_of - (len(micro_batch.input_ids) % pad_to_multiple_of)) % pad_to_multiple_of
|
||||
|
||||
if len(micro_batch.env_names) != len(micro_batch.input_ids):
|
||||
raise ValueError(
|
||||
f"MicroBatch.env_names must match input_ids length before padding: "
|
||||
f"env_names={len(micro_batch.env_names)}, input_ids={len(micro_batch.input_ids)}"
|
||||
)
|
||||
|
||||
if not (pad_to_multiple_of > 1 and padding_size > 0):
|
||||
return micro_batch
|
||||
|
||||
@@ -178,6 +190,7 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
|
||||
)
|
||||
if micro_batch.mm_token_type_ids is not None:
|
||||
micro_batch.mm_token_type_ids.extend([0] * padding_size)
|
||||
micro_batch.env_names.extend([""] * padding_size)
|
||||
|
||||
return micro_batch
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.models.auto.auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
|
||||
from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES
|
||||
from transformers.models.llama.configuration_llama import LlamaConfig
|
||||
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
|
||||
|
||||
from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
@@ -18,6 +19,7 @@ from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, cast_float_and
|
||||
from prime_rl.trainer.models.llama import LlamaForCausalLM
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
|
||||
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
|
||||
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
|
||||
|
||||
@@ -34,6 +36,7 @@ AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
|
||||
|
||||
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3Config, Qwen3ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(AfmoeConfig, AfmoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Glm4MoeConfig, Glm4MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(GlmMoeDsaConfig, GlmMoeDsaForCausalLM, exist_ok=True)
|
||||
|
||||
@@ -38,6 +38,7 @@ class AttentionConfig:
|
||||
use_qk_norm: bool
|
||||
rms_norm_eps: float
|
||||
qk_norm_type: Literal["per_head", "per_layer"] = "per_head"
|
||||
output_bias: bool = False
|
||||
|
||||
|
||||
# TODO: Does torch compile support config._attn_implementation forking?
|
||||
@@ -70,7 +71,7 @@ class FlashAttention(nn.Module):
|
||||
self.v_proj = nn.Linear(
|
||||
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
||||
)
|
||||
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
||||
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.output_bias)
|
||||
self.use_qk_norm = config.use_qk_norm
|
||||
self.qk_norm_type = config.qk_norm_type
|
||||
if self.use_qk_norm:
|
||||
@@ -201,7 +202,7 @@ class SDPAAttention(nn.Module):
|
||||
self.v_proj = nn.Linear(
|
||||
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
||||
)
|
||||
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
||||
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.output_bias)
|
||||
self.use_qk_norm = config.use_qk_norm
|
||||
self.qk_norm_type = config.qk_norm_type
|
||||
if self.use_qk_norm:
|
||||
|
||||
@@ -20,25 +20,6 @@ def _get_quack_rmsnorm():
|
||||
return None
|
||||
|
||||
|
||||
class _ContiguousGrad(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(ctx, x):
|
||||
return x
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad):
|
||||
return grad.contiguous()
|
||||
|
||||
|
||||
def _contiguous_grad(x: torch.Tensor) -> torch.Tensor:
|
||||
"""Identity in forward, makes gradient contiguous in backward.
|
||||
|
||||
Quack's RMSNorm backward kernel requires contiguous gradients (stride[-1]==1)
|
||||
but upstream ops like attention permute can produce non-contiguous ones.
|
||||
"""
|
||||
return _ContiguousGrad.apply(x) if x.requires_grad else x
|
||||
|
||||
|
||||
@dataclass
|
||||
class RMSNormConfig:
|
||||
hidden_size: int
|
||||
@@ -55,8 +36,7 @@ class RMSNorm(nn.Module):
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
quack_fn = _get_quack_rmsnorm() if hidden_states.is_cuda else None
|
||||
if quack_fn is not None:
|
||||
out = quack_fn(hidden_states, self.weight, eps=self.variance_epsilon)
|
||||
return _contiguous_grad(out)
|
||||
return quack_fn(hidden_states, self.weight, eps=self.variance_epsilon)
|
||||
input_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.to(torch.float32)
|
||||
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from prime_rl.trainer.models.qwen3.modeling_qwen3 import Qwen3ForCausalLM, Qwen3Model, Qwen3PreTrainedModel
|
||||
|
||||
__all__ = ["Qwen3ForCausalLM", "Qwen3Model", "Qwen3PreTrainedModel"]
|
||||
@@ -0,0 +1,263 @@
|
||||
from typing import Optional, Union
|
||||
|
||||
import torch
|
||||
from torch import Tensor, nn
|
||||
from transformers.cache_utils import Cache
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import BaseModelOutputWithPast
|
||||
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
def _get_rope_type(config: Qwen3Config) -> str:
|
||||
rope_parameters = getattr(config, "rope_parameters", None)
|
||||
if isinstance(rope_parameters, dict):
|
||||
return rope_parameters.get("rope_type", rope_parameters.get("type", "default"))
|
||||
if rope_parameters is not None:
|
||||
return getattr(rope_parameters, "rope_type", getattr(rope_parameters, "type", "default"))
|
||||
rope_scaling = getattr(config, "rope_scaling", None)
|
||||
if isinstance(rope_scaling, dict):
|
||||
return rope_scaling.get("rope_type", rope_scaling.get("type", "default"))
|
||||
return "default"
|
||||
|
||||
|
||||
class Qwen3DecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: Qwen3Config, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
self.layer_type = config.layer_types[layer_idx]
|
||||
|
||||
attn_config = AttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=getattr(config, "head_dim", config.hidden_size // config.num_attention_heads),
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
is_causal=True,
|
||||
attention_bias=config.attention_bias,
|
||||
output_bias=config.attention_bias,
|
||||
use_qk_norm=True,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
)
|
||||
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
|
||||
if self.layer_type == "sliding_attention":
|
||||
if config._attn_implementation == "sdpa":
|
||||
raise ValueError("Qwen3 sliding attention is only supported by the custom model with flash attention.")
|
||||
self.self_attn.sliding_window = config.sliding_window
|
||||
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.intermediate_size,
|
||||
gate_act=config.hidden_act,
|
||||
bias=False,
|
||||
)
|
||||
self.mlp = MLP(mlp_config)
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
||||
cu_seqlens: torch.LongTensor | None = None,
|
||||
max_seqlen: int | None = None,
|
||||
) -> torch.FloatTensor:
|
||||
residual = hidden_states
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
hidden_states, _ = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
hidden_states = residual + hidden_states
|
||||
|
||||
residual = hidden_states
|
||||
hidden_states = self.post_attention_layernorm(hidden_states)
|
||||
hidden_states = self.mlp(hidden_states)
|
||||
return residual + hidden_states
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class Qwen3PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config: Qwen3Config
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["Qwen3DecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_flex_attn = True
|
||||
_can_compile_fullgraph = True
|
||||
_supports_attention_backend = True
|
||||
_can_record_outputs = {
|
||||
"hidden_states": Qwen3DecoderLayer,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class Qwen3Model(Qwen3PreTrainedModel):
|
||||
def __init__(self, config: Qwen3Config):
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
self.layers = nn.ModuleList(
|
||||
[Qwen3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
)
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
rotary_config = RotaryEmbeddingConfig(
|
||||
max_position_embeddings=config.max_position_embeddings,
|
||||
rope_type=_get_rope_type(config),
|
||||
model_config=config,
|
||||
)
|
||||
self.rotary_emb = RotaryEmbedding(rotary_config)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
self.post_init()
|
||||
|
||||
@auto_docstring
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
) -> BaseModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
if position_ids is None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
cu_seqlens = None
|
||||
max_seqlen = None
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
cu_seqlens=cu_seqlens,
|
||||
max_seqlen=max_seqlen,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(hidden_states)
|
||||
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class Qwen3ForCausalLM(Qwen3PreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
_tp_plan = {"lm_head": "colwise_gather_output"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.model = Qwen3Model(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
|
||||
self.post_init()
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
@can_return_tuple
|
||||
@auto_docstring
|
||||
def forward(
|
||||
self,
|
||||
input_ids: Optional[torch.LongTensor] = None,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
past_key_values: Optional[Cache] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
labels: Optional[torch.LongTensor] = None,
|
||||
use_cache: Optional[bool] = None,
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
logits_to_keep: Union[int, torch.Tensor] = 0,
|
||||
temperature: Optional[torch.Tensor] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
||||
Indices of input tokens in the KV cache. Accepted only for HuggingFace API
|
||||
compatibility; prime-rl asserts `use_cache is None` since training does not
|
||||
perform autoregressive decoding, so this argument is unused.
|
||||
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Labels used by PrimeRL's wrapped LM head to optionally compute per-token logprobs/entropy.
|
||||
If not provided, the wrapped LM head returns logits only.
|
||||
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Per-token temperatures for logprobs/entropy computation when `labels` are provided.
|
||||
"""
|
||||
assert use_cache is None, "use_cache is not supported for custom qwen3 for now"
|
||||
assert past_key_values is None, "past_key_values is not supported for custom qwen3 for now"
|
||||
|
||||
outputs: BaseModelOutputWithPast = self.model(
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
)
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
return self.lm_head(
|
||||
hidden_states[:, slice_indices, :],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
temperature=temperature,
|
||||
)
|
||||
|
||||
def init_buffers_post_meta(self):
|
||||
buffer_names = [name for name, _ in self.named_buffers()]
|
||||
if "model.rotary_emb.inv_freq" in buffer_names:
|
||||
rotary_emb = self.model.rotary_emb
|
||||
inv_freq, rotary_emb.attention_scaling = rotary_emb.rope_init_fn(
|
||||
rotary_emb.config, rotary_emb.inv_freq.device
|
||||
)
|
||||
rotary_emb.inv_freq.copy_(inv_freq)
|
||||
|
||||
|
||||
__all__ = ["Qwen3ForCausalLM", "Qwen3Model", "Qwen3PreTrainedModel"]
|
||||
@@ -78,7 +78,7 @@ class FileSystemWeightBroadcast(WeightBroadcast):
|
||||
self.logger.debug(f"Saving weights for run {idx} to {save_dir}")
|
||||
save_state_dict(state_dict, save_dir, self.save_format, self.save_sharded, adapter=adapter_only)
|
||||
if adapter_only:
|
||||
orch_lora = self.multi_run_manager.config[idx].model.lora
|
||||
orch_lora = self.multi_run_manager.config[idx].student.model.lora
|
||||
save_lora_config(
|
||||
model,
|
||||
save_dir,
|
||||
|
||||
@@ -24,6 +24,7 @@ class TensorMicroBatch(TypedDict):
|
||||
teacher_logprobs: Float[Tensor, "batch seq"] | None
|
||||
loss_mask: Bool[Tensor, "batch seq"]
|
||||
temperatures: Float[Tensor, "batch seq"] # Per-token temperatures
|
||||
env_names: list[str]
|
||||
|
||||
# Batch level
|
||||
lora_num_tokens: Int[Tensor, "n_loras"]
|
||||
@@ -39,8 +40,9 @@ class TensorMicroBatch(TypedDict):
|
||||
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
|
||||
mm_token_type_ids: Int[Tensor, "batch seq"] | None
|
||||
|
||||
# When True, trainer uses SFT loss instead of RL loss for this batch
|
||||
sft_loss: bool
|
||||
# Selects loss dispatch (rl/opd → default loss with mode-specific taus,
|
||||
# sft → sft loss). All samples in a micro batch share the same mode.
|
||||
training_mode: str
|
||||
|
||||
|
||||
class FakeDataLoader:
|
||||
@@ -108,13 +110,14 @@ class FakeDataLoader:
|
||||
"inference_logprobs": inference_logprobs.unsqueeze(0),
|
||||
"teacher_logprobs": None,
|
||||
"temperatures": torch.ones(input_ids.shape[0]).unsqueeze(0),
|
||||
"env_names": ["fake"] * input_ids.shape[0],
|
||||
"loss_mask": loss_mask.unsqueeze(0),
|
||||
"lora_num_tokens": lora_num_tokens,
|
||||
"routed_experts": None,
|
||||
"pixel_values": None,
|
||||
"image_grid_thw": None,
|
||||
"mm_token_type_ids": None,
|
||||
"sft_loss": False,
|
||||
"training_mode": "rl",
|
||||
}
|
||||
|
||||
def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch:
|
||||
@@ -135,13 +138,14 @@ class FakeDataLoader:
|
||||
"inference_logprobs": torch.randn(self.seq_len, generator=generator).unsqueeze(0),
|
||||
"teacher_logprobs": None,
|
||||
"temperatures": torch.ones(self.seq_len).unsqueeze(0),
|
||||
"env_names": ["fake"] * self.seq_len,
|
||||
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
|
||||
"lora_num_tokens": lora_num_tokens,
|
||||
"routed_experts": None,
|
||||
"pixel_values": None,
|
||||
"image_grid_thw": None,
|
||||
"mm_token_type_ids": None,
|
||||
"sft_loss": False,
|
||||
"training_mode": "rl",
|
||||
}
|
||||
|
||||
|
||||
@@ -205,6 +209,7 @@ class DataLoader:
|
||||
else None,
|
||||
loss_mask=torch.tensor(micro_batch.loss_mask, dtype=torch.bool).unsqueeze(0),
|
||||
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
|
||||
env_names=micro_batch.env_names,
|
||||
lora_num_tokens=torch.tensor(micro_batch.lora_num_tokens, dtype=torch.int32),
|
||||
# Multimodal fields - no batch dimension for these as they are variable-sized
|
||||
pixel_values=torch.frombuffer(bytearray(micro_batch.pixel_values), dtype=torch.float32).reshape(
|
||||
@@ -223,5 +228,5 @@ class DataLoader:
|
||||
) # [1, seq_len, layers, topk]
|
||||
if micro_batch.routed_experts is not None
|
||||
else None,
|
||||
sft_loss=micro_batch.sft_loss,
|
||||
training_mode=micro_batch.training_mode,
|
||||
)
|
||||
|
||||
+108
-36
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
|
||||
from jaxtyping import Bool, Float, Int, jaxtyped
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig, SFTLossConfig
|
||||
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -104,9 +104,18 @@ def _safe_mean(values: Tensor, mask: Tensor) -> Tensor:
|
||||
return values[mask].sum() / denom
|
||||
|
||||
|
||||
def compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs: Tensor, inference_logprobs: Tensor
|
||||
) -> tuple[Tensor, Tensor, Tensor]:
|
||||
log_importance_ratio = trainer_logprobs - inference_logprobs
|
||||
importance_ratio = torch.exp(log_importance_ratio)
|
||||
mismatch_kl = importance_ratio - log_importance_ratio - 1
|
||||
return log_importance_ratio, importance_ratio, mismatch_kl
|
||||
|
||||
|
||||
def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossOutputs:
|
||||
"""
|
||||
DPPO+KL loss, combining:
|
||||
DPPO+KL loss for RL training, combining:
|
||||
- DPPO-Binary TV Loss (https://arxiv.org/pdf/2602.04879)
|
||||
- Kimi-K2.5 KL Loss (https://arxiv.org/pdf/2602.02276)
|
||||
|
||||
@@ -118,13 +127,14 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
"""
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
teacher_logprobs = inputs.teacher_logprobs
|
||||
advantages = inputs.advantages
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
trainer_probs = torch.exp(trainer_logprobs)
|
||||
inference_probs = torch.exp(inference_logprobs)
|
||||
probs_diff = trainer_probs - inference_probs
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
|
||||
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
|
||||
dppo_invalid_mask_high = probs_diff > loss_config.dppo_mask_high
|
||||
dppo_invalid_mask_low = probs_diff < -loss_config.dppo_mask_low
|
||||
positive_advantages = advantages > 0
|
||||
@@ -137,23 +147,12 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
drop_mask = loss_mask & is_masked
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
log_importance_ratio = trainer_logprobs - inference_logprobs
|
||||
importance_ratio = torch.exp(log_importance_ratio)
|
||||
mismatch_kl = importance_ratio - log_importance_ratio - 1
|
||||
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
if teacher_logprobs is not None:
|
||||
teacher_kl = teacher_logprobs - trainer_logprobs
|
||||
advantages = advantages + loss_config.teacher_tau * teacher_kl.detach()
|
||||
else:
|
||||
teacher_kl = None
|
||||
|
||||
pg_loss = keep_mask * advantages * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
loss = (-pg_loss + loss_config.kl_tau * kl_loss).sum()
|
||||
|
||||
metrics = {
|
||||
"mismatch_kl": _safe_mean(mismatch_kl, loss_mask), # all trainable tokens
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
@@ -162,8 +161,59 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
|
||||
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
|
||||
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
|
||||
}
|
||||
if teacher_kl is not None:
|
||||
metrics["teacher_kl"] = _safe_mean(teacher_kl, loss_mask)
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def opd_loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
"""
|
||||
On-policy distillation loss: the default DPPO+KL math with the tau knobs
|
||||
hardcoded to drop the reward signal and use the teacher KL as the
|
||||
per-token policy-gradient signal.
|
||||
"""
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
teacher_logprobs = inputs.teacher_logprobs
|
||||
advantages = inputs.advantages
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
if teacher_logprobs is None:
|
||||
raise ValueError("opd_loss_fn requires teacher_logprobs - configure a teacher for opd mode.")
|
||||
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
|
||||
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
|
||||
dppo_invalid_mask_high = probs_diff > 0.2
|
||||
dppo_invalid_mask_low = probs_diff < -0.2
|
||||
positive_advantages = advantages > 0
|
||||
negative_advantages = advantages < 0
|
||||
dppo_invalid_mask = torch.where(positive_advantages, dppo_invalid_mask_high, dppo_invalid_mask_low)
|
||||
|
||||
is_masked = dppo_invalid_mask
|
||||
is_masked_high = positive_advantages & dppo_invalid_mask_high
|
||||
is_masked_low = negative_advantages & dppo_invalid_mask_low
|
||||
drop_mask = loss_mask & is_masked
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
|
||||
teacher_kl = teacher_logprobs - trainer_logprobs
|
||||
advantages = 0.0 * advantages + 1.0 * teacher_kl.detach()
|
||||
|
||||
pg_loss = keep_mask * advantages * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
loss = (-pg_loss + 1e-3 * kl_loss).sum()
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked),
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
"is_masked_low": _safe_mean(is_masked_low, loss_mask),
|
||||
"is_masked_high": _safe_mean(is_masked_high, loss_mask),
|
||||
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
|
||||
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
|
||||
"teacher_kl": _safe_mean(teacher_kl, loss_mask),
|
||||
}
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
@@ -180,24 +230,32 @@ def sft_loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
|
||||
def setup_loss_fn(loss_config: LossConfig) -> LossFn:
|
||||
"""Setup the loss function based on config."""
|
||||
def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
|
||||
"""Build the per-training-mode loss fn dispatch table.
|
||||
|
||||
Always returns all three modes - the trainer is mode-agnostic and routes
|
||||
per batch from ``TrainingSample.training_mode``:
|
||||
|
||||
- ``"sft"`` → ``sft_loss_fn`` (masked NLL on teacher tokens)
|
||||
- ``"opd"`` → ``opd_loss_fn`` (teacher KL as gradient signal, hardcoded
|
||||
DPPO + KL knobs)
|
||||
- ``"rl"`` → ``default_loss_fn(loss_config)`` for ``DefaultLossConfig``,
|
||||
or the imported function for ``CustomLossConfig``.
|
||||
|
||||
``trainer.loss`` only affects the rl path - opd and sft are independent.
|
||||
"""
|
||||
if isinstance(loss_config, CustomLossConfig):
|
||||
custom_fn = import_object(loss_config.import_path)
|
||||
kwargs = loss_config.kwargs
|
||||
|
||||
def loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return custom_fn(inputs, **kwargs)
|
||||
else:
|
||||
|
||||
return loss_fn
|
||||
def rl_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return default_loss_fn(inputs, loss_config)
|
||||
|
||||
if isinstance(loss_config, SFTLossConfig):
|
||||
return sft_loss_fn
|
||||
|
||||
def loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
return default_loss_fn(inputs, loss_config)
|
||||
|
||||
return loss_fn
|
||||
return {"sft": sft_loss_fn, "opd": opd_loss_fn, "rl": rl_fn}
|
||||
|
||||
|
||||
def compute_loss(
|
||||
@@ -206,27 +264,37 @@ def compute_loss(
|
||||
teacher_logprobs: list[Float[Tensor, " seq_i"]] | None,
|
||||
advantages: list[Float[Tensor, " seq_i"]],
|
||||
loss_mask: list[Bool[Tensor, " seq_i"]],
|
||||
loss_fn: LossFn,
|
||||
loss_fns: dict[str, LossFn],
|
||||
loss_scale: int,
|
||||
sft_loss: bool = False,
|
||||
training_mode: str = "rl",
|
||||
) -> tuple[Float[Tensor, ""], dict[str, Any]]:
|
||||
"""
|
||||
Compute loss for packed sequences (batch size = 1, multiple sequences packed along sequence dimension).
|
||||
|
||||
Loss dispatch is batch-driven: ``training_mode`` selects the loss fn from
|
||||
``loss_fns`` (built by ``setup_loss_fns``). sft → sft_loss_fn, opd →
|
||||
opd_loss_fn, rl → the configured default/custom loss.
|
||||
|
||||
Args:
|
||||
trainer_logprobs: Log probabilities for each sequence
|
||||
inference_logprobs: Reference log probabilities for each sequence
|
||||
teacher_logprobs: Teacher log probabilities for each sequence, or None
|
||||
advantages: Advantages for each sequence
|
||||
loss_mask: Loss mask for each sequence
|
||||
loss_fn: Per-sequence loss function
|
||||
loss_fns: Per-mode loss fn dispatch table from setup_loss_fns()
|
||||
loss_scale: Scale factor to normalize the loss
|
||||
sft_loss: If True, use SFT loss instead of the configured loss_fn for this batch
|
||||
training_mode: Selects which loss fn to apply
|
||||
|
||||
Returns:
|
||||
Tuple of (scaled_loss, aggregated_metrics)
|
||||
"""
|
||||
effective_loss_fn = sft_loss_fn if sft_loss else loss_fn
|
||||
try:
|
||||
effective_loss_fn = loss_fns[training_mode]
|
||||
except KeyError:
|
||||
raise ValueError(
|
||||
f"No loss fn available for training_mode={training_mode!r} "
|
||||
f"(available: {sorted(loss_fns)}). Check trainer.loss.type."
|
||||
)
|
||||
|
||||
total_loss = 0.0
|
||||
all_metrics: dict[str, list[Tensor]] = {}
|
||||
@@ -235,7 +303,11 @@ def compute_loss(
|
||||
teacher_logprobs = [None] * len(trainer_logprobs)
|
||||
|
||||
for t_logp, i_logp, teach_logp, adv, mask in zip(
|
||||
trainer_logprobs, inference_logprobs, teacher_logprobs, advantages, loss_mask
|
||||
trainer_logprobs,
|
||||
inference_logprobs,
|
||||
teacher_logprobs,
|
||||
advantages,
|
||||
loss_mask,
|
||||
):
|
||||
inputs = LossInputs(
|
||||
trainer_logprobs=t_logp,
|
||||
|
||||
@@ -29,8 +29,9 @@ from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.trainer.rl.loss import (
|
||||
compute_entropy,
|
||||
compute_loss,
|
||||
compute_importance_ratio_and_mismatch_kl,
|
||||
selective_log_softmax,
|
||||
setup_loss_fn,
|
||||
setup_loss_fns,
|
||||
shift_tensor_left,
|
||||
shift_tensor_right,
|
||||
)
|
||||
@@ -149,7 +150,7 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Set up the loss function
|
||||
logger.info(f"Setting up loss function ({config.loss})")
|
||||
loss_fn = setup_loss_fn(config.loss)
|
||||
loss_fns = setup_loss_fns(config.loss)
|
||||
|
||||
# Set up the optimizer
|
||||
logger.info(f"Initializing optimizer ({config.optim})")
|
||||
@@ -464,9 +465,9 @@ def train(config: TrainerConfig):
|
||||
else None,
|
||||
advantages=advantages.squeeze().split(response_lengths),
|
||||
loss_mask=loss_mask.squeeze().split(response_lengths),
|
||||
loss_fn=loss_fn,
|
||||
loss_fns=loss_fns,
|
||||
loss_scale=loss_scale,
|
||||
sft_loss=micro_batch["sft_loss"],
|
||||
training_mode=micro_batch["training_mode"],
|
||||
)
|
||||
|
||||
# Backward pass
|
||||
@@ -474,9 +475,27 @@ def train(config: TrainerConfig):
|
||||
loss.backward()
|
||||
|
||||
# Add relevant tensors to tensor dict for logging purposes
|
||||
tensors["entropy"].append(out["entropy"][loss_mask].detach().to("cpu"))
|
||||
entropy = out["entropy"][loss_mask].detach().to("cpu")
|
||||
tensors["entropy/all"].append(entropy)
|
||||
tensors["loss"].append(loss.detach().to("cpu").unsqueeze(0))
|
||||
|
||||
env_names = micro_batch["env_names"]
|
||||
masked_env_names = [env_name for env_name, keep in zip(env_names, loss_mask.flatten().tolist()) if keep]
|
||||
env_to_indices: dict[str, list[int]] = {}
|
||||
for idx, env_name in enumerate(masked_env_names):
|
||||
env_to_indices.setdefault(env_name, []).append(idx)
|
||||
|
||||
for env_name, indices in env_to_indices.items():
|
||||
tensors[f"entropy/{env_name}"].append(entropy[indices])
|
||||
|
||||
if micro_batch["training_mode"] != "sft":
|
||||
with torch.no_grad():
|
||||
_, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(out["logprobs"], inference_logprobs)
|
||||
mismatch_kl = mismatch_kl[loss_mask].detach().to("cpu")
|
||||
tensors["mismatch_kl/all"].append(mismatch_kl)
|
||||
for env_name, indices in env_to_indices.items():
|
||||
tensors[f"mismatch_kl/{env_name}"].append(mismatch_kl[indices])
|
||||
|
||||
if is_tt_moe_model(model):
|
||||
load_balance_stats = get_load_balance_stats(model)
|
||||
for k, v in load_balance_stats.items():
|
||||
@@ -485,13 +504,12 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Add loss tensors to tensor dict for logging purposes
|
||||
for key, loss_tensor in loss_tensors.items():
|
||||
loss_tensor = loss_tensor.detach().to("cpu")
|
||||
tensors[key].append(loss_tensor)
|
||||
tensors[key].append(loss_tensor.detach().to("cpu"))
|
||||
|
||||
# Debug log with *local, micro step* stats
|
||||
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss: {tensors['loss'][-1].mean().item():.4f} | Entropy: {tensors['entropy'][-1].mean().item():.4f}"
|
||||
if "mismatch_kl" in tensors:
|
||||
micro_step_message += f" | Mismatch KL: {tensors['mismatch_kl'][-1].mean().item():.4f}"
|
||||
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss: {tensors['loss'][-1].mean().item():.4f} | Entropy: {tensors['entropy/all'][-1].mean().item():.4f}"
|
||||
if micro_batch["training_mode"] != "sft":
|
||||
micro_step_message += f" | Mismatch KL: {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
|
||||
if "max_vio" in tensors:
|
||||
micro_step_message += f" | Max Vio: {tensors['max_vio'][-1].mean().item():.4f}"
|
||||
logger.debug(micro_step_message)
|
||||
@@ -539,9 +557,9 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Log step metrics
|
||||
step_time = time.perf_counter() - step_start_time
|
||||
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Loss: {tensor_stats['loss/mean']:.4f} | Entropy: {tensor_stats['entropy/mean']:.4f}"
|
||||
if "mismatch_kl/mean" in tensor_stats:
|
||||
step_message += f" | Mismatch KL: {tensor_stats['mismatch_kl/mean']:.4f}"
|
||||
step_message = f"Step {progress.step} | Time: {step_time:.2f}s | Loss: {tensor_stats['loss/mean']:.4f} | Entropy: {tensor_stats['entropy/all/mean']:.4f}"
|
||||
if "mismatch_kl/all/mean" in tensor_stats:
|
||||
step_message += f" | Mismatch KL: {tensor_stats['mismatch_kl/all/mean']:.4f}"
|
||||
if grad_norm is not None:
|
||||
step_message += f" | Grad. Norm: {grad_norm:.4f}"
|
||||
step_message += f" | LR: {current_lr:.2e} | Throughput: {throughput:.0f} tokens/s | MFU: {mfu:.1f}% | Peak Mem.: {peak_memory:.1f} GiB"
|
||||
@@ -570,8 +588,8 @@ def train(config: TrainerConfig):
|
||||
monitor.log(optim_metrics, step=progress.step)
|
||||
|
||||
# Compute derived metrics
|
||||
entropy_mean = tensor_stats.get("entropy/mean", 0.0)
|
||||
mismatch_kl_mean = tensor_stats.get("mismatch_kl/mean")
|
||||
entropy_mean = tensor_stats.get("entropy/all/mean", 0.0)
|
||||
mismatch_kl_mean = tensor_stats.get("mismatch_kl/all/mean")
|
||||
if mismatch_kl_mean is not None and entropy_mean > 0:
|
||||
tensor_stats["kl_ent_ratio/mean"] = mismatch_kl_mean / entropy_mean
|
||||
|
||||
@@ -605,8 +623,8 @@ def train(config: TrainerConfig):
|
||||
peak_memory_gib=peak_memory,
|
||||
learning_rate=current_lr,
|
||||
mfu=mfu,
|
||||
entropy=tensor_stats.get("entropy/mean", 0.0),
|
||||
mismatch_kl=tensor_stats.get("mismatch_kl/mean", 0.0),
|
||||
entropy=tensor_stats.get("entropy/all/mean", 0.0),
|
||||
mismatch_kl=tensor_stats.get("mismatch_kl/all/mean", 0.0),
|
||||
zero_grad_ratio=zero_grad_ratio,
|
||||
)
|
||||
# Update run/LoRA metrics
|
||||
|
||||
@@ -511,19 +511,21 @@ def setup_multi_run_manager(
|
||||
|
||||
def validate_lora_rank(orch_config: "OrchestratorConfig") -> tuple[bool, str]:
|
||||
# Default to trainer's rank/alpha if not specified
|
||||
if orch_config.model.lora.rank is None:
|
||||
orch_config.model.lora.rank = trainer_lora.rank
|
||||
if orch_config.model.lora.alpha is None:
|
||||
orch_config.model.lora.alpha = trainer_lora.alpha
|
||||
if orch_config.model.lora.rank > trainer_lora.rank:
|
||||
if orch_config.student.model.lora.rank is None:
|
||||
orch_config.student.model.lora.rank = trainer_lora.rank
|
||||
if orch_config.student.model.lora.alpha is None:
|
||||
orch_config.student.model.lora.alpha = trainer_lora.alpha
|
||||
if orch_config.student.model.lora.rank > trainer_lora.rank:
|
||||
return (
|
||||
False,
|
||||
f"model.lora.rank ({orch_config.model.lora.rank}) exceeds trainer max rank ({trainer_lora.rank})",
|
||||
f"student.model.lora.rank ({orch_config.student.model.lora.rank}) exceeds trainer max rank ({trainer_lora.rank})",
|
||||
)
|
||||
return True, ""
|
||||
|
||||
def on_run_discovered(idx: int, run_id: str, orch_config: "OrchestratorConfig") -> None:
|
||||
_MULTI_RUN_MANAGER.scaling_factors[idx] = orch_config.model.lora.alpha / orch_config.model.lora.rank
|
||||
_MULTI_RUN_MANAGER.scaling_factors[idx] = (
|
||||
orch_config.student.model.lora.alpha / orch_config.student.model.lora.rank
|
||||
)
|
||||
|
||||
_MULTI_RUN_MANAGER.register_config_validation_hook(validate_lora_rank)
|
||||
_MULTI_RUN_MANAGER.register_discovered_hook(on_run_discovered)
|
||||
|
||||
@@ -166,6 +166,8 @@ def train(config: SFTConfig):
|
||||
renderer=config.renderer.name,
|
||||
tool_parser=config.renderer.tool_parser,
|
||||
reasoning_parser=config.renderer.reasoning_parser,
|
||||
preserve_all_thinking=config.renderer.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=config.renderer.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
raise ValueError(
|
||||
|
||||
@@ -352,10 +352,16 @@ class Tensors(defaultdict):
|
||||
def compute_stats(self) -> dict[str, float | int]:
|
||||
"""Synchronize the tensor statistic across all ranks for each key and compute relevant statistics."""
|
||||
|
||||
local_keys = list(self.keys())
|
||||
gathered_keys: list[list[str] | None] = [None] * dist.get_world_size()
|
||||
dist.all_gather_object(gathered_keys, local_keys)
|
||||
keys = sorted({key for rank_keys in gathered_keys if rank_keys is not None for key in rank_keys})
|
||||
|
||||
metrics = {}
|
||||
for key in list(self.keys()):
|
||||
for key in keys:
|
||||
# All-gather tensors across steps and ranks (get global distribution)
|
||||
tensors = torch.cat(self.pop(key), dim=0).to("cuda")
|
||||
values = self.pop(key, [])
|
||||
tensors = torch.cat(values, dim=0).to("cuda") if values else torch.empty(0, device="cuda")
|
||||
assert tensors.ndim == 1, "Can only aggregate 1D tensors"
|
||||
tensors = flexible_all_gather(tensors)
|
||||
assert tensors.ndim == 1, "Can only aggregate 1D tensors"
|
||||
@@ -382,6 +388,11 @@ class Tensors(defaultdict):
|
||||
return metrics
|
||||
|
||||
|
||||
def _is_env_tensor_stat(key: str, allowed_stats: set[str]) -> bool:
|
||||
parts = key.split("/")
|
||||
return len(parts) >= 3 and parts[-1] in allowed_stats
|
||||
|
||||
|
||||
def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) -> dict[str, float | int]:
|
||||
"""Drop noisy per-token distribution keys before sending RL trainer stats to W&B."""
|
||||
skip_prefixes = ("trainer_probs/", "inference_probs/")
|
||||
@@ -402,9 +413,12 @@ def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) ->
|
||||
continue
|
||||
if any(k.startswith(p) for p in skip_prefixes):
|
||||
continue
|
||||
if k.startswith("entropy/") and k != "entropy/mean":
|
||||
if k.startswith("entropy/") and not _is_env_tensor_stat(k, {"mean", "std", "max"}):
|
||||
continue
|
||||
if any(k.startswith(p) for p in mean_max_only_prefixes):
|
||||
if _is_env_tensor_stat(k, {"mean", "std", "max"}):
|
||||
out[k] = v
|
||||
continue
|
||||
if not (k.endswith("/mean") or k.endswith("/max")):
|
||||
continue
|
||||
out[k] = v
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
from typing import Literal
|
||||
|
||||
import msgspec
|
||||
|
||||
TrainingMode = Literal["rl", "opd", "sft"]
|
||||
|
||||
|
||||
# Orchestrator -> Packer
|
||||
class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
@@ -11,6 +15,7 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
|
||||
completion_mask: list[bool]
|
||||
completion_logprobs: list[float]
|
||||
completion_temperatures: list[float] # Per-token temperatures used during generation
|
||||
env_name: str
|
||||
teacher_logprobs: list[float] | None = None
|
||||
advantage: float | None = None
|
||||
reward: float | None = None
|
||||
@@ -26,7 +31,9 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
|
||||
# mm_token_type_ids: token type ids per token [batch seq], int64 (0=text, 1=image, 2=video)
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
|
||||
sft_loss: bool = False # When True, trainer uses SFT loss instead of RL loss for this sample
|
||||
# Loss dispatch is batch-driven: rl/opd use default_loss_fn (with mode-specific
|
||||
# taus), sft uses sft_loss_fn. Stamped by the orchestrator from training_mode.
|
||||
training_mode: TrainingMode = "rl"
|
||||
|
||||
|
||||
class TrainingBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
@@ -47,6 +54,7 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
inference_logprobs: list[float]
|
||||
position_ids: list[int]
|
||||
temperatures: list[float] # Per-token temperatures used during generation
|
||||
env_names: list[str]
|
||||
teacher_logprobs: list[float] | None = None
|
||||
lora_num_tokens: list[int] | None = None
|
||||
routed_experts: list[list[list[int]]] | None = None
|
||||
@@ -59,4 +67,6 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
# mm_token_type_ids: token type ids per token [batch seq], int64 (0=text, 1=image, 2=video)
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
|
||||
sft_loss: bool = False # When True, trainer uses SFT loss instead of RL loss for this batch
|
||||
# Loss dispatch is batch-driven (rl/opd → default loss with mode-specific taus,
|
||||
# sft → sft loss). All samples packed into a micro batch share the same mode.
|
||||
training_mode: TrainingMode = "rl"
|
||||
|
||||
@@ -20,6 +20,11 @@ from prime_rl.utils.logger import get_logger
|
||||
class InferencePool(Protocol):
|
||||
"""Protocol for inference pools (static or elastic)."""
|
||||
|
||||
@property
|
||||
def model_name(self) -> str:
|
||||
"""Get current model name for inference requests."""
|
||||
...
|
||||
|
||||
@property
|
||||
def train_clients(self) -> list[vf.ClientConfig]:
|
||||
"""Get inference clients."""
|
||||
@@ -62,12 +67,14 @@ class StaticInferencePool:
|
||||
self,
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
train_client_type: str = "openai_chat_completions",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
):
|
||||
renderer_model_name = model_name if train_client_type == "renderer" else None
|
||||
self._train_clients = setup_clients(
|
||||
@@ -78,6 +85,8 @@ class StaticInferencePool:
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
preserve_all_thinking=preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
|
||||
)
|
||||
self._eval_clients = setup_clients(client_config, client_type=eval_client_type)
|
||||
self._admin_clients = setup_admin_clients(client_config)
|
||||
@@ -123,23 +132,16 @@ class StaticInferencePool:
|
||||
async def setup_inference_pool(
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
train_client_type: str = "openai_chat_completions",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
) -> InferencePool:
|
||||
"""Create an inference pool from config (static or elastic)."""
|
||||
logger = get_logger()
|
||||
|
||||
if train_client_type == "openai_chat_completions_token":
|
||||
logger.warning(
|
||||
"Token-in-token-out (TITO) client is enabled for training. Only use "
|
||||
"this if your environment has a linear history and the chat "
|
||||
"template has the extension property."
|
||||
)
|
||||
|
||||
if client_config.is_elastic:
|
||||
from prime_rl.utils.elastic import ElasticInferencePool
|
||||
|
||||
@@ -152,13 +154,10 @@ async def setup_inference_pool(
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
preserve_all_thinking=preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Initializing static inference pool (base_url={', '.join(client_config.base_url)}, "
|
||||
f"dp_rank_count={client_config.dp_rank_count}, "
|
||||
f"api_key_var={client_config.api_key_var}, headers={client_config.headers})"
|
||||
)
|
||||
return StaticInferencePool(
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
@@ -168,6 +167,8 @@ async def setup_inference_pool(
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
preserve_all_thinking=preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
|
||||
)
|
||||
|
||||
|
||||
@@ -179,12 +180,26 @@ def setup_clients(
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
) -> list[vf.ClientConfig]:
|
||||
clients = []
|
||||
client_idx = 0
|
||||
# Only forward preserve flags when the client actually uses a renderer —
|
||||
# MITO/TITO clients ignore them and the verifiers ClientConfig may reject
|
||||
# unknown extras on older versions.
|
||||
renderer_extra: dict = {}
|
||||
if client_type == "renderer":
|
||||
renderer_extra = {
|
||||
"preserve_all_thinking": preserve_all_thinking,
|
||||
"preserve_thinking_between_tool_calls": preserve_thinking_between_tool_calls,
|
||||
}
|
||||
env_headers = {
|
||||
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
|
||||
}
|
||||
for base_url in client_config.base_url:
|
||||
for dp_rank in range(client_config.dp_rank_count):
|
||||
headers = client_config.headers.copy()
|
||||
headers = {**client_config.headers, **env_headers}
|
||||
if client_config.dp_rank_count > 1:
|
||||
headers["X-data-parallel-rank"] = str(dp_rank)
|
||||
clients.append(
|
||||
@@ -205,6 +220,7 @@ def setup_clients(
|
||||
max_retries=10,
|
||||
extra_headers=headers,
|
||||
extra_headers_from_state=client_config.extra_headers_from_state,
|
||||
**renderer_extra,
|
||||
)
|
||||
)
|
||||
client_idx += 1
|
||||
@@ -221,7 +237,10 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
urls = client_config.admin_base_url if client_config.admin_base_url else client_config.base_url
|
||||
|
||||
def _setup_admin_client(base_url: str) -> httpx.AsyncClient:
|
||||
headers = client_config.headers.copy() # avoid mutating config
|
||||
env_headers = {
|
||||
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
|
||||
}
|
||||
headers = {**client_config.headers, **env_headers}
|
||||
api_key = os.getenv(client_config.api_key_var, "EMPTY")
|
||||
if api_key and api_key != "EMPTY":
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
|
||||
@@ -104,12 +104,14 @@ class ElasticInferencePool:
|
||||
self,
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
train_client_type: str = "openai_chat_completions",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.client_config = client_config
|
||||
@@ -125,6 +127,8 @@ class ElasticInferencePool:
|
||||
self.tool_parser = tool_parser
|
||||
self.reasoning_parser = reasoning_parser
|
||||
self.renderer_pool_size = renderer_pool_size
|
||||
self.preserve_all_thinking = preserve_all_thinking
|
||||
self.preserve_thinking_between_tool_calls = preserve_thinking_between_tool_calls
|
||||
self.router_url = client_config.router_url
|
||||
|
||||
self._servers: dict[str, ServerState] = {}
|
||||
@@ -146,12 +150,14 @@ class ElasticInferencePool:
|
||||
cls,
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
train_client_type: str = "openai_chat_completions",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
renderer_name: str = "auto",
|
||||
tool_parser: str | None = None,
|
||||
reasoning_parser: str | None = None,
|
||||
renderer_pool_size: int | None = None,
|
||||
preserve_all_thinking: bool = False,
|
||||
preserve_thinking_between_tool_calls: bool = False,
|
||||
) -> ElasticInferencePool:
|
||||
if client_config.elastic is None:
|
||||
raise ValueError("Elastic inference pool requires elastic config")
|
||||
@@ -164,6 +170,8 @@ class ElasticInferencePool:
|
||||
tool_parser=tool_parser,
|
||||
reasoning_parser=reasoning_parser,
|
||||
renderer_pool_size=renderer_pool_size,
|
||||
preserve_all_thinking=preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
|
||||
)
|
||||
await pool.start()
|
||||
return pool
|
||||
@@ -202,6 +210,7 @@ class ElasticInferencePool:
|
||||
base_url=urls,
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
headers_from_env=self.client_config.headers_from_env,
|
||||
dp_rank_count=self.client_config.dp_rank_count,
|
||||
extra_headers_from_state=self.client_config.extra_headers_from_state,
|
||||
)
|
||||
@@ -214,6 +223,8 @@ class ElasticInferencePool:
|
||||
tool_parser=self.tool_parser,
|
||||
reasoning_parser=self.reasoning_parser,
|
||||
renderer_pool_size=self.renderer_pool_size,
|
||||
preserve_all_thinking=self.preserve_all_thinking,
|
||||
preserve_thinking_between_tool_calls=self.preserve_thinking_between_tool_calls,
|
||||
)
|
||||
if urls
|
||||
else []
|
||||
@@ -257,6 +268,7 @@ class ElasticInferencePool:
|
||||
base_url=[f"{url}/v1"],
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
headers_from_env=self.client_config.headers_from_env,
|
||||
)
|
||||
return setup_admin_clients(config)[0]
|
||||
|
||||
|
||||
@@ -134,7 +134,6 @@ class PrimeMonitor(Monitor):
|
||||
return
|
||||
|
||||
assert config is not None
|
||||
self.logger.info(f"Initializing {self.__class__.__name__} ({config})")
|
||||
|
||||
api_key = os.getenv(config.api_key_var)
|
||||
if api_key is None:
|
||||
|
||||
@@ -44,7 +44,6 @@ class WandbMonitor(Monitor):
|
||||
return
|
||||
|
||||
assert config is not None
|
||||
self.logger.info(f"Initializing {self.__class__.__name__} ({config})")
|
||||
self._maybe_overwrite_wandb_command()
|
||||
|
||||
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user