Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
30a14c1702 | ||
|
|
a646ad6050 | ||
|
|
10135d4814 | ||
|
|
29cc7b24ef | ||
|
|
deb1aa92bc | ||
|
|
5c3008b3a5 | ||
|
|
54b3e4cd24 | ||
|
|
bc55a1c85a | ||
|
|
6f9c1362a1 | ||
|
|
46d210bf6e | ||
|
|
1e365924ac | ||
|
|
decced2093 | ||
|
|
a77725e5c0 | ||
|
|
3102ca47cb | ||
|
|
7c40b334e6 | ||
|
|
aaeb711501 | ||
|
|
6c8faec459 | ||
|
|
95a53f39e7 | ||
|
|
0756df77c1 | ||
|
|
66b1f4b6b7 | ||
|
|
bb5e48292d | ||
|
|
187b7a438c | ||
|
|
1b725b84b8 | ||
|
|
c28eaf874b | ||
|
|
26db10418e | ||
|
|
c2a84f5604 | ||
|
|
bdac9df86e | ||
|
|
39ce147af0 | ||
|
|
5e9548d425 | ||
|
|
3d1056a607 |
@@ -25,10 +25,10 @@ jobs:
|
||||
const { owner, repo } = context.repo;
|
||||
const sha = context.sha;
|
||||
|
||||
let baseTag;
|
||||
let latestTag;
|
||||
try {
|
||||
const latestRelease = await github.rest.repos.getLatestRelease({ owner, repo });
|
||||
baseTag = latestRelease.data.tag_name;
|
||||
latestTag = latestRelease.data.tag_name;
|
||||
} catch (error) {
|
||||
if (error.status === 404) {
|
||||
core.notice("No releases found. Skipping .dev tag creation.");
|
||||
@@ -37,6 +37,18 @@ jobs:
|
||||
throw error;
|
||||
}
|
||||
|
||||
const semverMatch = /^(v?)(\d+)\.(\d+)(?:\.(\d+))?$/.exec(latestTag);
|
||||
if (!semverMatch) {
|
||||
core.setFailed(`Latest release tag '${latestTag}' is not semver-like.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const [, versionPrefix, majorRaw, minorRaw, patchRaw] = semverMatch;
|
||||
const major = Number.parseInt(majorRaw, 10);
|
||||
const minor = Number.parseInt(minorRaw, 10);
|
||||
const patch = Number.parseInt(patchRaw ?? "0", 10) + 1;
|
||||
const baseTag = `${versionPrefix}${major}.${minor}.${patch}`;
|
||||
|
||||
const prefix = `${baseTag}.dev`;
|
||||
const escapeRegex = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const pattern = new RegExp(`^refs/tags/${escapeRegex(baseTag)}\\.dev(\\d+)$`);
|
||||
|
||||
@@ -65,10 +65,13 @@ jobs:
|
||||
include:
|
||||
- test: base
|
||||
runner: vm
|
||||
pytest_args: "tests/integration -m gpu --ignore=tests/integration/test_rl_lora.py --ignore=tests/integration/test_rl_multi_run_lora.py --ignore=tests/integration/test_benchmark_regression.py"
|
||||
pytest_args: "tests/integration -m gpu --ignore=tests/integration/test_rl_lora.py --ignore=tests/integration/test_rl_multi_run_lora.py --ignore=tests/integration/test_benchmark_regression.py --ignore=tests/integration/test_alphabet_sort.py"
|
||||
- test: rl_lora
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_rl_lora.py -m gpu"
|
||||
- test: alphabet_sort
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_alphabet_sort.py -m gpu"
|
||||
- test: rl_multi_run
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_rl_multi_run_lora.py -m gpu"
|
||||
@@ -102,6 +105,8 @@ jobs:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
|
||||
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
|
||||
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
|
||||
GITHUB_REF_NAME: ${{ github.ref_name }}
|
||||
GITHUB_HEAD_REF: ${{ github.head_ref }}
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
|
||||
@@ -5,6 +5,10 @@ configs/endpoints.py
|
||||
|
||||
# Artifacts
|
||||
**/slurm
|
||||
!src/prime_rl/slurm
|
||||
!examples/slurm
|
||||
!scripts/slurm_tmux.sh
|
||||
!docs/slurm.md
|
||||
**/torchrun
|
||||
**/weights
|
||||
**/checkpoints
|
||||
|
||||
+4
-2
@@ -37,7 +37,7 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`orchestrator.env.log`**: Removed. Use `orchestrator.log` for env worker logging instead (2026-01-15)
|
||||
- **`orchestrator.eval.retry.reraise`**: Changed default from `True` to `False`. When `False`, raises `tenacity.RetryError` after retries are exhausted instead of the original exception, allowing failed eval environments to be skipped with a warning (#1586, 2026-01-14)
|
||||
- **`model.ep`**: Expert parallelism now supported (with auto/custom impl only), changed from the old behaviour when `ep>1` was a no-op to a proper parallelization of the MoE layers. (#1595, 2026-01-15)
|
||||
- **`orchestrator.reload_weights_on_start`**: Added flag to control resetting inference weights to the base model when starting from scratch (default: True) (2026-01-21)
|
||||
- **`orchestrator.reload_weights_on_start`**: Removed. The reload was a no-op in practice since vLLM servers already start with base weights, and LoRA runs skipped it. (#1829, 2026-02-19)
|
||||
- **`orchestrator.client.elastic`**: Added elastic inference pool with DNS-based service discovery. Supports dynamic server scaling via any DNS hostname with multiple A records (Kubernetes headless services, Consul, Route53, etc.). Automatically syncs LoRA adapters on new servers and only exposes ready servers to workers (#1617, 2026-01-19)
|
||||
- **`model.fused_lm_head_chunk_size`**: Replaced chunk size `int | None` setting with `int | Literal["auto", "disabled"]` setting. `auto` auto-sets to 2048 if possible. `disabled` explicitly disables chunked loss (use vanilla LM head). Default behaviour is to use `auto` for RL training and `disabled` for SFT training. (not changed from previous version) (#1649, 2026-01-23)
|
||||
- **`client.skip_model_check`**: Added configuration 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 (default: False) (#1543, 2026-01-06)
|
||||
@@ -56,6 +56,8 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
|
||||
- **`EvalSaveDiskConfig`**, **`EvalSaveConfig`**, **`RetryConfig`**, **`OnlineEvalConfig`**: Removed (2026-02-06)
|
||||
- **`TemperatureScheduleConfig`**: Renamed to `TemperatureSchedulerConfig` (2026-02-06)
|
||||
- **`optim.mu`**: Added Muon momentum (`mu`) config field (default: 0.95). Previously hardcoded to Muon class default. Also fixed `optim.betas1`/`optim.betas2` not being passed through to the Muon optimizer (2026-02-09)
|
||||
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12
|
||||
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12)
|
||||
- **`client.api_key_var`**: Changed default from "OPENAI_API_KEY" to "VLLM_API_KEY" (2026-02-12)
|
||||
- **`orchestrator.filters`**: Added orchestrator-side rollout filters for detecting degenerate generations. Supports `[[filters]] type = "gibberish"` (rare tokens at high entropy) and `[[filters]] type = "repetition"` (high-confidence token streaks). Detected rollouts get reward zeroed and completion mask cleared (2026-02-13)
|
||||
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 8
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 384
|
||||
|
||||
[[orchestrator.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 }
|
||||
|
||||
[inference]
|
||||
@@ -0,0 +1,29 @@
|
||||
inference_gpu_ids = [0]
|
||||
trainer_gpu_ids = [1]
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "samsja/mini-glm-moe"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 128
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.7
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 2048
|
||||
@@ -0,0 +1,35 @@
|
||||
# Based on configs/multimodal/rl_color_codeword.toml but tuned for CI
|
||||
inference_gpu_ids = [0,1,2,3]
|
||||
trainer_gpu_ids = [4,5,6,7]
|
||||
|
||||
max_steps = 25
|
||||
seq_len = 4096
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-VL-4B-Instruct"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 64
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "primeintellect/color-codeword"
|
||||
args = { images_per_turn = 1, max_turns = 3, num_examples = 1000, seed = 42 }
|
||||
|
||||
[orchestrator.val]
|
||||
interval = 5
|
||||
num_examples = 100
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
optimization_dtype = "bfloat16"
|
||||
reduce_dtype = "bfloat16"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
+2
-2
@@ -83,7 +83,7 @@ uv run torchrun \
|
||||
|
||||
### SLURM
|
||||
|
||||
TBD.
|
||||
See the dedicated [SLURM guide](slurm.md).
|
||||
|
||||
## Inference
|
||||
|
||||
@@ -281,7 +281,7 @@ Of course, you can further scale up the number of nodes used by the trainer and
|
||||
|
||||
### SLURM
|
||||
|
||||
TBD.
|
||||
See the dedicated [SLURM guide](slurm.md).
|
||||
|
||||
## Kubernetes
|
||||
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ The trainer is responsible for producing an updated policy model given rollouts
|
||||
|
||||
### Inference
|
||||
|
||||
The inference service in its simplest form is a standard OpenAI-compatible server with a vLLM backend. The API specification is extended with two custom endpoints to enable updating the server with the latest policy: `update_weights` is used to reload model weights from a HF-compatible checkpoint on disk, and `reload_weights` is used to reset the weights to the base model in between experiments. Otherwise, we rely on vLLM's optimized kernels, parallelism strategies, and scheduling for fast rollout generation. Given the disaggregated nature of the service architecture, it can be directly extended to include multiple engines with a shared request pool, allowing operation across multiple clusters and straightforward integration of alternative inference engines (e.g. SGLang, Tokasaurus). We also heavily rely on native data parallelism in vLLM (also available in SGLang) for orchestrating the fleet of nodes dedicated to inference.
|
||||
The inference service in its simplest form is a standard OpenAI-compatible server with a vLLM backend. The API specification is extended with a custom `update_weights` endpoint to reload model weights from a HF-compatible checkpoint on disk. Otherwise, we rely on vLLM's optimized kernels, parallelism strategies, and scheduling for fast rollout generation. Given the disaggregated nature of the service architecture, it can be directly extended to include multiple engines with a shared request pool, allowing operation across multiple clusters and straightforward integration of alternative inference engines (e.g. SGLang, Tokasaurus). We also heavily rely on native data parallelism in vLLM (also available in SGLang) for orchestrating the fleet of nodes dedicated to inference.
|
||||
|
||||
### RL
|
||||
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
# SLURM
|
||||
|
||||
For SLURM clusters, use the `rl_slurm` entrypoint. It resolves the full config (trainer, orchestrator, inference), dumps sub-configs as TOML files, renders a SLURM batch script from a Jinja2 template, and submits it with `sbatch`.
|
||||
|
||||
```bash
|
||||
uv run rl_slurm @ examples/slurm/hendrycks_math.toml
|
||||
```
|
||||
|
||||
This will:
|
||||
|
||||
1. Write resolved sub-configs to `{output_dir}/configs/` (trainer.toml, orchestrator.toml, inference.toml)
|
||||
2. Render the SLURM script to `{output_dir}/rl.sh`
|
||||
3. Submit the job via `sbatch`
|
||||
|
||||
To only generate the script without submitting, use `--dry-run`:
|
||||
|
||||
```bash
|
||||
uv run rl_slurm @ examples/slurm/hendrycks_math.toml --dry-run
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
The SLURM config extends the standard RL config with the following fields:
|
||||
|
||||
| Field | Description |
|
||||
|---|---|
|
||||
| `job_name` | SLURM job name |
|
||||
| `output_dir` | Directory for outputs, sub-configs, and logs |
|
||||
| `project_dir` | Path to the project root on the cluster (defaults to cwd) |
|
||||
| `num_train_nodes` | Number of nodes for training |
|
||||
| `num_infer_nodes` | Number of nodes for inference |
|
||||
| `gpus_per_node` | Number of GPUs per node (default: 8) |
|
||||
| `nodes_per_fsdp_group` | Number of train nodes per FSDP island (optional, auto-sets `trainer.dp_replicate`) |
|
||||
| `slurm_template` | Path to a custom Jinja2 template (optional) |
|
||||
| `dry_run` | Only generate the script without submitting (default: false) |
|
||||
|
||||
All standard RL config fields (model, trainer, orchestrator, inference, wandb, ckpt, etc.) are available and will be resolved into the sub-configs.
|
||||
|
||||
### Dense model (Hendrycks Math)
|
||||
|
||||
```toml
|
||||
job_name = "hendrycks-math"
|
||||
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 2048
|
||||
|
||||
[wandb]
|
||||
project = "hendrycks-math"
|
||||
name = "hendrycks-math"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 1
|
||||
dp = 8
|
||||
```
|
||||
|
||||
### MoE model (Hendrycks Math)
|
||||
|
||||
For MoE models like `Qwen3-30B-A3B`, the config is designed to minimize memory usage on a single training node. It enables activation checkpointing with offloading, optimizer CPU offload, and NCCL weight broadcast:
|
||||
|
||||
```toml
|
||||
job_name = "hendrycks-math-moe"
|
||||
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 2048
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
optim_cpu_offload = true
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 4
|
||||
dp = 2
|
||||
```
|
||||
|
||||
## Custom SLURM Templates
|
||||
|
||||
The default template handles a standard multi-node setup with NCCL weight broadcast, InfiniBand detection, and `srun`-based process dispatch. For more advanced use cases (custom partitions, account settings, module loads, different networking setups, etc.), provide your own Jinja2 template:
|
||||
|
||||
```bash
|
||||
uv run rl_slurm \
|
||||
@ my_config.toml \
|
||||
--slurm-template path/to/my_template.sh.j2
|
||||
```
|
||||
|
||||
The template receives the following variables: `job_name`, `project_dir`, `output_dir`, `config_dir`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `hf_hub_offline`. See `src/prime_rl/slurm/rl_slurm.sh.j2` for the default template as a starting point.
|
||||
|
||||
## Monitoring
|
||||
|
||||
After submission, the logs are available at:
|
||||
|
||||
```bash
|
||||
tail -f {output_dir}/slurm/latest_train_node_rank_0.log
|
||||
tail -f {output_dir}/slurm/latest_infer_node_rank_0.log
|
||||
tail -f {output_dir}/slurm/latest_orchestrator.log
|
||||
```
|
||||
|
||||
For convenience, a tmux launcher is provided that sets up a session with all three log streams:
|
||||
|
||||
```bash
|
||||
bash scripts/slurm_tmux.sh my-rl-job /shared/outputs/my-rl-job
|
||||
```
|
||||
|
||||
This creates a tmux session `slurm-my-rl-job` with two windows:
|
||||
|
||||
- **Window 0 (Terminal)**: a plain shell for running commands
|
||||
- **Window 1 (Logs)**: three vertical panes tailing trainer, orchestrator, and inference logs
|
||||
|
||||
The trainer and inference panes use glob patterns (`latest_train_node_rank_*.log`, `latest_infer_node_rank_*.log`) to follow logs from all node ranks. Re-running the same command attaches to the existing session.
|
||||
@@ -0,0 +1,41 @@
|
||||
job_name = "hendrycks-math"
|
||||
output_dir = "outputs/hendrycks-math"
|
||||
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[wandb]
|
||||
project = "hendrycks-math-debug"
|
||||
name = "hendrycks-math"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference.parallel]
|
||||
tp = 1
|
||||
dp = 8
|
||||
@@ -0,0 +1,53 @@
|
||||
job_name = "hendrycks-math-moe"
|
||||
output_dir = "outputs/hendrycks-math-moe"
|
||||
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
max_steps = 500
|
||||
seq_len = 2048
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[wandb]
|
||||
project = "hendrycks-math-debug"
|
||||
name = "hendrycks-math"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
optim_cpu_offload = true
|
||||
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
rollouts_per_example = 16
|
||||
|
||||
[orchestrator.sampling]
|
||||
max_tokens = 2048
|
||||
|
||||
[[orchestrator.env]]
|
||||
id = "math-env"
|
||||
name = "hendrycks-math"
|
||||
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
|
||||
|
||||
[orchestrator.buffer]
|
||||
easy_threshold = 1.0
|
||||
hard_threshold = 0.0
|
||||
|
||||
[inference.parallel]
|
||||
tp = 4
|
||||
dp = 2
|
||||
@@ -27,7 +27,7 @@ spec:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl
|
||||
- name: prime-rl-orchestrator
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.orchestrator.autoStart }}
|
||||
@@ -133,7 +133,7 @@ spec:
|
||||
runtimeClassName: {{ .Values.inference.runtimeClassName }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl
|
||||
- name: prime-rl-inference
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.inference.autoStart }}
|
||||
@@ -262,7 +262,7 @@ spec:
|
||||
runtimeClassName: {{ .Values.trainer.runtimeClassName }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: prime-rl
|
||||
- name: prime-rl-trainer
|
||||
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
{{- if .Values.trainer.autoStart }}
|
||||
|
||||
+8
-2
@@ -25,6 +25,7 @@ dependencies = [
|
||||
"prime>=0.5.37",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"math-env",
|
||||
"tenacity>=8.2.0",
|
||||
"openai>=1.106.1",
|
||||
"rich>=14.0.0",
|
||||
@@ -37,15 +38,19 @@ dependencies = [
|
||||
|
||||
[project.scripts]
|
||||
rl = "prime_rl.rl:main"
|
||||
rl_slurm = "prime_rl.slurm.rl:main"
|
||||
trainer = "prime_rl.trainer.rl.train:main"
|
||||
orchestrator = "prime_rl.orchestrator.orchestrator:main"
|
||||
inference = "prime_rl.inference.server:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
sft = "prime_rl.trainer.sft.train:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
|
||||
|
||||
[project.optional-dependencies]
|
||||
flash-attn = [
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.6.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl",
|
||||
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl",
|
||||
]
|
||||
flash-attn-3 = [
|
||||
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl",
|
||||
@@ -77,7 +82,8 @@ override-dependencies = [
|
||||
|
||||
[tool.uv.sources]
|
||||
torch = { index = "pytorch-cu128" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "ccef044" }
|
||||
math-env = { index = "primeintellect" }
|
||||
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "013d4da" }
|
||||
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 = "609e3d5" }
|
||||
|
||||
+61
-9
@@ -15,12 +15,14 @@ import argparse
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from transformers import AutoConfig, AutoTokenizer
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
|
||||
from transformers import Glm4MoeForCausalLM as HFGlm4MoeForCausalLM
|
||||
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
@@ -57,21 +59,70 @@ ARCH_PRESETS = {
|
||||
"prime_model_class": PrimeRLGlm4MoeForCausalLM,
|
||||
"tokenizer_source": "THUDM/GLM-4-9B-0414",
|
||||
},
|
||||
"minimax_m2": {
|
||||
"config_class": MiniMaxM2Config,
|
||||
"config_kwargs": dict(
|
||||
vocab_size=200064,
|
||||
hidden_size=512,
|
||||
intermediate_size=256,
|
||||
num_hidden_layers=12,
|
||||
num_attention_heads=8,
|
||||
num_key_value_heads=4,
|
||||
head_dim=64,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=4096,
|
||||
rms_norm_eps=1e-6,
|
||||
rope_theta=5000000,
|
||||
rotary_dim=32,
|
||||
num_local_experts=8,
|
||||
num_experts_per_tok=4,
|
||||
scoring_func="sigmoid",
|
||||
use_routing_bias=True,
|
||||
use_qk_norm=True,
|
||||
qk_norm_type="per_layer",
|
||||
use_grouped_mm=False,
|
||||
auto_map={"AutoModelForCausalLM": "MiniMaxAI/MiniMax-M2.1--modeling_minimax_m2.MiniMaxM2ForCausalLM"},
|
||||
),
|
||||
"hf_model_class": None, # uses AutoModelForCausalLM with trust_remote_code
|
||||
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
|
||||
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _create_hf_model(preset, config):
|
||||
"""Create an HF model from a preset and config."""
|
||||
hf_cls = preset["hf_model_class"]
|
||||
if hf_cls is not None:
|
||||
return hf_cls(config)
|
||||
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
|
||||
|
||||
|
||||
def _load_hf_model(preset, model_dir, config):
|
||||
"""Load an HF model from a preset and directory."""
|
||||
hf_cls = preset["hf_model_class"]
|
||||
if hf_cls is not None:
|
||||
return hf_cls.from_pretrained(str(model_dir), config=config)
|
||||
return AutoModelForCausalLM.from_pretrained(str(model_dir), config=config, trust_remote_code=True)
|
||||
|
||||
|
||||
def _create_hf_model_from_config(preset, config):
|
||||
"""Create an empty HF model from config (for roundtrip verification)."""
|
||||
hf_cls = preset["hf_model_class"]
|
||||
if hf_cls is not None:
|
||||
return hf_cls._from_config(config)
|
||||
return AutoModelForCausalLM.from_config(config, trust_remote_code=True)
|
||||
|
||||
|
||||
def create(arch: str, output_dir: Path) -> None:
|
||||
preset = ARCH_PRESETS[arch]
|
||||
config = preset["config_class"](**preset["config_kwargs"])
|
||||
|
||||
print(f"Creating mini {arch} model...")
|
||||
print(
|
||||
f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}, "
|
||||
f"experts={config.n_routed_experts}, moe_intermediate_size={config.moe_intermediate_size}"
|
||||
)
|
||||
print(f" hidden_size={config.hidden_size}, layers={config.num_hidden_layers}")
|
||||
|
||||
with torch.device("cpu"):
|
||||
model = preset["hf_model_class"](config)
|
||||
model = _create_hf_model(preset, config)
|
||||
|
||||
param_count = sum(p.numel() for p in model.parameters())
|
||||
print(f" Parameters: {param_count / 1e6:.1f}M")
|
||||
@@ -89,11 +140,12 @@ def verify(arch: str, model_dir: Path) -> None:
|
||||
preset = ARCH_PRESETS[arch]
|
||||
print(f"Verifying HF <-> PrimeRL roundtrip for {model_dir}...")
|
||||
|
||||
config = AutoConfig.from_pretrained(str(model_dir))
|
||||
trust_remote_code = preset["hf_model_class"] is None
|
||||
config = AutoConfig.from_pretrained(str(model_dir), trust_remote_code=trust_remote_code)
|
||||
config._attn_implementation = "sdpa"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_model = preset["hf_model_class"].from_pretrained(str(model_dir), config=config)
|
||||
hf_model = _load_hf_model(preset, model_dir, config)
|
||||
prime_model = preset["prime_model_class"]._from_config(config)
|
||||
|
||||
with torch.no_grad():
|
||||
@@ -118,7 +170,7 @@ def verify(arch: str, model_dir: Path) -> None:
|
||||
with torch.no_grad():
|
||||
roundtrip_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_roundtrip = preset["hf_model_class"]._from_config(config)
|
||||
hf_roundtrip = _create_hf_model_from_config(preset, config)
|
||||
hf_roundtrip.load_state_dict(roundtrip_state_dict)
|
||||
|
||||
hf_roundtrip_output = hf_roundtrip(input_ids, position_ids)
|
||||
|
||||
Executable
+50
@@ -0,0 +1,50 @@
|
||||
#!/bin/bash
|
||||
|
||||
JOB_NAME="$1"
|
||||
OUTPUT_DIR="$2"
|
||||
|
||||
if [[ -z "$JOB_NAME" || -z "$OUTPUT_DIR" ]]; then
|
||||
echo "Usage: $0 JOB_NAME OUTPUT_DIR" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SLURM_LOG_DIR="${OUTPUT_DIR}/slurm"
|
||||
SESSION_NAME="slurm-${JOB_NAME}"
|
||||
|
||||
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
|
||||
echo "Attaching to existing tmux session: $SESSION_NAME"
|
||||
exec tmux attach-session -t "$SESSION_NAME"
|
||||
fi
|
||||
|
||||
echo "Creating tmux session: $SESSION_NAME"
|
||||
|
||||
# Window 0: Terminal
|
||||
tmux new-session -d -s "$SESSION_NAME" -n "Terminal"
|
||||
|
||||
# Window 1: Logs - 3 vertical panes
|
||||
tmux new-window -t "$SESSION_NAME" -n "Logs"
|
||||
|
||||
tmux split-window -v -t "$SESSION_NAME:Logs.0"
|
||||
tmux split-window -v -t "$SESSION_NAME:Logs.1"
|
||||
tmux select-layout -t "$SESSION_NAME:Logs" even-vertical
|
||||
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.0" -T "Trainer"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.1" -T "Orchestrator"
|
||||
tmux select-pane -t "$SESSION_NAME:Logs.2" -T "Inference"
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.0" \
|
||||
"tail -F ${SLURM_LOG_DIR}/latest_train_node_rank_*.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.1" \
|
||||
"tail -F ${SLURM_LOG_DIR}/latest_orchestrator.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.2" \
|
||||
"tail -F ${SLURM_LOG_DIR}/latest_infer_node_rank_*.log 2>/dev/null" C-m
|
||||
|
||||
# Pane title styling
|
||||
tmux set-option -t "$SESSION_NAME" -g pane-border-status top
|
||||
tmux set-option -t "$SESSION_NAME" -g pane-border-format " #{pane_title} "
|
||||
|
||||
# Focus Terminal window and attach
|
||||
tmux select-window -t "$SESSION_NAME:Terminal"
|
||||
exec tmux attach-session -t "$SESSION_NAME"
|
||||
@@ -1,3 +1,15 @@
|
||||
def transformers_v5_compat():
|
||||
"""vLLM general plugin: patch transformers v5 config attrs that vLLM 0.16 still expects.
|
||||
|
||||
Registered as a ``vllm.general_plugins`` entry-point so it runs automatically
|
||||
in every vLLM process, including spawned workers.
|
||||
"""
|
||||
from transformers import Qwen3VLMoeTextConfig
|
||||
|
||||
if not hasattr(Qwen3VLMoeTextConfig, "tie_word_embeddings"):
|
||||
Qwen3VLMoeTextConfig.tie_word_embeddings = False
|
||||
|
||||
|
||||
# Monkeypatch PrometheusStatLogger to avoid NotImplementedError for LoRA in DP mode
|
||||
def monkey_patch_prometheus_stat_logger_for_lora_in_dp_mode():
|
||||
from vllm.v1.metrics import loggers as vllm_metrics_loggers
|
||||
@@ -191,3 +203,78 @@ def monkey_patch_tokenize_params_validation():
|
||||
|
||||
TokenizeParams._token_len_check = _patched_token_len_check
|
||||
TokenizeParams._text_len_check = _patched_text_len_check
|
||||
|
||||
|
||||
def monkey_patch_minimax_m2_for_lora():
|
||||
"""Patch vLLM's MiniMaxM2 model for LoRA compatibility.
|
||||
|
||||
These patches are only needed when using LoRA with MiniMax M2 but are safe
|
||||
to apply unconditionally (verified with non-LoRA runs). We apply them at
|
||||
import time because the worker __init__ runs before the vLLM config is
|
||||
available, so we can't check if LoRA is enabled.
|
||||
|
||||
Problem 1 — Gate dtype mismatch:
|
||||
vLLM's MiniMaxM2MoE creates the gate (router) with params_dtype=float32
|
||||
and casts inputs to float32. When LoRA is enabled, vLLM wraps ALL
|
||||
ReplicatedLinear layers (including the gate) with LoRA support. Even
|
||||
though our adapter has no gate LoRA weights, the LoRA Triton kernel
|
||||
still runs for all wrapped layers when any adapter is active — and it
|
||||
asserts inputs are float16/bfloat16. Qwen3 MoE doesn't have this
|
||||
problem because its gate uses the model dtype.
|
||||
Fix: recreate the gate in model dtype and remove the float32 cast.
|
||||
FusedMoE already has router_logits_dtype=float32, so routing precision
|
||||
is preserved inside the expert dispatch.
|
||||
|
||||
Problem 2 — Adapter key naming mismatch:
|
||||
PrimeRL saves adapter keys using its internal naming convention
|
||||
(mlp.experts.{j}.gate_proj/down_proj/up_proj), which matches Qwen3 MoE
|
||||
but not MiniMax M2. vLLM's MiniMax M2 model expects HF-style keys
|
||||
(block_sparse_moe.experts.{j}.w1/w2/w3). For full model weights this
|
||||
is handled by vLLM's load_weights(), but LoRA adapters are loaded
|
||||
through a separate path (LoRAModel.from_local_checkpoint) that doesn't
|
||||
have model-specific key translation.
|
||||
Fix: set hf_to_vllm_mapper on the model class so vLLM remaps adapter
|
||||
keys during LoRA loading. This attribute is only read by _load_adapter
|
||||
in the LoRA worker manager — it has no effect without LoRA.
|
||||
"""
|
||||
from vllm.model_executor.models.minimax_m2 import MiniMaxM2ForCausalLM, MiniMaxM2MoE
|
||||
from vllm.model_executor.models.utils import WeightsMapper
|
||||
|
||||
# --- Gate dtype fix (only matters with LoRA, safe without) ---
|
||||
_original_init = MiniMaxM2MoE.__init__
|
||||
|
||||
def _patched_init(self, config, quant_config=None, prefix=""):
|
||||
_original_init(self, config, quant_config, prefix)
|
||||
from vllm.model_executor.layers.linear import ReplicatedLinear
|
||||
|
||||
self.gate = ReplicatedLinear(
|
||||
config.hidden_size,
|
||||
config.num_local_experts,
|
||||
bias=False,
|
||||
quant_config=None,
|
||||
prefix=f"{prefix}.gate",
|
||||
)
|
||||
|
||||
def _patched_forward(self, hidden_states):
|
||||
from vllm.distributed import tensor_model_parallel_all_reduce
|
||||
|
||||
num_tokens, hidden_dim = hidden_states.shape
|
||||
hidden_states = hidden_states.view(-1, hidden_dim)
|
||||
router_logits, _ = self.gate(hidden_states)
|
||||
final_hidden_states = self.experts(hidden_states=hidden_states, router_logits=router_logits)
|
||||
if self.tp_size > 1:
|
||||
final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states)
|
||||
return final_hidden_states.view(num_tokens, hidden_dim)
|
||||
|
||||
MiniMaxM2MoE.__init__ = _patched_init
|
||||
MiniMaxM2MoE.forward = _patched_forward
|
||||
|
||||
# --- Adapter key remapping (only read by vLLM's LoRA adapter loader) ---
|
||||
MiniMaxM2ForCausalLM.hf_to_vllm_mapper = WeightsMapper(
|
||||
orig_to_new_substr={
|
||||
".mlp.experts.": ".block_sparse_moe.experts.",
|
||||
".gate_proj.": ".w1.",
|
||||
".down_proj.": ".w2.",
|
||||
".up_proj.": ".w3.",
|
||||
},
|
||||
)
|
||||
|
||||
@@ -76,14 +76,6 @@ async def update_weights(request: Request):
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/reload_weights")
|
||||
async def reload_weights(request: Request):
|
||||
await engine_client(request).collective_rpc("reload_weights")
|
||||
# Reset prefix cache to invalidate KV states computed with old weights
|
||||
await engine_client(request).reset_prefix_cache()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/load_lora_adapter")
|
||||
async def load_lora_adapter(lora_request: LoadLoRAAdapterRequest, raw_request: Request):
|
||||
"""Load a LoRA adapter and reset the prefix cache.
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from prime_rl.inference.patches import monkey_patch_LRUCacheWorkerLoRAManager
|
||||
from prime_rl.inference.patches import monkey_patch_LRUCacheWorkerLoRAManager, monkey_patch_minimax_m2_for_lora
|
||||
|
||||
# Monkeypatch LRUCacheWorkerLoRAManager to allow loading adapter inplace without doing it every request
|
||||
monkey_patch_LRUCacheWorkerLoRAManager()
|
||||
# Monkeypatch MiniMaxM2 MoE gate dtype and adapter key mapping for LoRA compatibility
|
||||
monkey_patch_minimax_m2_for_lora()
|
||||
|
||||
@@ -29,7 +29,7 @@ class CheckpointManager:
|
||||
def get_ckpt_path(self, step: int) -> Path:
|
||||
return get_step_path(self.ckpt_dir, step) / "orchestrator"
|
||||
|
||||
def _save_to_path(
|
||||
def save_to_path(
|
||||
self,
|
||||
ckpt_path: Path,
|
||||
progress: Progress,
|
||||
@@ -47,7 +47,7 @@ class CheckpointManager:
|
||||
|
||||
self.logger.debug(f"Orchestrator checkpoint saved in {time.perf_counter() - start_time:.2f} seconds")
|
||||
|
||||
def _load_from_path(self, ckpt_path: Path, progress: Progress, buffer: Buffer) -> None:
|
||||
def load_from_path(self, ckpt_path: Path, progress: Progress, buffer: Buffer) -> None:
|
||||
"""Loads a checkpoint from a given path in-place."""
|
||||
self.logger.debug(f"Loading checkpoint from {ckpt_path}")
|
||||
start_time = time.perf_counter()
|
||||
@@ -76,7 +76,7 @@ class CheckpointManager:
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
if not ckpt_path.exists():
|
||||
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
|
||||
self._load_from_path(ckpt_path, progress, buffer)
|
||||
self.load_from_path(ckpt_path, progress, buffer)
|
||||
|
||||
def save(
|
||||
self,
|
||||
@@ -87,7 +87,7 @@ class CheckpointManager:
|
||||
"""Saves the full checkpoint state for a specified step."""
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
ckpt_path.mkdir(parents=True, exist_ok=True)
|
||||
self._save_to_path(ckpt_path, progress, buffer)
|
||||
self.save_to_path(ckpt_path, progress, buffer)
|
||||
|
||||
|
||||
def setup_ckpt_manager(output_dir: Path, config: CheckpointConfig | None) -> CheckpointManager | None:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import AliasChoices, BaseModel, Discriminator, Field, Tag, model_validator
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Discriminator, Field, Tag, model_validator
|
||||
|
||||
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfigType
|
||||
from prime_rl.utils.config import (
|
||||
@@ -284,7 +284,7 @@ class EnvConfig(BaseConfig):
|
||||
dict[str, Any],
|
||||
Field(
|
||||
description=(
|
||||
"Extra kwargs passed to an env (e.g. seq_len, interleaved_rollouts, score_rollouts). This field is auto-populated with the seq_len, interleaved_rollouts, and score_rollouts for training envs on the orchestrator. It is generally NOT recommended for this field to be overriden by the user. It's main use case is to match the extra_env_kwargs when running an env in an isolated environment server."
|
||||
"Extra kwargs passed to an env (e.g. seq_len, score_rollouts). This field is auto-populated with the seq_len, and score_rollouts for training envs on the orchestrator. It is generally NOT recommended for this field to be overriden by the user. It's main use case is to match the extra_env_kwargs when running an env in an isolated environment server."
|
||||
),
|
||||
),
|
||||
] = {}
|
||||
@@ -313,6 +313,17 @@ class EvalEnvConfig(EnvConfig):
|
||||
),
|
||||
] = 0
|
||||
|
||||
# TODO: should live on the EnvConfig and also apply to training envs but
|
||||
# this is hard right now because we use the vf.EnvGroup which treats all
|
||||
# envs as one. for now training envs hardcode no retries, but we should
|
||||
# probably treat them like environment groups long-term
|
||||
max_retries: Annotated[
|
||||
int,
|
||||
Field(
|
||||
description="Maximum number of times the environment will try to retry running a rollout.",
|
||||
),
|
||||
] = 0
|
||||
|
||||
|
||||
class ValConfig(BaseConfig):
|
||||
"""Configures the validation of the model."""
|
||||
@@ -365,6 +376,13 @@ class EvalConfig(BaseConfig):
|
||||
),
|
||||
] = True
|
||||
|
||||
cancel_inflight_rollouts_on_eval: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to cancel in-flight training rollouts before starting online evals. This is useful to avoid congestion (e.g. do not have training + eval rollouts happening at the same time) but leads to slower training steps as rollouts get cancelled and the pipeline has to fill up after each eval",
|
||||
),
|
||||
] = False
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
"""Configures checkpointing the orchestrator."""
|
||||
@@ -561,6 +579,62 @@ AdvantageConfigType: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class GibberishFilterConfig(BaseModel):
|
||||
"""Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387)."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["gibberish"] = "gibberish"
|
||||
enforce: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
|
||||
),
|
||||
] = False
|
||||
token_id_threshold: Annotated[
|
||||
int,
|
||||
Field(description="Token IDs above this are candidates for gibberish. BPE tokens are sorted by merge order."),
|
||||
] = 100_000
|
||||
logprob_offset: Annotated[
|
||||
float,
|
||||
Field(description="Offset from uniform distribution logprob. Threshold = -log(vocab_size) - logprob_offset."),
|
||||
] = 2.0
|
||||
|
||||
|
||||
class RepetitionFilterConfig(BaseModel):
|
||||
"""Flags rollouts where the model gets stuck in a repetition loop, emitting high-confidence tokens
|
||||
for an extended stretch. A rollout is flagged when `window` consecutive tokens are each sampled
|
||||
with probability above `prob_threshold`. (Section 3.2, https://arxiv.org/abs/2506.13585)"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
type: Literal["repetition"] = "repetition"
|
||||
enforce: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="If True, mask detected rollouts so they don't contribute to training. If False, only track detection metrics."
|
||||
),
|
||||
] = False
|
||||
window: Annotated[
|
||||
int,
|
||||
Field(ge=1, description="Number of consecutive high-probability steps before flagging."),
|
||||
] = 3_000
|
||||
prob_threshold: Annotated[
|
||||
float,
|
||||
Field(
|
||||
gt=0,
|
||||
le=1,
|
||||
description="Tokens sampled with probability above this are considered repetitive. Consecutive such tokens count toward the window.",
|
||||
),
|
||||
] = 0.99
|
||||
|
||||
|
||||
FilterConfigType: TypeAlias = Annotated[
|
||||
GibberishFilterConfig | RepetitionFilterConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class FileSystemWeightBroadcastConfig(BaseModel):
|
||||
"""Configures the filesystem weight broadcast."""
|
||||
|
||||
@@ -631,6 +705,9 @@ class OrchestratorConfig(BaseSettings):
|
||||
# The advantage configuration
|
||||
advantage: AdvantageConfigType | None = AdvantageConfig()
|
||||
|
||||
# Rollout filters (monitor by default, enforce optionally)
|
||||
filters: list[FilterConfigType] = [GibberishFilterConfig(), RepetitionFilterConfig()]
|
||||
|
||||
# The logging configuration
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
@@ -643,12 +720,6 @@ class OrchestratorConfig(BaseSettings):
|
||||
# The checkpoint configuration
|
||||
ckpt: CheckpointConfig | None = None
|
||||
|
||||
# Whether to reset inference weights to base model when starting from scratch
|
||||
reload_weights_on_start: Annotated[
|
||||
bool,
|
||||
Field(description="Whether to reset inference weights to the base model when starting from scratch."),
|
||||
] = True
|
||||
|
||||
# The validation configuration
|
||||
val: ValConfig | None = None
|
||||
|
||||
@@ -754,6 +825,13 @@ class OrchestratorConfig(BaseSettings):
|
||||
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
|
||||
] = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_filter_types(self):
|
||||
types = [f.type for f in self.filters]
|
||||
if len(types) != len(set(types)):
|
||||
raise ValueError(f"Duplicate filter types: {types}. Each filter type may only appear once.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_max_concurrent(self):
|
||||
if self.max_concurrent is not None and self.max_concurrent < self.rollouts_per_example:
|
||||
@@ -798,7 +876,6 @@ class OrchestratorConfig(BaseSettings):
|
||||
def resolve_extra_env_kwargs(self):
|
||||
train_extra_env_kwargs = dict(
|
||||
seq_len=self.seq_len,
|
||||
interleaved_rollouts=True,
|
||||
score_rollouts=not self.buffer.skip_verification,
|
||||
)
|
||||
for env in self.env:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from loguru import logger
|
||||
import asyncio
|
||||
|
||||
from verifiers.workers import ZMQEnvServer
|
||||
|
||||
from prime_rl.orchestrator.env_server.config import EnvServerConfig
|
||||
@@ -9,7 +10,6 @@ from prime_rl.utils.utils import clean_exit, get_env_ids_to_install, install_env
|
||||
|
||||
|
||||
@clean_exit
|
||||
@logger.catch(reraise=True)
|
||||
def run_server(config: EnvServerConfig):
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
@@ -21,15 +21,18 @@ def run_server(config: EnvServerConfig):
|
||||
|
||||
env_name = config.env.name or config.env.id
|
||||
log_file = (get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix()
|
||||
ZMQEnvServer.run_server(
|
||||
|
||||
server = ZMQEnvServer(
|
||||
env_id=strip_env_version(config.env.id),
|
||||
env_args=config.env.args,
|
||||
extra_env_kwargs=config.env.extra_env_kwargs,
|
||||
log_level=config.log.level,
|
||||
log_file_level=config.log.vf_level,
|
||||
log_file=log_file,
|
||||
json_logging=config.log.json_logging,
|
||||
**{"address": config.env.address} if config.env.address is not None else {},
|
||||
)
|
||||
asyncio.run(server.run())
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
@@ -44,39 +45,47 @@ def get_eval_sampling_args(sampling_config: EvalSamplingConfig) -> dict[str, Any
|
||||
return sampling_args
|
||||
|
||||
|
||||
def compute_pass_at_k(rewards: list[int]) -> dict[str, float]:
|
||||
total_attempts = len(rewards)
|
||||
k = total_attempts // 2
|
||||
def _pass_at_k(n: int, c: int, k: int) -> float:
|
||||
"""Unbiased estimator of pass@k (Chen et al., 2021).
|
||||
|
||||
if k == 0:
|
||||
return {"pass@1": float(any(reward == 1.0 for reward in rewards))}
|
||||
Computes 1 - C(n-c, k) / C(n, k) in a numerically stable way.
|
||||
"""
|
||||
if n - c < k:
|
||||
return 1.0
|
||||
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
|
||||
|
||||
num_trials = 100
|
||||
pass_rates = []
|
||||
|
||||
for _ in range(num_trials):
|
||||
sampled_rewards = np.random.choice(rewards, size=k, replace=False)
|
||||
pass_rate = float(any(reward == 1.0 for reward in sampled_rewards))
|
||||
pass_rates.append(pass_rate)
|
||||
|
||||
return {f"pass@{k}": float(np.mean(pass_rates))}
|
||||
def compute_pass_at_k(rewards: list[float]) -> dict[str, float]:
|
||||
n = len(rewards)
|
||||
c = sum(r == 1.0 for r in rewards)
|
||||
ks = [2**i for i in range(n.bit_length())]
|
||||
return {f"pass@{k}": _pass_at_k(n, c, k) for k in ks}
|
||||
|
||||
|
||||
async def evaluate_env(
|
||||
env: vf.Environment,
|
||||
env_name: str,
|
||||
clients: list[vf.ClientConfig],
|
||||
model_name: str,
|
||||
sampling_args: dict,
|
||||
num_examples: int,
|
||||
rollouts_per_example: int,
|
||||
max_retries: int,
|
||||
ckpt_step: int,
|
||||
step: int | None,
|
||||
get_client: Callable[[], Awaitable[vf.ClientConfig]],
|
||||
):
|
||||
logger = get_logger()
|
||||
logger.info(f"Evaluating {env_name} ({num_examples=}, {rollouts_per_example=})")
|
||||
eval_start_time = time.perf_counter()
|
||||
outputs = await evaluate(env, clients, model_name, sampling_args, num_examples, rollouts_per_example)
|
||||
outputs = await evaluate(
|
||||
env=env,
|
||||
model_name=model_name,
|
||||
sampling_args=sampling_args,
|
||||
num_examples=num_examples,
|
||||
rollouts_per_example=rollouts_per_example,
|
||||
get_client=get_client,
|
||||
max_retries=max_retries,
|
||||
)
|
||||
eval_time = time.perf_counter() - eval_start_time
|
||||
|
||||
rows = []
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Orchestrator-side rollout filters for detecting degenerate generations.
|
||||
|
||||
Filters run after rollouts complete, inspecting token IDs and logprobs to
|
||||
detect gibberish or repetition. Detection metrics are always tracked.
|
||||
When enforce=True, detected rollouts get their completion mask cleared so
|
||||
they don't contribute to training. Reward is kept as-is for baseline
|
||||
calculation.
|
||||
"""
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
import verifiers as vf
|
||||
from loguru import logger
|
||||
|
||||
from prime_rl.orchestrator.config import FilterConfigType
|
||||
|
||||
|
||||
@dataclass
|
||||
class FilterResult:
|
||||
detected: bool
|
||||
detection_index: int | None = None
|
||||
|
||||
|
||||
class RolloutFilter(Protocol):
|
||||
name: str
|
||||
enforce: bool
|
||||
|
||||
def check(self, rollout: vf.RolloutOutput) -> FilterResult: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
class GibberishFilter:
|
||||
"""Flags rollouts containing rare tokens generated at high entropy.
|
||||
|
||||
A token is flagged when both:
|
||||
- id(token) > token_id_threshold (rare BPE token)
|
||||
- logprob(token) < -log(vocab_size) - logprob_offset (high entropy)
|
||||
|
||||
References:
|
||||
Section 5.2, https://arxiv.org/abs/2510.02387
|
||||
"""
|
||||
|
||||
name: str
|
||||
token_id_threshold: int
|
||||
logprob_threshold: float
|
||||
enforce: bool = False
|
||||
|
||||
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
|
||||
global_idx = 0
|
||||
for step in rollout["trajectory"]:
|
||||
tokens = step["tokens"]
|
||||
if tokens is None:
|
||||
continue
|
||||
for token_id, logprob in zip(tokens["completion_ids"], tokens["completion_logprobs"]):
|
||||
if token_id > self.token_id_threshold and logprob < self.logprob_threshold:
|
||||
return FilterResult(detected=True, detection_index=global_idx)
|
||||
global_idx += 1
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RepetitionFilter:
|
||||
"""Flags rollouts with pathological repetition loops.
|
||||
|
||||
Counts consecutive tokens where logprob > log(prob_threshold), indicating
|
||||
the model is generating with very high confidence. When the streak reaches
|
||||
the window size, the rollout is flagged.
|
||||
|
||||
References:
|
||||
Section 3.2, https://arxiv.org/abs/2506.13585
|
||||
"""
|
||||
|
||||
name: str
|
||||
window: int
|
||||
logprob_threshold: float
|
||||
enforce: bool = False
|
||||
|
||||
def check(self, rollout: vf.RolloutOutput) -> FilterResult:
|
||||
consecutive = 0
|
||||
global_idx = 0
|
||||
for step in rollout["trajectory"]:
|
||||
tokens = step["tokens"]
|
||||
if tokens is None:
|
||||
continue
|
||||
for logprob in tokens["completion_logprobs"]:
|
||||
if logprob > self.logprob_threshold:
|
||||
consecutive += 1
|
||||
else:
|
||||
consecutive = 0
|
||||
if consecutive >= self.window:
|
||||
return FilterResult(detected=True, detection_index=global_idx)
|
||||
global_idx += 1
|
||||
return FilterResult(detected=False)
|
||||
|
||||
|
||||
def setup_filter(config: FilterConfigType, vocab_size: int) -> RolloutFilter:
|
||||
"""Create a RolloutFilter from a filter config."""
|
||||
if config.type == "gibberish":
|
||||
return GibberishFilter(
|
||||
name="gibberish",
|
||||
token_id_threshold=config.token_id_threshold,
|
||||
logprob_threshold=-math.log(vocab_size) - config.logprob_offset,
|
||||
enforce=config.enforce,
|
||||
)
|
||||
elif config.type == "repetition":
|
||||
return RepetitionFilter(
|
||||
name="repetition",
|
||||
window=config.window,
|
||||
logprob_threshold=math.log(config.prob_threshold),
|
||||
enforce=config.enforce,
|
||||
)
|
||||
raise ValueError(f"Unknown filter type: {config.type}")
|
||||
|
||||
|
||||
def setup_filters(configs: list[FilterConfigType], vocab_size: int) -> list[RolloutFilter]:
|
||||
"""Create RolloutFilters from a list of filter configs."""
|
||||
return [setup_filter(config, vocab_size) for config in configs]
|
||||
|
||||
|
||||
def apply_filters(
|
||||
filters: list[RolloutFilter],
|
||||
rollouts: list[vf.RolloutOutput],
|
||||
) -> dict[str, float]:
|
||||
"""Apply filters to rollouts. Detection metrics are always tracked.
|
||||
|
||||
When a filter has enforce=True, detected rollouts get their completion
|
||||
mask cleared and stop_condition set. Reward is kept as-is for baseline
|
||||
calculation.
|
||||
|
||||
First matching filter wins per rollout (no double-counting).
|
||||
|
||||
Returns aggregate metrics dict for logging.
|
||||
"""
|
||||
if not filters:
|
||||
return {}
|
||||
|
||||
counts: dict[str, int] = {f.name: 0 for f in filters}
|
||||
total_detected = 0
|
||||
total_enforced = 0
|
||||
|
||||
for rollout in rollouts:
|
||||
if rollout.get("metrics") is None:
|
||||
rollout["metrics"] = {}
|
||||
for filt in filters:
|
||||
rollout["metrics"].setdefault(f"filter/{filt.name}", 0.0)
|
||||
|
||||
for filt in filters:
|
||||
result = filt.check(rollout)
|
||||
if result.detected:
|
||||
counts[filt.name] += 1
|
||||
total_detected += 1
|
||||
rollout["metrics"][f"filter/{filt.name}"] = 1.0
|
||||
|
||||
if filt.enforce:
|
||||
for step in rollout["trajectory"]:
|
||||
tokens = step["tokens"]
|
||||
if tokens is not None:
|
||||
tokens["completion_mask"] = [0] * len(tokens["completion_mask"])
|
||||
rollout["stop_condition"] = filt.name
|
||||
total_enforced += 1
|
||||
|
||||
break
|
||||
|
||||
n = len(rollouts)
|
||||
metrics: dict[str, float] = {}
|
||||
for f in filters:
|
||||
metrics[f"filter/{f.name}_count"] = float(counts[f.name])
|
||||
metrics[f"filter/{f.name}_rate"] = counts[f.name] / n if n > 0 else 0.0
|
||||
metrics["filter/total_detected_rate"] = total_detected / n if n > 0 else 0.0
|
||||
metrics["filter/total_enforced_rate"] = total_enforced / n if n > 0 else 0.0
|
||||
|
||||
if total_detected > 0:
|
||||
enforced_msg = f", enforced {total_enforced}" if total_enforced > 0 else ""
|
||||
logger.info(
|
||||
f"Detected {total_detected}/{n} rollouts "
|
||||
f"({', '.join(f'{name}={c}' for name, c in counts.items() if c > 0)})" + enforced_msg
|
||||
)
|
||||
|
||||
return metrics
|
||||
@@ -24,13 +24,13 @@ monkey_patch_chat_completion_logprobs()
|
||||
|
||||
import pandas as pd
|
||||
import verifiers as vf
|
||||
from loguru import logger
|
||||
from transformers import AutoProcessor, AutoTokenizer
|
||||
|
||||
from prime_rl.orchestrator.buffer import Buffer
|
||||
from prime_rl.orchestrator.ckpt import Progress, setup_ckpt_manager
|
||||
from prime_rl.orchestrator.config import BufferConfig, OrchestratorConfig
|
||||
from prime_rl.orchestrator.eval_utils import evaluate_env
|
||||
from prime_rl.orchestrator.filters import apply_filters, setup_filters
|
||||
from prime_rl.orchestrator.scheduler import Scheduler
|
||||
from prime_rl.orchestrator.utils import (
|
||||
compute_teacher_logprobs,
|
||||
@@ -42,15 +42,14 @@ from prime_rl.orchestrator.utils import (
|
||||
from prime_rl.orchestrator.vf_utils import (
|
||||
generate,
|
||||
get_completion_len,
|
||||
get_prompt_len,
|
||||
get_seq_len,
|
||||
intercept_vf_logging,
|
||||
setup_env_client,
|
||||
spawn_env_server,
|
||||
wait_for_env_servers,
|
||||
)
|
||||
from prime_rl.utils.client import (
|
||||
init_nccl_broadcast,
|
||||
reload_weights,
|
||||
setup_inference_pool,
|
||||
)
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
@@ -60,7 +59,6 @@ from prime_rl.utils.pydantic_config import parse_argv
|
||||
from prime_rl.utils.temp_scheduling import compute_temperature
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
count_chinese_chars,
|
||||
get_env_ids_to_install,
|
||||
install_env,
|
||||
resolve_latest_ckpt_step,
|
||||
@@ -71,7 +69,6 @@ from prime_rl.utils.vlm import is_vlm_model
|
||||
|
||||
|
||||
@clean_exit
|
||||
@logger.catch(reraise=True)
|
||||
async def orchestrate(config: OrchestratorConfig):
|
||||
# Initialize the logger
|
||||
logger = setup_logger(
|
||||
@@ -79,7 +76,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_file=config.output_dir / "logs" / "orchestrator.log" if config.log.file else None,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
vf.setup_logging(level="CRITICAL")
|
||||
intercept_vf_logging(logger="verifiers.workers", level=config.log.vf_level) # show logs from env clients
|
||||
logger.info("Starting orchestrator")
|
||||
|
||||
event_loop_lag_monitor = EventLoopLagMonitor()
|
||||
@@ -133,6 +130,11 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
config.model.name, trust_remote_code=config.model.trust_remote_code, use_fast=True
|
||||
)
|
||||
|
||||
# Build rollout filters
|
||||
rollout_filters = setup_filters(config.filters, vocab_size=tokenizer.vocab_size)
|
||||
if rollout_filters:
|
||||
logger.info(f"Initialized {len(rollout_filters)} rollout filter(s): {[f.name for f in rollout_filters]}")
|
||||
|
||||
# Setup monitor
|
||||
logger.info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
|
||||
monitor = setup_monitor(
|
||||
@@ -154,14 +156,15 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
f"Loading {len(config.env)} training environment(s) ({', '.join(env.name or env.id for env in config.env)})"
|
||||
)
|
||||
env_ids = [strip_env_version(env.id) for env in config.env]
|
||||
train_env_names = [env.name or env_id for env_id, env in zip(env_ids, config.env)]
|
||||
train_env_group = vf.EnvGroup(
|
||||
envs=[vf.load_environment(env_id, **env.args) for env_id, env in zip(env_ids, config.env)],
|
||||
env_names=[env.name or env_id for env_id, env in zip(env_ids, config.env)],
|
||||
env_names=train_env_names,
|
||||
map_kwargs=dict(writer_batch_size=1), # set defensively to not error on map operations on large datasets
|
||||
)
|
||||
|
||||
train_env_addresses = []
|
||||
for env_id, env, env_name in zip(env_ids, config.env, train_env_group.env_names):
|
||||
for env_id, env, env_name in zip(env_ids, config.env, train_env_names):
|
||||
if env.address is None:
|
||||
address = spawn_env_server(
|
||||
env_id=env_id,
|
||||
@@ -170,12 +173,15 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_level="CRITICAL",
|
||||
log_file=(get_log_dir(config.output_dir) / "train" / f"{env_name}.log").as_posix(),
|
||||
log_file_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
else:
|
||||
address = env.address
|
||||
logger.info(f"Connecting train environment {env_name} to server at {address}")
|
||||
train_env_addresses.append(address)
|
||||
train_env_clients = [setup_env_client(address) for address in train_env_addresses]
|
||||
train_env_clients = [
|
||||
setup_env_client(address=address, name=name) for name, address in zip(train_env_names, train_env_addresses)
|
||||
]
|
||||
|
||||
logger.info("Waiting for train environment servers to be ready")
|
||||
await wait_for_env_servers(train_env_clients)
|
||||
@@ -202,13 +208,16 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
log_level="CRITICAL",
|
||||
log_file=(get_log_dir(config.output_dir) / "eval" / f"{eval_env_name}.log").as_posix(),
|
||||
log_file_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
else:
|
||||
address = env.address
|
||||
logger.info(f"Connecting eval environment {eval_env_name} to server at {address}")
|
||||
eval_env_addresses.append(address)
|
||||
|
||||
eval_env_clients = [setup_env_client(address) for address in eval_env_addresses]
|
||||
eval_env_clients = [
|
||||
setup_env_client(address=address, name=name) for name, address in zip(eval_env_names, eval_env_addresses)
|
||||
]
|
||||
|
||||
logger.info("Waiting for eval environment servers to be ready")
|
||||
await wait_for_env_servers(eval_env_clients)
|
||||
@@ -311,14 +320,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
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)
|
||||
else:
|
||||
if config.reload_weights_on_start:
|
||||
if config.model.lora is None:
|
||||
logger.info("Training from scratch. Resetting weights to base model")
|
||||
await reload_weights(inference_pool.admin_clients)
|
||||
else:
|
||||
logger.info("Training from scratch. Skipping base weight reload because LoRA is enabled")
|
||||
else:
|
||||
logger.info("Training from scratch. Skipping base weight reload")
|
||||
logger.info("Training from scratch")
|
||||
|
||||
# Iterate over dataset in batches
|
||||
max_steps = config.max_steps or int(1e9)
|
||||
@@ -384,21 +386,26 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
last_eval_step = ckpt_step
|
||||
logger.info(f"Running evals for checkpoint step {ckpt_step}")
|
||||
|
||||
# Pause weight updates during eval and cancel inflight rollouts
|
||||
# this avoid doing eval across different checkpoints and avoid congestion
|
||||
# Pause weight updates and re-scheduling of training rollouts during eval
|
||||
# to avoid evaluating across different checkpoints and avoid congestion
|
||||
scheduler.checkpoint_ready.clear()
|
||||
scheduler.cancel_all_inflight_rollouts()
|
||||
|
||||
# For heavy eval workloads, it might be necessary additionally cancel in-flight training rollouts
|
||||
if config.eval.cancel_inflight_rollouts_on_eval:
|
||||
logger.info("Cancelling in-flight training rollouts before starting evals to avoid congestion.")
|
||||
scheduler.cancel_inflight_rollouts()
|
||||
|
||||
results = await asyncio.gather(
|
||||
*[
|
||||
evaluate_env(
|
||||
env=eval_env,
|
||||
env_name=eval_env_name,
|
||||
clients=inference_pool.clients,
|
||||
get_client=inference_pool.get_next_client,
|
||||
model_name=scheduler.model_name,
|
||||
sampling_args=eval_sampling_args,
|
||||
num_examples=eval_env_config.num_examples or config.eval.num_examples,
|
||||
rollouts_per_example=eval_env_config.rollouts_per_example or config.eval.rollouts_per_example,
|
||||
max_retries=eval_env_config.max_retries,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
)
|
||||
@@ -422,11 +429,11 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
val_task = asyncio.create_task(
|
||||
generate(
|
||||
env=train_env_group,
|
||||
clients=inference_pool.clients,
|
||||
model_name=scheduler.model_name,
|
||||
examples=val_examples,
|
||||
rollouts_per_example=config.val.rollouts_per_example,
|
||||
sampling_args=sampling_args,
|
||||
clients=inference_pool.clients,
|
||||
pbar_description="Generating rollouts (val)",
|
||||
)
|
||||
)
|
||||
@@ -438,6 +445,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
generate_completions_time = scheduler.last_batch_generation_time
|
||||
train_rollouts = train_task.result()
|
||||
|
||||
# Apply rollout filters (zeros reward/mask for degenerate generations)
|
||||
filter_metrics = apply_filters(rollout_filters, train_rollouts)
|
||||
|
||||
# Compute advantages
|
||||
example_ids = [r["example_id"] for r in train_rollouts]
|
||||
rewards = [r["reward"] for r in train_rollouts]
|
||||
@@ -475,12 +485,26 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Collect results and assign advantages
|
||||
train_examples: list[TrainingSample] = []
|
||||
rollout_prefill_lens: list[int] = []
|
||||
rollout_decode_lens: list[int] = []
|
||||
num_prefill_tokens = 0
|
||||
num_decode_tokens = 0
|
||||
for rollout, advantage, samples in zip(train_rollouts, advantages, results):
|
||||
rollout_prefill_tokens = 0
|
||||
rollout_decode_tokens = 0
|
||||
if samples is not None:
|
||||
for sample in samples:
|
||||
sample.advantage = advantage
|
||||
sample.reward = rollout["reward"]
|
||||
train_examples.extend(samples)
|
||||
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
|
||||
rollout_prefill_tokens += sample_prefill_tokens
|
||||
train_examples.append(sample)
|
||||
rollout_prefill_lens.append(rollout_prefill_tokens)
|
||||
rollout_decode_lens.append(rollout_decode_tokens)
|
||||
num_prefill_tokens += rollout_prefill_tokens
|
||||
num_decode_tokens += rollout_decode_tokens
|
||||
|
||||
parallel_preprocess_time = time.perf_counter() - parallel_preprocess_start
|
||||
logger.debug(
|
||||
@@ -541,9 +565,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"reward": [rollout["reward"] for rollout in train_rollouts],
|
||||
"is_truncated": [rollout["is_truncated"] for rollout in train_rollouts],
|
||||
"error": [rollout["error"] for rollout in train_rollouts],
|
||||
"completion_len": [get_completion_len(rollout) for rollout in train_rollouts],
|
||||
"prompt_len": [get_prompt_len(rollout) for rollout in train_rollouts],
|
||||
"seq_len": [get_seq_len(rollout) for rollout in train_rollouts],
|
||||
"prefill_len": rollout_prefill_lens,
|
||||
"decode_len": rollout_decode_lens,
|
||||
"num_turns": [len(rollout["trajectory"]) for rollout in train_rollouts],
|
||||
"generation_ms": [rollout["timing"]["generation_ms"] for rollout in train_rollouts],
|
||||
"scoring_ms": [rollout["timing"]["scoring_ms"] for rollout in train_rollouts],
|
||||
@@ -553,21 +577,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Gather individual reward function metrics
|
||||
metrics_df = pd.DataFrame([rollout["metrics"] for rollout in train_rollouts])
|
||||
|
||||
# Count Chinese characters in completions
|
||||
chinese_stats = []
|
||||
for rollout in train_rollouts:
|
||||
trajectory = rollout["trajectory"]
|
||||
if not trajectory:
|
||||
continue
|
||||
last_step = trajectory[-1]
|
||||
tokens = last_step["tokens"]
|
||||
completion_text = tokenizer.decode(tokens["completion_ids"])
|
||||
chinese_count, total_count = count_chinese_chars(completion_text)
|
||||
chinese_stats.append(
|
||||
{"chinese_chars": chinese_count, "total_chars": total_count, "has_chinese": chinese_count > 0}
|
||||
)
|
||||
chinese_df = pd.DataFrame(chinese_stats)
|
||||
|
||||
val_results_df = (
|
||||
pd.DataFrame(
|
||||
{
|
||||
@@ -600,6 +609,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
to_log = {
|
||||
# Progress metrics
|
||||
"progress/tokens": num_tokens,
|
||||
"progress/prefill_tokens": num_prefill_tokens,
|
||||
"progress/decode_tokens": num_decode_tokens,
|
||||
"progress/samples": config.batch_size,
|
||||
"progress/problems": config.batch_size // config.rollouts_per_example,
|
||||
"progress/total_tokens": progress.total_tokens,
|
||||
@@ -610,12 +621,12 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
"seq_len/mean": results_df.groupby("example_id").seq_len.mean().mean(),
|
||||
"seq_len/max": results_df.groupby("example_id").seq_len.mean().max(),
|
||||
"seq_len/min": results_df.groupby("example_id").seq_len.mean().min(),
|
||||
"prompt_len/mean": results_df.groupby("example_id").prompt_len.mean().mean(),
|
||||
"prompt_len/max": results_df.groupby("example_id").prompt_len.mean().max(),
|
||||
"prompt_len/min": results_df.groupby("example_id").prompt_len.mean().min(),
|
||||
"completion_len/mean": results_df.groupby("example_id").completion_len.mean().mean(),
|
||||
"completion_len/max": results_df.groupby("example_id").completion_len.mean().max(),
|
||||
"completion_len/min": results_df.groupby("example_id").completion_len.mean().min(),
|
||||
"prefill_len/mean": results_df.groupby("example_id").prefill_len.mean().mean(),
|
||||
"prefill_len/max": results_df.groupby("example_id").prefill_len.mean().max(),
|
||||
"prefill_len/min": results_df.groupby("example_id").prefill_len.mean().min(),
|
||||
"decode_len/mean": results_df.groupby("example_id").decode_len.mean().mean(),
|
||||
"decode_len/max": results_df.groupby("example_id").decode_len.mean().max(),
|
||||
"decode_len/min": results_df.groupby("example_id").decode_len.mean().min(),
|
||||
"is_truncated/mean": results_df.groupby("example_id").is_truncated.mean().mean(),
|
||||
"is_truncated/max": results_df.groupby("example_id").is_truncated.mean().max(),
|
||||
"is_truncated/min": results_df.groupby("example_id").is_truncated.mean().min(),
|
||||
@@ -650,14 +661,6 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
},
|
||||
# Env metrics
|
||||
**{f"metrics/{metric}": metrics_df[metric].mean() for metric in metrics_df.columns},
|
||||
# Chinese character metrics (cast to native Python types for JSON serialization)
|
||||
"chinese/char_count": int(chinese_df.chinese_chars.sum()),
|
||||
"chinese/char_ratio": (
|
||||
float(chinese_df.chinese_chars.sum() / chinese_df.total_chars.sum())
|
||||
if chinese_df.total_chars.sum() > 0
|
||||
else 0.0
|
||||
),
|
||||
"chinese/rollout_ratio": float(chinese_df.has_chinese.mean()),
|
||||
# Time metrics
|
||||
"time/step": step_time,
|
||||
"time/generate_completions": generate_completions_time,
|
||||
@@ -670,6 +673,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
**buffer.get_metrics(),
|
||||
# Event loop lag metrics
|
||||
**event_loop_lag_monitor.get_metrics(),
|
||||
# Rollout filter metrics
|
||||
**filter_metrics,
|
||||
# W&B axis
|
||||
"step": progress.step,
|
||||
}
|
||||
@@ -729,11 +734,12 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
evaluate_env(
|
||||
env=eval_env,
|
||||
env_name=eval_env_name,
|
||||
clients=inference_pool.clients,
|
||||
get_client=inference_pool.get_next_client,
|
||||
model_name=scheduler.model_name,
|
||||
sampling_args=eval_sampling_args,
|
||||
num_examples=eval_env_config.num_examples or config.eval.num_examples,
|
||||
rollouts_per_example=eval_env_config.rollouts_per_example or config.eval.rollouts_per_example,
|
||||
max_retries=eval_env_config.max_retries,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
)
|
||||
@@ -757,7 +763,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
rollout_executor.shutdown(wait=False)
|
||||
|
||||
# Stop scheduler
|
||||
scheduler.cancel_all_inflight_rollouts()
|
||||
scheduler.cancel_inflight_rollouts()
|
||||
update_policy_task.cancel()
|
||||
|
||||
# Stop inference pool
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
@@ -94,11 +95,8 @@ class Scheduler:
|
||||
"""Update sampling args for future rollout requests."""
|
||||
self.sampling_args = sampling_args
|
||||
|
||||
def cancel_all_inflight_rollouts(self):
|
||||
"""Cancel all in-flight rollout requests.
|
||||
|
||||
Used when weights are updated to discard stale rollouts generated with old weights.
|
||||
"""
|
||||
def cancel_inflight_rollouts(self):
|
||||
"""Cancel all in-flight rollout requests."""
|
||||
count = len(self.inflight_group_rollouts)
|
||||
for future in list(self.inflight_group_rollouts.keys()):
|
||||
if not future.done():
|
||||
@@ -106,12 +104,21 @@ class Scheduler:
|
||||
self.inflight_group_rollouts.clear()
|
||||
self.cancelled_rollouts_count += count
|
||||
|
||||
async def _select_least_loaded_client(self) -> vf.ClientConfig:
|
||||
"""Select the client with the fewest in-flight tasks."""
|
||||
clients = self.inference_pool.clients
|
||||
while not clients:
|
||||
await asyncio.sleep(1)
|
||||
clients = self.inference_pool.clients
|
||||
inflight_by_url = Counter(info.client_config.api_base_url for info in self.inflight_group_rollouts.values())
|
||||
return min(clients, key=lambda c: inflight_by_url[c.api_base_url])
|
||||
|
||||
async def schedule_group_rollout(self):
|
||||
"""Asynchronously schedules a group rollout request."""
|
||||
if self.rate_limiter:
|
||||
await self.rate_limiter.acquire()
|
||||
example = self.buffer.sample_examples(n=1)[0]
|
||||
client_config = await self.inference_pool.get_next_client()
|
||||
client_config = await self._select_least_loaded_client()
|
||||
run_group_task = asyncio.create_task(
|
||||
run_group(
|
||||
env=self.env,
|
||||
|
||||
@@ -11,7 +11,7 @@ from openai.types.completion_usage import CompletionUsage
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from verifiers.utils.async_utils import maybe_semaphore
|
||||
from verifiers.utils.client_utils import setup_client
|
||||
from verifiers.utils.client_utils import setup_openai_client
|
||||
|
||||
from prime_rl.orchestrator.config import SamplingConfig
|
||||
from prime_rl.transport import TrainingSample
|
||||
@@ -151,7 +151,7 @@ async def compute_teacher_logprobs(
|
||||
"""Compute teacher model logprobs for a batch of training samples via prefill."""
|
||||
|
||||
async def _compute_single(client_config: vf.ClientConfig, sample: TrainingSample) -> list[float]:
|
||||
client = setup_client(client_config)
|
||||
client = setup_openai_client(client_config)
|
||||
|
||||
async with await get_semaphore():
|
||||
response = await client.post(
|
||||
@@ -168,7 +168,10 @@ async def compute_teacher_logprobs(
|
||||
},
|
||||
cast_to=ChatCompletion,
|
||||
)
|
||||
return [0.0 if lp is None else float(next(iter(lp.values()))["logprob"]) for lp in response.prompt_logprobs]
|
||||
return [
|
||||
0.0 if lp is None else float(next(iter(lp.values()))["logprob"])
|
||||
for lp in getattr(response, "prompt_logprobs", [])
|
||||
]
|
||||
|
||||
return await asyncio.gather(*[_compute_single(client, sample) for client, sample in zip(cycle(clients), samples)])
|
||||
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import multiprocessing as mp
|
||||
from collections.abc import Awaitable, Callable
|
||||
from itertools import cycle
|
||||
from multiprocessing import Process
|
||||
from typing import Any
|
||||
|
||||
import verifiers as vf
|
||||
from verifiers.envs.environment import EnvClient
|
||||
from verifiers.utils.worker_utils import get_free_port
|
||||
from verifiers.utils.worker_utils import get_free_port_pair
|
||||
from verifiers.workers import ZMQEnvClient, ZMQEnvServer
|
||||
|
||||
from prime_rl.utils.logger import InterceptHandler, ProgressTracker, get_logger
|
||||
from prime_rl.utils.logger import InterceptHandler, ProgressTracker
|
||||
|
||||
DEFAULT_RETRIES = 3
|
||||
DEFAULT_RETRIES = 0
|
||||
REQUIRED_STATE_COLUMNS = ["trajectory", "sampling_args"]
|
||||
DEFAULT_STATE_COLUMNS = []
|
||||
|
||||
@@ -21,9 +22,11 @@ def spawn_env_server(
|
||||
env_args: dict[str, Any],
|
||||
extra_env_kwargs: dict[str, Any],
|
||||
address: str | None = None,
|
||||
# logging configs
|
||||
log_level: str | None = None,
|
||||
log_file: str | None = None,
|
||||
log_file_level: str | None = None,
|
||||
json_logging: bool = False,
|
||||
daemon: bool = True,
|
||||
) -> str:
|
||||
"""
|
||||
@@ -31,8 +34,11 @@ def spawn_env_server(
|
||||
|
||||
Mirrors vf.Environment.start_server().
|
||||
"""
|
||||
address = address or f"tcp://127.0.0.1:{get_free_port()}"
|
||||
Process(
|
||||
address = address or f"tcp://127.0.0.1:{get_free_port_pair()}"
|
||||
# Use spawn to avoid inheriting file descriptors (e.g. sockets) from
|
||||
# the parent process, which has caused hangs when multiple env server
|
||||
# subprocesses share the same fds.
|
||||
mp.get_context("spawn").Process(
|
||||
target=ZMQEnvServer.run_server,
|
||||
args=(
|
||||
env_id,
|
||||
@@ -42,71 +48,35 @@ def spawn_env_server(
|
||||
log_file,
|
||||
log_file_level,
|
||||
),
|
||||
kwargs=dict(address=address),
|
||||
kwargs=dict(address=address, json_logging=json_logging),
|
||||
daemon=daemon,
|
||||
).start()
|
||||
|
||||
return address
|
||||
|
||||
|
||||
def setup_env_client(address: str) -> EnvClient:
|
||||
def setup_env_client(
|
||||
address: str,
|
||||
name: str | None = None,
|
||||
# health check configs
|
||||
health_check_interval: float = 5.0, # 5s (we detect an env server as unhealth after 3 * 5s = 15s of unsuccessful health checks)
|
||||
startup_timeout: float = 600.0, # 10m
|
||||
recovery_timeout: float = 600.0, # 10m
|
||||
) -> EnvClient:
|
||||
"""Sets up a ZMQEnvClient for a given address."""
|
||||
return ZMQEnvClient(address=address)
|
||||
|
||||
|
||||
async def wait_for_env_servers(
|
||||
env_clients: list[EnvClient], interval: int = 1, log_interval: int = 10, timeout: int = 1800
|
||||
) -> None:
|
||||
logger = get_logger()
|
||||
|
||||
async def wait_for_env_server(env_client: EnvClient) -> None:
|
||||
wait_time = 0
|
||||
logger.debug(f"Starting pinging environment server at {env_client.address}")
|
||||
while wait_time < timeout:
|
||||
try:
|
||||
await env_client.health(timeout=1) # quick timeout
|
||||
logger.debug(f"Environment server at {env_client.address} is ready after {wait_time} seconds")
|
||||
return
|
||||
except Exception as e:
|
||||
if wait_time % log_interval == 0 and wait_time > 0:
|
||||
logger.warning(
|
||||
f"Environment server at {env_client.address} was not reached after {wait_time} seconds (Error: {e})"
|
||||
)
|
||||
await asyncio.sleep(interval)
|
||||
wait_time += interval
|
||||
msg = f"Environment server at {env_client.address} is not ready after {wait_time} (>{timeout}) seconds. Aborting..."
|
||||
logger.error(msg)
|
||||
raise TimeoutError(msg)
|
||||
|
||||
await asyncio.gather(*[wait_for_env_server(env_client) for env_client in env_clients])
|
||||
|
||||
|
||||
async def run_rollout(
|
||||
env: vf.Environment,
|
||||
client: vf.ClientConfig,
|
||||
model_name: str,
|
||||
example: dict,
|
||||
sampling_args: dict,
|
||||
max_retries: int = DEFAULT_RETRIES,
|
||||
state_columns: list[str] = DEFAULT_STATE_COLUMNS,
|
||||
) -> vf.RolloutOutput:
|
||||
"""
|
||||
Wrapper for vf.Environment.run_rollout().
|
||||
|
||||
Asynchronously generates and scores a rollout.
|
||||
"""
|
||||
state_columns = state_columns + REQUIRED_STATE_COLUMNS
|
||||
rollout_input = vf.RolloutInput(**example)
|
||||
return await env.run_rollout(
|
||||
rollout_input,
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling_args=sampling_args,
|
||||
max_retries=max_retries,
|
||||
state_columns=state_columns,
|
||||
return ZMQEnvClient(
|
||||
address=address,
|
||||
name=name,
|
||||
health_check_interval=health_check_interval,
|
||||
startup_timeout=startup_timeout,
|
||||
recovery_timeout=recovery_timeout,
|
||||
)
|
||||
|
||||
|
||||
async def wait_for_env_servers(env_clients: list[EnvClient]) -> None:
|
||||
await asyncio.gather(*[env_client.wait_for_server_startup() for env_client in env_clients])
|
||||
|
||||
|
||||
async def run_group(
|
||||
env: vf.Environment,
|
||||
client: vf.ClientConfig,
|
||||
@@ -137,11 +107,12 @@ async def run_group(
|
||||
# TODO: migrate this to vf.Environment.generate() once it supports multiple clients
|
||||
async def generate(
|
||||
env: vf.Environment,
|
||||
clients: list[vf.ClientConfig],
|
||||
model_name: str,
|
||||
examples: list,
|
||||
rollouts_per_example: int,
|
||||
sampling_args: dict,
|
||||
clients: list[vf.ClientConfig] | None = None,
|
||||
get_client: Callable[[], Awaitable[vf.ClientConfig]] | None = None,
|
||||
max_retries: int = DEFAULT_RETRIES,
|
||||
state_columns: list[str] = DEFAULT_STATE_COLUMNS,
|
||||
pbar_description: str = "Generating rollouts",
|
||||
@@ -154,10 +125,20 @@ async def generate(
|
||||
Asynchronously generates and scores a list of groups.
|
||||
"""
|
||||
|
||||
if not clients and get_client is None:
|
||||
raise ValueError("generate requires at least one client or a get_client callback")
|
||||
|
||||
if get_client is None:
|
||||
client_cycle = cycle(clients)
|
||||
|
||||
async def get_client() -> vf.ClientConfig:
|
||||
return next(client_cycle)
|
||||
|
||||
total_rollouts = len(examples) * rollouts_per_example
|
||||
pbar = ProgressTracker(total=total_rollouts, desc=pbar_description)
|
||||
|
||||
async def run_group_with_progress(client, example):
|
||||
async def run_group_with_progress(example):
|
||||
client = await get_client()
|
||||
result = await run_group(
|
||||
env=env,
|
||||
client=client,
|
||||
@@ -173,7 +154,7 @@ async def generate(
|
||||
|
||||
try:
|
||||
group_outputs_list: list[list[vf.RolloutOutput]] = await asyncio.gather(
|
||||
*[run_group_with_progress(client, example) for client, example in zip(cycle(clients), examples)]
|
||||
*[run_group_with_progress(example) for example in examples]
|
||||
)
|
||||
finally:
|
||||
pbar.close()
|
||||
@@ -183,11 +164,12 @@ async def generate(
|
||||
|
||||
async def evaluate(
|
||||
env: vf.Environment,
|
||||
clients: list[vf.ClientConfig],
|
||||
model_name: str,
|
||||
sampling_args: dict,
|
||||
num_examples: int,
|
||||
rollouts_per_example: int,
|
||||
clients: list[vf.ClientConfig] | None = None,
|
||||
get_client: Callable[[], Awaitable[vf.ClientConfig]] | None = None,
|
||||
max_retries: int = DEFAULT_RETRIES,
|
||||
state_columns: list[str] = DEFAULT_STATE_COLUMNS,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
@@ -202,6 +184,7 @@ async def evaluate(
|
||||
outputs = await generate(
|
||||
env=env,
|
||||
clients=clients,
|
||||
get_client=get_client,
|
||||
model_name=model_name,
|
||||
examples=inputs,
|
||||
# _get_eval_inputs() already repeats the examples, this currently means
|
||||
@@ -258,9 +241,9 @@ def get_completion_len(output: vf.RolloutOutput) -> int:
|
||||
return get_seq_len(output) - get_prompt_len(output)
|
||||
|
||||
|
||||
def intercept_vf_logging(level: str = "DEBUG", prefix: str = "verifiers"):
|
||||
"""Intercepts verifiers logging and routes through prime-rl logger with [verifiers] prefix."""
|
||||
vf_logger = logging.getLogger("verifiers")
|
||||
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
|
||||
"""Intercepts verifiers logging and routes through prime-rl logger with optional prefix."""
|
||||
vf_logger = logging.getLogger(logger)
|
||||
vf_logger.handlers.clear()
|
||||
vf_logger.addHandler(InterceptHandler(prefix=prefix))
|
||||
vf_logger.setLevel(level.upper())
|
||||
|
||||
+2
-266
@@ -16,17 +16,8 @@ import tomli_w
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.inference.config import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.config import CheckpointConfig as OrchestratorCheckpointConfig
|
||||
from prime_rl.orchestrator.config import FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.config import NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.trainer.config import CheckpointConfig as TrainerCheckpointConfig
|
||||
from prime_rl.rl_config import BaseRLConfig
|
||||
from prime_rl.trainer.rl.config import FakeDataLoaderConfig
|
||||
from prime_rl.trainer.rl.config import FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig
|
||||
from prime_rl.trainer.rl.config import NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig
|
||||
from prime_rl.trainer.rl.config import RLTrainerConfig as TrainerConfig
|
||||
from prime_rl.utils.config import WandbConfig, WandbWithExtrasConfig
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pydantic_config import BaseSettings, parse_argv
|
||||
from prime_rl.utils.utils import (
|
||||
@@ -35,15 +26,6 @@ from prime_rl.utils.utils import (
|
||||
get_log_dir,
|
||||
get_rollout_dir,
|
||||
)
|
||||
from prime_rl.utils.validation import (
|
||||
validate_shared_ckpt_config,
|
||||
validate_shared_max_async_level,
|
||||
validate_shared_max_steps,
|
||||
validate_shared_model_name,
|
||||
validate_shared_output_dir,
|
||||
validate_shared_wandb_config,
|
||||
validate_shared_weight_broadcast,
|
||||
)
|
||||
|
||||
|
||||
class SharedLogConfig(BaseSettings):
|
||||
@@ -112,29 +94,9 @@ class SharedWeightBroadcastConfig(BaseSettings):
|
||||
)
|
||||
|
||||
|
||||
class RLConfig(BaseSettings):
|
||||
class RLConfig(BaseRLConfig):
|
||||
"""Configures an RL training run."""
|
||||
|
||||
### Submodule configurations
|
||||
|
||||
trainer: TrainerConfig
|
||||
orchestrator: OrchestratorConfig
|
||||
inference: Annotated[
|
||||
InferenceConfig | None,
|
||||
Field(
|
||||
description="The inference config. If None, will not start an inference process. Only viable, if an inference server was started manually."
|
||||
),
|
||||
] = None
|
||||
|
||||
### Top-level configurations
|
||||
|
||||
log: Annotated[
|
||||
SharedLogConfig,
|
||||
Field(
|
||||
description="Shared log configs. If None, will fallback to the log configs specified on submodule configs."
|
||||
),
|
||||
] = SharedLogConfig()
|
||||
|
||||
clean: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
@@ -165,55 +127,6 @@ class RLConfig(BaseSettings):
|
||||
Field(description="The directory to store the outputs. Should typically be set to an experiment identifier."),
|
||||
] = Path("outputs") # NOTE: Must match `OUTPUT_DIR` in `tmux.sh` to see logs
|
||||
|
||||
ckpt: Annotated[
|
||||
SharedCheckpointConfig | None,
|
||||
Field(
|
||||
description="Shared checkpoint configs. If None, will fallback to the checkpoint configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
wandb: Annotated[
|
||||
SharedWandbConfig | None,
|
||||
Field(
|
||||
description="Shared W&B configs. If None, will fallback to the W&B configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
model: Annotated[
|
||||
SharedModelConfig | None,
|
||||
Field(
|
||||
description="Shared model configs. If None, will fallback to the model configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
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_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
|
||||
|
||||
seq_len: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="The sequence length to use. If set, will configure both trainer.model.seq_len and orchestrator.seq_len to this value. If None, each can be set independently."
|
||||
),
|
||||
] = None
|
||||
|
||||
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
|
||||
|
||||
bench: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
@@ -221,10 +134,6 @@ class RLConfig(BaseSettings):
|
||||
),
|
||||
] = False
|
||||
|
||||
weight_broadcast: Annotated[
|
||||
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
|
||||
] = None
|
||||
|
||||
dump_config: Annotated[
|
||||
Path | None,
|
||||
Field(
|
||||
@@ -250,83 +159,6 @@ class RLConfig(BaseSettings):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_logs(self):
|
||||
# Copy log level
|
||||
if self.log is not None:
|
||||
if self.log.level is not None:
|
||||
self.trainer.log.level = self.log.level
|
||||
self.orchestrator.log.level = self.log.level
|
||||
if self.log.file is not None:
|
||||
self.trainer.log.file = self.log.file
|
||||
self.orchestrator.log.file = self.log.file
|
||||
self.trainer.log.json_logging = self.log.json_logging
|
||||
self.orchestrator.log.json_logging = self.log.json_logging
|
||||
|
||||
return self
|
||||
|
||||
### Setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_ckpt(self):
|
||||
# If specified, automatically setup checkpoint configs for trainer and orchestrator
|
||||
if self.ckpt is not None:
|
||||
# Create checkpoint configs if not specified
|
||||
if self.trainer.ckpt is None:
|
||||
self.trainer.ckpt = TrainerCheckpointConfig()
|
||||
if self.orchestrator.ckpt is None:
|
||||
self.orchestrator.ckpt = OrchestratorCheckpointConfig()
|
||||
|
||||
# If specified, use the same ckpt interval
|
||||
if self.ckpt.interval is not None:
|
||||
self.trainer.ckpt.interval = self.ckpt.interval
|
||||
self.orchestrator.ckpt.interval = self.ckpt.interval
|
||||
|
||||
# If resuming training, ensure orchestrator resume from the same step
|
||||
if self.ckpt.resume_step is not None:
|
||||
self.trainer.ckpt.resume_step = self.ckpt.resume_step
|
||||
self.orchestrator.ckpt.resume_step = self.ckpt.resume_step
|
||||
|
||||
# If specified, propagate keep policy
|
||||
if self.ckpt.keep_last is not None:
|
||||
self.trainer.ckpt.keep_last = self.ckpt.keep_last
|
||||
self.orchestrator.ckpt.keep_last = self.ckpt.keep_last
|
||||
|
||||
if self.ckpt.keep_interval is not None:
|
||||
self.trainer.ckpt.keep_interval = self.ckpt.keep_interval
|
||||
self.orchestrator.ckpt.keep_interval = self.ckpt.keep_interval
|
||||
|
||||
validate_shared_ckpt_config(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_wandb(self):
|
||||
# If specified, automatically use shared W&B project for orchestrator and trainer
|
||||
if self.wandb is not None:
|
||||
if not self.trainer.wandb:
|
||||
self.trainer.wandb = WandbConfig()
|
||||
if not self.orchestrator.wandb:
|
||||
self.orchestrator.wandb = WandbWithExtrasConfig()
|
||||
|
||||
if self.wandb.project:
|
||||
self.trainer.wandb.project = self.wandb.project
|
||||
self.orchestrator.wandb.project = self.wandb.project
|
||||
|
||||
# If specified, automatically use shared W&B name for orchestrator and trainer with suffixes
|
||||
if self.wandb.name:
|
||||
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
|
||||
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
|
||||
|
||||
# If specified, automatically use shared W&B offline mode for orchestrator and trainer
|
||||
if self.wandb.offline:
|
||||
self.trainer.wandb.offline = self.wandb.offline
|
||||
self.orchestrator.wandb.offline = self.wandb.offline
|
||||
|
||||
validate_shared_wandb_config(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_bench(self):
|
||||
if self.bench:
|
||||
@@ -347,88 +179,6 @@ class RLConfig(BaseSettings):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_model(self):
|
||||
# Use the same model for trainer, orchestrator and inference
|
||||
if self.model is not None:
|
||||
self.trainer.model.name = self.model.name
|
||||
self.orchestrator.model.name = self.model.name
|
||||
if self.inference is not None:
|
||||
self.inference.model.name = self.model.name
|
||||
|
||||
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_max_steps(self):
|
||||
# If specified, use the same max steps for trainer and orchestrator
|
||||
if self.max_steps is not None:
|
||||
self.trainer.max_steps = self.max_steps
|
||||
self.orchestrator.max_steps = self.max_steps
|
||||
|
||||
validate_shared_max_steps(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_async_level(self):
|
||||
# If specified, use the same async level for trainer and orchestrator
|
||||
if self.max_async_level is not None:
|
||||
self.trainer.max_async_level = self.max_async_level
|
||||
self.orchestrator.max_async_level = self.max_async_level
|
||||
|
||||
validate_shared_max_async_level(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_output_dir(self):
|
||||
# If specified, use the same outputs directory for trainer and orchestrator
|
||||
if self.output_dir is not None:
|
||||
self.trainer.output_dir = self.output_dir
|
||||
self.orchestrator.output_dir = self.output_dir / "run_default"
|
||||
|
||||
validate_shared_output_dir(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_seq_len(self):
|
||||
# If specified, use the same seq_len for trainer and orchestrator
|
||||
if self.seq_len is not None:
|
||||
self.trainer.model.seq_len = self.seq_len
|
||||
self.orchestrator.seq_len = self.seq_len
|
||||
|
||||
if self.trainer.model.seq_len < self.orchestrator.seq_len:
|
||||
raise ValueError(
|
||||
f"Trainer model seq_len ({self.trainer.model.seq_len}) must be >= orchestrator seq_len ({self.orchestrator.seq_len}). "
|
||||
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_weight_broadcast(self):
|
||||
if self.weight_broadcast is not None:
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type, inference_world_size=inference_world_size
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type
|
||||
)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_lora(self):
|
||||
if self.trainer.model.lora is not None:
|
||||
@@ -485,20 +235,6 @@ class RLConfig(BaseSettings):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def warn_wandb_resume_id_missing(self):
|
||||
if self.trainer.ckpt is not None and self.trainer.ckpt.resume_step is not None:
|
||||
if self.trainer.wandb and not self.trainer.wandb.id:
|
||||
warnings.warn(
|
||||
"W&B run ID is not set for trainer even though resuming training. The current run will be created as a new run."
|
||||
)
|
||||
if self.orchestrator.ckpt is not None and self.orchestrator.ckpt.resume_step is not None:
|
||||
if self.orchestrator.wandb and not self.orchestrator.wandb.id:
|
||||
warnings.warn(
|
||||
"W&B run ID is not set for orchestrator even though resuming training. The current run will be created as a new run."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_enough_devices_for_nccl(self):
|
||||
if self.trainer.weight_broadcast.type == "nccl":
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.inference.config import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.config import CheckpointConfig as OrchestratorCheckpointConfig
|
||||
from prime_rl.orchestrator.config import FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.config import NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.trainer.config import CheckpointConfig as TrainerCheckpointConfig
|
||||
from prime_rl.trainer.rl.config import FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig
|
||||
from prime_rl.trainer.rl.config import NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig
|
||||
from prime_rl.trainer.rl.config import RLTrainerConfig as TrainerConfig
|
||||
from prime_rl.utils.config import WandbConfig, WandbWithExtrasConfig
|
||||
from prime_rl.utils.pydantic_config import BaseSettings
|
||||
from prime_rl.utils.validation import (
|
||||
validate_shared_ckpt_config,
|
||||
validate_shared_max_async_level,
|
||||
validate_shared_max_steps,
|
||||
validate_shared_model_name,
|
||||
validate_shared_output_dir,
|
||||
validate_shared_wandb_config,
|
||||
validate_shared_weight_broadcast,
|
||||
)
|
||||
|
||||
|
||||
class SharedLogConfig(BaseSettings):
|
||||
"""Configures shared logging."""
|
||||
|
||||
level: Annotated[str | None, Field(description="The log level to use.")] = "info"
|
||||
|
||||
file: Annotated[bool | None, Field(description="Whether to log to a file.")] = True
|
||||
|
||||
json_logging: Annotated[
|
||||
bool,
|
||||
Field(description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.)."),
|
||||
] = False
|
||||
|
||||
|
||||
class SharedWandbConfig(BaseSettings):
|
||||
"""Configures shared W&B configs."""
|
||||
|
||||
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
|
||||
|
||||
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
|
||||
|
||||
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
|
||||
|
||||
|
||||
class SharedCheckpointConfig(BaseSettings):
|
||||
"""Configures shared checkpoint configs."""
|
||||
|
||||
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
|
||||
|
||||
resume_step: Annotated[
|
||||
int | None, Field(description="The step to resume from. If None, will not resume from a checkpoint.")
|
||||
] = None
|
||||
|
||||
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
|
||||
|
||||
|
||||
class SharedModelConfig(BaseSettings):
|
||||
"""Configures shared model settings."""
|
||||
|
||||
name: Annotated[
|
||||
str,
|
||||
Field(description="The name of the model to use."),
|
||||
] = "Qwen/Qwen3-0.6B"
|
||||
|
||||
|
||||
class SharedWeightBroadcastConfig(BaseSettings):
|
||||
"""Configures shared weight broadcast settings."""
|
||||
|
||||
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
|
||||
"filesystem"
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
|
||||
class BaseRLConfig(BaseSettings):
|
||||
"""Configures an RL training run."""
|
||||
|
||||
### Submodule configurations
|
||||
|
||||
trainer: TrainerConfig
|
||||
orchestrator: OrchestratorConfig
|
||||
|
||||
output_dir: Annotated[
|
||||
Path | None,
|
||||
Field(description="The directory to store the outputs. Should typically be set to an experiment identifier."),
|
||||
] = None
|
||||
inference: Annotated[
|
||||
InferenceConfig | None,
|
||||
Field(
|
||||
description="The inference config. If None, will not start an inference process. Only viable, if an inference server was started manually."
|
||||
),
|
||||
] = None
|
||||
|
||||
### Top-level configurations
|
||||
|
||||
log: Annotated[
|
||||
SharedLogConfig,
|
||||
Field(
|
||||
description="Shared log configs. If None, will fallback to the log configs specified on submodule configs."
|
||||
),
|
||||
] = SharedLogConfig()
|
||||
|
||||
ckpt: Annotated[
|
||||
SharedCheckpointConfig | None,
|
||||
Field(
|
||||
description="Shared checkpoint configs. If None, will fallback to the checkpoint configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
wandb: Annotated[
|
||||
SharedWandbConfig | None,
|
||||
Field(
|
||||
description="Shared W&B configs. If None, will fallback to the W&B configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
model: Annotated[
|
||||
SharedModelConfig | None,
|
||||
Field(
|
||||
description="Shared model configs. If None, will fallback to the model configs specified on submodule configs."
|
||||
),
|
||||
] = None
|
||||
|
||||
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_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
|
||||
|
||||
seq_len: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
description="The sequence length to use. If set, will configure both trainer.model.seq_len and orchestrator.seq_len to this value. If None, each can be set independently."
|
||||
),
|
||||
] = None
|
||||
|
||||
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
|
||||
|
||||
weight_broadcast: Annotated[
|
||||
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
|
||||
] = None
|
||||
|
||||
### Setup and validate shared configs
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_logs(self):
|
||||
if self.log is not None:
|
||||
if self.log.level is not None:
|
||||
self.trainer.log.level = self.log.level
|
||||
self.orchestrator.log.level = self.log.level
|
||||
if self.log.file is not None:
|
||||
self.trainer.log.file = self.log.file
|
||||
self.orchestrator.log.file = self.log.file
|
||||
self.trainer.log.json_logging = self.log.json_logging
|
||||
self.orchestrator.log.json_logging = self.log.json_logging
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_ckpt(self):
|
||||
# If specified, automatically setup checkpoint configs for trainer and orchestrator
|
||||
if self.ckpt is not None:
|
||||
# Create checkpoint configs if not specified
|
||||
if self.trainer.ckpt is None:
|
||||
self.trainer.ckpt = TrainerCheckpointConfig()
|
||||
if self.orchestrator.ckpt is None:
|
||||
self.orchestrator.ckpt = OrchestratorCheckpointConfig()
|
||||
|
||||
# If specified, use the same ckpt interval
|
||||
if self.ckpt.interval is not None:
|
||||
self.trainer.ckpt.interval = self.ckpt.interval
|
||||
self.orchestrator.ckpt.interval = self.ckpt.interval
|
||||
|
||||
# If resuming training, ensure orchestrator resume from the same step
|
||||
if self.ckpt.resume_step is not None:
|
||||
self.trainer.ckpt.resume_step = self.ckpt.resume_step
|
||||
self.orchestrator.ckpt.resume_step = self.ckpt.resume_step
|
||||
|
||||
# If specified, propagate keep policy
|
||||
if self.ckpt.keep_last is not None:
|
||||
self.trainer.ckpt.keep_last = self.ckpt.keep_last
|
||||
self.orchestrator.ckpt.keep_last = self.ckpt.keep_last
|
||||
|
||||
if self.ckpt.keep_interval is not None:
|
||||
self.trainer.ckpt.keep_interval = self.ckpt.keep_interval
|
||||
self.orchestrator.ckpt.keep_interval = self.ckpt.keep_interval
|
||||
|
||||
validate_shared_ckpt_config(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_wandb(self):
|
||||
# If specified, automatically use shared W&B project for orchestrator and trainer
|
||||
if self.wandb is not None:
|
||||
if not self.trainer.wandb:
|
||||
self.trainer.wandb = WandbConfig()
|
||||
if not self.orchestrator.wandb:
|
||||
self.orchestrator.wandb = WandbWithExtrasConfig()
|
||||
|
||||
if self.wandb.project:
|
||||
self.trainer.wandb.project = self.wandb.project
|
||||
self.orchestrator.wandb.project = self.wandb.project
|
||||
|
||||
# If specified, automatically use shared W&B name for orchestrator and trainer with suffixes
|
||||
if self.wandb.name:
|
||||
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
|
||||
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
|
||||
|
||||
# If specified, automatically use shared W&B offline mode for orchestrator and trainer
|
||||
if self.wandb.offline:
|
||||
self.trainer.wandb.offline = self.wandb.offline
|
||||
self.orchestrator.wandb.offline = self.wandb.offline
|
||||
|
||||
validate_shared_wandb_config(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_model(self):
|
||||
# Use the same model for trainer, orchestrator and inference
|
||||
if self.model is not None:
|
||||
self.trainer.model.name = self.model.name
|
||||
self.orchestrator.model.name = self.model.name
|
||||
if self.inference is not None:
|
||||
self.inference.model.name = self.model.name
|
||||
|
||||
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_max_steps(self):
|
||||
# If specified, use the same max steps for trainer and orchestrator
|
||||
if self.max_steps is not None:
|
||||
self.trainer.max_steps = self.max_steps
|
||||
self.orchestrator.max_steps = self.max_steps
|
||||
|
||||
validate_shared_max_steps(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_async_level(self):
|
||||
# If specified, use the same async level for trainer and orchestrator
|
||||
if self.max_async_level is not None:
|
||||
self.trainer.max_async_level = self.max_async_level
|
||||
self.orchestrator.max_async_level = self.max_async_level
|
||||
|
||||
validate_shared_max_async_level(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_seq_len(self):
|
||||
# If specified, use the same seq_len for trainer and orchestrator
|
||||
if self.seq_len is not None:
|
||||
self.trainer.model.seq_len = self.seq_len
|
||||
self.orchestrator.seq_len = self.seq_len
|
||||
|
||||
if self.trainer.model.seq_len < self.orchestrator.seq_len:
|
||||
raise ValueError(
|
||||
f"Trainer model seq_len ({self.trainer.model.seq_len}) must be >= orchestrator seq_len ({self.orchestrator.seq_len}). "
|
||||
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_weight_broadcast(self):
|
||||
if self.weight_broadcast is not None:
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
inference_world_size=inference_world_size,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
|
||||
if self.inference is not None:
|
||||
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
|
||||
|
||||
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def warn_wandb_resume_id_missing(self):
|
||||
if self.trainer.ckpt is not None and self.trainer.ckpt.resume_step is not None:
|
||||
if self.trainer.wandb and not self.trainer.wandb.id:
|
||||
warnings.warn(
|
||||
"W&B run ID is not set for trainer even though resuming training. The current run will be created as a new run."
|
||||
)
|
||||
if self.orchestrator.ckpt is not None and self.orchestrator.ckpt.resume_step is not None:
|
||||
if self.orchestrator.wandb and not self.orchestrator.wandb.id:
|
||||
warnings.warn(
|
||||
"W&B run ID is not set for orchestrator even though resuming training. The current run will be created as a new run."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_output_dir(self):
|
||||
if self.output_dir is not None:
|
||||
self.trainer.output_dir = self.output_dir
|
||||
self.orchestrator.output_dir = self.output_dir / "run_default"
|
||||
|
||||
validate_shared_output_dir(self.trainer, self.orchestrator)
|
||||
|
||||
return self
|
||||
@@ -0,0 +1,155 @@
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import tomli_w
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.rl_config import BaseRLConfig
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
|
||||
TEMPLATE_DIR = Path(__file__).parent
|
||||
TEMPLATE_NAME = "rl_slurm.sh.j2"
|
||||
|
||||
|
||||
class RLSLURMConfig(BaseRLConfig):
|
||||
output_dir: Path
|
||||
|
||||
job_name: str
|
||||
num_train_nodes: int
|
||||
num_infer_nodes: int
|
||||
gpus_per_node: int = Field(default=8, description="Number of GPUs per node.")
|
||||
nodes_per_fsdp_group: int | None = Field(
|
||||
default=None,
|
||||
description="Number of train nodes per FSDP island. Auto-sets trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group.",
|
||||
)
|
||||
|
||||
project_dir: Path = Field(
|
||||
default_factory=lambda: Path.cwd(),
|
||||
description="Path to the project root. Used to source .env, activate .venv, and run uv sync.",
|
||||
)
|
||||
hf_hub_offline: bool = Field(
|
||||
default=False, description="Set HF_HUB_OFFLINE=1 on training nodes to prevent downloading models at runtime."
|
||||
)
|
||||
|
||||
slurm_template: Path | None = Field(
|
||||
default=None, description="The path to the SLURM template file. If none, will use the default template."
|
||||
)
|
||||
dry_run: bool = Field(default=False, description="Only generate the SLURM script and configs without submitting.")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_dp_replicate(self):
|
||||
if self.nodes_per_fsdp_group is not None:
|
||||
if self.num_train_nodes % self.nodes_per_fsdp_group != 0:
|
||||
raise ValueError(
|
||||
f"num_train_nodes ({self.num_train_nodes}) must be divisible by nodes_per_fsdp_group ({self.nodes_per_fsdp_group})"
|
||||
)
|
||||
self.trainer.dp_replicate = self.num_train_nodes // self.nodes_per_fsdp_group
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_slurm_nccl(self):
|
||||
"""Set SLURM-specific values for NCCL weight broadcast and num_train_workers."""
|
||||
# Set num_train_workers based on SLURM topology
|
||||
self.orchestrator.num_train_workers = self.num_train_nodes * self.gpus_per_node
|
||||
|
||||
# Set NCCL-specific values if using NCCL weight broadcast
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
|
||||
# Trainer listens on all interfaces
|
||||
self.trainer.weight_broadcast.host = "0.0.0.0"
|
||||
# Compute inference world size from SLURM topology
|
||||
self.trainer.weight_broadcast.inference_world_size = self.gpus_per_node * self.num_infer_nodes
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_inference_config(self):
|
||||
"""Validate that inference config is provided when num_infer_nodes > 0."""
|
||||
if self.num_infer_nodes > 0 and self.inference is None:
|
||||
raise ValueError(
|
||||
f"inference config is required when num_infer_nodes > 0 (got {self.num_infer_nodes}). "
|
||||
"The SLURM template will launch inference servers on these nodes."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
def write_subconfigs(config: RLSLURMConfig, output_dir: Path) -> None:
|
||||
"""Write resolved subconfigs to disk as TOML files."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_dir / "trainer.toml", "wb") as f:
|
||||
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
with open(output_dir / "orchestrator.toml", "wb") as f:
|
||||
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
if config.inference is not None:
|
||||
with open(output_dir / "inference.toml", "wb") as f:
|
||||
tomli_w.dump(config.inference.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
|
||||
def render_slurm_script(config: RLSLURMConfig, config_dir: Path) -> str:
|
||||
"""Render the SLURM script template with config values."""
|
||||
if config.slurm_template is not None:
|
||||
template_dir = config.slurm_template.parent
|
||||
template_name = config.slurm_template.name
|
||||
else:
|
||||
template_dir = TEMPLATE_DIR
|
||||
template_name = TEMPLATE_NAME
|
||||
env = Environment(loader=FileSystemLoader(template_dir), keep_trailing_newline=True)
|
||||
template = env.get_template(template_name)
|
||||
return template.render(
|
||||
job_name=config.job_name,
|
||||
output_dir=config.output_dir,
|
||||
orchestrator_output_dir=config.orchestrator.output_dir,
|
||||
config_dir=config_dir,
|
||||
num_train_nodes=config.num_train_nodes,
|
||||
num_infer_nodes=config.num_infer_nodes,
|
||||
project_dir=config.project_dir,
|
||||
gpus_per_node=config.gpus_per_node,
|
||||
hf_hub_offline=config.hf_hub_offline,
|
||||
)
|
||||
|
||||
|
||||
def rl_slurm(config: RLSLURMConfig):
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = config.output_dir / "configs"
|
||||
write_subconfigs(config, config_dir)
|
||||
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
script = render_slurm_script(config, config_dir)
|
||||
script_path = config.output_dir / "rl.sh"
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
script_path.write_text(script)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
slurm_log_dir = config.output_dir / "slurm"
|
||||
log_message = (
|
||||
f"Logs:\n"
|
||||
f" Trainer: tail -f {slurm_log_dir}/latest_train_node_rank_0.log\n"
|
||||
f" Inference: tail -f {slurm_log_dir}/latest_infer_node_rank_0.log\n"
|
||||
f" Orchestrator: tail -f {slurm_log_dir}/latest_orchestrator.log"
|
||||
)
|
||||
|
||||
if config.dry_run:
|
||||
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
|
||||
return
|
||||
|
||||
logger.info(f"Submitting: sbatch {script_path}")
|
||||
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
|
||||
if result.returncode != 0:
|
||||
logger.error(f"sbatch failed: {result.stderr.strip()}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
|
||||
|
||||
def main():
|
||||
rl_slurm(parse_argv(RLSLURMConfig))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/bin/bash
|
||||
|
||||
#SBATCH --job-name={{ job_name }}
|
||||
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
|
||||
#SBATCH --ntasks-per-node=1
|
||||
#SBATCH --gres=gpu:{{ gpus_per_node }}
|
||||
#SBATCH --partition=cluster
|
||||
#SBATCH --exclusive # Get the ENTIRE node exclusively
|
||||
#SBATCH --output=/shared/logs/job_%j.log
|
||||
#SBATCH --error=/shared/logs/job_%j.log
|
||||
|
||||
# Configs
|
||||
export NUM_TRAIN_NODES={{ num_train_nodes }}
|
||||
export NUM_INFER_NODES={{ num_infer_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
|
||||
# Paths
|
||||
export PROJECT_DIR={{ project_dir }}
|
||||
export CONFIG_DIR={{ config_dir }}
|
||||
export OUTPUT_DIR={{ output_dir }}
|
||||
export ORCHESTRATOR_OUTPUT_DIR={{ orchestrator_output_dir }}
|
||||
mkdir -p $OUTPUT_DIR/slurm
|
||||
|
||||
# Clear previous rollouts and broadcast flags from ALL runs (not just the current one)
|
||||
# to prevent the trainer from training on stale data from old run_* directories.
|
||||
# WARN: This is potentially dangerous and could lead to data loss
|
||||
rm -rf $OUTPUT_DIR/run_*/rollouts
|
||||
rm -rf $OUTPUT_DIR/run_*/broadcasts
|
||||
rm -rf $OUTPUT_DIR/rollouts
|
||||
|
||||
|
||||
# General
|
||||
export CUDA_DEVICE_ORDER=PCI_BUS_ID
|
||||
export PYTHONUNBUFFERED=1
|
||||
export OMP_NUM_THREADS=1
|
||||
|
||||
# Networking
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
export INFER_HOSTS=${HOSTNAMES[@]:0:$NUM_INFER_NODES}
|
||||
export TRAIN_HOSTS=${HOSTNAMES[@]:$NUM_INFER_NODES:$SLURM_JOB_NUM_NODES}
|
||||
|
||||
INFER_URLS=""
|
||||
for host in ${INFER_HOSTS[@]}; do
|
||||
if [ -z "$INFER_URLS" ]; then
|
||||
INFER_URLS="http://$host:8000/v1"
|
||||
else
|
||||
INFER_URLS="$INFER_URLS,http://$host:8000/v1"
|
||||
fi
|
||||
done
|
||||
export INFER_URLS
|
||||
echo "HOSTNAMES=${HOSTNAMES[@]}"
|
||||
echo "TRAIN_HOSTS=${TRAIN_HOSTS[@]}"
|
||||
echo "INFER_HOSTS=${INFER_HOSTS[@]}"
|
||||
echo "INFER_URLS=${INFER_URLS}"
|
||||
|
||||
export MASTER_ADDR="${HOSTNAMES[$NUM_INFER_NODES]}"
|
||||
export MASTER_PORT=29500
|
||||
echo "MASTER_ADDR=${MASTER_ADDR}"
|
||||
echo "MASTER_PORT=${MASTER_PORT}"
|
||||
|
||||
|
||||
# Install environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Install environment as local package
|
||||
cd $PROJECT_DIR && uv sync --all-extras
|
||||
|
||||
|
||||
# Run RL
|
||||
srun bash -c '
|
||||
# Setup environment
|
||||
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
|
||||
source $PROJECT_DIR/.venv/bin/activate
|
||||
|
||||
# Disable sync to avoid conflicts with lockfile
|
||||
|
||||
# Higher ulimit
|
||||
ulimit -n 65536
|
||||
export GIT_LFS_SKIP_SMUDGE=1
|
||||
|
||||
# Infiniband setup
|
||||
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
|
||||
export NCCL_IB_HCA=$IB_HCA
|
||||
|
||||
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
# This is required for vLLM graph compile to work
|
||||
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
|
||||
INFER_NODE_RANK=$SLURM_PROCID
|
||||
export VLLM_WORKER_MULTIPROC_METHOD=spawn
|
||||
|
||||
uv run inference \
|
||||
@ $CONFIG_DIR/inference.toml \
|
||||
--enable-auto-tool-choice \
|
||||
--enable-log-requests \
|
||||
--no-disable-log-requests \
|
||||
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${INFER_NODE_RANK}_infer_node_rank_${INFER_NODE_RANK}.log
|
||||
else
|
||||
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
|
||||
|
||||
if [ "$TRAIN_NODE_RANK" -eq 0 ]; then
|
||||
uv run orchestrator \
|
||||
@ $CONFIG_DIR/orchestrator.toml \
|
||||
--weight_broadcast.host $MASTER_ADDR \
|
||||
--client.base-url $INFER_URLS \
|
||||
2>&1 | tee $OUTPUT_DIR/slurm/latest_orchestrator.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_orchestrator.log & disown
|
||||
fi
|
||||
|
||||
export HF_HUB_OFFLINE={{ 1 if hf_hub_offline else 0 }}
|
||||
|
||||
|
||||
# This is required for compilation to work correctly
|
||||
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
|
||||
|
||||
echo $HOSTNAMES | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
|
||||
uv run torchrun \
|
||||
--nnodes=$NUM_TRAIN_NODES \
|
||||
--nproc-per-node=$GPUS_PER_NODE \
|
||||
--node-rank=$TRAIN_NODE_RANK \
|
||||
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
|
||||
--rdzv-id=job_$SLURM_JOB_ID \
|
||||
--log-dir=$OUTPUT_DIR/torchrun \
|
||||
--tee=3 \
|
||||
--redirects=3 \
|
||||
--local-ranks-filter=$(seq -s, 0 $((GPUS_PER_NODE - 1))) \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.toml \
|
||||
2>&1 | tee -a $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_train_node_rank_${TRAIN_NODE_RANK}.log
|
||||
fi
|
||||
'
|
||||
@@ -30,7 +30,6 @@ from prime_rl.trainer.weights import (
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.tensor_hashing import get_module_signature, get_optimizer_signature
|
||||
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path, get_weights_dir
|
||||
|
||||
|
||||
@@ -214,9 +213,6 @@ class CheckpointManager:
|
||||
if not ckpt_path.exists():
|
||||
raise FileNotFoundError(f"Checkpoint not found at {ckpt_path}")
|
||||
self.load_from_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
|
||||
self.logger.debug(
|
||||
f"Signatures after loading training checkpoint: model={get_module_signature(model, compress=True)}, optimizers={', '.join(get_optimizer_signature(optimizer, compress=True) for optimizer in optimizers)}"
|
||||
)
|
||||
|
||||
def save(
|
||||
self,
|
||||
@@ -230,9 +226,6 @@ class CheckpointManager:
|
||||
"""Save the full checkpoint state for a specified step."""
|
||||
ckpt_path = self.get_ckpt_path(step)
|
||||
ckpt_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.logger.debug(
|
||||
f"Signatures before saving training checkpoint: model={get_module_signature(model, compress=True)}, optimizers={', '.join(get_optimizer_signature(optimizer, compress=True) for optimizer in optimizers)}"
|
||||
)
|
||||
|
||||
self.save_to_path(ckpt_path, model, optimizers, scheduler, progress, dataloader)
|
||||
bisect.insort(self.ckpt_steps, step)
|
||||
@@ -305,6 +298,12 @@ class WeightCheckpointManager:
|
||||
"""Get the path to write the weight checkpoint for a given step."""
|
||||
return get_step_path(self.weights_dir, step)
|
||||
|
||||
def mark_stable(self, step: int) -> None:
|
||||
"""Write STABLE file to indicate weight checkpoint is complete."""
|
||||
if self.world.is_master:
|
||||
step_path = self.get_step_path(step)
|
||||
(step_path / "STABLE").touch()
|
||||
|
||||
def save_to_path(
|
||||
self,
|
||||
path: Path,
|
||||
@@ -314,44 +313,45 @@ class WeightCheckpointManager:
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
):
|
||||
"""Save HF-compatible weight checkpoint to a given path."""
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
start_time = time.perf_counter()
|
||||
if self.world.is_master:
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
start_time = time.perf_counter()
|
||||
|
||||
self.logger.debug(f"Saving weight checkpoint to {path}")
|
||||
# Suppress torch.distributed warnings during checkpoint saving
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
|
||||
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
|
||||
self.logger.debug(f"Saving weight checkpoint to {path}")
|
||||
# Suppress torch.distributed warnings during checkpoint saving
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
|
||||
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
|
||||
|
||||
# Save weights
|
||||
save_state_dict(state_dict, path, self.config.save_format, self.config.save_sharded)
|
||||
# Save weights
|
||||
save_state_dict(state_dict, path, self.config.save_format, self.config.save_sharded)
|
||||
|
||||
# Save model config, generation arguments and tokenizer
|
||||
model.config.save_pretrained(path)
|
||||
if model.generation_config:
|
||||
# training sets use_cache=False which can conflict with
|
||||
# cache_implementation — save with use_cache=True without
|
||||
# mutating the model's config
|
||||
from copy import deepcopy
|
||||
# Save model config, generation arguments and tokenizer
|
||||
model.config.save_pretrained(path)
|
||||
if model.generation_config:
|
||||
# training sets use_cache=False which can conflict with
|
||||
# cache_implementation — save with use_cache=True without
|
||||
# mutating the model's config
|
||||
from copy import deepcopy
|
||||
|
||||
gen_config = deepcopy(model.generation_config)
|
||||
gen_config.use_cache = True
|
||||
gen_config.save_pretrained(path)
|
||||
tokenizer.save_pretrained(path)
|
||||
gen_config = deepcopy(model.generation_config)
|
||||
gen_config.use_cache = True
|
||||
gen_config.save_pretrained(path)
|
||||
tokenizer.save_pretrained(path)
|
||||
|
||||
if self.config.save_adapter_separately and lora_state_dict is not None:
|
||||
adapter_path = path / "lora_adapters"
|
||||
adapter_path.mkdir(parents=True, exist_ok=True)
|
||||
torch.save(lora_state_dict, adapter_path / "adapter_model.bin")
|
||||
if self.lora_config:
|
||||
save_lora_config(
|
||||
model,
|
||||
adapter_path,
|
||||
rank=self.lora_config.rank,
|
||||
alpha=self.lora_config.alpha,
|
||||
dropout=self.lora_config.dropout,
|
||||
)
|
||||
self.logger.debug(f"Saved weight checkpoint to {path} in {time.perf_counter() - start_time:.2f} seconds")
|
||||
if self.config.save_adapter_separately and lora_state_dict is not None:
|
||||
adapter_path = path / "lora_adapters"
|
||||
adapter_path.mkdir(parents=True, exist_ok=True)
|
||||
torch.save(lora_state_dict, adapter_path / "adapter_model.bin")
|
||||
if self.lora_config:
|
||||
save_lora_config(
|
||||
model,
|
||||
adapter_path,
|
||||
rank=self.lora_config.rank,
|
||||
alpha=self.lora_config.alpha,
|
||||
dropout=self.lora_config.dropout,
|
||||
)
|
||||
self.logger.debug(f"Saved weight checkpoint to {path} in {time.perf_counter() - start_time:.2f} seconds")
|
||||
|
||||
def save(
|
||||
self,
|
||||
@@ -400,10 +400,8 @@ class WeightCheckpointManager:
|
||||
self.logger.debug(f"Reverted to HF hub format in {time.perf_counter() - start_time:.2f} seconds")
|
||||
|
||||
# Save weight checkpoint on master rank
|
||||
if self.world.is_master:
|
||||
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer)
|
||||
# Write STABLE file to indicate checkpoint is complete (for eval to safely read)
|
||||
(step_path / "STABLE").touch()
|
||||
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer)
|
||||
self.mark_stable(step)
|
||||
bisect.insort(self.ckpt_steps, step)
|
||||
|
||||
def maybe_clean(self) -> None:
|
||||
|
||||
@@ -17,7 +17,7 @@ from torch.distributed.device_mesh import DeviceMesh
|
||||
from torch.distributed.fsdp import CPUOffloadPolicy, FSDPModule, MixedPrecisionPolicy, OffloadPolicy, fully_shard
|
||||
from torch.distributed.tensor.parallel import parallelize_module
|
||||
from torchtitan.distributed.expert_parallel import ExpertParallel
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, PretrainedConfig
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, PretrainedConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from transformers.utils.import_utils import is_flash_attn_3_available
|
||||
|
||||
@@ -40,7 +40,6 @@ from prime_rl.trainer.weights import (
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.tensor_hashing import get_module_signature
|
||||
from prime_rl.utils.vlm import is_vlm_model
|
||||
|
||||
# Add filter to the standard logging module for transformers.modeling_utils to supress the
|
||||
@@ -147,9 +146,20 @@ def get_model(
|
||||
model_config.use_cache = False
|
||||
model_config.use_grouped_mm = config.moe_use_grouped_mm
|
||||
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it)
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
|
||||
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
|
||||
if not hasattr(model_config, "pad_token_id") or model_config.pad_token_id is None:
|
||||
model_config.pad_token_id = model_config.eos_token_id
|
||||
gen_config = GenerationConfig.from_model_config(model_config)
|
||||
# Use `is not None` instead of truthiness: token ID 0 is valid.
|
||||
pad_token_id = next(
|
||||
(
|
||||
v
|
||||
for v in [gen_config.pad_token_id, gen_config.eos_token_id, getattr(model_config, "eos_token_id", None)]
|
||||
if v is not None
|
||||
),
|
||||
None,
|
||||
)
|
||||
model_config.pad_token_id = pad_token_id
|
||||
|
||||
# NOTE: For VLM models, we do NOT propagate dtype to sub_configs.
|
||||
# The model should load in its default dtype (bf16) to match vLLM inference.
|
||||
@@ -180,11 +190,10 @@ def get_model(
|
||||
)
|
||||
|
||||
with device:
|
||||
# For VLM models, use AutoModelForVision2Seq or import specific model class
|
||||
if is_vlm:
|
||||
from transformers import AutoModelForVision2Seq
|
||||
from transformers import AutoModelForImageTextToText
|
||||
|
||||
model_cls = AutoModelForVision2Seq
|
||||
model_cls = AutoModelForImageTextToText
|
||||
else:
|
||||
match impl_to_use:
|
||||
case "hf":
|
||||
@@ -669,7 +678,6 @@ def setup_model(
|
||||
else:
|
||||
load_dcp_from_hf(model, config, parallel_dims)
|
||||
|
||||
logger.debug(f"Model signature: {get_module_signature(model, compress=True)}")
|
||||
return model
|
||||
|
||||
|
||||
|
||||
@@ -13,17 +13,20 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, cast_float_and_contiguous
|
||||
from prime_rl.trainer.models.llama import LlamaForCausalLM
|
||||
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
|
||||
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
|
||||
|
||||
# Make custom config discoverable by AutoConfig
|
||||
AutoConfig.register("afmoe", AfmoeConfig, exist_ok=True)
|
||||
AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
|
||||
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, 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(AfmoeConfig, AfmoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Glm4MoeConfig, Glm4MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
|
||||
|
||||
|
||||
|
||||
@@ -132,19 +132,16 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_index: int):
|
||||
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
|
||||
# Routed experts - convert to new fused format (transformers 5.0+)
|
||||
w1 = state_dict[f"model.layers.{i}.mlp.experts.w1"] # (num_experts, moe_dim, dim)
|
||||
w2 = state_dict[f"model.layers.{i}.mlp.experts.w2"] # (num_experts, dim, moe_dim)
|
||||
w3 = state_dict[f"model.layers.{i}.mlp.experts.w3"] # (num_experts, moe_dim, dim)
|
||||
# Routed experts - convert to per-expert format (compatible with vLLM and transformers)
|
||||
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1") # (num_experts, moe_dim, dim)
|
||||
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2") # (num_experts, dim, moe_dim)
|
||||
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3") # (num_experts, moe_dim, dim)
|
||||
|
||||
# Fuse w1 (gate) and w3 (up) into gate_up_proj
|
||||
gate_up_proj = torch.cat([w1, w3], dim=1) # (num_experts, 2*moe_dim, dim)
|
||||
state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"] = gate_up_proj
|
||||
state_dict[f"model.layers.{i}.mlp.experts.down_proj"] = w2
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w1"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w2"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w3"]
|
||||
num_experts = w1.shape[0]
|
||||
for j in range(num_experts):
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
|
||||
|
||||
|
||||
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import functools
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
@@ -36,6 +37,7 @@ class AttentionConfig:
|
||||
attention_bias: bool
|
||||
use_qk_norm: bool
|
||||
rms_norm_eps: float
|
||||
qk_norm_type: Literal["per_head", "per_layer"] = "per_head"
|
||||
|
||||
|
||||
# TODO: Does torch compile support config._attn_implementation forking?
|
||||
@@ -70,9 +72,18 @@ class FlashAttention(nn.Module):
|
||||
)
|
||||
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
||||
self.use_qk_norm = config.use_qk_norm
|
||||
self.qk_norm_type = config.qk_norm_type
|
||||
if self.use_qk_norm:
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
if self.qk_norm_type == "per_layer":
|
||||
self.q_norm = RMSNorm(
|
||||
RMSNormConfig(hidden_size=config.num_attention_heads * self.head_dim, eps=config.rms_norm_eps)
|
||||
)
|
||||
self.k_norm = RMSNorm(
|
||||
RMSNormConfig(hidden_size=config.num_key_value_heads * self.head_dim, eps=config.rms_norm_eps)
|
||||
)
|
||||
else:
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
|
||||
self._flash_attn_version = flash_attn_version
|
||||
self.func = self._funcs[flash_attn_version]
|
||||
@@ -90,11 +101,19 @@ class FlashAttention(nn.Module):
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states).view(hidden_shape)
|
||||
key_states = self.k_proj(hidden_states).view(hidden_shape)
|
||||
value_states = self.v_proj(hidden_states).view(hidden_shape)
|
||||
query_states = self.q_proj(hidden_states)
|
||||
key_states = self.k_proj(hidden_states)
|
||||
value_states = self.v_proj(hidden_states)
|
||||
|
||||
if self.use_qk_norm: # main diff from Llama
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.view(hidden_shape)
|
||||
key_states = key_states.view(hidden_shape)
|
||||
value_states = value_states.view(hidden_shape)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_head":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
@@ -156,9 +175,18 @@ class SDPAAttention(nn.Module):
|
||||
)
|
||||
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
||||
self.use_qk_norm = config.use_qk_norm
|
||||
self.qk_norm_type = config.qk_norm_type
|
||||
if self.use_qk_norm:
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
if self.qk_norm_type == "per_layer":
|
||||
self.q_norm = RMSNorm(
|
||||
RMSNormConfig(hidden_size=config.num_attention_heads * self.head_dim, eps=config.rms_norm_eps)
|
||||
)
|
||||
self.k_norm = RMSNorm(
|
||||
RMSNormConfig(hidden_size=config.num_key_value_heads * self.head_dim, eps=config.rms_norm_eps)
|
||||
)
|
||||
else:
|
||||
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -170,11 +198,19 @@ class SDPAAttention(nn.Module):
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states: torch.Tensor = self.q_proj(hidden_states).view(hidden_shape)
|
||||
key_states: torch.Tensor = self.k_proj(hidden_states).view(hidden_shape)
|
||||
value_states: torch.Tensor = self.v_proj(hidden_states).view(hidden_shape)
|
||||
query_states: torch.Tensor = self.q_proj(hidden_states)
|
||||
key_states: torch.Tensor = self.k_proj(hidden_states)
|
||||
value_states: torch.Tensor = self.v_proj(hidden_states)
|
||||
|
||||
if self.use_qk_norm: # main diff from Llama
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.view(hidden_shape)
|
||||
key_states = key_states.view(hidden_shape)
|
||||
value_states = value_states.view(hidden_shape)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_head":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
@@ -229,11 +265,19 @@ def substitute_prime_rl_flash_attn(
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
query_states = self.q_proj(hidden_states).view(hidden_shape)
|
||||
key_states = self.k_proj(hidden_states).view(hidden_shape)
|
||||
value_states = self.v_proj(hidden_states).view(hidden_shape)
|
||||
query_states = self.q_proj(hidden_states)
|
||||
key_states = self.k_proj(hidden_states)
|
||||
value_states = self.v_proj(hidden_states)
|
||||
|
||||
if self.use_qk_norm: # main diff from Llama
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_layer":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
query_states = query_states.view(hidden_shape)
|
||||
key_states = key_states.view(hidden_shape)
|
||||
value_states = value_states.view(hidden_shape)
|
||||
|
||||
if self.use_qk_norm and self.qk_norm_type == "per_head":
|
||||
query_states = self.q_norm(query_states)
|
||||
key_states = self.k_norm(key_states)
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
from prime_rl.trainer.models.minimax_m2.configuration_minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2.modeling_minimax_m2 import (
|
||||
MiniMaxM2ForCausalLM,
|
||||
MiniMaxM2Model,
|
||||
MiniMaxM2PreTrainedModel,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"MiniMaxM2Config",
|
||||
"MiniMaxM2ForCausalLM",
|
||||
"MiniMaxM2Model",
|
||||
"MiniMaxM2PreTrainedModel",
|
||||
]
|
||||
@@ -0,0 +1,151 @@
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.modeling_rope_utils import rope_config_validation
|
||||
|
||||
|
||||
class MiniMaxM2Config(PretrainedConfig):
|
||||
r"""
|
||||
Configuration class for MiniMax M2.1 MoE model.
|
||||
|
||||
Args:
|
||||
vocab_size (`int`, *optional*, defaults to 200064):
|
||||
Vocabulary size of the model.
|
||||
hidden_size (`int`, *optional*, defaults to 6144):
|
||||
Dimension of the hidden representations.
|
||||
intermediate_size (`int`, *optional*, defaults to 24576):
|
||||
Dimension of the MoE expert FFN.
|
||||
num_hidden_layers (`int`, *optional*, defaults to 92):
|
||||
Number of hidden layers in the Transformer.
|
||||
num_attention_heads (`int`, *optional*, defaults to 48):
|
||||
Number of attention heads.
|
||||
num_key_value_heads (`int`, *optional*, defaults to 8):
|
||||
Number of key-value heads for GQA.
|
||||
head_dim (`int`, *optional*, defaults to 128):
|
||||
Dimension of each attention head.
|
||||
hidden_act (`str`, *optional*, defaults to `"silu"`):
|
||||
Activation function for the MLP.
|
||||
max_position_embeddings (`int`, *optional*, defaults to 131072):
|
||||
Maximum sequence length.
|
||||
rms_norm_eps (`float`, *optional*, defaults to 1e-6):
|
||||
Epsilon for RMS normalization.
|
||||
rope_theta (`float`, *optional*, defaults to 5000000):
|
||||
Base period for RoPE.
|
||||
rotary_dim (`int`, *optional*, defaults to 64):
|
||||
Dimension of the rotary embeddings. Converted to `partial_rotary_factor` for HF rope init.
|
||||
num_local_experts (`int`, *optional*, defaults to 256):
|
||||
Number of routed experts per layer.
|
||||
num_experts_per_tok (`int`, *optional*, defaults to 8):
|
||||
Number of experts selected per token.
|
||||
scoring_func (`str`, *optional*, defaults to `"sigmoid"`):
|
||||
Scoring function for the router.
|
||||
use_routing_bias (`bool`, *optional*, defaults to `True`):
|
||||
Whether to use e_score_correction_bias for load balancing.
|
||||
use_qk_norm (`bool`, *optional*, defaults to `True`):
|
||||
Whether to use QK normalization.
|
||||
qk_norm_type (`str`, *optional*, defaults to `"per_layer"`):
|
||||
Type of QK normalization. "per_layer" means each head has its own scale.
|
||||
attention_bias (`bool`, *optional*, defaults to `False`):
|
||||
Whether to use bias in attention projections.
|
||||
use_grouped_mm (`bool`, *optional*, defaults to `True`):
|
||||
Whether to use grouped matmul for experts.
|
||||
"""
|
||||
|
||||
model_type = "minimax_m2"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
base_model_tp_plan = {
|
||||
"layers.*.self_attn.q_proj": "colwise",
|
||||
"layers.*.self_attn.k_proj": "colwise",
|
||||
"layers.*.self_attn.v_proj": "colwise",
|
||||
"layers.*.self_attn.o_proj": "rowwise",
|
||||
}
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
||||
"norm": (["hidden_states"], ["hidden_states"]),
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=200064,
|
||||
hidden_size=6144,
|
||||
intermediate_size=24576,
|
||||
num_hidden_layers=92,
|
||||
num_attention_heads=48,
|
||||
num_key_value_heads=8,
|
||||
head_dim=128,
|
||||
hidden_act="silu",
|
||||
max_position_embeddings=131072,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-6,
|
||||
use_cache=True,
|
||||
tie_word_embeddings=False,
|
||||
rope_theta=5000000,
|
||||
rope_scaling=None,
|
||||
rotary_dim=64,
|
||||
pad_token_id=None,
|
||||
bos_token_id=1,
|
||||
eos_token_id=2,
|
||||
num_local_experts=256,
|
||||
num_experts_per_tok=8,
|
||||
scoring_func="sigmoid",
|
||||
use_routing_bias=True,
|
||||
use_qk_norm=True,
|
||||
qk_norm_type="per_layer",
|
||||
attention_bias=False,
|
||||
sliding_window=None,
|
||||
attention_dropout=0.0,
|
||||
output_router_logits=False,
|
||||
router_aux_loss_coef=0.001,
|
||||
router_jitter_noise=0.0,
|
||||
use_grouped_mm=True,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.hidden_act = hidden_act
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
self.attention_bias = attention_bias
|
||||
self.sliding_window = sliding_window
|
||||
self.attention_dropout = attention_dropout
|
||||
|
||||
# Compute partial_rotary_factor from rotary_dim for HF rope init compatibility
|
||||
self.rotary_dim = rotary_dim
|
||||
self.partial_rotary_factor = rotary_dim / head_dim
|
||||
|
||||
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
||||
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
||||
rope_config_validation(self)
|
||||
|
||||
# MoE arguments
|
||||
self.num_local_experts = num_local_experts
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.scoring_func = scoring_func
|
||||
self.use_routing_bias = use_routing_bias
|
||||
self.output_router_logits = output_router_logits
|
||||
self.router_aux_loss_coef = router_aux_loss_coef
|
||||
self.router_jitter_noise = router_jitter_noise
|
||||
|
||||
# Attention
|
||||
self.use_qk_norm = use_qk_norm
|
||||
self.qk_norm_type = qk_norm_type
|
||||
|
||||
# Training
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -0,0 +1,101 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
|
||||
"""Get the maximum number of layers in the model."""
|
||||
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
"""Convert a layer from HF to PrimeRL format in-place.
|
||||
|
||||
HF MiniMax M2.1 uses `block_sparse_moe` as the MoE block name, with
|
||||
expert weights stored as `experts.{j}.w1.weight` (nn.Linear format).
|
||||
"""
|
||||
i = layer_idx
|
||||
prefix = f"model.layers.{i}"
|
||||
|
||||
# Check if this layer has MoE experts
|
||||
num_experts = len([k for k in state_dict.keys() if f"{prefix}.block_sparse_moe.experts" in k]) // 3
|
||||
if num_experts == 0:
|
||||
return
|
||||
|
||||
# Router: block_sparse_moe.gate.weight -> mlp.router.gate.weight
|
||||
state_dict[f"{prefix}.mlp.router.gate.weight"] = state_dict[f"{prefix}.block_sparse_moe.gate.weight"]
|
||||
del state_dict[f"{prefix}.block_sparse_moe.gate.weight"]
|
||||
|
||||
# e_score_correction_bias: direct tensor under block_sparse_moe -> mlp.expert_bias
|
||||
bias_key = f"{prefix}.block_sparse_moe.e_score_correction_bias"
|
||||
if bias_key in state_dict:
|
||||
state_dict[f"{prefix}.mlp.expert_bias"] = state_dict[bias_key]
|
||||
del state_dict[bias_key]
|
||||
|
||||
# Expert weights: stack individual experts into grouped tensors
|
||||
# HF uses w1.weight, w2.weight, w3.weight (nn.Linear with .weight suffix)
|
||||
dim, moe_dim = state_dict[f"{prefix}.block_sparse_moe.experts.0.w2.weight"].shape
|
||||
dtype = state_dict[f"{prefix}.block_sparse_moe.experts.0.w2.weight"].dtype
|
||||
|
||||
w1 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
|
||||
w2 = torch.empty((num_experts, dim, moe_dim), dtype=dtype)
|
||||
w3 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
|
||||
|
||||
for j in range(num_experts):
|
||||
w1[j].copy_(state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w1.weight"])
|
||||
w2[j].copy_(state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"])
|
||||
w3[j].copy_(state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"])
|
||||
|
||||
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w1.weight"]
|
||||
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"]
|
||||
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"]
|
||||
|
||||
state_dict[f"{prefix}.mlp.experts.w1"] = w1
|
||||
state_dict[f"{prefix}.mlp.experts.w2"] = w2
|
||||
state_dict[f"{prefix}.mlp.experts.w3"] = w3
|
||||
|
||||
|
||||
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
"""Convert a layer from PrimeRL to HF format in-place."""
|
||||
i = layer_idx
|
||||
prefix = f"model.layers.{i}"
|
||||
|
||||
if f"{prefix}.mlp.router.gate.weight" not in state_dict:
|
||||
return
|
||||
|
||||
# Router: mlp.router.gate.weight -> block_sparse_moe.gate.weight
|
||||
state_dict[f"{prefix}.block_sparse_moe.gate.weight"] = state_dict[f"{prefix}.mlp.router.gate.weight"]
|
||||
del state_dict[f"{prefix}.mlp.router.gate.weight"]
|
||||
|
||||
# expert_bias -> block_sparse_moe.e_score_correction_bias
|
||||
if f"{prefix}.mlp.expert_bias" in state_dict:
|
||||
state_dict[f"{prefix}.block_sparse_moe.e_score_correction_bias"] = state_dict[f"{prefix}.mlp.expert_bias"]
|
||||
del state_dict[f"{prefix}.mlp.expert_bias"]
|
||||
|
||||
# tokens_per_expert is a runtime buffer, remove if present
|
||||
if f"{prefix}.mlp.tokens_per_expert" in state_dict:
|
||||
del state_dict[f"{prefix}.mlp.tokens_per_expert"]
|
||||
|
||||
# Expert weights: unstack grouped tensors into individual experts
|
||||
num_experts, moe_dim, dim = state_dict[f"{prefix}.mlp.experts.w1"].shape
|
||||
for j in range(num_experts):
|
||||
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w1.weight"] = state_dict[f"{prefix}.mlp.experts.w1"][j]
|
||||
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"] = state_dict[f"{prefix}.mlp.experts.w2"][j]
|
||||
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"] = state_dict[f"{prefix}.mlp.experts.w3"][j]
|
||||
|
||||
del state_dict[f"{prefix}.mlp.experts.w1"]
|
||||
del state_dict[f"{prefix}.mlp.experts.w2"]
|
||||
del state_dict[f"{prefix}.mlp.experts.w3"]
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert MoE weights from HF to PrimeRL format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_hf_layer_to_tt(state_dict, i)
|
||||
|
||||
|
||||
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert MoE weights from PrimeRL to HF format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_tt_layer_to_hf(state_dict, i)
|
||||
@@ -0,0 +1,276 @@
|
||||
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.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
|
||||
|
||||
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.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.trainer.models.minimax_m2.configuration_minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2.converting_minimax_m2 import (
|
||||
convert_hf_layer_to_tt,
|
||||
convert_hf_to_tt_moe,
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
class MiniMaxM2DecoderLayer(GradientCheckpointingLayer):
|
||||
def __init__(self, config: MiniMaxM2Config, layer_idx: int):
|
||||
super().__init__()
|
||||
self.hidden_size = config.hidden_size
|
||||
|
||||
attn_config = AttentionConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
head_dim=config.head_dim,
|
||||
num_attention_heads=config.num_attention_heads,
|
||||
num_key_value_heads=config.num_key_value_heads,
|
||||
is_causal=True,
|
||||
attention_bias=config.attention_bias,
|
||||
use_qk_norm=config.use_qk_norm,
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
qk_norm_type=config.qk_norm_type,
|
||||
)
|
||||
self.self_attn = ATTN_IMPL2CLASS[config._attn_implementation](attn_config)
|
||||
|
||||
moe_args = MoEArgs(
|
||||
num_experts=config.num_local_experts,
|
||||
num_shared_experts=0,
|
||||
score_func=config.scoring_func,
|
||||
route_norm=True,
|
||||
route_scale=1.0,
|
||||
score_before_experts=False,
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=1e-3 if config.use_routing_bias else None,
|
||||
)
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.intermediate_size)
|
||||
|
||||
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)
|
||||
hidden_states = residual + hidden_states
|
||||
return hidden_states
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class MiniMaxM2PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config: MiniMaxM2Config
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["MiniMaxM2DecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
_supports_flash_attn = True
|
||||
_supports_sdpa = True
|
||||
_supports_flex_attn = True
|
||||
_can_compile_fullgraph = False
|
||||
_supports_attention_backend = True
|
||||
_can_record_outputs = {
|
||||
"hidden_states": MiniMaxM2DecoderLayer,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("block_sparse_moe.experts.1.w1" in name for name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in name for name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_tt_to_hf_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_hf_to_tt_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
|
||||
def __init__(self, config: MiniMaxM2Config):
|
||||
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(
|
||||
[MiniMaxM2DecoderLayer(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))
|
||||
|
||||
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
||||
rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
||||
else:
|
||||
rope_type = "default"
|
||||
rotary_config = RotaryEmbeddingConfig(
|
||||
max_position_embeddings=config.max_position_embeddings,
|
||||
rope_type=rope_type,
|
||||
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 self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
cu_seqlens = 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 MiniMaxM2ForCausalLM(MiniMaxM2PreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = ["lm_head.weight"]
|
||||
_tp_plan = {"lm_head": "colwise_rep"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.model = MiniMaxM2Model(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
|
||||
self.post_init()
|
||||
|
||||
@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: Union[torch.Tensor, None] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> PrimeLmOutput:
|
||||
r"""
|
||||
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Labels for computing the masked language modeling loss.
|
||||
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Per-token temperatures for logprobs/entropy computation.
|
||||
"""
|
||||
assert use_cache is None, "use_cache is not supported for custom minimax_m2 for now"
|
||||
assert past_key_values is None, "past_key_values is not supported for custom minimax_m2 for now"
|
||||
|
||||
if position_ids is None:
|
||||
if inputs_embeds is not None:
|
||||
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
|
||||
else:
|
||||
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
|
||||
|
||||
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__ = [
|
||||
"MiniMaxM2ForCausalLM",
|
||||
"MiniMaxM2Model",
|
||||
"MiniMaxM2PreTrainedModel",
|
||||
]
|
||||
@@ -74,19 +74,16 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_index: int):
|
||||
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
|
||||
# Routed experts - convert to new fused format (transformers 5.0+)
|
||||
w1 = state_dict[f"model.layers.{i}.mlp.experts.w1"] # (num_experts, moe_dim, dim)
|
||||
w2 = state_dict[f"model.layers.{i}.mlp.experts.w2"] # (num_experts, dim, moe_dim)
|
||||
w3 = state_dict[f"model.layers.{i}.mlp.experts.w3"] # (num_experts, moe_dim, dim)
|
||||
# Routed experts - convert to per-expert format (compatible with vLLM and transformers)
|
||||
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1") # (num_experts, moe_dim, dim)
|
||||
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2") # (num_experts, dim, moe_dim)
|
||||
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3") # (num_experts, moe_dim, dim)
|
||||
|
||||
# Fuse w1 (gate) and w3 (up) into gate_up_proj
|
||||
gate_up_proj = torch.cat([w1, w3], dim=1) # (num_experts, 2*moe_dim, dim)
|
||||
state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"] = gate_up_proj
|
||||
state_dict[f"model.layers.{i}.mlp.experts.down_proj"] = w2
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w1"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w2"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.w3"]
|
||||
num_experts = w1.shape[0]
|
||||
for j in range(num_experts):
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
|
||||
|
||||
@@ -12,7 +12,6 @@ import torch
|
||||
import torch.distributed as dist
|
||||
import torch.distributed.nn as dist_nn
|
||||
from torch.profiler import profile, ProfilerActivity, record_function
|
||||
from loguru import logger
|
||||
from prime_rl.trainer.ckpt import setup_ckpt_managers
|
||||
from prime_rl.trainer.multi_ckpt import setup_multi_checkpoint_manager
|
||||
from prime_rl.trainer.optim import setup_optimizer, setup_multi_optimizer
|
||||
@@ -63,7 +62,6 @@ from torchtitan.distributed.utils import clip_grad_norm_
|
||||
|
||||
|
||||
@clean_exit
|
||||
@logger.catch(reraise=True)
|
||||
def train(config: RLTrainerConfig):
|
||||
# Setup world and logger
|
||||
world = get_world()
|
||||
@@ -507,6 +505,12 @@ def train(config: RLTrainerConfig):
|
||||
}
|
||||
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")
|
||||
if mismatch_kl_mean is not None and entropy_mean > 0:
|
||||
tensor_stats["kl_ent_ratio/mean"] = mismatch_kl_mean / entropy_mean
|
||||
|
||||
# Log tensor stats
|
||||
tensor_stats["step"] = progress.step
|
||||
monitor.log(tensor_stats, step=progress.step)
|
||||
|
||||
@@ -11,7 +11,7 @@ import torch.distributed.distributed_c10d as c10d
|
||||
from prime_rl.trainer.config import LoRAConfig
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.pathing import get_stable_ckpt_steps
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_stable_ckpt_steps
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
@@ -264,8 +264,11 @@ class MultiRunManager:
|
||||
if config.ckpt is None or config.ckpt.resume_step is None:
|
||||
self.progress[new_id].step = 0
|
||||
elif config.ckpt.resume_step == -1:
|
||||
stable_steps = get_stable_ckpt_steps(self.get_run_dir(new_id) / "checkpoints")
|
||||
self.progress[new_id].step = max(stable_steps) if stable_steps else 0
|
||||
ckpt_dir = self.get_run_dir(new_id) / "checkpoints"
|
||||
# In multi-run, the trainer writes STABLE after saving LoRA weights to the run's checkpoint dir.
|
||||
# In single-run, only the orchestrator writes checkpoints here (trainer has its own dir), so no STABLE exists.
|
||||
steps = get_stable_ckpt_steps(ckpt_dir) if self.max_runs > 1 else get_all_ckpt_steps(ckpt_dir)
|
||||
self.progress[new_id].step = max(steps) if steps else 0
|
||||
else:
|
||||
self.progress[new_id].step = config.ckpt.resume_step
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ from prime_rl.trainer.models.layers.attn import substitute_prime_rl_flash_attn
|
||||
from prime_rl.utils.act_offloading import maybe_activation_offloading
|
||||
import torch
|
||||
from torch.profiler import profile, ProfilerActivity, record_function
|
||||
from loguru import logger
|
||||
from prime_rl.trainer.ckpt import setup_ckpt_managers
|
||||
from prime_rl.utils.pathing import resolve_latest_ckpt_step
|
||||
from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
@@ -51,7 +50,6 @@ from torchtitan.distributed.utils import clip_grad_norm_
|
||||
|
||||
|
||||
@clean_exit
|
||||
@logger.catch(reraise=True)
|
||||
def train(config: SFTTrainerConfig):
|
||||
# Setup world and logger
|
||||
world = get_world()
|
||||
|
||||
@@ -106,7 +106,7 @@ async def setup_inference_pool(client_config: ClientConfig, model_name: str) ->
|
||||
return await ElasticInferencePool.from_config(client_config, model_name=model_name)
|
||||
|
||||
logger.info(
|
||||
f"Initializing OpenAI client (base_url={', '.join(client_config.base_url)}, "
|
||||
f"Initializing static inference pool (base_url={', '.join(client_config.base_url)}, "
|
||||
f"api_key_var={client_config.api_key_var}, headers={client_config.headers})"
|
||||
)
|
||||
return StaticInferencePool(
|
||||
@@ -117,9 +117,10 @@ async def setup_inference_pool(client_config: ClientConfig, model_name: str) ->
|
||||
|
||||
|
||||
def setup_clients(client_config: ClientConfig) -> list[vf.ClientConfig]:
|
||||
def _setup_client(client_idx: int, base_url: str) -> vf.ClientConfig:
|
||||
def setup_client(client_idx: int, base_url: str) -> vf.ClientConfig:
|
||||
return vf.ClientConfig(
|
||||
client_idx=client_idx,
|
||||
client_type="openai_chat_completions_token",
|
||||
api_base_url=base_url,
|
||||
api_key_var=client_config.api_key_var,
|
||||
timeout=client_config.timeout,
|
||||
@@ -129,7 +130,7 @@ def setup_clients(client_config: ClientConfig) -> list[vf.ClientConfig]:
|
||||
extra_headers=client_config.headers,
|
||||
)
|
||||
|
||||
return [_setup_client(client_idx, base_url) for client_idx, base_url in enumerate(client_config.base_url)]
|
||||
return [setup_client(client_idx, base_url) for client_idx, base_url in enumerate(client_config.base_url)]
|
||||
|
||||
|
||||
def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
|
||||
@@ -248,24 +249,6 @@ async def update_weights(
|
||||
await asyncio.gather(*[_update_weights(admin_client, weight_dir_posix) for admin_client in admin_clients])
|
||||
|
||||
|
||||
async def reload_weights(admin_clients: list[AsyncClient]) -> None:
|
||||
"""Make a HTTP post request to the vLLM server to reload weights (reset to base model)."""
|
||||
logger = get_logger()
|
||||
|
||||
async def _reload_weights(admin_client: AsyncClient) -> None:
|
||||
logger.debug("Sending request to reload weights (reset to base model)")
|
||||
try:
|
||||
response = await admin_client.post("/reload_weights", json={})
|
||||
response.raise_for_status()
|
||||
except httpx.HTTPStatusError as e:
|
||||
if e.response.status_code == 404:
|
||||
logger.warning("The route /reload_weights does not exist. Skipping weight reload.")
|
||||
return
|
||||
raise
|
||||
|
||||
await asyncio.gather(*[_reload_weights(admin_client) for admin_client in admin_clients])
|
||||
|
||||
|
||||
def _is_retryable_lora_error(exception: BaseException) -> bool:
|
||||
"""Check if an exception should trigger a retry for LoRA loading."""
|
||||
if isinstance(exception, httpx.HTTPStatusError):
|
||||
|
||||
@@ -118,7 +118,7 @@ class LogConfig(BaseConfig):
|
||||
vf_level: Annotated[
|
||||
str,
|
||||
Field(description="Logging level for the verifiers package. Will determine the logging verbosity and format."),
|
||||
] = "warn"
|
||||
] = "info"
|
||||
|
||||
file: Annotated[
|
||||
bool,
|
||||
|
||||
@@ -14,7 +14,7 @@ NO_BOLD = "\033[22m"
|
||||
RESET = "\033[0m"
|
||||
|
||||
|
||||
def _build_log_entry(record) -> dict:
|
||||
def build_log_entry(record) -> dict:
|
||||
"""Build a flat JSON log entry from a loguru record."""
|
||||
extra = record["extra"]
|
||||
|
||||
@@ -54,14 +54,14 @@ def _build_log_entry(record) -> dict:
|
||||
return log_entry
|
||||
|
||||
|
||||
def _json_sink(message) -> None:
|
||||
def json_sink(message) -> None:
|
||||
"""Sink that outputs flat JSON to stdout for log aggregation (Loki, Grafana, etc.)."""
|
||||
log_entry = _build_log_entry(message.record)
|
||||
log_entry = build_log_entry(message.record)
|
||||
sys.stdout.write(json_module.dumps(log_entry) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
class _JsonFileSink:
|
||||
class JsonFileSink:
|
||||
"""File sink that keeps the handle open and writes flat JSON lines."""
|
||||
|
||||
def __init__(self, log_file: Path):
|
||||
@@ -74,7 +74,7 @@ class _JsonFileSink:
|
||||
self._file.close()
|
||||
|
||||
def write(self, message) -> None:
|
||||
log_entry = _build_log_entry(message.record)
|
||||
log_entry = build_log_entry(message.record)
|
||||
self._file.write(json_module.dumps(log_entry) + "\n")
|
||||
self._file.flush()
|
||||
|
||||
@@ -82,7 +82,7 @@ class _JsonFileSink:
|
||||
class InterceptHandler(logging.Handler):
|
||||
"""Intercept standard logging library and routes to our prime-rl logger with specified prefix."""
|
||||
|
||||
def __init__(self, prefix: str):
|
||||
def __init__(self, prefix: str | None):
|
||||
super().__init__()
|
||||
self.prefix = prefix
|
||||
|
||||
@@ -98,21 +98,26 @@ class InterceptHandler(logging.Handler):
|
||||
frame = frame.f_back
|
||||
depth += 1
|
||||
|
||||
logger.opt(depth=depth, exception=record.exc_info).log(level, f"[{self.prefix}] {record.getMessage()}")
|
||||
message = record.getMessage()
|
||||
if self.prefix is not None:
|
||||
message = f"[{self.prefix}] {message}"
|
||||
logger.opt(depth=depth, exception=record.exc_info).log(level, message)
|
||||
|
||||
|
||||
def setup_logger(
|
||||
log_level: str,
|
||||
log_level: str = "info",
|
||||
log_file: Path | None = None,
|
||||
append: bool = False,
|
||||
tag: str | None = None,
|
||||
json_logging: bool = False,
|
||||
):
|
||||
global _LOGGER, _JSON_LOGGING
|
||||
if _LOGGER is not None:
|
||||
raise RuntimeError("Logger already set. Please call `setup_logger` only once.")
|
||||
_JSON_LOGGING = json_logging
|
||||
|
||||
# Clean up old logger instance to prevent resource leaks
|
||||
if _LOGGER is not None:
|
||||
_LOGGER.remove()
|
||||
|
||||
# Format message with optional tag prefix
|
||||
tag_prefix = f"[{tag}] " if tag else ""
|
||||
message = "".join(
|
||||
@@ -154,7 +159,7 @@ def setup_logger(
|
||||
|
||||
# Install console handler (enqueue=True only for JSON mode to avoid blocking in async contexts)
|
||||
if json_logging:
|
||||
logger.add(_json_sink, level=log_level.upper(), enqueue=True)
|
||||
logger.add(json_sink, level=log_level.upper(), enqueue=True)
|
||||
else:
|
||||
logger.add(sys.stdout, format=format, level=log_level.upper(), colorize=True)
|
||||
|
||||
@@ -163,7 +168,7 @@ def setup_logger(
|
||||
if not append and log_file.exists():
|
||||
log_file.unlink()
|
||||
if json_logging:
|
||||
file_sink = _JsonFileSink(log_file)
|
||||
file_sink = JsonFileSink(log_file)
|
||||
logger.add(file_sink.write, level=log_level.upper(), enqueue=True)
|
||||
else:
|
||||
logger.add(log_file, format=format, level=log_level.upper(), colorize=True)
|
||||
@@ -178,23 +183,17 @@ def setup_logger(
|
||||
|
||||
|
||||
def get_logger():
|
||||
"""
|
||||
Get the global logger. This function is shared across submodules such as
|
||||
training and inference to access the global logger instance. Raises if the
|
||||
logger has not been set.
|
||||
|
||||
Returns:
|
||||
The global logger.
|
||||
"""
|
||||
global _LOGGER
|
||||
if _LOGGER is None:
|
||||
raise RuntimeError("Logger not set. Please call `set_logger` first.")
|
||||
_LOGGER = setup_logger()
|
||||
return _LOGGER
|
||||
|
||||
|
||||
def reset_logger():
|
||||
"""Reset the global logger. Useful mainly in test to clear loggers between tests."""
|
||||
"""Reset the logger. Useful mainly in tests."""
|
||||
global _LOGGER, _JSON_LOGGING
|
||||
if _LOGGER is not None:
|
||||
_LOGGER.remove()
|
||||
_LOGGER = None
|
||||
_JSON_LOGGING = False
|
||||
|
||||
|
||||
@@ -114,6 +114,7 @@ class MetricsServer(HealthServer):
|
||||
self._mismatch_kl = Gauge(
|
||||
"trainer_mismatch_kl", "KL divergence between trainer and inference model", registry=self._registry
|
||||
)
|
||||
self._kl_ent_ratio = Gauge("trainer_kl_ent_ratio", "Ratio of mismatch KL to entropy", registry=self._registry)
|
||||
# Aggregate run metrics
|
||||
self._runs_discovered = Gauge(
|
||||
"trainer_runs_discovered", "Number of run folders discovered", registry=self._registry
|
||||
@@ -206,6 +207,8 @@ class MetricsServer(HealthServer):
|
||||
self._mfu.set(mfu)
|
||||
self._entropy.set(entropy)
|
||||
self._mismatch_kl.set(mismatch_kl)
|
||||
if entropy > 0:
|
||||
self._kl_ent_ratio.set(mismatch_kl / entropy)
|
||||
self._last_step_ts.set(time.time())
|
||||
|
||||
def update_runs(
|
||||
|
||||
@@ -130,6 +130,7 @@ def clean_exit(func: Callable) -> Callable:
|
||||
wandb.finish()
|
||||
return ret
|
||||
except Exception as e:
|
||||
get_logger().opt(exception=True).error(f"Fatal error in {func.__name__}")
|
||||
wandb.finish(exit_code=1)
|
||||
raise e
|
||||
finally:
|
||||
@@ -146,6 +147,7 @@ def clean_exit(func: Callable) -> Callable:
|
||||
wandb.finish()
|
||||
return ret
|
||||
except Exception as e:
|
||||
get_logger().opt(exception=True).error(f"Fatal error in {func.__name__}")
|
||||
wandb.finish(exit_code=1)
|
||||
raise e
|
||||
finally:
|
||||
@@ -317,28 +319,3 @@ def get_env_ids_to_install(env_configs: list[EnvConfig] | list[EvalEnvConfig]) -
|
||||
if "/" in env_config.id:
|
||||
env_ids_to_install.add(env_config.id)
|
||||
return env_ids_to_install
|
||||
|
||||
|
||||
def is_chinese_char(char: str) -> bool:
|
||||
"""Check if a character is Chinese (CJK Unified Ideographs and extensions)."""
|
||||
code_point = ord(char)
|
||||
return (
|
||||
0x4E00 <= code_point <= 0x9FFF # CJK Unified Ideographs
|
||||
or 0x3400 <= code_point <= 0x4DBF # CJK Extension A
|
||||
or 0x20000 <= code_point <= 0x2A6DF # CJK Extension B
|
||||
or 0x2A700 <= code_point <= 0x2B73F # CJK Extension C
|
||||
or 0x2B740 <= code_point <= 0x2B81F # CJK Extension D
|
||||
or 0x2B820 <= code_point <= 0x2CEAF # CJK Extension E
|
||||
or 0xF900 <= code_point <= 0xFAFF # CJK Compatibility Ideographs
|
||||
or 0x2F800 <= code_point <= 0x2FA1F # CJK Compatibility Ideographs Supplement
|
||||
)
|
||||
|
||||
|
||||
def count_chinese_chars(text: str) -> tuple[int, int]:
|
||||
"""Count Chinese characters in text.
|
||||
|
||||
Returns:
|
||||
Tuple of (chinese_char_count, total_char_count)
|
||||
"""
|
||||
chinese_count = sum(1 for char in text if is_chinese_char(char))
|
||||
return chinese_count, len(text)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error, check_number_goes_up_or_down, check_reward_in_range, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
|
||||
TIMEOUT = 900 # 15 minutes
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_output_dir(output_dir: Path) -> Path:
|
||||
rl_dir = output_dir / "alphabet_sort_start"
|
||||
rl_dir.mkdir(parents=True, exist_ok=True)
|
||||
return rl_dir
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for alphabet sort RL CI integration tests."""
|
||||
return f"test-alphabet-sort-{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
rl_output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/alphabet_sort/start.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
rl_output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
check_reward_goes_up = partial(check_number_goes_up_or_down, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, rl_output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, rl_output_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, rl_output_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process."""
|
||||
with open(rl_output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
|
||||
def test_reward_in_range(rl_process: ProcessResult, test_no_error, rl_output_dir: Path):
|
||||
"""Tests that the reward is in range in the RL process."""
|
||||
with open(rl_output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_in_range(orchestrator_stdout, min_threshold=0.05)
|
||||
@@ -0,0 +1,104 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_no_error
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
TIMEOUT = 900 # 15 minutes
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
return f"test-rl-moe-{branch_name}"
|
||||
|
||||
|
||||
# --- MoE with HF impl (default) ---
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_hf_output_dir(output_dir: Path) -> Path:
|
||||
d = output_dir / "rl_moe_hf"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_hf_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
moe_hf_output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_moe/start.toml",
|
||||
"--trainer.model.impl",
|
||||
"hf",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
f"{wandb_name}-hf",
|
||||
"--output-dir",
|
||||
moe_hf_output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_hf(moe_hf_process: ProcessResult, moe_hf_output_dir: Path):
|
||||
check_no_error(moe_hf_process, moe_hf_output_dir)
|
||||
|
||||
|
||||
def test_moe_hf_runs(moe_hf_process: ProcessResult, test_no_error_hf):
|
||||
"""MoE RL with HF model impl completes without error."""
|
||||
|
||||
|
||||
# --- MoE with custom impl ---
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_custom_output_dir(output_dir: Path) -> Path:
|
||||
d = output_dir / "rl_moe_custom"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def moe_custom_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
moe_custom_output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/rl_moe/start.toml",
|
||||
"--trainer.model.impl",
|
||||
"custom",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
f"{wandb_name}-custom",
|
||||
"--output-dir",
|
||||
moe_custom_output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd, timeout=TIMEOUT)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error_custom(moe_custom_process: ProcessResult, moe_custom_output_dir: Path):
|
||||
check_no_error(moe_custom_process, moe_custom_output_dir)
|
||||
|
||||
|
||||
def test_moe_custom_runs(moe_custom_process: ProcessResult, test_no_error_custom):
|
||||
"""MoE RL with custom model impl completes without error."""
|
||||
@@ -0,0 +1,67 @@
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import ProcessResult
|
||||
from tests.utils import check_avg_reward_in_range, check_no_error, check_number_goes_up_or_down, strip_escape_codes
|
||||
|
||||
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
|
||||
|
||||
REWARD_MIN_THRESHOLD = 0.85
|
||||
REWARD_AVG_LAST_N_STEPS = 7
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wandb_name(branch_name: str) -> str:
|
||||
"""Fixture for W&B name for RL CI integration tests."""
|
||||
return f"multimodal-color-codeword-{branch_name}"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rl_process(
|
||||
run_process: Callable[..., ProcessResult],
|
||||
output_dir: Path,
|
||||
wandb_project: str,
|
||||
wandb_name: str,
|
||||
) -> ProcessResult:
|
||||
cmd = [
|
||||
"uv",
|
||||
"run",
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/nightly/multimodal_color_codeword.toml",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
wandb_name,
|
||||
"--output-dir",
|
||||
output_dir.as_posix(),
|
||||
]
|
||||
return run_process(cmd)
|
||||
|
||||
|
||||
check_reward_goes_up = partial(check_number_goes_up_or_down, go_up=True, pattern=r"Reward:\s*(\d+\.\d{4})")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def test_no_error(rl_process: ProcessResult, output_dir: Path):
|
||||
"""Tests that the RL process does not fail."""
|
||||
check_no_error(rl_process, output_dir)
|
||||
|
||||
|
||||
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the reward goes up in the RL process"""
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_reward_goes_up(orchestrator_stdout)
|
||||
|
||||
|
||||
def test_reward_reaches_threshold(rl_process: ProcessResult, test_no_error, output_dir: Path):
|
||||
"""Tests that the average reward over the last steps exceeds the threshold"""
|
||||
with open(output_dir / "logs" / "orchestrator.stdout", "r") as f:
|
||||
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
|
||||
check_avg_reward_in_range(
|
||||
orchestrator_stdout, last_n_steps=REWARD_AVG_LAST_N_STEPS, min_threshold=REWARD_MIN_THRESHOLD
|
||||
)
|
||||
@@ -0,0 +1,347 @@
|
||||
import math
|
||||
|
||||
from prime_rl.orchestrator.config import GibberishFilterConfig, RepetitionFilterConfig
|
||||
from prime_rl.orchestrator.filters import (
|
||||
GibberishFilter,
|
||||
RepetitionFilter,
|
||||
apply_filters,
|
||||
setup_filter,
|
||||
setup_filters,
|
||||
)
|
||||
|
||||
|
||||
def _make_rollout(completion_ids, completion_logprobs, reward=1.0, multi_step=False):
|
||||
"""Create a minimal rollout dict matching the verifiers RolloutOutput structure."""
|
||||
if multi_step:
|
||||
mid = len(completion_ids) // 2
|
||||
trajectory = [
|
||||
{
|
||||
"tokens": {
|
||||
"completion_ids": completion_ids[:mid],
|
||||
"completion_logprobs": completion_logprobs[:mid],
|
||||
"completion_mask": [1] * mid,
|
||||
}
|
||||
},
|
||||
{
|
||||
"tokens": {
|
||||
"completion_ids": completion_ids[mid:],
|
||||
"completion_logprobs": completion_logprobs[mid:],
|
||||
"completion_mask": [1] * (len(completion_ids) - mid),
|
||||
}
|
||||
},
|
||||
]
|
||||
else:
|
||||
trajectory = [
|
||||
{
|
||||
"tokens": {
|
||||
"completion_ids": completion_ids,
|
||||
"completion_logprobs": completion_logprobs,
|
||||
"completion_mask": [1] * len(completion_ids),
|
||||
}
|
||||
}
|
||||
]
|
||||
return {
|
||||
"trajectory": trajectory,
|
||||
"reward": reward,
|
||||
"stop_condition": None,
|
||||
"metrics": {},
|
||||
}
|
||||
|
||||
|
||||
def _make_gibberish_filter(vocab_size=128_000, token_id_threshold=100_000, logprob_offset=2.0, enforce=False):
|
||||
logprob_threshold = -math.log(vocab_size) - logprob_offset
|
||||
return GibberishFilter(
|
||||
name="gibberish", token_id_threshold=token_id_threshold, logprob_threshold=logprob_threshold, enforce=enforce
|
||||
)
|
||||
|
||||
|
||||
def _make_repetition_filter(window=5, prob_threshold=0.99, enforce=False):
|
||||
return RepetitionFilter(
|
||||
name="repetition", window=window, logprob_threshold=math.log(prob_threshold), enforce=enforce
|
||||
)
|
||||
|
||||
|
||||
# --- GibberishFilter tests ---
|
||||
|
||||
|
||||
def test_gibberish_detects_rare_low_prob_token():
|
||||
gibberish_filter = _make_gibberish_filter()
|
||||
|
||||
result = gibberish_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=[50, 120_000, 80],
|
||||
completion_logprobs=[-1.0, gibberish_filter.logprob_threshold - 1.0, -0.5],
|
||||
)
|
||||
)
|
||||
assert result.detected is True
|
||||
assert result.detection_index == 1
|
||||
|
||||
|
||||
def test_gibberish_ignores_normal_tokens():
|
||||
gibberish_filter = _make_gibberish_filter()
|
||||
|
||||
result = gibberish_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=[10, 200, 5000],
|
||||
completion_logprobs=[-1.0, -2.0, -3.0],
|
||||
)
|
||||
)
|
||||
assert result.detected is False
|
||||
assert result.detection_index is None
|
||||
|
||||
|
||||
def test_gibberish_ignores_high_prob_rare_token():
|
||||
gibberish_filter = _make_gibberish_filter()
|
||||
|
||||
result = gibberish_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=[120_000],
|
||||
completion_logprobs=[-0.5],
|
||||
)
|
||||
)
|
||||
assert result.detected is False
|
||||
|
||||
|
||||
def test_gibberish_works_across_trajectory_steps():
|
||||
gibberish_filter = _make_gibberish_filter()
|
||||
|
||||
result = gibberish_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=[50, 60, 120_000, 80],
|
||||
completion_logprobs=[-1.0, -0.5, gibberish_filter.logprob_threshold - 1.0, -0.5],
|
||||
multi_step=True,
|
||||
)
|
||||
)
|
||||
assert result.detected is True
|
||||
assert result.detection_index == 2
|
||||
|
||||
|
||||
# --- RepetitionFilter tests ---
|
||||
|
||||
|
||||
def test_repetition_triggers_after_window():
|
||||
repetition_filter = _make_repetition_filter(window=5)
|
||||
|
||||
result = repetition_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=list(range(5)),
|
||||
completion_logprobs=[-0.001] * 5,
|
||||
)
|
||||
)
|
||||
assert result.detected is True
|
||||
assert result.detection_index == 4
|
||||
|
||||
|
||||
def test_repetition_no_trigger_below_window():
|
||||
repetition_filter = _make_repetition_filter(window=5)
|
||||
|
||||
result = repetition_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=list(range(4)),
|
||||
completion_logprobs=[-0.001] * 4,
|
||||
)
|
||||
)
|
||||
assert result.detected is False
|
||||
|
||||
|
||||
def test_repetition_resets_on_low_prob():
|
||||
repetition_filter = _make_repetition_filter(window=5)
|
||||
|
||||
logprobs = [-0.001] * 3 + [-2.0] + [-0.001] * 3
|
||||
result = repetition_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=list(range(7)),
|
||||
completion_logprobs=logprobs,
|
||||
)
|
||||
)
|
||||
assert result.detected is False
|
||||
|
||||
|
||||
def test_repetition_varied_probs_no_trigger():
|
||||
repetition_filter = _make_repetition_filter(window=3)
|
||||
|
||||
result = repetition_filter.check(
|
||||
_make_rollout(
|
||||
completion_ids=list(range(6)),
|
||||
completion_logprobs=[-0.001, -3.0, -0.001, -3.0, -0.001, -3.0],
|
||||
)
|
||||
)
|
||||
assert result.detected is False
|
||||
|
||||
|
||||
# --- setup_filter / setup_filters tests ---
|
||||
|
||||
|
||||
def test_setup_filter_gibberish():
|
||||
config = GibberishFilterConfig(token_id_threshold=100_000, logprob_offset=2.0)
|
||||
gibberish_filter = setup_filter(config, vocab_size=128_000)
|
||||
assert isinstance(gibberish_filter, GibberishFilter)
|
||||
assert gibberish_filter.name == "gibberish"
|
||||
assert gibberish_filter.token_id_threshold == 100_000
|
||||
assert abs(gibberish_filter.logprob_threshold - (-math.log(128_000) - 2.0)) < 1e-10
|
||||
assert gibberish_filter.enforce is False
|
||||
|
||||
|
||||
def test_setup_filter_gibberish_enforce():
|
||||
config = GibberishFilterConfig(enforce=True)
|
||||
gibberish_filter = setup_filter(config, vocab_size=128_000)
|
||||
assert gibberish_filter.enforce is True
|
||||
|
||||
|
||||
def test_setup_filter_repetition():
|
||||
config = RepetitionFilterConfig(window=3_000, prob_threshold=0.99)
|
||||
repetition_filter = setup_filter(config, vocab_size=128_000)
|
||||
assert isinstance(repetition_filter, RepetitionFilter)
|
||||
assert repetition_filter.name == "repetition"
|
||||
assert repetition_filter.window == 3_000
|
||||
assert abs(repetition_filter.logprob_threshold - math.log(0.99)) < 1e-10
|
||||
assert repetition_filter.enforce is False
|
||||
|
||||
|
||||
def test_setup_filter_repetition_enforce():
|
||||
config = RepetitionFilterConfig(enforce=True)
|
||||
repetition_filter = setup_filter(config, vocab_size=128_000)
|
||||
assert repetition_filter.enforce is True
|
||||
|
||||
|
||||
def test_setup_filters_multiple():
|
||||
configs = [
|
||||
GibberishFilterConfig(),
|
||||
RepetitionFilterConfig(),
|
||||
]
|
||||
filters = setup_filters(configs, vocab_size=128_000)
|
||||
assert len(filters) == 2
|
||||
assert filters[0].name == "gibberish"
|
||||
assert filters[1].name == "repetition"
|
||||
|
||||
|
||||
# --- apply_filters tests (enforce=True) ---
|
||||
|
||||
|
||||
def test_apply_filters_enforced_zeros_mask():
|
||||
gibberish_filter = _make_gibberish_filter(enforce=True)
|
||||
|
||||
rollout = _make_rollout(
|
||||
completion_ids=[120_000],
|
||||
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0],
|
||||
reward=1.0,
|
||||
)
|
||||
|
||||
metrics = apply_filters([gibberish_filter], [rollout])
|
||||
|
||||
assert rollout["reward"] == 1.0
|
||||
assert all(m == 0 for m in rollout["trajectory"][0]["tokens"]["completion_mask"])
|
||||
assert rollout["stop_condition"] == "gibberish"
|
||||
assert rollout["metrics"]["filter/gibberish"] == 1.0
|
||||
assert metrics["filter/gibberish_count"] == 1.0
|
||||
assert metrics["filter/gibberish_rate"] == 1.0
|
||||
assert metrics["filter/total_detected_rate"] == 1.0
|
||||
assert metrics["filter/total_enforced_rate"] == 1.0
|
||||
|
||||
|
||||
def test_apply_filters_preserves_clean_rollouts():
|
||||
gibberish_filter = _make_gibberish_filter(enforce=True)
|
||||
|
||||
rollout = _make_rollout(
|
||||
completion_ids=[50, 60, 70],
|
||||
completion_logprobs=[-1.0, -2.0, -1.5],
|
||||
reward=1.0,
|
||||
)
|
||||
|
||||
metrics = apply_filters([gibberish_filter], [rollout])
|
||||
|
||||
assert rollout["reward"] == 1.0
|
||||
assert all(m == 1 for m in rollout["trajectory"][0]["tokens"]["completion_mask"])
|
||||
assert rollout["stop_condition"] is None
|
||||
assert metrics["filter/gibberish_count"] == 0.0
|
||||
assert metrics["filter/total_detected_rate"] == 0.0
|
||||
assert metrics["filter/total_enforced_rate"] == 0.0
|
||||
|
||||
|
||||
def test_apply_filters_first_filter_wins():
|
||||
gibberish_filter = _make_gibberish_filter(enforce=True)
|
||||
repetition_filter = _make_repetition_filter(window=2, enforce=True)
|
||||
|
||||
rollout = _make_rollout(
|
||||
completion_ids=[120_000, 1, 2],
|
||||
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0, -0.001, -0.001],
|
||||
reward=1.0,
|
||||
)
|
||||
|
||||
metrics = apply_filters([gibberish_filter, repetition_filter], [rollout])
|
||||
|
||||
assert rollout["stop_condition"] == "gibberish"
|
||||
assert metrics["filter/gibberish_count"] == 1.0
|
||||
assert metrics["filter/repetition_count"] == 0.0
|
||||
assert metrics["filter/total_detected_rate"] == 1.0
|
||||
assert metrics["filter/total_enforced_rate"] == 1.0
|
||||
|
||||
|
||||
def test_apply_filters_empty_list():
|
||||
rollout = _make_rollout(
|
||||
completion_ids=[1, 2, 3],
|
||||
completion_logprobs=[-1.0, -1.0, -1.0],
|
||||
)
|
||||
metrics = apply_filters([], [rollout])
|
||||
assert metrics == {}
|
||||
assert rollout["reward"] == 1.0
|
||||
|
||||
|
||||
def test_apply_filters_mixed_batch():
|
||||
gibberish_filter = _make_gibberish_filter(enforce=True)
|
||||
|
||||
clean = _make_rollout(completion_ids=[50], completion_logprobs=[-1.0], reward=1.0)
|
||||
dirty = _make_rollout(
|
||||
completion_ids=[120_000], completion_logprobs=[gibberish_filter.logprob_threshold - 1.0], reward=1.0
|
||||
)
|
||||
|
||||
metrics = apply_filters([gibberish_filter], [clean, dirty])
|
||||
|
||||
assert clean["reward"] == 1.0
|
||||
assert dirty["reward"] == 1.0
|
||||
assert all(m == 0 for m in dirty["trajectory"][0]["tokens"]["completion_mask"])
|
||||
assert metrics["filter/gibberish_count"] == 1.0
|
||||
assert metrics["filter/gibberish_rate"] == 0.5
|
||||
assert metrics["filter/total_detected_rate"] == 0.5
|
||||
assert metrics["filter/total_enforced_rate"] == 0.5
|
||||
|
||||
|
||||
# --- apply_filters tests (monitor-only, enforce=False) ---
|
||||
|
||||
|
||||
def test_apply_filters_monitor_only_tracks_detection():
|
||||
gibberish_filter = _make_gibberish_filter(enforce=False)
|
||||
|
||||
rollout = _make_rollout(
|
||||
completion_ids=[120_000],
|
||||
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0],
|
||||
reward=1.0,
|
||||
)
|
||||
|
||||
metrics = apply_filters([gibberish_filter], [rollout])
|
||||
|
||||
assert rollout["reward"] == 1.0
|
||||
assert all(m == 1 for m in rollout["trajectory"][0]["tokens"]["completion_mask"])
|
||||
assert rollout["stop_condition"] is None
|
||||
assert rollout["metrics"]["filter/gibberish"] == 1.0
|
||||
assert metrics["filter/gibberish_count"] == 1.0
|
||||
assert metrics["filter/gibberish_rate"] == 1.0
|
||||
assert metrics["filter/total_detected_rate"] == 1.0
|
||||
assert metrics["filter/total_enforced_rate"] == 0.0
|
||||
|
||||
|
||||
def test_apply_filters_monitor_only_mixed_batch():
|
||||
gibberish_filter = _make_gibberish_filter(enforce=False)
|
||||
|
||||
clean = _make_rollout(completion_ids=[50], completion_logprobs=[-1.0], reward=1.0)
|
||||
dirty = _make_rollout(
|
||||
completion_ids=[120_000], completion_logprobs=[gibberish_filter.logprob_threshold - 1.0], reward=1.0
|
||||
)
|
||||
|
||||
metrics = apply_filters([gibberish_filter], [clean, dirty])
|
||||
|
||||
assert clean["reward"] == 1.0
|
||||
assert dirty["reward"] == 1.0
|
||||
assert metrics["filter/gibberish_rate"] == 0.5
|
||||
assert metrics["filter/total_detected_rate"] == 0.5
|
||||
assert metrics["filter/total_enforced_rate"] == 0.0
|
||||
@@ -7,12 +7,20 @@ from pydantic import ValidationError
|
||||
from prime_rl.inference.config import InferenceConfig
|
||||
from prime_rl.orchestrator.config import OrchestratorConfig
|
||||
from prime_rl.rl import RLConfig
|
||||
from prime_rl.slurm.rl import RLSLURMConfig
|
||||
from prime_rl.trainer.rl.config import RLTrainerConfig
|
||||
from prime_rl.trainer.sft.config import SFTTrainerConfig
|
||||
from prime_rl.utils.pydantic_config import parse_argv
|
||||
|
||||
# All config config classes
|
||||
CONFIG_CLASSES = [RLConfig, RLTrainerConfig, SFTTrainerConfig, OrchestratorConfig, InferenceConfig]
|
||||
CONFIG_CLASSES = [
|
||||
RLConfig,
|
||||
RLTrainerConfig,
|
||||
SFTTrainerConfig,
|
||||
OrchestratorConfig,
|
||||
InferenceConfig,
|
||||
RLSLURMConfig,
|
||||
]
|
||||
|
||||
|
||||
def get_config_files() -> list[Path]:
|
||||
|
||||
@@ -118,21 +118,6 @@ def test_glm4_moe() -> None:
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_from_prime_model = HFGlm4MoeForCausalLM._from_config(hf_model.config)
|
||||
converted_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
|
||||
hf_from_prime_model.load_state_dict(converted_state_dict)
|
||||
|
||||
hf_from_prime_output = hf_from_prime_model(input_ids, position_ids)
|
||||
hf_from_prime_output.logits.sum().backward()
|
||||
|
||||
logits_diff = hf_from_prime_output.logits - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_from_prime_model.model.embed_tokens.weight.grad - hf_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_glm4_moe_mlp_only()
|
||||
|
||||
@@ -117,21 +117,6 @@ def test_qwen3_moe():
|
||||
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
with torch.device("cuda"), default_dtype(torch.float32):
|
||||
hf_from_prime_model = HFQwen3MoeForCausalLM._from_config(hf_model.config)
|
||||
converted_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
|
||||
hf_from_prime_model.load_state_dict(converted_state_dict)
|
||||
|
||||
hf_from_prime_output = hf_from_prime_model(input_ids, position_ids)
|
||||
hf_from_prime_output.logits.sum().backward()
|
||||
|
||||
logits_diff = hf_from_prime_output.logits - hf_output.logits
|
||||
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
|
||||
f"Max logits diff: {logits_diff.abs().max()}"
|
||||
)
|
||||
grad_diff = hf_from_prime_model.model.embed_tokens.weight.grad - hf_model.model.embed_tokens.weight.grad
|
||||
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_qwen3_moe_mlp_only()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
import torch
|
||||
from transformers import AutoConfig, AutoModelForCausalLM
|
||||
from transformers import AutoConfig, AutoModelForCausalLM, GenerationConfig
|
||||
|
||||
from prime_rl.trainer.perf import PerfCounter
|
||||
|
||||
@@ -14,7 +14,16 @@ def test_perf_counter(model_name: str, active_params: int, flops_per_token: int)
|
||||
with torch.device("meta"):
|
||||
config = AutoConfig.from_pretrained(model_name)
|
||||
if getattr(config, "pad_token_id", None) is None:
|
||||
config.pad_token_id = config.eos_token_id
|
||||
gen_config = GenerationConfig.from_model_config(config)
|
||||
# Use `is not None` instead of truthiness: token ID 0 is valid.
|
||||
config.pad_token_id = next(
|
||||
(
|
||||
v
|
||||
for v in [gen_config.pad_token_id, gen_config.eos_token_id, getattr(config, "eos_token_id", None)]
|
||||
if v is not None
|
||||
),
|
||||
None,
|
||||
)
|
||||
model = AutoModelForCausalLM.from_config(config)
|
||||
perf_counter = PerfCounter(model, seq_len=1024, window_size=10)
|
||||
|
||||
|
||||
@@ -92,6 +92,7 @@ def test_server_update_metrics():
|
||||
assert "trainer_loss" in content
|
||||
assert "trainer_last_step_timestamp_seconds" in content
|
||||
assert "trainer_mismatch_kl" in content
|
||||
assert "trainer_kl_ent_ratio" in content
|
||||
|
||||
server.stop()
|
||||
|
||||
@@ -102,6 +103,8 @@ def test_server_metrics_values_are_correct():
|
||||
server.start()
|
||||
time.sleep(0.1)
|
||||
|
||||
entropy = 1.5
|
||||
mismatch_kl = 0.045
|
||||
server.update(
|
||||
step=100,
|
||||
loss=0.123,
|
||||
@@ -109,7 +112,8 @@ def test_server_metrics_values_are_correct():
|
||||
grad_norm=2.5,
|
||||
peak_memory_gib=16.0,
|
||||
learning_rate=3e-5,
|
||||
mismatch_kl=0.045,
|
||||
entropy=entropy,
|
||||
mismatch_kl=mismatch_kl,
|
||||
)
|
||||
|
||||
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
|
||||
@@ -118,6 +122,7 @@ def test_server_metrics_values_are_correct():
|
||||
assert "trainer_step 100.0" in content
|
||||
assert "trainer_loss 0.123" in content
|
||||
assert "trainer_mismatch_kl 0.045" in content
|
||||
assert f"trainer_kl_ent_ratio {mismatch_kl / entropy}" in content
|
||||
|
||||
server.stop()
|
||||
|
||||
|
||||
@@ -116,6 +116,39 @@ def check_reward_in_range(
|
||||
)
|
||||
|
||||
|
||||
def check_avg_reward_in_range(
|
||||
lines: list[str],
|
||||
last_n_steps: int,
|
||||
min_threshold: float | None = None,
|
||||
max_threshold: float | None = None,
|
||||
):
|
||||
"""Helper to assert that the average reward over the last N steps is within a threshold"""
|
||||
pattern = r"Reward:\s*(\d+\.\d{4})"
|
||||
step_lines = [line for line in lines if "SUCCESS" in line and "Step" in line and re.search(pattern, line)]
|
||||
assert len(step_lines) >= last_n_steps, (
|
||||
f"Not enough step lines found. Expected at least {last_n_steps}, got {len(step_lines)}"
|
||||
)
|
||||
|
||||
recent_lines = step_lines[-last_n_steps:]
|
||||
rewards = []
|
||||
for line in recent_lines:
|
||||
match = re.search(pattern, line)
|
||||
assert match is not None, f"Could not find Reward in line: {line}"
|
||||
rewards.append(float(match.group(1)))
|
||||
|
||||
avg_reward = sum(rewards) / len(rewards)
|
||||
if min_threshold is not None:
|
||||
assert avg_reward >= min_threshold, (
|
||||
f"Average reward over last {last_n_steps} steps did not reach minimum threshold. "
|
||||
f"Found avg_reward={avg_reward:.4f} < {min_threshold} (rewards={rewards})"
|
||||
)
|
||||
if max_threshold is not None:
|
||||
assert avg_reward <= max_threshold, (
|
||||
f"Average reward over last {last_n_steps} steps exceeded maximum threshold. "
|
||||
f"Found avg_reward={avg_reward:.4f} > {max_threshold} (rewards={rewards})"
|
||||
)
|
||||
|
||||
|
||||
def check_mismatch_kl_in_range(
|
||||
lines: list[str],
|
||||
step: int = -1,
|
||||
|
||||
@@ -118,7 +118,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "anthropic"
|
||||
version = "0.71.0"
|
||||
version = "0.79.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "anyio" },
|
||||
@@ -130,9 +130,9 @@ dependencies = [
|
||||
{ name = "sniffio" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/82/4f/70682b068d897841f43223df82d96ec1d617435a8b759c4a2d901a50158b/anthropic-0.71.0.tar.gz", hash = "sha256:eb8e6fa86d049061b3ef26eb4cbae0174ebbff21affa6de7b3098da857d8de6a", size = 489102, upload-time = "2025-10-16T15:54:40.08Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/15/b1/91aea3f8fd180d01d133d931a167a78a3737b3fd39ccef2ae8d6619c24fd/anthropic-0.79.0.tar.gz", hash = "sha256:8707aafb3b1176ed6c13e2b1c9fb3efddce90d17aee5d8b83a86c70dcdcca871", size = 509825, upload-time = "2026-02-07T18:06:18.388Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5d/77/073e8ac488f335aec7001952825275582fb8f433737e90f24eeef9d878f6/anthropic-0.71.0-py3-none-any.whl", hash = "sha256:85c5015fcdbdc728390f11b17642a65a4365d03b12b799b18b6cc57e71fdb327", size = 355035, upload-time = "2025-10-16T15:54:38.238Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/95/b2/cc0b8e874a18d7da50b0fda8c99e4ac123f23bf47b471827c5f6f3e4a767/anthropic-0.79.0-py3-none-any.whl", hash = "sha256:04cbd473b6bbda4ca2e41dd670fe2f829a911530f01697d0a1e37321eb75f3cf", size = 405918, upload-time = "2026-02-07T18:06:20.246Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -755,14 +755,14 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "flash-attn"
|
||||
version = "2.6.3+cu128torch2.10"
|
||||
source = { url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.6.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl" }
|
||||
version = "2.8.3+cu128torch2.10"
|
||||
source = { url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl" }
|
||||
dependencies = [
|
||||
{ name = "einops" },
|
||||
{ name = "torch" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.6.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl", hash = "sha256:e883225b48075ea57790527ae3f653421a58c25d207375d00a1dfa9221b5bd43" },
|
||||
{ url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl", hash = "sha256:5ef676dfd01d198eed36795d924eb6af4c87674896de6bd102390afa7f522bc0" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
@@ -1481,6 +1481,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/80/a61f99dc3a936413c3ee4e1eecac96c0da5ed07ad56fd975f1a9da5bc630/MarkupSafe-3.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:8e06879fc22a25ca47312fbe7c8264eb0b662f6db27cb2d3bbbc74b1df4b9b87", size = 15601, upload-time = "2024-10-18T15:21:23.499Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "math-env"
|
||||
version = "0.1.2"
|
||||
source = { registry = "https://hub.primeintellect.ai/primeintellect/simple/" }
|
||||
dependencies = [
|
||||
{ name = "math-verify" },
|
||||
{ name = "prime-sandboxes" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://hub.primeintellect.ai/primeintellect/math-env/@07fdeaab/math_env-0.1.2-py3-none-any.whl", hash = "sha256:87003ca56c65818e7a7707f12e80511180038190abe4df5ec66cb2012d38b6d9" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "math-verify"
|
||||
version = "0.8.0"
|
||||
@@ -2285,6 +2298,7 @@ dependencies = [
|
||||
{ name = "jaxtyping" },
|
||||
{ name = "liger-kernel" },
|
||||
{ name = "loguru" },
|
||||
{ name = "math-env" },
|
||||
{ name = "numpy" },
|
||||
{ name = "openai" },
|
||||
{ name = "prime" },
|
||||
@@ -2334,12 +2348,13 @@ requires-dist = [
|
||||
{ name = "beartype", specifier = ">=0.21.0" },
|
||||
{ name = "datasets", specifier = ">=4.0.0" },
|
||||
{ name = "dion", git = "https://github.com/samsja/dion.git?rev=d891eeb" },
|
||||
{ name = "flash-attn", marker = "extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.6.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "flash-attn", marker = "extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3%2Bcu128torch2.10-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "flash-attn-3", marker = "extra == 'flash-attn-3'", url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl" },
|
||||
{ name = "flash-attn-cute", marker = "extra == 'flash-attn-cute'", git = "https://github.com/Dao-AILab/flash-attention.git?subdirectory=flash_attn%2Fcute&rev=main" },
|
||||
{ name = "jaxtyping", specifier = ">=0.3.2" },
|
||||
{ name = "liger-kernel", specifier = ">=0.5.10" },
|
||||
{ name = "loguru", specifier = ">=0.7.3" },
|
||||
{ name = "math-env", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
|
||||
{ name = "numpy", specifier = ">=2.2.6" },
|
||||
{ name = "openai", specifier = ">=1.106.1" },
|
||||
{ name = "prime", specifier = ">=0.5.37" },
|
||||
@@ -2358,7 +2373,7 @@ requires-dist = [
|
||||
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
|
||||
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=609e3d5" },
|
||||
{ name = "uvloop", specifier = ">=0.21.0" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=ccef044" },
|
||||
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=013d4da" },
|
||||
{ name = "vllm", url = "https://github.com/vllm-project/vllm/releases/download/v0.16.0/vllm-0.16.0-cp38-abi3-manylinux_2_31_x86_64.whl" },
|
||||
{ name = "wandb", specifier = ">=0.24.2" },
|
||||
]
|
||||
@@ -3686,9 +3701,10 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "verifiers"
|
||||
version = "0.1.10"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=ccef044#ccef04486cda1759981dfc41b81b3939e5b69a9f" }
|
||||
version = "0.1.11.dev0"
|
||||
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=013d4da#013d4da8a906bef2e1cbb6b4bc4347214c1fd534" }
|
||||
dependencies = [
|
||||
{ name = "anthropic" },
|
||||
{ name = "datasets" },
|
||||
{ name = "gepa" },
|
||||
{ name = "jinja2" },
|
||||
|
||||
Reference in New Issue
Block a user